rust: cpu: Add CpuId::current() to retrieve current CPU ID
authorViresh Kumar <viresh.kumar@linaro.org>
Mon, 9 Jun 2025 11:14:16 +0000 (16:44 +0530)
committerViresh Kumar <viresh.kumar@linaro.org>
Thu, 12 Jun 2025 05:01:28 +0000 (10:31 +0530)
Introduce `CpuId::current()`, a constructor that wraps the C function
`raw_smp_processor_id()` to retrieve the current CPU identifier without
guaranteeing stability.

This function should be used only when the caller can ensure that
the CPU ID won't change unexpectedly due to preemption or migration.

Suggested-by: Boqun Feng <boqun.feng@gmail.com>
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
MAINTAINERS
rust/helpers/cpu.c [new file with mode: 0644]
rust/helpers/helpers.c
rust/kernel/cpu.rs

index a92290fffa163f9fe8fe3f04bf66426f9a894409..4255186784c49816f30c80b5aaba622b128caa8c 100644 (file)
@@ -6254,6 +6254,7 @@ F:        include/linux/cpuhotplug.h
 F:     include/linux/smpboot.h
 F:     kernel/cpu.c
 F:     kernel/smpboot.*
+F:     rust/helper/cpu.c
 F:     rust/kernel/cpu.rs
 
 CPU IDLE TIME MANAGEMENT FRAMEWORK
diff --git a/rust/helpers/cpu.c b/rust/helpers/cpu.c
new file mode 100644 (file)
index 0000000..824e0ad
--- /dev/null
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/smp.h>
+
+unsigned int rust_helper_raw_smp_processor_id(void)
+{
+       return raw_smp_processor_id();
+}
index 0f1b5d11598591bc62bb6439747211af164b76d6..16fa9bca5949b85e8d4cdcfe8e6886124f72d8d8 100644 (file)
@@ -13,6 +13,7 @@
 #include "build_assert.c"
 #include "build_bug.c"
 #include "clk.c"
+#include "cpu.c"
 #include "cpufreq.c"
 #include "cpumask.c"
 #include "cred.c"
index abc780d7a8ec64e82e6d87148a82cfeade206d0f..b75403b0eb5614e5652e6cad9341ae217edbe5bb 100644 (file)
@@ -102,6 +102,17 @@ impl CpuId {
     pub fn as_u32(&self) -> u32 {
         self.0
     }
+
+    /// Returns the ID of the CPU the code is currently running on.
+    ///
+    /// The returned value is considered unstable because it may change
+    /// unexpectedly due to preemption or CPU migration. It should only be
+    /// used when the context ensures that the task remains on the same CPU
+    /// or the users could use a stale (yet valid) CPU ID.
+    pub fn current() -> Self {
+        // SAFETY: raw_smp_processor_id() always returns a valid CPU ID.
+        unsafe { Self::from_u32_unchecked(bindings::raw_smp_processor_id()) }
+    }
 }
 
 impl From<CpuId> for u32 {