Skip to content

Commit 3accb57

Browse files
committed
rust: cpu: Add from_cpu()
This implements cpu::from_cpu(), which returns a reference to Device for a CPU. The C struct is created at initialization time for CPUs and is never freed and so ARef isn't returned from this function. The new helper will be used by Rust based cpufreq drivers. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
1 parent a4e3b76 commit 3accb57

File tree

4 files changed

+33
-0
lines changed

4 files changed

+33
-0
lines changed

MAINTAINERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6155,6 +6155,7 @@ F: include/linux/cpuhotplug.h
61556155
F: include/linux/smpboot.h
61566156
F: kernel/cpu.c
61576157
F: kernel/smpboot.*
6158+
F: rust/kernel/cpu.rs
61586159

61596160
CPU IDLE TIME MANAGEMENT FRAMEWORK
61606161
M: "Rafael J. Wysocki" <rafael@kernel.org>

rust/bindings/bindings_helper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <linux/blk_types.h>
1212
#include <linux/blkdev.h>
1313
#include <linux/clk.h>
14+
#include <linux/cpu.h>
1415
#include <linux/cpumask.h>
1516
#include <linux/cred.h>
1617
#include <linux/device/faux.h>

rust/kernel/cpu.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Generic CPU definitions.
4+
//!
5+
//! C header: [`include/linux/cpu.h`](srctree/include/linux/cpu.h)
6+
7+
use crate::{bindings, device::Device, error::Result, prelude::ENODEV};
8+
9+
/// Creates a new instance of CPU's device.
10+
///
11+
/// # Safety
12+
///
13+
/// Reference counting is not implemented for the CPU device in the C code. When a CPU is
14+
/// hot-unplugged, the corresponding CPU device is unregistered, but its associated memory
15+
/// is not freed.
16+
///
17+
/// Callers must ensure that the CPU device is not used after it has been unregistered.
18+
/// This can be achieved, for example, by registering a CPU hotplug notifier and removing
19+
/// any references to the CPU device within the notifier's callback.
20+
pub unsafe fn from_cpu(cpu: u32) -> Result<&'static Device> {
21+
// SAFETY: It is safe to call `get_cpu_device()` for any CPU.
22+
let ptr = unsafe { bindings::get_cpu_device(cpu) };
23+
if ptr.is_null() {
24+
return Err(ENODEV);
25+
}
26+
27+
// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to
28+
// a `struct device` and is never freed by the C code.
29+
Ok(unsafe { Device::as_ref(ptr) })
30+
}

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ pub mod block;
4343
#[doc(hidden)]
4444
pub mod build_assert;
4545
pub mod clk;
46+
pub mod cpu;
4647
pub mod cpumask;
4748
pub mod cred;
4849
pub mod device;

0 commit comments

Comments
 (0)