Skip to contentSkip to conversation

Rust: Add cpumask abstractions

PATCH Superseded Viresh Kumar 3 participants 18 messages Feb 25, 2025 – Feb 28, 2025

Subsystems (2)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Viresh Kumar

author maintainer
#0 lore raw

cover Rust: Add cpumask abstractions

Hello,

This series adds initial cpumask Rust abstractions and adds a new maintenance entry for the same.

This was earlier sent as part of a larger series [1] and it was suggested to send these separately.

Depends on: [2].

--
Viresh

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Viresh Kumar (2):
rust: Add initial cpumask abstractions
MAINTAINERS: Add entry for Rust bitmap API

 MAINTAINERS            |   6 ++
 rust/kernel/cpumask.rs | 168 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs     |   1 +
 3 files changed, 175 insertions(+)
 create mode 100644 rust/kernel/cpumask.rs
Signature · 1 line
2.31.1.272.g89b43f80a514
author maintainer
#1 lore raw

PATCH 1/2 rust: Add initial cpumask abstractions

Add initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed.

These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks.

---
 rust/kernel/cpumask.rs | 168 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs     |   1 +
 2 files changed, 169 insertions(+)
 create mode 100644 rust/kernel/cpumask.rs
rust/kernel/cpumask.rs new file +168 -0
new file mode 100644
index 000000000000..13864424420b
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! CPU mask abstractions.
+//!
+//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h)
+
+use crate::{bindings, error::Result, prelude::ENOMEM};
+
+#[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+use crate::prelude::{KBox, GFP_KERNEL};
+
+#[cfg(CONFIG_CPUMASK_OFFSTACK)]
+use core::ptr;
+
+/// A simple implementation of `struct cpumask` from the C code.
+pub struct Cpumask {
+    ptr: *mut bindings::cpumask,
+    owned: bool,
+}
+
+impl Cpumask {
+    /// Creates cpumask.
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    fn new_inner(empty: bool) -> Result<Self> {
+        let mut ptr: *mut bindings::cpumask = ptr::null_mut();
+
+        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
+        // is always safe to call this method.
+        if !unsafe {
+            if empty {
+                bindings::zalloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL)
+            } else {
+                bindings::alloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL)
+            }
+        } {
+            return Err(ENOMEM);
+        }
+
+        Ok(Self { ptr, owned: true })
+    }
+
+    /// Creates cpumask.
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    fn new_inner(empty: bool) -> Result<Self> {
+        let ptr = KBox::into_raw(KBox::new([bindings::cpumask::default(); 1], GFP_KERNEL)?);
+
+        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
+        // is always safe to call this method.
+        if !unsafe {
+            if empty {
+                bindings::zalloc_cpumask_var(ptr, bindings::GFP_KERNEL)
+            } else {
+                bindings::alloc_cpumask_var(ptr, bindings::GFP_KERNEL)
+            }
+        } {
+            return Err(ENOMEM);
+        }
+
+        Ok(Self {
+            ptr: ptr as *mut _,
+            owned: true,
+        })
+    }
+
+    /// Creates empty cpumask.
+    pub fn new() -> Result<Self> {
+        Self::new_inner(true)
+    }
+
+    /// Creates uninitialized cpumask.
+    fn new_uninit() -> Result<Self> {
+        Self::new_inner(false)
+    }
+
+    /// Clones cpumask.
+    pub fn try_clone(&self) -> Result<Self> {
+        let mut cpumask = Self::new_uninit()?;
+
+        self.copy(&mut cpumask);
+        Ok(cpumask)
+    }
+
+    /// Creates a new abstraction instance of an existing `struct cpumask` pointer.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that `ptr` is valid, and non-null.
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    pub unsafe fn get_cpumask(ptr: &mut *mut bindings::cpumask) -> Self {
+        Self {
+            ptr: *ptr,
+            owned: false,
+        }
+    }
+
+    /// Creates a new abstraction instance of an existing `struct cpumask` pointer.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that `ptr` is valid, and non-null.
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    pub unsafe fn get_cpumask(ptr: &mut bindings::cpumask_var_t) -> Self {
+        Self {
+            ptr: ptr as *mut _,
+            owned: false,
+        }
+    }
+
+    /// Obtain the raw `struct cpumask *`.
+    pub fn as_raw(&mut self) -> *mut bindings::cpumask {
+        self.ptr
+    }
+
+    /// Sets CPU in the cpumask.
+    ///
+    /// Update the cpumask with a single CPU.
+    pub fn set(&mut self, cpu: u32) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_set_cpus()` for any CPU.
+        unsafe { bindings::cpumask_set_cpu(cpu, self.ptr) };
+    }
+
+    /// Clears CPU in the cpumask.
+    ///
+    /// Update the cpumask with a single CPU.
+    pub fn clear(&mut self, cpu: i32) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_clear_cpu()` for any CPU.
+        unsafe { bindings::cpumask_clear_cpu(cpu, self.ptr) };
+    }
+
+    /// Sets all CPUs in the cpumask.
+    pub fn set_all(&mut self) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_setall()`.
+        unsafe { bindings::cpumask_setall(self.ptr) };
+    }
+
+    /// Gets weight of a cpumask.
+    pub fn weight(&self) -> u32 {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_weight()`.
+        unsafe { bindings::cpumask_weight(self.ptr) }
+    }
+
+    /// Copies cpumask.
+    pub fn copy(&self, dstp: &mut Self) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_copy()`.
+        unsafe { bindings::cpumask_copy(dstp.as_raw(), self.ptr) };
+    }
+}
+
+impl Drop for Cpumask {
+    fn drop(&mut self) {
+        if self.owned {
+            // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe
+            // to call `free_cpumask_var()`.
+            unsafe { bindings::free_cpumask_var(self.ptr) }
+
+            #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
+            unsafe {
+                drop(KBox::from_raw(self.ptr))
+            };
+        }
+    }
+}
rust/kernel/lib.rs +1 -0
index 496ed32b0911..efbd7be98dab 100644
@@ -40,6 +40,7 @@
 pub mod block;
 #[doc(hidden)]
 pub mod build_assert;
+pub mod cpumask;
 pub mod cred;
 pub mod device;
 pub mod device_id;
Signature · 1 line
2.31.1.272.g89b43f80a514
author maintainer
#16 lore raw

PATCH 2/2 MAINTAINERS: Add entry for Rust bitmap API

In reply to Viresh Kumar

Update the MAINTAINERS file to include the Rust abstractions for bitmap API.

Yury has indicated that he does not wish to maintain the Rust code but would like to be listed as a reviewer.

---
 MAINTAINERS | 6 ++++++
 1 file changed, 6 insertions(+)
MAINTAINERS +6 -0
index ec2428b82103..17e98d757b9b 100644
@@ -4034,6 +4034,12 @@ M:	Yury Norov <[email protected]>
 S:	Maintained
 F:	rust/helpers/cpumask.c
 
+BITMAP API [RUST]
+M:	Viresh Kumar <[email protected]> (cpumask)
+R:	Yury Norov <[email protected]>
+S:	Maintained
+F:	rust/kernel/cpumask.rs
+
 BITOPS API
 M:	Yury Norov <[email protected]>
 R:	Rasmus Villemoes <[email protected]>
Signature · 1 line
2.31.1.272.g89b43f80a514
reviewer
#2 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

In reply to Viresh Kumar
Quoted 55 lines · Viresh Kumar

Add initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed.

These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks.

---
 rust/kernel/cpumask.rs | 168 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs     |   1 +
 2 files changed, 169 insertions(+)
 create mode 100644 rust/kernel/cpumask.rs
rust/kernel/cpumask.rs new file +35 -0
new file mode 100644
index 000000000000..13864424420b
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! CPU mask abstractions.
+//!
+//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h)
+
+use crate::{bindings, error::Result, prelude::ENOMEM};
+
+#[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+use crate::prelude::{KBox, GFP_KERNEL};
+
+#[cfg(CONFIG_CPUMASK_OFFSTACK)]
+use core::ptr;
+
+/// A simple implementation of `struct cpumask` from the C code.
+pub struct Cpumask {
+    ptr: *mut bindings::cpumask,
+    owned: bool,
+}
+
+impl Cpumask {
+    /// Creates cpumask.
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    fn new_inner(empty: bool) -> Result<Self> {
+        let mut ptr: *mut bindings::cpumask = ptr::null_mut();
+
+        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
+        // is always safe to call this method.
+        if !unsafe {
+            if empty {
+                bindings::zalloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL)
+            } else {
+                bindings::alloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL)
+            }
+        } {

rust/kernel/cpumask.rs line 45

Quoted 10 lines
rust/kernel/cpumask.rs new file +10 -0
+            return Err(ENOMEM);
+        }
+
+        Ok(Self { ptr, owned: true })
+    }
+
+    /// Creates cpumask.
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    fn new_inner(empty: bool) -> Result<Self> {
+        let ptr = KBox::into_raw(KBox::new([bindings::cpumask::default(); 1], GFP_KERNEL)?);

I don't really understand this CPUMASK_OFFSTACK logic. You seem to always allocate memory, but if OFFSTACK=n, then shouldn't it be on the stack ...?

Quoted 36 lines
rust/kernel/cpumask.rs new file +36 -0
+        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
+        // is always safe to call this method.
+        if !unsafe {
+            if empty {
+                bindings::zalloc_cpumask_var(ptr, bindings::GFP_KERNEL)
+            } else {
+                bindings::alloc_cpumask_var(ptr, bindings::GFP_KERNEL)
+            }
+        } {
+            return Err(ENOMEM);
+        }
+
+        Ok(Self {
+            ptr: ptr as *mut _,
+            owned: true,
+        })
+    }
+
+    /// Creates empty cpumask.
+    pub fn new() -> Result<Self> {
+        Self::new_inner(true)
+    }
+
+    /// Creates uninitialized cpumask.
+    fn new_uninit() -> Result<Self> {
+        Self::new_inner(false)
+    }
+
+    /// Clones cpumask.
+    pub fn try_clone(&self) -> Result<Self> {
+        let mut cpumask = Self::new_uninit()?;
+
+        self.copy(&mut cpumask);
+        Ok(cpumask)
+    }
+

rust/kernel/cpumask.rs line 92

Quoted 10 lines
rust/kernel/cpumask.rs new file +10 -0
+    /// Creates a new abstraction instance of an existing `struct cpumask` pointer.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that `ptr` is valid, and non-null.
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    pub unsafe fn get_cpumask(ptr: &mut *mut bindings::cpumask) -> Self {
+        Self {
+            ptr: *ptr,
+            owned: false,

Using an owned variable in this way isn't great, IMO. We should use two different types such as Owned<CpuMask> and &CpuMask to represent owned vs borrowed instead.

Quoted 57 lines
rust/kernel/cpumask.rs new file +57 -0
+        }
+    }
+
+    /// Creates a new abstraction instance of an existing `struct cpumask` pointer.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that `ptr` is valid, and non-null.
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    pub unsafe fn get_cpumask(ptr: &mut bindings::cpumask_var_t) -> Self {
+        Self {
+            ptr: ptr as *mut _,
+            owned: false,
+        }
+    }
+
+    /// Obtain the raw `struct cpumask *`.
+    pub fn as_raw(&mut self) -> *mut bindings::cpumask {
+        self.ptr
+    }
+
+    /// Sets CPU in the cpumask.
+    ///
+    /// Update the cpumask with a single CPU.
+    pub fn set(&mut self, cpu: u32) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_set_cpus()` for any CPU.
+        unsafe { bindings::cpumask_set_cpu(cpu, self.ptr) };
+    }
+
+    /// Clears CPU in the cpumask.
+    ///
+    /// Update the cpumask with a single CPU.
+    pub fn clear(&mut self, cpu: i32) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_clear_cpu()` for any CPU.
+        unsafe { bindings::cpumask_clear_cpu(cpu, self.ptr) };
+    }
+
+    /// Sets all CPUs in the cpumask.
+    pub fn set_all(&mut self) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_setall()`.
+        unsafe { bindings::cpumask_setall(self.ptr) };
+    }
+
+    /// Gets weight of a cpumask.
+    pub fn weight(&self) -> u32 {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_weight()`.
+        unsafe { bindings::cpumask_weight(self.ptr) }
+    }
+
+    /// Copies cpumask.
+    pub fn copy(&self, dstp: &mut Self) {
+        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // call `cpumask_copy()`.

rust/kernel/cpumask.rs line 159

Quoted 10 lines
rust/kernel/cpumask.rs new file +10 -0
+        unsafe { bindings::cpumask_copy(dstp.as_raw(), self.ptr) };
+    }
+}
+
+impl Drop for Cpumask {
+    fn drop(&mut self) {
+        if self.owned {
+            // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe
+            // to call `free_cpumask_var()`.
+            unsafe { bindings::free_cpumask_var(self.ptr) }

This is missing a semicolon, but it's not the last statement in the block. Did you compile this with CPUMASK_OFFSTACK=n? I don't think it compiles with that setting.

rust/kernel/cpumask.rs line 165

Quoted 5 lines
rust/kernel/cpumask.rs new file +5 -0
+            #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
+            unsafe {
+                drop(KBox::from_raw(self.ptr))
+            };

This looks like you did not run rustfmt.

Alice

author maintainer
#3 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 11 lines · Alice Ryhl

rust/kernel/cpumask.rs line 159

Quoted 6 lines · Viresh Kumar
rust/kernel/cpumask.rs new file +6 -0
+impl Drop for Cpumask {
+    fn drop(&mut self) {
+        if self.owned {
+            // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe
+            // to call `free_cpumask_var()`.
+            unsafe { bindings::free_cpumask_var(self.ptr) }

This is missing a semicolon, but it's not the last statement in the block. Did you compile this with CPUMASK_OFFSTACK=n? I don't think it compiles with that setting.

I would always add a semicolon here, yeah I missed adding that but ..

I have missed minor things before sending a series a few times in the past and this one really scared me thinking here I did it again :)

Though I was sure that I have built the code with both CPUMASK_OFFSTACK=y and =n, I performed the builds again and it worked (again). That confused me even more :)

And here is what I think is happening here (which makes it build fine accidentally):
- free_cpumask_var() has a return type of void.
- The block {} allows it to build fine without a semicolon here.
- I performed a simple test for this [1] and it works too.

Quoted 7 lines

rust/kernel/cpumask.rs line 165

Quoted 5 lines
rust/kernel/cpumask.rs new file +5 -0
+            #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
+            unsafe {
+                drop(KBox::from_raw(self.ptr))
+            };

This looks like you did not run rustfmt.

I did this:

make CLIPPY=1 rustfmtcheck ARCH=arm64 O=../barm64t/ -j8 CROSS_COMPILE=aarch64-linux-gnu- CONFIG_DEBUG_SECTION_MISMATCH=y

I hope that is all I need ? I checked again with both CONFIG options, doesn't complain with rustc 1.84.1.

Signature · 3 lines
viresh

[1] https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=70cd7d31633d98774a088fed68ebb00d
reviewer
#4 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 23 lines · Viresh Kumar
Quoted 11 lines · Alice Ryhl

rust/kernel/cpumask.rs line 159

Quoted 6 lines · Viresh Kumar
rust/kernel/cpumask.rs new file +6 -0
+impl Drop for Cpumask {
+    fn drop(&mut self) {
+        if self.owned {
+            // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe
+            // to call `free_cpumask_var()`.
+            unsafe { bindings::free_cpumask_var(self.ptr) }

This is missing a semicolon, but it's not the last statement in the block. Did you compile this with CPUMASK_OFFSTACK=n? I don't think it compiles with that setting.

I would always add a semicolon here, yeah I missed adding that but ..

I have missed minor things before sending a series a few times in the past and this one really scared me thinking here I did it again :)

Though I was sure that I have built the code with both CPUMASK_OFFSTACK=y and =n, I performed the builds again and it worked (again). That confused me even more :)

Quoted 5 lines

And here is what I think is happening here (which makes it build fine accidentally):
- free_cpumask_var() has a return type of void.
- The block {} allows it to build fine without a semicolon here.
- I performed a simple test for this [1] and it works too.

Ah, you are right, the block makes it work in this particular case.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
rust/kernel/cpumask.rs new file +5 -0
+            #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
+            unsafe {
+                drop(KBox::from_raw(self.ptr))
+            };
Quoted 8 lines
Quoted 1 line

This looks like you did not run rustfmt.

I did this:

make CLIPPY=1 rustfmtcheck ARCH=arm64 O=../barm64t/ -j8 CROSS_COMPILE=aarch64-linux-gnu- CONFIG_DEBUG_SECTION_MISMATCH=y

I hope that is all I need ? I checked again with both CONFIG options, doesn't complain with rustc 1.84.1.

Hmm, ok. I would have expected it to format on one line:
unsafe { drop(KBox::from_raw(self.ptr)) };

That is what normally happens when the semi-colon is outside the block. Not sure why it did not happen in this case.

Alice

author maintainer
#5 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 2 lines · Alice Ryhl

Hmm, ok. I would have expected it to format on one line:
unsafe { drop(KBox::from_raw(self.ptr)) };

I did try this earlier and rustfmt suggested to format it the way I have done it currently :)

Quoted 2 lines

That is what normally happens when the semi-colon is outside the block. Not sure why it did not happen in this case.

Signature · 1 line
viresh
reviewer
#6 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 10 lines · Viresh Kumar
Quoted 2 lines · Alice Ryhl

Hmm, ok. I would have expected it to format on one line:
unsafe { drop(KBox::from_raw(self.ptr)) };

I did try this earlier and rustfmt suggested to format it the way I have done it currently :)

Quoted 2 lines

That is what normally happens when the semi-colon is outside the block. Not sure why it did not happen in this case.

Very weird. I'd guess that the #[cfg] is at fault.

Alice

author maintainer
#8 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

In reply to Alice Ryhl
Quoted 9 lines · Alice Ryhl

rust/kernel/cpumask.rs line 45

Quoted 4 lines · Viresh Kumar
rust/kernel/cpumask.rs new file +4 -0
+    /// Creates cpumask.
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    fn new_inner(empty: bool) -> Result<Self> {
+        let ptr = KBox::into_raw(KBox::new([bindings::cpumask::default(); 1], GFP_KERNEL)?);

I don't really understand this CPUMASK_OFFSTACK logic. You seem to always allocate memory, but if OFFSTACK=n, then shouldn't it be on the stack ...?

IIUC, the idea of the config option is to prevent stack overflow on systems with high number of CPUs (> 256), in which case the memory for the masks is allocated dynamically. Otherwise a local variable, in a function or a struct (which may itself get allocated dynamically) is fine.

In the CONFIG_CPUMASK_OFFSTACK=y case, the cpumask C core does the allocation and the Rust code doesn't need to take care of the same.

In the CONFIG_CPUMASK_OFFSTACK=n case, the allocation must be done by the caller (on stack or heap) and the cpumask C core will only clear the mask.

I tried with an on-stack variable earlier but ran into problems as the memory is shared with the C FFI and Rust moves it unless it is pinned.

One easy way to make it work was using Box, which keeps the code simple.

Should I do it differently ?

Signature · 1 line
viresh
author maintainer
#7 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

In reply to Alice Ryhl
Quoted 6 lines · Alice Ryhl
Quoted 5 lines · Viresh Kumar
Quoted 2 lines · Alice Ryhl

Hmm, ok. I would have expected it to format on one line:
unsafe { drop(KBox::from_raw(self.ptr)) };

Quoted 7 lines
Quoted 5 lines

I did try this earlier and rustfmt suggested to format it the way I have done it currently :)

Quoted 2 lines

That is what normally happens when the semi-colon is outside the block. Not sure why it did not happen in this case.

Very weird. I'd guess that the #[cfg] is at fault.

Dropping #[cfg] does make it complain with current code and suggests to format on one line.

Signature · 1 line
viresh
reviewer
#9 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

In reply to Viresh Kumar
Quoted 21 lines · Viresh Kumar
Quoted 9 lines · Alice Ryhl

rust/kernel/cpumask.rs line 45

Quoted 4 lines · Viresh Kumar
rust/kernel/cpumask.rs new file +4 -0
+    /// Creates cpumask.
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    fn new_inner(empty: bool) -> Result<Self> {
+        let ptr = KBox::into_raw(KBox::new([bindings::cpumask::default(); 1], GFP_KERNEL)?);

I don't really understand this CPUMASK_OFFSTACK logic. You seem to always allocate memory, but if OFFSTACK=n, then shouldn't it be on the stack ...?

IIUC, the idea of the config option is to prevent stack overflow on systems with high number of CPUs (> 256), in which case the memory for the masks is allocated dynamically. Otherwise a local variable, in a function or a struct (which may itself get allocated dynamically) is fine.

In the CONFIG_CPUMASK_OFFSTACK=y case, the cpumask C core does the allocation and the Rust code doesn't need to take care of the same.

Quoted 6 lines

In the CONFIG_CPUMASK_OFFSTACK=n case, the allocation must be done by the caller (on stack or heap) and the cpumask C core will only clear the mask.

I tried with an on-stack variable earlier but ran into problems as the memory is shared with the C FFI and Rust moves it unless it is pinned.

Is it a problem if a value of type struct cpumask is moved? It looks like it is just an array of longs?

Alice

author maintainer
#10 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 2 lines · Alice Ryhl

Is it a problem if a value of type struct cpumask is moved? It looks like it is just an array of longs?

With the current code, if I replace the Box with an on-stack variable, the kernel crashes.

In my usecase, the pointer to the cpumask array is sent to the OPP core, which may update the content, though it doesn't save the pointer.

But for another usecase, the C code may end up saving the pointer.

--
Viresh

reviewer
#11 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 6 lines · Viresh Kumar
Quoted 2 lines · Alice Ryhl

Is it a problem if a value of type struct cpumask is moved? It looks like it is just an array of longs?

Quoted 7 lines

With the current code, if I replace the Box with an on-stack variable, the kernel crashes.

In my usecase, the pointer to the cpumask array is sent to the OPP core, which may update the content, though it doesn't save the pointer.

But for another usecase, the C code may end up saving the pointer.

I don't think that case applies here. Variables that could be stashed like that need a destructor that removes the pointer from the relevant C structures. This is because pinning only prevents the owner from moving the variable - it doesn't prevent the owner from destroying it.

Alice

reviewer
#12 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 14 lines · Alice Ryhl
Quoted 12 lines · Viresh Kumar
Quoted 2 lines · Alice Ryhl

Is it a problem if a value of type struct cpumask is moved? It looks like it is just an array of longs?

With the current code, if I replace the Box with an on-stack variable, the kernel crashes.

In my usecase, the pointer to the cpumask array is sent to the OPP core, which may update the content, though it doesn't save the pointer.

Quoted 6 lines
Quoted 1 line

But for another usecase, the C code may end up saving the pointer.

I don't think that case applies here. Variables that could be stashed like that need a destructor that removes the pointer from the relevant C structures. This is because pinning only prevents the owner from moving the variable - it doesn't prevent the owner from destroying it.

I believe you can implement the offstack stuff like this. The idea is to have one type that corresponds to struct cpumask and another type that corresponds to cpumask_var_t on the C side. Only the latter type would need to do anything wrt. the CPUMASK_OFFSTACK setting.

rust/kernel/cpumask.rs +69 -104
index 13864424420b..f82dafbc4e61 100644
@@ -4,111 +4,45 @@
 //!
 //! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h)
 
-use crate::{bindings, error::Result, prelude::ENOMEM};
-
-#[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
-use crate::prelude::{KBox, GFP_KERNEL};
-
+use crate::{
+    alloc::{AllocError, Flags},
+    bindings,
+    prelude::*,
+    types::Opaque,
+};
 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
-use core::ptr;
+use core::ptr::{self, NonNull};
 
-/// A simple implementation of `struct cpumask` from the C code.
+/// This corresponds to the C type `struct cpumask`.
+#[repr(transparent)]
 pub struct Cpumask {
-    ptr: *mut bindings::cpumask,
-    owned: bool,
+    mask: Opaque<bindings::cpumask>,
 }
 
 impl Cpumask {
-    /// Creates cpumask.
-    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
-    fn new_inner(empty: bool) -> Result<Self> {
-        let mut ptr: *mut bindings::cpumask = ptr::null_mut();
-
-        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
-        // is always safe to call this method.
-        if !unsafe {
-            if empty {
-                bindings::zalloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL)
-            } else {
-                bindings::alloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL)
-            }
-        } {
-            return Err(ENOMEM);
-        }
-
-        Ok(Self { ptr, owned: true })
-    }
-
-    /// Creates cpumask.
-    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
-    fn new_inner(empty: bool) -> Result<Self> {
-        let ptr = KBox::into_raw(KBox::new([bindings::cpumask::default(); 1], GFP_KERNEL)?);
-
-        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
-        // is always safe to call this method.
-        if !unsafe {
-            if empty {
-                bindings::zalloc_cpumask_var(ptr, bindings::GFP_KERNEL)
-            } else {
-                bindings::alloc_cpumask_var(ptr, bindings::GFP_KERNEL)
-            }
-        } {
-            return Err(ENOMEM);
-        }
-
-        Ok(Self {
-            ptr: ptr as *mut _,
-            owned: true,
-        })
-    }
-
-    /// Creates empty cpumask.
-    pub fn new() -> Result<Self> {
-        Self::new_inner(true)
-    }
-
-    /// Creates uninitialized cpumask.
-    fn new_uninit() -> Result<Self> {
-        Self::new_inner(false)
-    }
-
-    /// Clones cpumask.
-    pub fn try_clone(&self) -> Result<Self> {
-        let mut cpumask = Self::new_uninit()?;
-
-        self.copy(&mut cpumask);
-        Ok(cpumask)
-    }
-
-    /// Creates a new abstraction instance of an existing `struct cpumask` pointer.
+    /// Creates a reference to an existing `struct cpumask` pointer.
     ///
     /// # Safety
     ///
-    /// Callers must ensure that `ptr` is valid, and non-null.
-    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
-    pub unsafe fn get_cpumask(ptr: &mut *mut bindings::cpumask) -> Self {
-        Self {
-            ptr: *ptr,
-            owned: false,
-        }
+    /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime
+    /// of the returned reference.
+    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self {
+        unsafe { &mut *ptr.cast() }
     }
 
-    /// Creates a new abstraction instance of an existing `struct cpumask` pointer.
+    /// Creates a reference to an existing `struct cpumask` pointer.
     ///
     /// # Safety
     ///
-    /// Callers must ensure that `ptr` is valid, and non-null.
-    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
-    pub unsafe fn get_cpumask(ptr: &mut bindings::cpumask_var_t) -> Self {
-        Self {
-            ptr: ptr as *mut _,
-            owned: false,
-        }
+    /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime
+    /// of the returned reference.
+    pub unsafe fn from_raw<'a>(ptr: *const bindings::cpumask) -> &'a Self {
+        unsafe { &*ptr.cast() }
     }
 
     /// Obtain the raw `struct cpumask *`.
-    pub fn as_raw(&mut self) -> *mut bindings::cpumask {
-        self.ptr
+    pub fn as_raw(&self) -> *mut bindings::cpumask {
+        self as *const Cpumask as *mut bindings::cpumask
     }
 
     /// Sets CPU in the cpumask.
@@ -117,7 +51,7 @@ pub fn as_raw(&mut self) -> *mut bindings::cpumask {
     pub fn set(&mut self, cpu: u32) {
         // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_set_cpus()` for any CPU.
-        unsafe { bindings::cpumask_set_cpu(cpu, self.ptr) };
+        unsafe { bindings::cpumask_set_cpu(cpu, self.as_raw()) };
     }
 
     /// Clears CPU in the cpumask.
@@ -126,43 +60,74 @@ pub fn set(&mut self, cpu: u32) {
     pub fn clear(&mut self, cpu: i32) {
         // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_clear_cpu()` for any CPU.
-        unsafe { bindings::cpumask_clear_cpu(cpu, self.ptr) };
+        unsafe { bindings::cpumask_clear_cpu(cpu, self.as_raw()) };
     }
 
     /// Sets all CPUs in the cpumask.
     pub fn set_all(&mut self) {
         // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_setall()`.
-        unsafe { bindings::cpumask_setall(self.ptr) };
+        unsafe { bindings::cpumask_setall(self.as_raw()) };
     }
 
     /// Gets weight of a cpumask.
     pub fn weight(&self) -> u32 {
         // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_weight()`.
-        unsafe { bindings::cpumask_weight(self.ptr) }
+        unsafe { bindings::cpumask_weight(self.as_raw()) }
     }
 
     /// Copies cpumask.
     pub fn copy(&self, dstp: &mut Self) {
         // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_copy()`.
-        unsafe { bindings::cpumask_copy(dstp.as_raw(), self.ptr) };
+        unsafe { bindings::cpumask_copy(dstp.as_raw(), self.as_raw()) };
     }
 }
 
-impl Drop for Cpumask {
-    fn drop(&mut self) {
-        if self.owned {
-            // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe
-            // to call `free_cpumask_var()`.
-            unsafe { bindings::free_cpumask_var(self.ptr) }
+/// This corresponds to the C type alias `cpumask_var_t`.
+pub struct CpumaskBox {
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    ptr: NonNull<Cpumask>,
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    mask: Cpumask,
+}
 
+impl CpumaskBox {
+    pub fn new(_flags: Flags) -> Result<Self, AllocError> {
+        Ok(Self {
+            #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+            ptr: {
+                let mut ptr: *mut bindings::cpumask = ptr::null_mut();
+                unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_raw()) };
+                NonNull::new(ptr.cast()).ok_or(AllocError)?
+            },
             #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
-            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
-            unsafe {
-                drop(KBox::from_raw(self.ptr))
-            };
-        }
+            mask: unsafe { core::mem::zeroed() },
+        })
+    }
+}
+
+// Make CpumaskBox behave like a pointer to Cpumask.
+impl core::ops::Deref for CpumaskBox {
+    type Target = Cpumask;
+
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    fn deref(&self) -> &Cpumask {
+        unsafe { &*self.ptr.as_ptr() }
+    }
+
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    fn deref(&self) -> &Cpumask {
+        &self.mask
+    }
+}
+
+impl Drop for CpumaskBox {
+    fn drop(&mut self) {
+        #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+        unsafe {
+            bindings::free_cpumask_var(self.as_raw())
+        };
     }
 }
reviewer Reviewed-by on v1 2/2
#17 lore raw

Re: [PATCH 2/2] MAINTAINERS: Add entry for Rust bitmap API

In reply to Viresh Kumar
Quoted 7 lines · Viresh Kumar

Update the MAINTAINERS file to include the Rust abstractions for bitmap API.

Yury has indicated that he does not wish to maintain the Rust code but would like to be listed as a reviewer.

Quoted 23 lines
---
 MAINTAINERS | 6 ++++++
 1 file changed, 6 insertions(+)
MAINTAINERS +6 -0
index ec2428b82103..17e98d757b9b 100644
@@ -4034,6 +4034,12 @@ M:	Yury Norov <[email protected]>
 S:	Maintained
 F:	rust/helpers/cpumask.c
 
+BITMAP API [RUST]
+M:	Viresh Kumar <[email protected]> (cpumask)
+R:	Yury Norov <[email protected]>
+S:	Maintained
+F:	rust/kernel/cpumask.rs
+
 BITOPS API
 M:	Yury Norov <[email protected]>
 R:	Rasmus Villemoes <[email protected]>
Signature · 1 line
2.31.1.272.g89b43f80a514
author maintainer
#13 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

In reply to Alice Ryhl
Quoted 15 lines · Alice Ryhl
rust/kernel/cpumask.rs +13 -0
+/// This corresponds to the C type alias `cpumask_var_t`.
+pub struct CpumaskBox {
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    ptr: NonNull<Cpumask>,
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    mask: Cpumask,
+}
 
+impl CpumaskBox {
+    pub fn new(_flags: Flags) -> Result<Self, AllocError> {
+        Ok(Self {
+            #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+            ptr: {
+                let mut ptr: *mut bindings::cpumask = ptr::null_mut();

rust/kernel/cpumask.rs

Quoted 10 lines
rust/kernel/cpumask.rs +4 -5
+                unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_raw()) };
+                NonNull::new(ptr.cast()).ok_or(AllocError)?
+            },
             #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
-            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
-            unsafe {
-                drop(KBox::from_raw(self.ptr))
-            };
-        }
+            mask: unsafe { core::mem::zeroed() },

This will work correctly, yes, but I wasn't sure if the Rust code should do this or depend on the C API and call zalloc_cpumask_var(). The implementation of struct cpumask allows this to work right now, but any change where some internal state management is done, for example, within the structure may break the Rust side.

I am okay with this way of doing it if that looks okay to you.

I have made following changes over your diff.

Thanks for your help in simplifying the code.

Signature · 3 lines
viresh

-------------------------8<-------------------------
rust/kernel/cpumask.rs +81 -19
index f82dafbc4e61..d56f7dc9d762 100644
@@ -13,20 +13,28 @@
 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
 use core::ptr::{self, NonNull};
 
+#[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+use core::mem::MaybeUninit;
+
+use core::ops::{Deref, DerefMut};
+
 /// This corresponds to the C type `struct cpumask`.
 #[repr(transparent)]
-pub struct Cpumask {
-    mask: Opaque<bindings::cpumask>,
-}
+pub struct Cpumask(Opaque<bindings::cpumask>);
 
 impl Cpumask {
-    /// Creates a reference to an existing `struct cpumask` pointer.
+    /// Creates a mutable reference to an existing `struct cpumask` pointer.
     ///
     /// # Safety
     ///
     /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime
     /// of the returned reference.
-    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self {
+    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask_var_t) -> &'a mut Self {
+        // For this configuration, `cpumask_var_t` is defined as `[cpumask; 1]`.
+        #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+        let ptr: *mut bindings::cpumask = ptr as *mut _;
+
+        // SAFETY: Guaranteed by the safety requirements of the function.
         unsafe { &mut *ptr.cast() }
     }
 
@@ -36,7 +44,12 @@ pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self {
     ///
     /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime
     /// of the returned reference.
-    pub unsafe fn from_raw<'a>(ptr: *const bindings::cpumask) -> &'a Self {
+    pub unsafe fn from_raw<'a>(ptr: *const bindings::cpumask_var_t) -> &'a Self {
+        // For this configuration, `cpumask_var_t` is defined as `[cpumask; 1]`.
+        #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+        let ptr: *const bindings::cpumask = ptr as *const _;
+
+        // SAFETY: Guaranteed by the safety requirements of the function.
         unsafe { &*ptr.cast() }
     }
 
@@ -45,41 +58,37 @@ pub fn as_raw(&self) -> *mut bindings::cpumask {
         self as *const Cpumask as *mut bindings::cpumask
     }
 
-    /// Sets CPU in the cpumask.
-    ///
-    /// Update the cpumask with a single CPU.
+    /// Sets `cpu` in the cpumask.
     pub fn set(&mut self, cpu: u32) {
-        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // SAFETY: `mask` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_set_cpus()` for any CPU.
         unsafe { bindings::cpumask_set_cpu(cpu, self.as_raw()) };
     }
 
-    /// Clears CPU in the cpumask.
-    ///
-    /// Update the cpumask with a single CPU.
+    /// Clears `cpu` in the cpumask.
     pub fn clear(&mut self, cpu: i32) {
-        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // SAFETY: `mask` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_clear_cpu()` for any CPU.
         unsafe { bindings::cpumask_clear_cpu(cpu, self.as_raw()) };
     }
 
     /// Sets all CPUs in the cpumask.
     pub fn set_all(&mut self) {
-        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // SAFETY: `mask` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_setall()`.
         unsafe { bindings::cpumask_setall(self.as_raw()) };
     }
 
-    /// Gets weight of a cpumask.
+    /// Gets weight of the cpumask.
     pub fn weight(&self) -> u32 {
-        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // SAFETY: `mask` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_weight()`.
         unsafe { bindings::cpumask_weight(self.as_raw()) }
     }
 
     /// Copies cpumask.
     pub fn copy(&self, dstp: &mut Self) {
-        // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to
+        // SAFETY: `mask` is guaranteed to be valid for the lifetime of `self`. And it is safe to
         // call `cpumask_copy()`.
         unsafe { bindings::cpumask_copy(dstp.as_raw(), self.as_raw()) };
     }
@@ -94,26 +103,65 @@ pub struct CpumaskBox {
 }
 
 impl CpumaskBox {
+    /// Creates an initialized instance of the `CpumaskBox`.
     pub fn new(_flags: Flags) -> Result<Self, AllocError> {
         Ok(Self {
             #[cfg(CONFIG_CPUMASK_OFFSTACK)]
             ptr: {
                 let mut ptr: *mut bindings::cpumask = ptr::null_mut();
+
+                // SAFETY: Depending on the value of `_flags`, this call may sleep. Other than
+                // that, it is always safe to call this method.
                 unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_raw()) };
                 NonNull::new(ptr.cast()).ok_or(AllocError)?
             },
+
             #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+            // SAFETY: FFI type is valid to be zero-initialized.
             mask: unsafe { core::mem::zeroed() },
         })
     }
+
+    /// Creates an uninitialized instance of the `CpumaskBox`.
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that the returned `CpumaskBox` is properly initialized before
+    /// getting used.
+    unsafe fn new_uninit(_flags: Flags) -> Result<Self, AllocError> {
+        Ok(Self {
+            #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+            ptr: {
+                let mut ptr: *mut bindings::cpumask = ptr::null_mut();
+
+                // SAFETY: Depending on the value of `_flags`, this call may sleep. Other than
+                // that, it is always safe to call this method.
+                unsafe { bindings::alloc_cpumask_var(&mut ptr, _flags.as_raw()) };
+                NonNull::new(ptr.cast()).ok_or(AllocError)?
+            },
+            #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+            // SAFETY: Guaranteed by the safety requirements of the function.
+            mask: unsafe { MaybeUninit::uninit().assume_init() },
+        })
+    }
+
+    /// Clones cpumask.
+    pub fn try_clone(cpumask: &Cpumask) -> Result<Self> {
+        // SAFETY: The returned cpumask_box is initialized right after this call.
+        let mut cpumask_box = unsafe { Self::new_uninit(GFP_KERNEL) }?;
+
+        cpumask.copy(&mut cpumask_box);
+        Ok(cpumask_box)
+    }
 }
 
 // Make CpumaskBox behave like a pointer to Cpumask.
-impl core::ops::Deref for CpumaskBox {
+impl Deref for CpumaskBox {
     type Target = Cpumask;
 
     #[cfg(CONFIG_CPUMASK_OFFSTACK)]
     fn deref(&self) -> &Cpumask {
+        // SAFETY: The caller owns CpumaskBox, so it is safe to deref the cpumask.
         unsafe { &*self.ptr.as_ptr() }
     }
 
@@ -123,9 +171,23 @@ fn deref(&self) -> &Cpumask {
     }
 }
 
+impl DerefMut for CpumaskBox {
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    fn deref_mut(&mut self) -> &mut Cpumask {
+        // SAFETY: The caller owns CpumaskBox, so it is safe to deref the cpumask.
+        unsafe { self.ptr.as_mut() }
+    }
+
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    fn deref_mut(&mut self) -> &mut Cpumask {
+        &mut self.mask
+    }
+}
+
 impl Drop for CpumaskBox {
     fn drop(&mut self) {
         #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+        // SAFETY: It is safe to free the cpumask.
         unsafe {
             bindings::free_cpumask_var(self.as_raw())
         };
reviewer
#14 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 65 lines · Viresh Kumar
Quoted 15 lines · Alice Ryhl
rust/kernel/cpumask.rs +13 -0
+/// This corresponds to the C type alias `cpumask_var_t`.
+pub struct CpumaskBox {
+    #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+    ptr: NonNull<Cpumask>,
+    #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+    mask: Cpumask,
+}
 
+impl CpumaskBox {
+    pub fn new(_flags: Flags) -> Result<Self, AllocError> {
+        Ok(Self {
+            #[cfg(CONFIG_CPUMASK_OFFSTACK)]
+            ptr: {
+                let mut ptr: *mut bindings::cpumask = ptr::null_mut();

rust/kernel/cpumask.rs

Quoted 10 lines
rust/kernel/cpumask.rs +4 -5
+                unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_raw()) };
+                NonNull::new(ptr.cast()).ok_or(AllocError)?
+            },
             #[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
-            // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`.
-            unsafe {
-                drop(KBox::from_raw(self.ptr))
-            };
-        }
+            mask: unsafe { core::mem::zeroed() },

This will work correctly, yes, but I wasn't sure if the Rust code should do this or depend on the C API and call zalloc_cpumask_var(). The implementation of struct cpumask allows this to work right now, but any change where some internal state management is done, for example, within the structure may break the Rust side.

I am okay with this way of doing it if that looks okay to you.

I have made following changes over your diff.

Thanks for your help in simplifying the code.

--
viresh

-------------------------8<-------------------------

rust/kernel/cpumask.rs +6 -3
index f82dafbc4e61..d56f7dc9d762 100644
@@ -13,20 +13,28 @@
 #[cfg(CONFIG_CPUMASK_OFFSTACK)]
 use core::ptr::{self, NonNull};
 
+#[cfg(not(CONFIG_CPUMASK_OFFSTACK))]
+use core::mem::MaybeUninit;
+
+use core::ops::{Deref, DerefMut};
+
 /// This corresponds to the C type `struct cpumask`.
 #[repr(transparent)]
-pub struct Cpumask {
-    mask: Opaque<bindings::cpumask>,
-}
+pub struct Cpumask(Opaque<bindings::cpumask>);
 

rust/kernel/cpumask.rs line 32

Quoted 10 lines
rust/kernel/cpumask.rs +2 -2
 impl Cpumask {
-    /// Creates a reference to an existing `struct cpumask` pointer.
+    /// Creates a mutable reference to an existing `struct cpumask` pointer.
     ///
     /// # Safety
     ///
     /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime
     /// of the returned reference.
-    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self {
+    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask_var_t) -> &'a mut Self {

Why?

Perhaps put this on the CpumaskBox and keep the struct cpumask one here?

Alice

author maintainer
#15 lore raw

Re: [PATCH 1/2] rust: Add initial cpumask abstractions

Quoted 12 lines · Alice Ryhl

rust/kernel/cpumask.rs line 32

Quoted 10 lines · Viresh Kumar

impl Cpumask {

rust/kernel/cpumask.rs +2 -2
-    /// Creates a reference to an existing `struct cpumask` pointer.
+    /// Creates a mutable reference to an existing `struct cpumask` pointer.
     ///
     /// # Safety
     ///
     /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime
     /// of the returned reference.
-    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self {
+    pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpumask_var_t) -> &'a mut Self {
Quoted 1 line

Why?

cpufreq core has a pointer to cpumask_var_t.

Quoted 1 line

Perhaps put this on the CpumaskBox and keep the struct cpumask one here?

Yeah, that worked. I think we will anyway have both type of users and its better to have both implemented.

Signature · 1 line
viresh