Skip to contentSkip to conversation

rust: Add Per-CPU Variable API

PATCH Superseded Mitchell Levy 3 participants 19 messages Nov 5, 2025 – Nov 14, 2025

Subsystems (4)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v4 cover rust: Add Per-CPU Variable API

This series adds an API for declaring and using per-CPU variables from Rust, and it also adds support for Rust access to C per-CPU variables (subject to some soundness requirements). It also adds a small sample module, samples/rust/rust_percpu.rs, in the vein of lib/percpu_test.c.

---

---
Changes in v4:
- Split what was the first patch into three patches (Thanks Yury Norov)
- Add intra-doc links to rustdoc comments (Thanks Miguel Ojeda)
- get_remote_ptr is no longer unsafe (Thanks Miguel Ojeda)
- Renamed the CPU mask getters to be more clear (Thanks Yury Norov)
- Add an ExternStaticPerCpuSymbol type for static per-CPU variables shared with C in order to make the extra soundness requirements for these variables more explicit.
- Properly drop the contents of dynamically allocated per-CPUs when the DynamicPerCpu is dropped, and properly document that PerCpuAllocation does not handle dropping values in the allocation.
- Functions on the numeric token types are now #[inline]
- Safety requirements of PerCpuPtr functions now include the fact that the pointed-to allocation must be live and appropriately laid out in memory, and SAFETY comments of uses of these functions have been
updated to reflect these requirements.
- Included the cpumask patches first, since it might make sense for
these to be merged separately.
- Documentation improvements throughout.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Add a CheckedPerCpuToken that enables usage of per-CPU variables via
a &T, allowing for a wholly safe interface when T allows for interior mutability (Thanks Benno Lossin)
- Add support for non-zeroable types to be used in a DynamicPerCpu.
- Remove necessity for unsafe to get a StaticPerCpu from its declaration (Thanks Benno Lossin)
- Allow the declaration of static per-CPU variables of types that are !Sync.
- Implement PerCpuPtr in terms of MaybeUninit<T> rather than T so
as to keep all invariants in the DynamicPerCpu and StaticPerCpu types --- this would also enable PerCpuPtr to be used in a per-CPU type that does lazy initialization.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Fix kernel test robot issues
- Fix documentation error
- Require T: Zeroable in the dynamic case
- Link to v1: https://lore.kernel.org/r/[email protected]

Changes in v1:
- Use wrapping_add in PerCpuPtr::get_ref since overflow is expected.
- Separate the dynamic and static cases, with shared logic in a
PerCpuPtr type.
- Implement pin-hole optimizations for numeric types
- Don't assume GFP_KERNEL when allocating the Arc in the dynamic
case.
- Link to RFC v2: https://lore.kernel.org/r/[email protected]

Changes in RFC v2:
- Renamed PerCpuVariable to StaticPerCpuSymbol to be more descriptive
- Support dynamically allocated per-CPU variables via the
PerCpuAllocation type. Rework statically allocated variables to use
this new type.
- Make use of a token/closure-based API via the PerCpu and PerCpuToken types, rather than an API based on PerCpuRef that automatically Deref(Mut)'s into a &(mut) T.
- Rebased
- Link to RFC: https://lore.kernel.org/r/[email protected]

---
Mitchell Levy (9):
rust: cpumask: Add a Cpumask iterator
rust: cpumask: Add getters for globally defined cpumasks
rust: percpu: Add C bindings for per-CPU variable API
rust: percpu: introduce a rust API for static per-CPU variables
rust: percpu: introduce a rust API for dynamic per-CPU variables
rust: percpu: add a rust per-CPU variable sample
rust: percpu: Support non-zeroable types for DynamicPerCpu
rust: percpu: Add pin-hole optimizations for numerics
rust: percpu: cache per-CPU pointers in the dynamic case

 rust/helpers/cpumask.c          |   5 +
 rust/helpers/helpers.c          |   2 +
 rust/helpers/percpu.c           |  20 +++
 rust/helpers/preempt.c          |  14 ++
 rust/kernel/cpumask.rs          |  94 ++++++++++++-
 rust/kernel/lib.rs              |   3 +
 rust/kernel/percpu.rs           | 273 +++++++++++++++++++++++++++++++++++++
 rust/kernel/percpu/cpu_guard.rs |  36 +++++
 rust/kernel/percpu/dynamic.rs   | 184 +++++++++++++++++++++++++
 rust/kernel/percpu/numeric.rs   | 138 +++++++++++++++++++
 rust/kernel/percpu/static_.rs   | 218 +++++++++++++++++++++++++++++
 samples/rust/Kconfig            |   9 ++
 samples/rust/Makefile           |   1 +
 samples/rust/rust_percpu.rs     | 294 ++++++++++++++++++++++++++++++++++++++++
 14 files changed, 1290 insertions(+), 1 deletion(-)

---
base-commit: f3f6b3664302e16ef1c6b91034a72df5564d6b8a
change-id: 20240813-rust-percpu-ea2f54b5da33

Best regards,

Signature · 1 line
Mitchell Levy <[email protected]>
#1 lore raw

PATCH v4 1/9 rust: cpumask: Add a `Cpumask` iterator

Add an iterator for Cpumask making use of C's cpumask_next.

---
 rust/helpers/cpumask.c |  5 +++++
 rust/kernel/cpumask.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 52 insertions(+), 1 deletion(-)
rust/helpers/cpumask.c +5 -0
index eb10598a0242..d95bfa111191 100644
@@ -42,6 +42,11 @@ bool rust_helper_cpumask_full(struct cpumask *srcp)
 	return cpumask_full(srcp);
 }
 
+unsigned int rust_helper_cpumask_next(int n, struct cpumask *srcp)
+{
+	return cpumask_next(n, srcp);
+}
+
 unsigned int rust_helper_cpumask_weight(struct cpumask *srcp)
 {
 	return cpumask_weight(srcp);
rust/kernel/cpumask.rs +47 -1

60 lines not on this page · raw message

Signature · 1 line
2.34.1
#5 lore raw

PATCH v4 2/9 rust: cpumask: Add getters for globally defined cpumasks

In reply to Mitchell Levy

Add getters for the global cpumasks documented in
include/linux/cpumask.h, specifically:
- cpu_possible_mask
- cpu_online_mask
- cpu_enabled_mask
- cpu_present_mask
- cpu_active_mask

---
 rust/kernel/cpumask.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
rust/kernel/cpumask.rs +46 -0
index b7401848f59e..a6a130092fcb 100644
@@ -77,6 +77,52 @@ pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self {
         unsafe { &*ptr.cast() }
     }
 
+    /// Get a CPU mask representing possible CPUs; has bit `cpu` set iff cpu is populatable
+    #[inline]
+    pub fn possible_cpus() -> &'static Self {
+        // SAFETY: `__cpu_possible_mask` is a valid global provided by the kernel that lives
+        // forever.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_possible_mask) }
+    }
+
+    /// Get a CPU mask representing online CPUs; has bit `cpu` set iff cpu available to the
+    /// scheduler
+    #[inline]
+    pub fn online_cpus() -> &'static Self {
+        // SAFETY: `__cpu_online_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_online_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_online_mask) }
+    }
+
+    /// Get a CPU mask representing enabled CPUs; has bit `cpu` set iff cpu can be brought online
+    #[inline]
+    pub fn enabled_cpus() -> &'static Self {
+        // SAFETY: `__cpu_enabled_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_enabled_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_enabled_mask) }
+    }
+
+    /// Get a CPU mask representing present CPUs; has bit `cpu` set iff cpu is populated
+    #[inline]
+    pub fn present_cpus() -> &'static Self {
+        // SAFETY: `__cpu_present_mask` is a valid global provided by the kernel that lives
+        // forever. Since we wrap the returned pointer in an `Opaque`, it's ok that
+        // `__cpu_present_mask` may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_present_mask) }
+    }
+
+    /// Get a CPU mask representing active CPUs; has bit `cpu` set iff cpu is available to
+    /// migration.
+    #[inline]
+    pub fn active_cpus() -> &'static Self {
+        // SAFETY: `__cpu_active_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_active_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_active_mask) }
+    }
+
     /// Obtain the raw `struct cpumask` pointer.
     pub fn as_raw(&self) -> *mut bindings::cpumask {
         let this: *const Self = self;
Signature · 1 line
2.34.1
#8 lore raw

PATCH v4 3/9 rust: percpu: Add C bindings for per-CPU variable API

In reply to Mitchell Levy

Add bindings necessary to implement a Rust per-CPU variable API, specifically per-CPU variable allocation and management of CPU preemption.

---
 rust/helpers/helpers.c |  2 ++
 rust/helpers/percpu.c  |  9 +++++++++
 rust/helpers/preempt.c | 14 ++++++++++++++
 3 files changed, 25 insertions(+)
rust/helpers/helpers.c +2 -0
index 7cf7fe95e41d..2fc8d26cfe66 100644
@@ -31,9 +31,11 @@
 #include "of.c"
 #include "page.c"
 #include "pci.c"
+#include "percpu.c"
 #include "pid_namespace.c"
 #include "platform.c"
 #include "poll.c"
+#include "preempt.c"
 #include "property.c"
 #include "rbtree.c"
 #include "rcu.c"
rust/helpers/percpu.c new file +9 -0
new file mode 100644
index 000000000000..a091389f730f
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/percpu.h>
+
+void __percpu *rust_helper_alloc_percpu(size_t sz, size_t align)
+{
+	return __alloc_percpu(sz, align);
+}
+
rust/helpers/preempt.c new file +14 -0
new file mode 100644
index 000000000000..2c7529528ddd
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/preempt.h>
+
+void rust_helper_preempt_disable(void)
+{
+	preempt_disable();
+}
+
+void rust_helper_preempt_enable(void)
+{
+	preempt_enable();
+}
+
Signature · 1 line
2.34.1
#10 lore raw

PATCH v4 4/9 rust: percpu: introduce a rust API for static per-CPU variables

In reply to Mitchell Levy

Per-CPU variables are an important tool for reducing lock contention, especially in systems with many processors. They also provide a convenient way to handle data that are logically associated with a particular CPU (e.g., the currently running task).

Therefore, add a Rust API to make use of statically-allocated per-CPU variables. Add a RAII CpuGuard type for disabling CPU preemption. Introduce unifying abstractions that can be reused for a Rust API for dynamically-allocated per-CPU variables.

---
Using rustc 1.83.0, I can confirm that the symbols __INIT_$id are optimized out by the compiler and do not appear in the final .ko file when compiling samples/rust/rust_percpu.rs (introduced in a later patch in this series).

---
 rust/kernel/lib.rs              |   3 +
 rust/kernel/percpu.rs           | 250 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/percpu/cpu_guard.rs |  36 ++++++
 rust/kernel/percpu/static_.rs   | 218 +++++++++++++++++++++++++++++++++++
 4 files changed, 507 insertions(+)
rust/kernel/lib.rs +3 -0
index f910a5ab80ba..2fdb194aa068 100644
@@ -108,6 +108,9 @@
 pub mod page;
 #[cfg(CONFIG_PCI)]
 pub mod pci;
+// Only x86_64 is supported by percpu for now
+#[cfg(CONFIG_X86_64)]
+pub mod percpu;
 pub mod pid_namespace;
 pub mod platform;
 pub mod prelude;
rust/kernel/percpu.rs new file +250 -0

250 lines not on this page · raw message

rust/kernel/percpu/cpu_guard.rs new file +36 -0
new file mode 100644
index 000000000000..2fb4c9218922
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0
+//! Contains abstractions for disabling CPU preemption. See [`CpuGuard`].
+
+/// A RAII guard for `bindings::preempt_disable` and `bindings::preempt_enable`.
+///
+/// Guarantees preemption is disabled for as long as this object exists.
+pub struct CpuGuard {
+    // Don't make one without using new()
+    _phantom: (),
+}
+
+impl CpuGuard {
+    /// Create a new [`CpuGuard`]. Disables preemption for its lifetime.
+    pub fn new() -> Self {
+        // SAFETY: There are no preconditions required to call preempt_disable
+        unsafe {
+            bindings::preempt_disable();
+        }
+        CpuGuard { _phantom: () }
+    }
+}
+
+impl Default for CpuGuard {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl Drop for CpuGuard {
+    fn drop(&mut self) {
+        // SAFETY: There are no preconditions required to call preempt_enable
+        unsafe {
+            bindings::preempt_enable();
+        }
+    }
+}
rust/kernel/percpu/static_.rs new file +218 -0

218 lines not on this page · raw message

Signature · 1 line
2.34.1
#12 lore raw

PATCH v4 5/9 rust: percpu: introduce a rust API for dynamic per-CPU variables

In reply to Mitchell Levy

Dynamically allocated per-CPU variables are core to many of the use-cases of per-CPU variables (e.g., ref counting). Add support for them using the core PerCpuPtr<T> primitive, implementing the PerCpu<T> trait.

---
 rust/helpers/percpu.c         |  10 ++++
 rust/kernel/percpu.rs         |  30 ++++++++--
 rust/kernel/percpu/dynamic.rs | 130 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 166 insertions(+), 4 deletions(-)
rust/helpers/percpu.c +10 -0
index a091389f730f..35656333dfae 100644
@@ -7,3 +7,13 @@ void __percpu *rust_helper_alloc_percpu(size_t sz, size_t align)
 	return __alloc_percpu(sz, align);
 }
 
+void *rust_helper_per_cpu_ptr(void __percpu *ptr, unsigned int cpu)
+{
+	return per_cpu_ptr(ptr, cpu);
+}
+
+void rust_helper_on_each_cpu(smp_call_func_t func, void *info, int wait)
+{
+	on_each_cpu(func, info, wait);
+}
+
rust/kernel/percpu.rs +26 -4
index 2fba9a165636..294b8ffc4f62 100644
@@ -1,14 +1,19 @@
 // SPDX-License-Identifier: GPL-2.0
 //! Per-CPU variables.
 //!
-//! See the [`crate::define_per_cpu!`] macro and the [`PerCpu<T>`] trait.
+//! See the [`crate::define_per_cpu!`] macro, the [`DynamicPerCpu`] type, and the [`PerCpu<T>`]
+//! trait.
 
 pub mod cpu_guard;
+mod dynamic;
 mod static_;
 
+#[doc(inline)]
+pub use dynamic::*;
 #[doc(inline)]
 pub use static_::*;
 
+use crate::cpu::CpuId;
 use crate::declare_extern_per_cpu;
 use crate::percpu::cpu_guard::CpuGuard;
 use crate::types::Opaque;
@@ -123,6 +128,23 @@ pub fn get_ptr(&self) -> *mut MaybeUninit<T> {
         // the invariant that self.0 is a valid offset into the per-CPU area.
         (this_cpu_area).wrapping_add(self.0 as usize).cast()
     }
+
+    /// Get a [`*mut MaybeUninit<T>`](MaybeUninit) to the per-CPU variable on the CPU represented
+    /// by `cpu`. Note that without some kind of synchronization, use of the returned pointer may
+    /// cause a data race. It is the caller's responsibility to use the returned pointer in a
+    /// reasonable way.
+    ///
+    /// # Returns
+    /// - The returned pointer is valid only if `self` is (that is, it points to a live allocation
+    ///   correctly sized and aligned to hold a `T`)
+    /// - The returned pointer is valid only if the bit corresponding to `cpu` is set in
+    ///   [`kernel::cpumask::Cpumask::possible_cpus()`].
+    pub fn get_remote_ptr(&self, cpu: CpuId) -> *mut MaybeUninit<T> {
+        // SAFETY: `bindings::per_cpu_ptr` is just doing pointer arithmetic. The returned pointer
+        // may not be valid (under the conditions specified in this function's documentation), but
+        // the act of producing the pointer is safe.
+        unsafe { bindings::per_cpu_ptr(self.0.cast(), cpu.as_u32()) }.cast()
+    }
 }
 
 // SAFETY: Sending a [`PerCpuPtr<T>`] to another thread is safe because as soon as it's sent, the
@@ -146,9 +168,9 @@ impl<T> Copy for PerCpuPtr<T> {}
 
 /// A trait representing a per-CPU variable.
 ///
-/// This is implemented for [`StaticPerCpu<T>`]. The main usage of this trait is to call
-/// [`Self::get_mut`] to get a [`PerCpuToken`] that can be used to access the underlying per-CPU
-/// variable.
+/// This is implemented for both [`StaticPerCpu<T>`] and [`DynamicPerCpu<T>`]. The main usage of
+/// this trait is to call [`Self::get_mut`] to get a [`PerCpuToken`] that can be used to access the
+/// underlying per-CPU variable.
 ///
 /// See [`PerCpuToken::with`].
 pub trait PerCpu<T> {
rust/kernel/percpu/dynamic.rs new file +130 -0

130 lines not on this page · raw message

Signature · 1 line
2.34.1
#14 lore raw

PATCH v4 6/9 rust: percpu: add a rust per-CPU variable sample

In reply to Mitchell Levy

Add a short exercise for Rust's per-CPU variable API, modelled after lib/percpu_test.c

---
 rust/helpers/percpu.c       |   1 +
 rust/kernel/percpu.rs       |   2 +-
 samples/rust/Kconfig        |   9 +++
 samples/rust/Makefile       |   1 +
 samples/rust/rust_percpu.rs | 163 ++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 175 insertions(+), 1 deletion(-)
rust/helpers/percpu.c +1 -0
index 35656333dfae..8d83b6b86106 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 
 #include <linux/percpu.h>
+#include <linux/smp.h>
 
 void __percpu *rust_helper_alloc_percpu(size_t sz, size_t align)
 {
rust/kernel/percpu.rs +1 -1
index 294b8ffc4f62..2db670c87fae 100644
@@ -2,7 +2,7 @@
 //! Per-CPU variables.
 //!
 //! See the [`crate::define_per_cpu!`] macro, the [`DynamicPerCpu`] type, and the [`PerCpu<T>`]
-//! trait.
+//! trait. Example usage can be found in `samples/rust/rust_percpu.rs`.
 
 pub mod cpu_guard;
 mod dynamic;
samples/rust/Kconfig +9 -0
index 7f7371a004ee..23e35d64ac78 100644
@@ -105,6 +105,15 @@ config SAMPLE_RUST_DRIVER_AUXILIARY
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_PERCPU
+	tristate "Per-CPU support"
+	depends on m
+	help
+	  Enable this option to build a module which demonstrates Rust per-CPU
+	  operations.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_HOSTPROGS
 	bool "Host programs"
 	help
samples/rust/Makefile +1 -0
index bd2faad63b4f..8a34d9d74754 100644
@@ -10,6 +10,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY)	+= rust_driver_auxiliary.o
 obj-$(CONFIG_SAMPLE_RUST_CONFIGFS)		+= rust_configfs.o
+obj-$(CONFIG_SAMPLE_RUST_PERCPU)		+= rust_percpu.o
 
 rust_print-y := rust_print_main.o rust_print_events.o
 
samples/rust/rust_percpu.rs new file +163 -0

163 lines not on this page · raw message

Signature · 1 line
2.34.1
#15 lore raw

PATCH v4 7/9 rust: percpu: Support non-zeroable types for DynamicPerCpu

In reply to Mitchell Levy

Add functionality to PerCpuPtr to compute pointers to per-CPU variable slots on other CPUs. Use this facility to initialize per-CPU variables on all possible CPUs when a dynamic per-CPU variable is created with a non-zeroable type. Since RefCell and other Cell-like types fall into this category, impl CheckedPerCpu on DynamicPerCpu for these InteriorMutable types since they can now be used. Add examples of these usages to samples/rust/rust_percpu.rs. Add a test to ensure dynamic per-CPU variables properly drop their contents, done here since non-trivially dropped types often aren't Zeroable.

---
 rust/kernel/percpu/dynamic.rs |  44 +++++++++++++++++
 samples/rust/rust_percpu.rs   | 109 +++++++++++++++++++++++++++++++++++++++---
 2 files changed, 146 insertions(+), 7 deletions(-)
rust/kernel/percpu/dynamic.rs +44 -0
index 1863f31a2817..a74c8841aeb2 100644
@@ -89,6 +89,36 @@ pub fn new_zero(flags: Flags) -> Option<Self> {
     }
 }
 
+impl<T: Clone> DynamicPerCpu<T> {
+    /// Allocates a new per-CPU variable
+    ///
+    /// # Arguments
+    /// * `val` - The initial value of the per-CPU variable on all CPUs.
+    /// * `flags` - Flags used to allocate an [`Arc`] that keeps track of the underlying
+    ///   [`PerCpuAllocation`].
+    pub fn new_with(val: &T, flags: Flags) -> Option<Self> {
+        let alloc: PerCpuAllocation<T> = PerCpuAllocation::new_uninit()?;
+        let ptr = alloc.0;
+
+        for cpu in Cpumask::possible_cpus().iter() {
+            let remote_ptr = ptr.get_remote_ptr(cpu);
+            // SAFETY: `remote_ptr` is valid because `ptr` points to a live allocation and `cpu`
+            // appears in `Cpumask::possible_cpus()`.
+            //
+            // Each CPU's slot corresponding to `ptr` is currently uninitialized, and no one else
+            // has a reference to it. Therefore, we can freely write to it without worrying about
+            // the need to drop what was there or whether we're racing with someone else.
+            unsafe {
+                (*remote_ptr).write(val.clone());
+            }
+        }
+
+        let arc = Arc::new(alloc, flags).ok()?;
+
+        Some(Self { alloc: Some(arc) })
+    }
+}
+
 impl<T> PerCpu<T> for DynamicPerCpu<T> {
     unsafe fn get_mut(&mut self, guard: CpuGuard) -> PerCpuToken<'_, T> {
         // SAFETY:
@@ -105,6 +135,20 @@ unsafe fn get_mut(&mut self, guard: CpuGuard) -> PerCpuToken<'_, T> {
     }
 }
 
+impl<T: InteriorMutable> CheckedPerCpu<T> for DynamicPerCpu<T> {
+    fn get(&mut self, guard: CpuGuard) -> CheckedPerCpuToken<'_, T> {
+        // SAFETY:
+        // 1. Invariants of this type assure that `alloc` is `Some`.
+        // 2. The invariants of `DynamicPerCpu` ensure that the contents of the allocation are
+        //    initialized on each CPU.
+        // 3. The existence of a reference to the `PerCpuAllocation` ensures that the allocation is
+        //    live.
+        // 4. The invariants of `DynamicPerCpu` ensure that the allocation is sized and aligned for
+        //    a `T`.
+        unsafe { CheckedPerCpuToken::new(guard, &self.alloc.as_ref().unwrap_unchecked().0) }
+    }
+}
+
 impl<T> Drop for DynamicPerCpu<T> {
     fn drop(&mut self) {
         // SAFETY: This type's invariant ensures that `self.alloc` is `Some`.
samples/rust/rust_percpu.rs +102 -7

138 lines not on this page · raw message

Signature · 1 line
2.34.1
#17 lore raw

PATCH v4 8/9 rust: percpu: Add pin-hole optimizations for numerics

In reply to Mitchell Levy

The C implementations of this_cpu_add, this_cpu_sub, etc., are optimized to save an instruction by avoiding having to compute this_cpu_ptr(&x) for some per-CPU variable x. For example, rather than

    u64 *x_ptr = this_cpu_ptr(&x);
    *x_ptr += 5;

the implementation of this_cpu_add is clever enough to make use of the fact that per-CPU variables are implemented on x86 via segment registers, and so we can use only a single instruction (where we assume &x is already in rax)

    add gs:[rax], 5

Add this optimization via a PerCpuNumeric type to enable code-reuse between DynamicPerCpu and StaticPerCpu.

---
 rust/kernel/percpu.rs         |   1 +
 rust/kernel/percpu/dynamic.rs |  10 ++-
 rust/kernel/percpu/numeric.rs | 138 ++++++++++++++++++++++++++++++++++++++++++
 samples/rust/rust_percpu.rs   |  36 +++++++++++
 4 files changed, 184 insertions(+), 1 deletion(-)
rust/kernel/percpu.rs +1 -0
index 2db670c87fae..c1148cb36eff 100644
@@ -6,6 +6,7 @@
 
 pub mod cpu_guard;
 mod dynamic;
+pub mod numeric;
 mod static_;
 
 #[doc(inline)]
rust/kernel/percpu/dynamic.rs +9 -1
index a74c8841aeb2..99acbf6363f5 100644
@@ -18,7 +18,7 @@
 /// the memory location on any particular CPU has been initialized. This means that it cannot tell
 /// whether it should drop the *contents* of the allocation when it is dropped. It is up to the
 /// user to do this via something like [`core::ptr::drop_in_place`].
-pub struct PerCpuAllocation<T>(PerCpuPtr<T>);
+pub struct PerCpuAllocation<T>(pub(super) PerCpuPtr<T>);
 
 impl<T: Zeroable> PerCpuAllocation<T> {
     /// Dynamically allocates a space in the per-CPU area suitably sized and aligned to hold a `T`,
@@ -119,6 +119,14 @@ pub fn new_with(val: &T, flags: Flags) -> Option<Self> {
     }
 }
 
+impl<T> DynamicPerCpu<T> {
+    /// Gets the allocation backing this per-CPU variable.
+    pub(crate) fn alloc(&self) -> &Arc<PerCpuAllocation<T>> {
+        // SAFETY: This type's invariant ensures that `self.alloc` is `Some`.
+        unsafe { self.alloc.as_ref().unwrap_unchecked() }
+    }
+}
+
 impl<T> PerCpu<T> for DynamicPerCpu<T> {
     unsafe fn get_mut(&mut self, guard: CpuGuard) -> PerCpuToken<'_, T> {
         // SAFETY:
rust/kernel/percpu/numeric.rs new file +138 -0

138 lines not on this page · raw message

samples/rust/rust_percpu.rs +36 -0
index be70ee2e513f..31ab3fcf5c6c 100644
@@ -28,6 +28,26 @@
 define_per_cpu!(UPERCPU: u64 = 0);
 define_per_cpu!(CHECKED: RefCell<u64> = RefCell::new(0));
 
+macro_rules! make_optimization_test {
+    ($ty:ty) => {
+        let mut test: DynamicPerCpu<$ty> = DynamicPerCpu::new_zero(GFP_KERNEL).unwrap();
+        {
+            let _ = CpuGuard::new();
+            // SAFETY: No other usage of `test`
+            unsafe { test.get_mut(CpuGuard::new()) }.with(|val: &mut $ty| *val = 10);
+            test.num().add(1);
+            // SAFETY: No other usage of `test`
+            unsafe { test.get_mut(CpuGuard::new()) }.with(|val: &mut $ty| assert_eq!(*val, 11));
+            test.num().add(10);
+            // SAFETY: No other usage of `test`
+            unsafe { test.get_mut(CpuGuard::new()) }.with(|val: &mut $ty| assert_eq!(*val, 21));
+            test.num().sub(5);
+            // SAFETY: No other usage of `test`
+            unsafe { test.get_mut(CpuGuard::new()) }.with(|val: &mut $ty| assert_eq!(*val, 16));
+        }
+    };
+}
+
 impl kernel::Module for PerCpuMod {
     fn init(_module: &'static ThisModule) -> Result<Self, Error> {
         pr_info!("rust percpu test start\n");
@@ -208,6 +228,22 @@ fn init(_module: &'static ThisModule) -> Result<Self, Error> {
 
         pr_info!("rust dynamic percpu test done\n");
 
+        pr_info!("rust numeric optimizations test start\n");
+
+        make_optimization_test!(u8);
+        make_optimization_test!(u16);
+        make_optimization_test!(u32);
+        make_optimization_test!(u64);
+        make_optimization_test!(usize);
+
+        make_optimization_test!(i8);
+        make_optimization_test!(i16);
+        make_optimization_test!(i32);
+        make_optimization_test!(i64);
+        make_optimization_test!(isize);
+
+        pr_info!("rust numeric optimizations test done\n");
+
         // Return Err to unload the module
         Result::Err(EINVAL)
     }
Signature · 1 line
2.34.1
#18 lore raw

PATCH v4 9/9 rust: percpu: cache per-CPU pointers in the dynamic case

In reply to Mitchell Levy

Currently, the creation of a PerCpuNumeric requires a memory read via the Arc managing the dynamic allocation. While the compiler might be clever enough to consolidate these reads in some cases, the read must happen *somewhere*, which, when we're concerning ourselves with individual instructions, is a very high burden.

Instead, cache the PerCpuPointer inside the DynamicPerCpu structure; then, the Arc is used solely to manage the allocation.

---
 rust/kernel/percpu/dynamic.rs | 22 ++++++++++++----------
 rust/kernel/percpu/numeric.rs |  4 ++--
 2 files changed, 14 insertions(+), 12 deletions(-)
rust/kernel/percpu/dynamic.rs +12 -10
index 99acbf6363f5..dcf3e1c4f7a9 100644
@@ -72,6 +72,9 @@ pub struct DynamicPerCpu<T> {
     // INVARIANT: The memory location in each CPU's per-CPU area pointed at by the alloc is
     // initialized.
     alloc: Option<Arc<PerCpuAllocation<T>>>,
+    // INVARIANT: `ptr` is the per-CPU pointer managed by `alloc`, which does not change for the
+    // lifetime of `self`.
+    pub(super) ptr: PerCpuPtr<T>,
 }
 
 impl<T: Zeroable> DynamicPerCpu<T> {
@@ -83,9 +86,13 @@ impl<T: Zeroable> DynamicPerCpu<T> {
     pub fn new_zero(flags: Flags) -> Option<Self> {
         let alloc: PerCpuAllocation<T> = PerCpuAllocation::new_zero()?;
 
+        let ptr = alloc.0;
         let arc = Arc::new(alloc, flags).ok()?;
 
-        Some(Self { alloc: Some(arc) })
+        Some(Self {
+            alloc: Some(arc),
+            ptr,
+        })
     }
 }
 
@@ -115,15 +122,10 @@ pub fn new_with(val: &T, flags: Flags) -> Option<Self> {
 
         let arc = Arc::new(alloc, flags).ok()?;
 
-        Some(Self { alloc: Some(arc) })
-    }
-}
-
-impl<T> DynamicPerCpu<T> {
-    /// Gets the allocation backing this per-CPU variable.
-    pub(crate) fn alloc(&self) -> &Arc<PerCpuAllocation<T>> {
-        // SAFETY: This type's invariant ensures that `self.alloc` is `Some`.
-        unsafe { self.alloc.as_ref().unwrap_unchecked() }
+        Some(Self {
+            alloc: Some(arc),
+            ptr,
+        })
     }
 }
 
rust/kernel/percpu/numeric.rs +2 -2
index e76461f05c66..23a7a09216d0 100644
@@ -22,7 +22,7 @@ impl DynamicPerCpu<$ty> {
             pub fn num(&mut self) -> PerCpuNumeric<'_, $ty> {
                 // The invariant is satisfied because `DynamicPerCpu`'s invariant guarantees that
                 // this pointer is valid and initialized on all CPUs.
-                PerCpuNumeric { ptr: &self.alloc().0 }
+                PerCpuNumeric { ptr: &self.ptr }
             }
         }
         impl StaticPerCpu<$ty> {
@@ -78,7 +78,7 @@ impl DynamicPerCpu<$ty> {
             pub fn num(&mut self) -> PerCpuNumeric<'_, $ty> {
                 // The invariant is satisfied because `DynamicPerCpu`'s invariant guarantees that
                 // this pointer is valid and initialized on all CPUs.
-                PerCpuNumeric { ptr: &self.alloc().0 }
+                PerCpuNumeric { ptr: &self.ptr }
             }
         }
         impl StaticPerCpu<$ty> {
Signature · 1 line
2.34.1
maintainer
#2 lore raw

Re: [PATCH v4 1/9] rust: cpumask: Add a `Cpumask` iterator

In reply to Mitchell Levy
Quoted 39 lines · Mitchell Levy

Add an iterator for Cpumask making use of C's cpumask_next.

---
 rust/helpers/cpumask.c |  5 +++++
 rust/kernel/cpumask.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 52 insertions(+), 1 deletion(-)
rust/helpers/cpumask.c +5 -0
index eb10598a0242..d95bfa111191 100644
@@ -42,6 +42,11 @@ bool rust_helper_cpumask_full(struct cpumask *srcp)
 	return cpumask_full(srcp);
 }
 
+unsigned int rust_helper_cpumask_next(int n, struct cpumask *srcp)
+{
+	return cpumask_next(n, srcp);
+}
+
 unsigned int rust_helper_cpumask_weight(struct cpumask *srcp)
 {
 	return cpumask_weight(srcp);
rust/kernel/cpumask.rs +1 -1
index 3fcbff438670..b7401848f59e 100644
@@ -6,7 +6,7 @@
 
 use crate::{
     alloc::{AllocError, Flags},
-    cpu::CpuId,
+    cpu::{self, CpuId},
     prelude::*,
     types::Opaque,
 };

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 167

Quoted 7 lines
rust/kernel/cpumask.rs +4 -0
@@ -161,6 +161,52 @@ pub fn copy(&self, dstp: &mut Self) {
     }
 }
 
+/// Iterator for a `Cpumask`.
+pub struct CpumaskIter<'a> {
+    mask: &'a Cpumask,
+    last: Option<u32>,

This is not the last, it's a current CPU.

Quoted 17 lines
rust/kernel/cpumask.rs +17 -0
+}
+
+impl<'a> CpumaskIter<'a> {
+    /// Creates a new `CpumaskIter` for the given `Cpumask`.
+    fn new(mask: &'a Cpumask) -> CpumaskIter<'a> {
+        Self { mask, last: None }
+    }
+}
+
+impl<'a> Iterator for CpumaskIter<'a> {
+    type Item = CpuId;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        // SAFETY: By the type invariant, `self.mask.as_raw` is a `struct cpumask *`.
+        let next = unsafe {
+            bindings::cpumask_next(
+                if let Some(last) = self.last {

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 194

Quoted 10 lines
rust/kernel/cpumask.rs +10 -0
+                    last.try_into().unwrap()
+                } else {
+                    -1
+                },
+                self.mask.as_raw(),
+            )
+        };
+
+        if next == cpu::nr_cpu_ids() {
+            None

Please: if next >= cpu::nr_cpu_ids() {

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 197

Quoted 3 lines
rust/kernel/cpumask.rs +3 -0
+        } else {
+            self.last = Some(next);
+            // SAFETY: `cpumask_next` returns either `nr_cpu_ids` or a valid CPU ID.

Now that you've handled the no-found case in the previous block, the comment doesn't look correct. Can you either move it on top of the if-else, or just drop entirely?

Quoted 18 lines
rust/kernel/cpumask.rs +12 -0
+            unsafe { Some(CpuId::from_u32_unchecked(next)) }
+        }
+    }
+}
+
+impl Cpumask {
+    /// Returns an iterator over the set bits in the cpumask.
+    pub fn iter(&self) -> CpumaskIter<'_> {
+        CpumaskIter::new(self)
+    }
+}
+
 /// A CPU Mask pointer.
 ///
 /// Rust abstraction for the C `struct cpumask_var_t`.
Signature · 2 lines
-- 
2.34.1
maintainer Acked-by on v4 2/9
#6 lore raw

Re: [PATCH v4 2/9] rust: cpumask: Add getters for globally defined cpumasks

In reply to Mitchell Levy
Quoted 20 lines · Mitchell Levy

Add getters for the global cpumasks documented in
include/linux/cpumask.h, specifically:
- cpu_possible_mask
- cpu_online_mask
- cpu_enabled_mask
- cpu_present_mask
- cpu_active_mask

---
 rust/kernel/cpumask.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
rust/kernel/cpumask.rs +0 -0
index b7401848f59e..a6a130092fcb 100644

rust/kernel/cpumask.rs pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self { · line 86

Quoted 10 lines
rust/kernel/cpumask.rs +7 -0
@@ -77,6 +77,52 @@ pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self {
         unsafe { &*ptr.cast() }
     }
 
+    /// Get a CPU mask representing possible CPUs; has bit `cpu` set iff cpu is populatable
+    #[inline]
+    pub fn possible_cpus() -> &'static Self {
+        // SAFETY: `__cpu_possible_mask` is a valid global provided by the kernel that lives
+        // forever.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_possible_mask) }
+    }

Not sure about this '&raw const' syntax, but I want to make sure that all this getters provide non-modifiable references. To modify any of those masks, one has to call a dedicated helper like set_cpu_possible().

Can you maybe explicitly mention it in the comments?

With that,

Quoted 44 lines
rust/kernel/cpumask.rs +38 -0
+    /// Get a CPU mask representing online CPUs; has bit `cpu` set iff cpu available to the
+    /// scheduler
+    #[inline]
+    pub fn online_cpus() -> &'static Self {
+        // SAFETY: `__cpu_online_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_online_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_online_mask) }
+    }
+
+    /// Get a CPU mask representing enabled CPUs; has bit `cpu` set iff cpu can be brought online
+    #[inline]
+    pub fn enabled_cpus() -> &'static Self {
+        // SAFETY: `__cpu_enabled_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_enabled_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_enabled_mask) }
+    }
+
+    /// Get a CPU mask representing present CPUs; has bit `cpu` set iff cpu is populated
+    #[inline]
+    pub fn present_cpus() -> &'static Self {
+        // SAFETY: `__cpu_present_mask` is a valid global provided by the kernel that lives
+        // forever. Since we wrap the returned pointer in an `Opaque`, it's ok that
+        // `__cpu_present_mask` may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_present_mask) }
+    }
+
+    /// Get a CPU mask representing active CPUs; has bit `cpu` set iff cpu is available to
+    /// migration.
+    #[inline]
+    pub fn active_cpus() -> &'static Self {
+        // SAFETY: `__cpu_active_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_active_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_active_mask) }
+    }
+
     /// Obtain the raw `struct cpumask` pointer.
     pub fn as_raw(&self) -> *mut bindings::cpumask {
         let this: *const Self = self;
Signature · 2 lines
-- 
2.34.1
maintainer Acked-by on v4 3/9
#9 lore raw

Re: [PATCH v4 3/9] rust: percpu: Add C bindings for per-CPU variable API

In reply to Mitchell Levy
Quoted 5 lines · Mitchell Levy

Add bindings necessary to implement a Rust per-CPU variable API, specifically per-CPU variable allocation and management of CPU preemption.

Quoted 60 lines
---
 rust/helpers/helpers.c |  2 ++
 rust/helpers/percpu.c  |  9 +++++++++
 rust/helpers/preempt.c | 14 ++++++++++++++
 3 files changed, 25 insertions(+)
rust/helpers/helpers.c +2 -0
index 7cf7fe95e41d..2fc8d26cfe66 100644
@@ -31,9 +31,11 @@
 #include "of.c"
 #include "page.c"
 #include "pci.c"
+#include "percpu.c"
 #include "pid_namespace.c"
 #include "platform.c"
 #include "poll.c"
+#include "preempt.c"
 #include "property.c"
 #include "rbtree.c"
 #include "rcu.c"
rust/helpers/percpu.c new file +9 -0
new file mode 100644
index 000000000000..a091389f730f
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/percpu.h>
+
+void __percpu *rust_helper_alloc_percpu(size_t sz, size_t align)
+{
+	return __alloc_percpu(sz, align);
+}
+
rust/helpers/preempt.c new file +14 -0
new file mode 100644
index 000000000000..2c7529528ddd
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/preempt.h>
+
+void rust_helper_preempt_disable(void)
+{
+	preempt_disable();
+}
+
+void rust_helper_preempt_enable(void)
+{
+	preempt_enable();
+}
+
Signature · 2 lines
-- 
2.34.1
#3 lore raw

Re: [PATCH v4 1/9] rust: cpumask: Add a `Cpumask` iterator

In reply to Yury Norov
Quoted 43 lines · Yury Norov
Quoted 42 lines · Mitchell Levy

Add an iterator for Cpumask making use of C's cpumask_next.

---
 rust/helpers/cpumask.c |  5 +++++
 rust/kernel/cpumask.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 52 insertions(+), 1 deletion(-)
rust/helpers/cpumask.c +5 -0
index eb10598a0242..d95bfa111191 100644
@@ -42,6 +42,11 @@ bool rust_helper_cpumask_full(struct cpumask *srcp)
 	return cpumask_full(srcp);
 }
 
+unsigned int rust_helper_cpumask_next(int n, struct cpumask *srcp)
+{
+	return cpumask_next(n, srcp);
+}
+
 unsigned int rust_helper_cpumask_weight(struct cpumask *srcp)
 {
 	return cpumask_weight(srcp);
rust/kernel/cpumask.rs +1 -1
index 3fcbff438670..b7401848f59e 100644
@@ -6,7 +6,7 @@
 
 use crate::{
     alloc::{AllocError, Flags},
-    cpu::CpuId,
+    cpu::{self, CpuId},
     prelude::*,
     types::Opaque,
 };
@@ -161,6 +161,52 @@ pub fn copy(&self, dstp: &mut Self) {
     }
 }
 
Quoted 6 lines

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 167

Quoted 4 lines
rust/kernel/cpumask.rs +4 -0
+/// Iterator for a `Cpumask`.
+pub struct CpumaskIter<'a> {
+    mask: &'a Cpumask,
+    last: Option<u32>,

This is not the last, it's a current CPU.

Ah, I meant it in the sense of "the last cpuid we've seen", though now that you point it out I agree the naming here is poor. Will correct to current.

Quoted 30 lines
Quoted 17 lines
rust/kernel/cpumask.rs +17 -0
+}
+
+impl<'a> CpumaskIter<'a> {
+    /// Creates a new `CpumaskIter` for the given `Cpumask`.
+    fn new(mask: &'a Cpumask) -> CpumaskIter<'a> {
+        Self { mask, last: None }
+    }
+}
+
+impl<'a> Iterator for CpumaskIter<'a> {
+    type Item = CpuId;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        // SAFETY: By the type invariant, `self.mask.as_raw` is a `struct cpumask *`.
+        let next = unsafe {
+            bindings::cpumask_next(
+                if let Some(last) = self.last {

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 194

Quoted 10 lines
rust/kernel/cpumask.rs +10 -0
+                    last.try_into().unwrap()
+                } else {
+                    -1
+                },
+                self.mask.as_raw(),
+            )
+        };
+
+        if next == cpu::nr_cpu_ids() {
+            None

Please: if next >= cpu::nr_cpu_ids() {

Quoted 7 lines

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 197

Quoted 3 lines
rust/kernel/cpumask.rs +3 -0
+        } else {
+            self.last = Some(next);
+            // SAFETY: `cpumask_next` returns either `nr_cpu_ids` or a valid CPU ID.

Now that you've handled the no-found case in the previous block, the comment doesn't look correct. Can you either move it on top of the if-else, or just drop entirely?

Actually, now that I'm looking at this again, I think this whole if-else thing should just be:

```
CpuId::from_u32(next)
```

which does exactly what we want here. I think this should address both of your concerns, though please let me know if it doesn't.

Thanks,
Mitchell

Quoted 18 lines
Quoted 18 lines
rust/kernel/cpumask.rs +12 -0
+            unsafe { Some(CpuId::from_u32_unchecked(next)) }
+        }
+    }
+}
+
+impl Cpumask {
+    /// Returns an iterator over the set bits in the cpumask.
+    pub fn iter(&self) -> CpumaskIter<'_> {
+        CpumaskIter::new(self)
+    }
+}
+
 /// A CPU Mask pointer.
 ///
 /// Rust abstraction for the C `struct cpumask_var_t`.
Signature · 2 lines
-- 
2.34.1
#7 lore raw

Re: [PATCH v4 2/9] rust: cpumask: Add getters for globally defined cpumasks

In reply to Yury Norov
Quoted 24 lines · Yury Norov
Quoted 23 lines · Mitchell Levy

Add getters for the global cpumasks documented in
include/linux/cpumask.h, specifically:
- cpu_possible_mask
- cpu_online_mask
- cpu_enabled_mask
- cpu_present_mask
- cpu_active_mask

---
 rust/kernel/cpumask.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
rust/kernel/cpumask.rs +0 -0
index b7401848f59e..a6a130092fcb 100644
@@ -77,6 +77,52 @@ pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self {
         unsafe { &*ptr.cast() }
     }
 
Quoted 11 lines

rust/kernel/cpumask.rs pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self { · line 86

Quoted 7 lines
rust/kernel/cpumask.rs +7 -0
+    /// Get a CPU mask representing possible CPUs; has bit `cpu` set iff cpu is populatable
+    #[inline]
+    pub fn possible_cpus() -> &'static Self {
+        // SAFETY: `__cpu_possible_mask` is a valid global provided by the kernel that lives
+        // forever.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_possible_mask) }
+    }

Not sure about this '&raw const' syntax, but I want to make sure that all this getters provide non-modifiable references. To modify any of those masks, one has to call a dedicated helper like set_cpu_possible().

For id: T, the syntax &raw const id produces a *const T pointing at id (the analogous syntax &raw mut id produces a *mut T).

All getters here provide const references (&'static Self as opposed to &'static mut Self) which will cause the compiler to prevent usage of any Cpumask methods with a &mut self reciever (i.e., methods that change the Cpumask).

Quoted 1 line

Can you maybe explicitly mention it in the comments?

The compiler will prevent using these values to change the underlying __cpu_possible_mask etc, so mentioning that these return values can't be used for that purpose seems redundant to me.

It is possible someone could get the pointer out via Cpumask::as_raw, and then do something bad with that pointer, but this isn't any different than someone doing something bad with bindings::__cpu_possible_mask.

Thanks,
Mitchell

Quoted 48 lines

With that,

Quoted 44 lines
rust/kernel/cpumask.rs +38 -0
+    /// Get a CPU mask representing online CPUs; has bit `cpu` set iff cpu available to the
+    /// scheduler
+    #[inline]
+    pub fn online_cpus() -> &'static Self {
+        // SAFETY: `__cpu_online_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_online_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_online_mask) }
+    }
+
+    /// Get a CPU mask representing enabled CPUs; has bit `cpu` set iff cpu can be brought online
+    #[inline]
+    pub fn enabled_cpus() -> &'static Self {
+        // SAFETY: `__cpu_enabled_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_enabled_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_enabled_mask) }
+    }
+
+    /// Get a CPU mask representing present CPUs; has bit `cpu` set iff cpu is populated
+    #[inline]
+    pub fn present_cpus() -> &'static Self {
+        // SAFETY: `__cpu_present_mask` is a valid global provided by the kernel that lives
+        // forever. Since we wrap the returned pointer in an `Opaque`, it's ok that
+        // `__cpu_present_mask` may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_present_mask) }
+    }
+
+    /// Get a CPU mask representing active CPUs; has bit `cpu` set iff cpu is available to
+    /// migration.
+    #[inline]
+    pub fn active_cpus() -> &'static Self {
+        // SAFETY: `__cpu_active_mask` is a valid global provided by the kernel that lives forever.
+        // Since we wrap the returned pointer in an `Opaque`, it's ok that `__cpu_active_mask`
+        // may change its value.
+        unsafe { Cpumask::as_ref(&raw const bindings::__cpu_active_mask) }
+    }
+
     /// Obtain the raw `struct cpumask` pointer.
     pub fn as_raw(&self) -> *mut bindings::cpumask {
         let this: *const Self = self;
Signature · 2 lines
-- 
2.34.1
maintainer
#4 lore raw

Re: [PATCH v4 1/9] rust: cpumask: Add a `Cpumask` iterator

In reply to Mitchell Levy
Quoted 93 lines · Mitchell Levy
Quoted 43 lines · Yury Norov
Quoted 42 lines · Mitchell Levy

Add an iterator for Cpumask making use of C's cpumask_next.

---
 rust/helpers/cpumask.c |  5 +++++
 rust/kernel/cpumask.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 52 insertions(+), 1 deletion(-)
rust/helpers/cpumask.c +5 -0
index eb10598a0242..d95bfa111191 100644
@@ -42,6 +42,11 @@ bool rust_helper_cpumask_full(struct cpumask *srcp)
 	return cpumask_full(srcp);
 }
 
+unsigned int rust_helper_cpumask_next(int n, struct cpumask *srcp)
+{
+	return cpumask_next(n, srcp);
+}
+
 unsigned int rust_helper_cpumask_weight(struct cpumask *srcp)
 {
 	return cpumask_weight(srcp);
rust/kernel/cpumask.rs +1 -1
index 3fcbff438670..b7401848f59e 100644
@@ -6,7 +6,7 @@
 
 use crate::{
     alloc::{AllocError, Flags},
-    cpu::CpuId,
+    cpu::{self, CpuId},
     prelude::*,
     types::Opaque,
 };
@@ -161,6 +161,52 @@ pub fn copy(&self, dstp: &mut Self) {
     }
 }
 
Quoted 6 lines

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 167

Quoted 4 lines
rust/kernel/cpumask.rs +4 -0
+/// Iterator for a `Cpumask`.
+pub struct CpumaskIter<'a> {
+    mask: &'a Cpumask,
+    last: Option<u32>,

This is not the last, it's a current CPU.

Ah, I meant it in the sense of "the last cpuid we've seen", though now that you point it out I agree the naming here is poor. Will correct to current.

Quoted 30 lines
Quoted 17 lines
rust/kernel/cpumask.rs +17 -0
+}
+
+impl<'a> CpumaskIter<'a> {
+    /// Creates a new `CpumaskIter` for the given `Cpumask`.
+    fn new(mask: &'a Cpumask) -> CpumaskIter<'a> {
+        Self { mask, last: None }
+    }
+}
+
+impl<'a> Iterator for CpumaskIter<'a> {
+    type Item = CpuId;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        // SAFETY: By the type invariant, `self.mask.as_raw` is a `struct cpumask *`.
+        let next = unsafe {
+            bindings::cpumask_next(
+                if let Some(last) = self.last {

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 194

Quoted 10 lines
rust/kernel/cpumask.rs +10 -0
+                    last.try_into().unwrap()
+                } else {
+                    -1
+                },
+                self.mask.as_raw(),
+            )
+        };
+
+        if next == cpu::nr_cpu_ids() {
+            None

Please: if next >= cpu::nr_cpu_ids() {

Quoted 7 lines

rust/kernel/cpumask.rs pub fn copy(&self, dstp: &mut Self) { · line 197

Quoted 3 lines
rust/kernel/cpumask.rs +3 -0
+        } else {
+            self.last = Some(next);
+            // SAFETY: `cpumask_next` returns either `nr_cpu_ids` or a valid CPU ID.

Now that you've handled the no-found case in the previous block, the comment doesn't look correct. Can you either move it on top of the if-else, or just drop entirely?

Quoted 7 lines

Actually, now that I'm looking at this again, I think this whole if-else thing should just be:

```
CpuId::from_u32(next)
```

which does exactly what we want here. I think this should address both of your concerns, though please let me know if it doesn't.

Looks like that.

#11 lore raw

Re: [PATCH v4 4/9] rust: percpu: introduce a rust API for static per-CPU variables

In reply to Mitchell Levy

Hi Mitchell,

Quoted 5 lines · Mitchell Levy

Per-CPU variables are an important tool for reducing lock contention, especially in systems with many processors. They also provide a convenient way to handle data that are logically associated with a particular CPU (e.g., the currently running task).

Quoted 8 lines

Therefore, add a Rust API to make use of statically-allocated per-CPU variables. Add a RAII CpuGuard type for disabling CPU preemption. Introduce unifying abstractions that can be reused for a Rust API for dynamically-allocated per-CPU variables.

I had to do the following change to make the doctests build when applying to v6.18-rc5:

commit 47fc7e30ab0fbcc7262b846286b4bae5124d858e

Author: Andreas Hindborg <[email protected]>
Date:   Fri Nov 14 15:43:47 2025 +0100

fixup! LIST: [PATCH v4 4/9] rust: percpu: introduce a rust API for static per-CPU variables

rust/kernel/percpu/static_.rs +1 -1
index 418fc2fa06f20..bf053e260f0c5 100644
@@ -162,7 +162,7 @@ pub unsafe trait PerCpuSyncMarkerType {
 /// # Example
 /// ```
 /// use kernel::define_per_cpu;
-/// use kernel::percpu::StaticPerCpuSymbol;
+/// use kernel::percpu::{PerCpuSyncMarkerType, StaticPerCpuSymbol};
 ///
 /// define_per_cpu!(pub MY_PERCPU: u64 = 0);
 /// ```

Best regards,
Andreas Hindborg

#16 lore raw

Re: [PATCH v4 7/9] rust: percpu: Support non-zeroable types for DynamicPerCpu

In reply to Mitchell Levy
Quoted 22 lines · Mitchell Levy

Add functionality to PerCpuPtr to compute pointers to per-CPU variable slots on other CPUs. Use this facility to initialize per-CPU variables on all possible CPUs when a dynamic per-CPU variable is created with a non-zeroable type. Since RefCell and other Cell-like types fall into this category, impl CheckedPerCpu on DynamicPerCpu for these InteriorMutable types since they can now be used. Add examples of these usages to samples/rust/rust_percpu.rs. Add a test to ensure dynamic per-CPU variables properly drop their contents, done here since non-trivially dropped types often aren't Zeroable.

---
 rust/kernel/percpu/dynamic.rs |  44 +++++++++++++++++
 samples/rust/rust_percpu.rs   | 109 +++++++++++++++++++++++++++++++++++++++---
 2 files changed, 146 insertions(+), 7 deletions(-)
rust/kernel/percpu/dynamic.rs +0 -0
index 1863f31a2817..a74c8841aeb2 100644
@@ -89,6 +89,36 @@ pub fn new_zero(flags: Flags) -> Option<Self> {
     }

rust/kernel/percpu/dynamic.rs pub fn new_zero(flags: Flags) -> Option<Self> { · line 99

Quoted 10 lines
rust/kernel/percpu/dynamic.rs +8 -0
 }
 
+impl<T: Clone> DynamicPerCpu<T> {
+    /// Allocates a new per-CPU variable
+    ///
+    /// # Arguments
+    /// * `val` - The initial value of the per-CPU variable on all CPUs.
+    /// * `flags` - Flags used to allocate an [`Arc`] that keeps track of the underlying
+    ///   [`PerCpuAllocation`].
+    pub fn new_with(val: &T, flags: Flags) -> Option<Self> {

It would be great to be able to pass a closure here that can be used to populate the value. Then the value does not have to be Clone.

Best regards,
Andreas Hindborg

#13 lore raw

Re: [PATCH v4 5/9] rust: percpu: introduce a rust API for dynamic per-CPU variables

In reply to Mitchell Levy
Quoted 16 lines · Mitchell Levy

Dynamically allocated per-CPU variables are core to many of the use-cases of per-CPU variables (e.g., ref counting). Add support for them using the core PerCpuPtr<T> primitive, implementing the PerCpu<T> trait.

---
 rust/helpers/percpu.c         |  10 ++++
 rust/kernel/percpu.rs         |  30 ++++++++--
 rust/kernel/percpu/dynamic.rs | 130 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 166 insertions(+), 4 deletions(-)
rust/helpers/percpu.c +0 -0
index a091389f730f..35656333dfae 100644

<cut>

Quoted 63 lines
rust/kernel/percpu/dynamic.rs new file +57 -0
new file mode 100644
index 000000000000..1863f31a2817
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: GPL-2.0
+//! Dynamically allocated per-CPU variables.
+
+use super::*;
+
+use crate::alloc::Flags;
+use crate::bindings::{alloc_percpu, free_percpu};
+use crate::cpumask::Cpumask;
+use crate::prelude::*;
+use crate::sync::Arc;
+use core::mem::{align_of, size_of, MaybeUninit};
+
+/// Represents a dynamic allocation of a per-CPU variable via `alloc_percpu`. Calls `free_percpu`
+/// when dropped.
+///
+/// # Contents
+/// Note that the allocated memory need not be initialized, and this type does not track when/if
+/// the memory location on any particular CPU has been initialized. This means that it cannot tell
+/// whether it should drop the *contents* of the allocation when it is dropped. It is up to the
+/// user to do this via something like [`core::ptr::drop_in_place`].
+pub struct PerCpuAllocation<T>(PerCpuPtr<T>);
+
+impl<T: Zeroable> PerCpuAllocation<T> {
+    /// Dynamically allocates a space in the per-CPU area suitably sized and aligned to hold a `T`,
+    /// initially filled with the zero value for `T`.
+    ///
+    /// Returns [`None`] under the same circumstances the C function `alloc_percpu` returns `NULL`.
+    pub fn new_zero() -> Option<PerCpuAllocation<T>> {
+        let ptr: *mut MaybeUninit<T> =
+            // SAFETY: No preconditions to call `alloc_percpu`; `MaybeUninit<T>` is
+            // `#[repr(transparent)]`, so we can cast a `*mut T` to it.
+            unsafe { alloc_percpu(size_of::<T>(), align_of::<T>()) }.cast();
+        if ptr.is_null() {
+            return None;
+        }
+
+        // alloc_percpu returns zero'ed memory
+        Some(Self(PerCpuPtr::new(ptr)))
+    }
+}
+
+impl<T> PerCpuAllocation<T> {
+    /// Makes a per-CPU allocation sized and aligned to hold a `T`.
+    ///
+    /// Returns [`None`] under the same circumstances the C function `alloc_percpu` returns `NULL`.
+    pub fn new_uninit() -> Option<PerCpuAllocation<T>> {
+        let ptr: *mut MaybeUninit<T> =
+            // SAFETY: No preconditions to call `alloc_percpu`; `MaybeUninit<T>` is
+            // `#[repr(transparent)]`, so we can cast a `*mut T` to it.
+            unsafe { alloc_percpu(size_of::<T>(), align_of::<T>()) }.cast();
+        if ptr.is_null() {
+            return None;
+        }
+
+        Some(Self(PerCpuPtr::new(ptr)))
+    }
+}

rust/kernel/percpu/dynamic.rs line 67

Quoted 10 lines
rust/kernel/percpu/dynamic.rs new file +10 -0
+
+impl<T> Drop for PerCpuAllocation<T> {
+    fn drop(&mut self) {
+        // SAFETY: self.0.0 was returned by alloc_percpu, and so was a valid pointer into
+        // the percpu area, and has remained valid by the invariants of PerCpuAllocation<T>.
+        unsafe { free_percpu(self.0 .0.cast()) }
+    }
+}
+
+/// Holds a dynamically-allocated per-CPU variable.

Can we place an example here? It was a bit difficult for me to figure out how to use this from browsing the documentation. Perhaps we can lift some of the sample out and add it as a documentation example here?

Best regards,
Andreas Hindborg