Skip to content

Commit c7f005f

Browse files
committed
rust: cpu: Add CpuId::current() to retrieve current CPU ID
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 <[email protected]> Signed-off-by: Viresh Kumar <[email protected]> Reviewed-by: Boqun Feng <[email protected]>
1 parent 33db8c9 commit c7f005f

File tree

4 files changed

+21
-0
lines changed

4 files changed

+21
-0
lines changed

MAINTAINERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6254,6 +6254,7 @@ F: include/linux/cpuhotplug.h
62546254
F: include/linux/smpboot.h
62556255
F: kernel/cpu.c
62566256
F: kernel/smpboot.*
6257+
F: rust/helper/cpu.c
62576258
F: rust/kernel/cpu.rs
62586259

62596260
CPU IDLE TIME MANAGEMENT FRAMEWORK

rust/helpers/cpu.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
#include <linux/smp.h>
4+
5+
unsigned int rust_helper_raw_smp_processor_id(void)
6+
{
7+
return raw_smp_processor_id();
8+
}

rust/helpers/helpers.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include "build_assert.c"
1414
#include "build_bug.c"
1515
#include "clk.c"
16+
#include "cpu.c"
1617
#include "cpufreq.c"
1718
#include "cpumask.c"
1819
#include "cred.c"

rust/kernel/cpu.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,17 @@ impl CpuId {
102102
pub fn as_u32(&self) -> u32 {
103103
self.0
104104
}
105+
106+
/// Returns the ID of the CPU the code is currently running on.
107+
///
108+
/// The returned value is considered unstable because it may change
109+
/// unexpectedly due to preemption or CPU migration. It should only be
110+
/// used when the context ensures that the task remains on the same CPU
111+
/// or the users could use a stale (yet valid) CPU ID.
112+
pub fn current() -> Self {
113+
// SAFETY: raw_smp_processor_id() always returns a valid CPU ID.
114+
unsafe { Self::from_u32_unchecked(bindings::raw_smp_processor_id()) }
115+
}
105116
}
106117

107118
impl From<CpuId> for u32 {

0 commit comments

Comments
 (0)