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

From: Alice Ryhl
Date: Thu Feb 27 2025 - 07:24:32 EST


On Thu, Feb 27, 2025 at 11:46 AM Viresh Kumar <viresh.kumar@xxxxxxxxxx> wrote:
>
> On 25-02-25, 18:02, Alice Ryhl wrote:
> > diff --git a/rust/kernel/cpumask.rs b/rust/kernel/cpumask.rs
> > +/// 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() },
>
> 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<-------------------------
>
> diff --git a/rust/kernel/cpumask.rs b/rust/kernel/cpumask.rs
> index f82dafbc4e61..d56f7dc9d762 100644
> --- a/rust/kernel/cpumask.rs
> +++ b/rust/kernel/cpumask.rs
> @@ -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 {

Why?

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

Alice