From: Alice Ryhl <aliceryhl@google.com>
To: aliceryhl@google.com
Cc: a.hindborg@kernel.org, alex.gaynor@gmail.com,
benno.lossin@proton.me, bjorn3_gh@protonmail.com,
boqun.feng@gmail.com, dakr@redhat.com, gary@garyguo.net,
linux-kernel@vger.kernel.org, linux@rasmusvillemoes.dk,
ojeda@kernel.org, rust-for-linux@vger.kernel.org,
tmgross@umich.edu, vincent.guittot@linaro.org,
viresh.kumar@linaro.org, yury.norov@gmail.com
Subject: Re: [PATCH 1/2] rust: Add initial cpumask abstractions
Date: Tue, 25 Feb 2025 18:02:23 +0000 [thread overview]
Message-ID: <20250225180223.763026-1-aliceryhl@google.com> (raw)
In-Reply-To: <CAH5fLggyEXyyaFNnmBCPOSX051TiFyAp0B8GfahbPg=+LrtUWA@mail.gmail.com>
On Tue, Feb 25, 2025 at 6:12 PM Alice Ryhl <aliceryhl@google.com> wrote:
>
> On Tue, Feb 25, 2025 at 6:02 PM Viresh Kumar <viresh.kumar@linaro.org> wrote:
> >
> > On Tue, 25 Feb 2025 at 17:23, Alice Ryhl <aliceryhl@google.com> wrote:
> >
> > > 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.
>
> 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.
diff --git a/rust/kernel/cpumask.rs b/rust/kernel/cpumask.rs
index 13864424420b..f82dafbc4e61 100644
--- a/rust/kernel/cpumask.rs
+++ b/rust/kernel/cpumask.rs
@@ -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())
+ };
}
}
next prev parent reply other threads:[~2025-02-25 18:02 UTC|newest]
Thread overview: 18+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-02-25 9:47 [PATCH 0/2] Rust: Add " Viresh Kumar
2025-02-25 9:47 ` [PATCH 1/2] rust: Add initial " Viresh Kumar
2025-02-25 9:55 ` Alice Ryhl
2025-02-25 10:54 ` Viresh Kumar
2025-02-25 11:34 ` Alice Ryhl
2025-02-25 11:36 ` Viresh Kumar
2025-02-25 11:39 ` Alice Ryhl
2025-02-25 11:52 ` Viresh Kumar
2025-02-25 11:48 ` Viresh Kumar
2025-02-25 11:53 ` Alice Ryhl
2025-02-25 17:02 ` Viresh Kumar
2025-02-25 17:12 ` Alice Ryhl
2025-02-25 18:02 ` Alice Ryhl [this message]
2025-02-27 10:46 ` Viresh Kumar
2025-02-27 12:19 ` Alice Ryhl
2025-02-28 7:09 ` Viresh Kumar
2025-02-25 9:47 ` [PATCH 2/2] MAINTAINERS: Add entry for Rust bitmap API Viresh Kumar
2025-02-26 15:03 ` Yury Norov
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20250225180223.763026-1-aliceryhl@google.com \
--to=aliceryhl@google.com \
--cc=a.hindborg@kernel.org \
--cc=alex.gaynor@gmail.com \
--cc=benno.lossin@proton.me \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=dakr@redhat.com \
--cc=gary@garyguo.net \
--cc=linux-kernel@vger.kernel.org \
--cc=linux@rasmusvillemoes.dk \
--cc=ojeda@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
--cc=tmgross@umich.edu \
--cc=vincent.guittot@linaro.org \
--cc=viresh.kumar@linaro.org \
--cc=yury.norov@gmail.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®