kernel/cpumask.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! CPU Mask abstractions.
4//!
5//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h)
6
7use crate::{
8 alloc::{AllocError, Flags},
9 cpu::CpuId,
10 prelude::*,
11 types::Opaque,
12};
13
14#[cfg(CONFIG_CPUMASK_OFFSTACK)]
15use core::ptr::{self, NonNull};
16
17use core::ops::{Deref, DerefMut};
18use safety_macro::safety;
19
20/// A CPU Mask.
21///
22/// Rust abstraction for the C `struct cpumask`.
23///
24/// # Invariants
25///
26/// A [`Cpumask`] instance always corresponds to a valid C `struct cpumask`.
27///
28/// The callers must ensure that the `struct cpumask` is valid for access and
29/// remains valid for the lifetime of the returned reference.
30///
31/// # Examples
32///
33/// The following example demonstrates how to update a [`Cpumask`].
34///
35/// ```
36/// use kernel::bindings;
37/// use kernel::cpu::CpuId;
38/// use kernel::cpumask::Cpumask;
39///
40/// fn set_clear_cpu(ptr: *mut bindings::cpumask, set_cpu: CpuId, clear_cpu: CpuId) {
41/// // SAFETY: The `ptr` is valid for writing and remains valid for the lifetime of the
42/// // returned reference.
43/// let mask = unsafe { Cpumask::as_mut_ref(ptr) };
44///
45/// mask.set(set_cpu);
46/// mask.clear(clear_cpu);
47/// }
48/// ```
49#[repr(transparent)]
50pub struct Cpumask(Opaque<bindings::cpumask>);
51
52impl Cpumask {
53 /// Creates a mutable reference to an existing `struct cpumask` pointer.
54 ///
55 /// # Safety
56 ///
57 /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime
58 /// of the returned reference.
59 #[safety{ValidWrite(ptr, "some"), Alive(ptr, "\'a")}]
60 pub unsafe fn as_mut_ref<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self {
61 // SAFETY: Guaranteed by the safety requirements of the function.
62 //
63 // INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the
64 // lifetime of the returned reference.
65 unsafe { &mut *ptr.cast() }
66 }
67
68 /// Creates a reference to an existing `struct cpumask` pointer.
69 ///
70 /// # Safety
71 ///
72 /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime
73 /// of the returned reference.
74 #[safety{ValidRead(ptr, "some"), Alive(ptr, "\'a")}]
75 pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self {
76 // SAFETY: Guaranteed by the safety requirements of the function.
77 //
78 // INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the
79 // lifetime of the returned reference.
80 unsafe { &*ptr.cast() }
81 }
82
83 /// Obtain the raw `struct cpumask` pointer.
84 pub fn as_raw(&self) -> *mut bindings::cpumask {
85 let this: *const Self = self;
86 this.cast_mut().cast()
87 }
88
89 /// Set `cpu` in the cpumask.
90 ///
91 /// ATTENTION: Contrary to C, this Rust `set()` method is non-atomic.
92 /// This mismatches kernel naming convention and corresponds to the C
93 /// function `__cpumask_set_cpu()`.
94 #[inline]
95 pub fn set(&mut self, cpu: CpuId) {
96 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `__cpumask_set_cpu`.
97 unsafe { bindings::__cpumask_set_cpu(u32::from(cpu), self.as_raw()) };
98 }
99
100 /// Clear `cpu` in the cpumask.
101 ///
102 /// ATTENTION: Contrary to C, this Rust `clear()` method is non-atomic.
103 /// This mismatches kernel naming convention and corresponds to the C
104 /// function `__cpumask_clear_cpu()`.
105 #[inline]
106 pub fn clear(&mut self, cpu: CpuId) {
107 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to
108 // `__cpumask_clear_cpu`.
109 unsafe { bindings::__cpumask_clear_cpu(i32::from(cpu), self.as_raw()) };
110 }
111
112 /// Test `cpu` in the cpumask.
113 ///
114 /// Equivalent to the kernel's `cpumask_test_cpu` API.
115 #[inline]
116 pub fn test(&self, cpu: CpuId) -> bool {
117 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_test_cpu`.
118 unsafe { bindings::cpumask_test_cpu(i32::from(cpu), self.as_raw()) }
119 }
120
121 /// Set all CPUs in the cpumask.
122 ///
123 /// Equivalent to the kernel's `cpumask_setall` API.
124 #[inline]
125 pub fn setall(&mut self) {
126 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_setall`.
127 unsafe { bindings::cpumask_setall(self.as_raw()) };
128 }
129
130 /// Checks if cpumask is empty.
131 ///
132 /// Equivalent to the kernel's `cpumask_empty` API.
133 #[inline]
134 pub fn empty(&self) -> bool {
135 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_empty`.
136 unsafe { bindings::cpumask_empty(self.as_raw()) }
137 }
138
139 /// Checks if cpumask is full.
140 ///
141 /// Equivalent to the kernel's `cpumask_full` API.
142 #[inline]
143 pub fn full(&self) -> bool {
144 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_full`.
145 unsafe { bindings::cpumask_full(self.as_raw()) }
146 }
147
148 /// Get weight of the cpumask.
149 ///
150 /// Equivalent to the kernel's `cpumask_weight` API.
151 #[inline]
152 pub fn weight(&self) -> u32 {
153 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_weight`.
154 unsafe { bindings::cpumask_weight(self.as_raw()) }
155 }
156
157 /// Copy cpumask.
158 ///
159 /// Equivalent to the kernel's `cpumask_copy` API.
160 #[inline]
161 pub fn copy(&self, dstp: &mut Self) {
162 // SAFETY: By the type invariant, `Self::as_raw` is a valid argument to `cpumask_copy`.
163 unsafe { bindings::cpumask_copy(dstp.as_raw(), self.as_raw()) };
164 }
165}
166
167/// A CPU Mask pointer.
168///
169/// Rust abstraction for the C `struct cpumask_var_t`.
170///
171/// # Invariants
172///
173/// A [`CpumaskVar`] instance always corresponds to a valid C `struct cpumask_var_t`.
174///
175/// The callers must ensure that the `struct cpumask_var_t` is valid for access and remains valid
176/// for the lifetime of [`CpumaskVar`].
177///
178/// # Examples
179///
180/// The following example demonstrates how to create and update a [`CpumaskVar`].
181///
182/// ```
183/// use kernel::cpu::CpuId;
184/// use kernel::cpumask::CpumaskVar;
185///
186/// let mut mask = CpumaskVar::new_zero(GFP_KERNEL).unwrap();
187///
188/// assert!(mask.empty());
189/// let mut count = 0;
190///
191/// let cpu2 = CpuId::from_u32(2);
192/// if let Some(cpu) = cpu2 {
193/// mask.set(cpu);
194/// assert!(mask.test(cpu));
195/// count += 1;
196/// }
197///
198/// let cpu3 = CpuId::from_u32(3);
199/// if let Some(cpu) = cpu3 {
200/// mask.set(cpu);
201/// assert!(mask.test(cpu));
202/// count += 1;
203/// }
204///
205/// assert_eq!(mask.weight(), count);
206///
207/// let mask2 = CpumaskVar::try_clone(&mask).unwrap();
208///
209/// if let Some(cpu) = cpu2 {
210/// assert!(mask2.test(cpu));
211/// }
212///
213/// if let Some(cpu) = cpu3 {
214/// assert!(mask2.test(cpu));
215/// }
216/// assert_eq!(mask2.weight(), count);
217/// ```
218#[repr(transparent)]
219pub struct CpumaskVar {
220 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
221 ptr: NonNull<Cpumask>,
222 #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
223 mask: Cpumask,
224}
225
226impl CpumaskVar {
227 /// Creates a zero-initialized instance of the [`CpumaskVar`].
228 pub fn new_zero(_flags: Flags) -> Result<Self, AllocError> {
229 Ok(Self {
230 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
231 ptr: {
232 let mut ptr: *mut bindings::cpumask = ptr::null_mut();
233
234 // SAFETY: It is safe to call this method as the reference to `ptr` is valid.
235 //
236 // INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of
237 // scope.
238 unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_raw()) };
239 NonNull::new(ptr.cast()).ok_or(AllocError)?
240 },
241
242 #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
243 mask: Cpumask(Opaque::zeroed()),
244 })
245 }
246
247 /// Creates an instance of the [`CpumaskVar`].
248 ///
249 /// # Safety
250 ///
251 /// The caller must ensure that the returned [`CpumaskVar`] is properly initialized before
252 /// getting used.
253 #[safety{Init}]
254 pub unsafe fn new(_flags: Flags) -> Result<Self, AllocError> {
255 Ok(Self {
256 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
257 ptr: {
258 let mut ptr: *mut bindings::cpumask = ptr::null_mut();
259
260 // SAFETY: It is safe to call this method as the reference to `ptr` is valid.
261 //
262 // INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of
263 // scope.
264 unsafe { bindings::alloc_cpumask_var(&mut ptr, _flags.as_raw()) };
265 NonNull::new(ptr.cast()).ok_or(AllocError)?
266 },
267 #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
268 mask: Cpumask(Opaque::uninit()),
269 })
270 }
271
272 /// Creates a mutable reference to an existing `struct cpumask_var_t` pointer.
273 ///
274 /// # Safety
275 ///
276 /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime
277 /// of the returned reference.
278 #[safety{ValidWrite(ptr, "some"), Alive(ptr, "\'a")}]
279 pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask_var_t) -> &'a mut Self {
280 // SAFETY: Guaranteed by the safety requirements of the function.
281 //
282 // INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the
283 // lifetime of the returned reference.
284 unsafe { &mut *ptr.cast() }
285 }
286
287 /// Creates a reference to an existing `struct cpumask_var_t` pointer.
288 ///
289 /// # Safety
290 ///
291 /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime
292 /// of the returned reference.
293 #[safety{ValidRead(ptr, "some"), Alive(ptr, "\'a")}]
294 pub unsafe fn from_raw<'a>(ptr: *const bindings::cpumask_var_t) -> &'a Self {
295 // SAFETY: Guaranteed by the safety requirements of the function.
296 //
297 // INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the
298 // lifetime of the returned reference.
299 unsafe { &*ptr.cast() }
300 }
301
302 /// Clones cpumask.
303 pub fn try_clone(cpumask: &Cpumask) -> Result<Self> {
304 // SAFETY: The returned cpumask_var is initialized right after this call.
305 let mut cpumask_var = unsafe { Self::new(GFP_KERNEL) }?;
306
307 cpumask.copy(&mut cpumask_var);
308 Ok(cpumask_var)
309 }
310}
311
312// Make [`CpumaskVar`] behave like a pointer to [`Cpumask`].
313impl Deref for CpumaskVar {
314 type Target = Cpumask;
315
316 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
317 fn deref(&self) -> &Self::Target {
318 // SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask.
319 unsafe { &*self.ptr.as_ptr() }
320 }
321
322 #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
323 fn deref(&self) -> &Self::Target {
324 &self.mask
325 }
326}
327
328impl DerefMut for CpumaskVar {
329 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
330 fn deref_mut(&mut self) -> &mut Cpumask {
331 // SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask.
332 unsafe { self.ptr.as_mut() }
333 }
334
335 #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
336 fn deref_mut(&mut self) -> &mut Cpumask {
337 &mut self.mask
338 }
339}
340
341impl Drop for CpumaskVar {
342 fn drop(&mut self) {
343 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
344 // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `free_cpumask_var`.
345 unsafe {
346 bindings::free_cpumask_var(self.as_raw())
347 };
348 }
349}