Rust abstractions for clk, cpumask, cpufreq, OPP
Subsystems (8)
Viresh Kumar
maintainerv9 cover Rust abstractions for clk, cpumask, cpufreq, OPP
Hello,
This series introduces initial Rust abstractions for a few subsystems: clk, cpumask, cpufreq and Operating Performance Points (OPP).
After the previous version (V8) was posted, patches for clk and cpumask abstractions were sent separately for thorough review. Now that most of the reviews are done for them, I am sending them with client code (cpufreq/opp) again. Yury also suggested the same earlier.
The abstractions cover most of the interfaces exposed by cpufreq and OPP subsystems. It also includes minimal abstractions for the clk and cpumask frameworks, which are required by the cpufreq / OPP abstractions.
Additionally, a sample rcpufreq-dt driver is included. This is a duplicate of the existing cpufreq-dt driver, which is a platform-agnostic, device-tree based cpufreq driver commonly used on ARM platforms.
The implementation has been tested using QEMU, ensuring that frequency transitions, various configurations, and driver binding/unbinding work as expected. However, performance measurements have not been conducted yet.
For those interested in testing these patches, they can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/vireshk/pm.git rust/cpufreq-dt
Based on 6.15-rc1.
V8->V9:
- clk (changes since V4):
- V4: https://lore.kernel.org/all/[email protected]/
- Add more methods in Hertz (as_khz/mhz/ghz).
- Reword a comment.
- cpumask (changes since V4):
- V4: https://lore.kernel.org/all/[email protected]/
- Add support for cpumask_{test_cpu|empty|full} and switch to using non-atomic helpers for set/clear.
- s/CpumaskBox/CpumaskVar/
- s/set_all/setall/
- Improved examples, comments and commit logs.
- cpufreq/opp:
- V8: https://lore.kernel.org/all/[email protected]/
- Based on review comments received for clk/cpumask, a lot of changes were made to cpufreq/opp bindings in code, comments, examples, etc..
- attr fields were dropped from cpufreq support, not required anymore because of latest changes in cpufreq core.
- Use Hertz/MicroVolt/MicroWatt as units.
- Lots of other cleanups.
- Dropped Reviewed-by from Manos (there were too many changes).
V7->V8:
- Updated cpumask bindings to work with !CONFIG_CPUMASK_OFFSTACK case.
- Dropped few patches (property_present() and opp helpers), as they are already merged.
- from_cpu() is marked unsafe.
- Included a patch by Anisse Astier, to solve a long standing issue with this series.
- Dropped: "DO-NOT_MERGE: cpufreq: Rename cpufreq-dt platdev."
- Updated MAINTAINERS for new files.
- Other minor changes / cleanups.
V6->V7:
- from_cpu() is moved to cpu.rs and doesn't return ARef anymore, but just a reference.
- Dropped cpufreq_table_len() and related validation in cpufreq core.
- Solved the issue with BIT() macro differently, using an enum now.
- Few patches are broken into smaller / independent patches.
- Improved Commit logs and SAFETY comments at few places.
- Removed print message from cpufreq driver.
- Rebased over linux-next/master.
- Few other minor changes.
V5->V6:
- Rebase over latest rust/dev branch, which changed few interfaces that the patches were using.
- Included all other patches, which weren't included until now to focus only on core APIs.
- Other minor cleanups, additions.
V4->V5:
- Rename Registration::register() as new().
- Provide a new API: Registration::new_foreign_owned() and use it for rcpufreq_dt driver.
- Update MAINTAINERS file.
V3->V4:
- Fix bugs with freeing of OPP structure. Dropped the Drop routine and fixed reference counting.
- Registration object of the cpufreq core is modified a bit to remove the registered field, and few other cleanups.
- Use Devres for instead of platform data.
- Improve SAFETY comments.
V2->V3:
- Rebased on latest rust-device changes, which removed Data and so few changes were required to make it work.
- use srctree links (Alice Ryhl).
- Various changes the OPP creation APIs, new APIs: from_raw_opp() and from_raw_opp_owned() (Alice Ryhl).
- Inline as_raw() helpers (Alice Ryhl).
- Add new interface (OPP::Token) for dynamically created OPPs.
- Add Reviewed-by tag from Manos.
- Modified/simplified cpufreq registration structure / method a bit.
V1->V2:
- Create and use separate bindings for OF, clk, cpumask, etc (not included in this patchset but pushed to the above branch). This helped removing direct calls from the driver.
- Fix wrong usage of Pinning + Vec.
- Use Token for OPP Config.
- Use Opaque, transparent and Aref for few structures.
- Broken down into smaller patches to make it easy for reviewers.
- Based over staging/rust-device.
--
Viresh
Anisse Astier (1):
rust: macros: enable use of hyphens in module names
Viresh Kumar (16):
rust: cpumask: Use non-atomic helpers
rust: cpumask: Add few more helpers
rust: cpumask: Add initial abstractions
MAINTAINERS: Add entry for Rust cpumask API
rust: clk: Add helpers for Rust code
rust: clk: Add initial abstractions
cpufreq: Use enum for cpufreq flags that use BIT()
rust: cpu: Add from_cpu()
rust: opp: Add initial abstractions for OPP framework
rust: opp: Add abstractions for the OPP table
rust: opp: Add abstractions for the configuration options
rust: cpufreq: Add initial abstractions for cpufreq framework
rust: cpufreq: Extend abstractions for policy and driver ops
rust: cpufreq: Extend abstractions for driver registration
rust: opp: Extend OPP abstractions with cpufreq support
cpufreq: Add Rust-based cpufreq-dt driver
MAINTAINERS | 11 + drivers/cpufreq/Kconfig | 12 + drivers/cpufreq/Makefile | 1 + drivers/cpufreq/rcpufreq_dt.rs | 236 ++++++ include/linux/cpufreq.h | 96 +-- rust/bindings/bindings_helper.h | 4 + rust/helpers/clk.c | 66 ++ rust/helpers/cpufreq.c | 10 + rust/helpers/cpumask.c | 23 +- rust/helpers/helpers.c | 2 + rust/kernel/clk.rs | 319 ++++++++ rust/kernel/cpu.rs | 31 + rust/kernel/cpufreq.rs | 1320 +++++++++++++++++++++++++++++++ rust/kernel/cpumask.rs | 328 ++++++++ rust/kernel/lib.rs | 8 + rust/kernel/opp.rs | 1151 +++++++++++++++++++++++++++ rust/macros/module.rs | 20 +- 17 files changed, 3581 insertions(+), 57 deletions(-) create mode 100644 drivers/cpufreq/rcpufreq_dt.rs create mode 100644 rust/helpers/clk.c create mode 100644 rust/helpers/cpufreq.c create mode 100644 rust/kernel/clk.rs create mode 100644 rust/kernel/cpu.rs create mode 100644 rust/kernel/cpufreq.rs create mode 100644 rust/kernel/cpumask.rs create mode 100644 rust/kernel/opp.rs
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 1/17 rust: cpumask: Use non-atomic helpers
The cpumask Rust abstractions don't need the atomic variants of helpers for now. Use the non-atomic helpers instead.
--- rust/helpers/cpumask.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
rust/helpers/cpumask.c +4 -4
@@ -2,14 +2,14 @@#include <linux/cpumask.h> -void rust_helper_cpumask_set_cpu (unsigned int cpu,struct cpumask *dstp) +void rust_helper___cpumask_set_cpu (unsigned int cpu,struct cpumask *dstp) { -cpumask_set_cpu (cpu, dstp); +__cpumask_set_cpu (cpu, dstp); } -void rust_helper_cpumask_clear_cpu (int cpu,struct cpumask *dstp) +void rust_helper___cpumask_clear_cpu (int cpu,struct cpumask *dstp) { -cpumask_clear_cpu (cpu, dstp); +__cpumask_clear_cpu (cpu, dstp); }void rust_helper_cpumask_setall (struct cpumask *dstp)
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 2/17 rust: cpumask: Add few more helpers
In reply to Viresh KumarAdd few more cpumask helpers that are required by the Rust abstraction.
--- rust/helpers/cpumask.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
rust/helpers/cpumask.c +15 -0
@@ -12,11 +12,26 @@ void rust_helper___cpumask_clear_cpu(int cpu, struct cpumask *dstp)__cpumask_clear_cpu (cpu, dstp); } +bool rust_helper_cpumask_test_cpu (int cpu,struct cpumask *srcp) +{ +return cpumask_test_cpu (cpu, srcp); +} +void rust_helper_cpumask_setall (struct cpumask *dstp) {cpumask_setall (dstp); } +bool rust_helper_cpumask_empty (struct cpumask *srcp) +{ +return cpumask_empty (srcp); +} + +bool rust_helper_cpumask_full (struct cpumask *srcp) +{ +return cpumask_full (srcp); +} +unsigned int rust_helper_cpumask_weight (struct cpumask *srcp) {return cpumask_weight (srcp);
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 3/17 rust: cpumask: Add initial abstractions
In reply to Viresh KumarAdd initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed.
These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks.
--- rust/kernel/cpumask.rs | 328 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 329 insertions(+) create mode 100644 rust/kernel/cpumask.rs
rust/kernel/cpumask.rs new file +328 -0
@@ -0,0 +1,328 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU Mask abstractions. +//! +//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h) + +use crate ::{ + alloc::{AllocError ,Flags }, + bindings, + prelude::*, + types::Opaque , +}; + +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +use core::ptr::{self,NonNull }; + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +use core::mem::MaybeUninit ; + +use core::ops::{Deref ,DerefMut }; + +/// A CPU Mask. +/// +/// Rust abstraction for the C `struct cpumask`. +/// +/// # Invariants +/// +/// A [`Cpumask`] instance always corresponds to a valid C `struct cpumask`. +/// +/// The callers must ensure that the `struct cpumask` is valid for access and remains valid for the +/// lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to update a [`Cpumask`]. +/// +/// ``` +/// use kernel::bindings; +/// use kernel::cpumask::Cpumask; +/// +/// fn set_clear_cpu(ptr: *mut bindings::cpumask, set_cpu: u32, clear_cpu: i32) { +/// // SAFETY: The `ptr` is valid for writing and remains valid for the lifetime of the +/// // returned reference. +/// let mask = unsafe { Cpumask::from_raw_mut(ptr) }; +/// +/// mask.set(set_cpu); +/// mask.clear(clear_cpu); +/// } +/// ``` +#[repr(transparent)] +pub struct Cpumask (Opaque <bindings::cpumask >); + +impl Cpumask { +/// Creates a mutable reference to an existing `struct cpumask` pointer. +/// +/// # Safety +/// +/// 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 ) -> &'amut Self { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the +// lifetime of the returned reference. +unsafe { &mut *ptr.cast () } + } + +/// Creates a reference to an existing `struct cpumask` pointer. +/// +/// # Safety +/// +/// 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 ) -> &'aSelf { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the +// lifetime of the returned reference. +unsafe { &*ptr.cast () } + } + +/// Obtain the raw `struct cpumask` pointer. +pub fn as_raw (&self) -> *mut bindings::cpumask { + selfas *const _ as _ + } + +/// Set `cpu` in the cpumask. +/// +/// Equivalent to the kernel's `__cpumask_set_cpu` API. +#[inline] +pub fn set (&mut self, cpu:u32 ) { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `__cpumask_set_cpu`. +unsafe { bindings::__cpumask_set_cpu (cpu, self.as_raw ()) }; + } + +/// Clear `cpu` in the cpumask. +/// +/// Equivalent to the kernel's `__cpumask_clear_cpu` API. +#[inline] +pub fn clear (&mut self, cpu:i32 ) { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to +// `__cpumask_clear_cpu`. +unsafe { bindings::__cpumask_clear_cpu (cpu, self.as_raw ()) }; + } + +/// Test `cpu` in the cpumask. +/// +/// Equivalent to the kernel's `cpumask_test_cpu` API. +#[inline] +pub fn test (&self, cpu:i32 ) ->bool { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_test_cpu`. +unsafe { bindings::cpumask_test_cpu (cpu, self.as_raw ()) } + } + +/// Set all CPUs in the cpumask. +/// +/// Equivalent to the kernel's `cpumask_setall` API. +#[inline] +pub fn setall (&mut self) { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_setall`. +unsafe { bindings::cpumask_setall (self.as_raw ()) }; + } + +/// Checks if cpumask is empty. +/// +/// Equivalent to the kernel's `cpumask_empty` API. +#[inline] +pub fn empty (&self) ->bool { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_empty`. +unsafe { bindings::cpumask_empty (self.as_raw ()) } + } + +/// Checks if cpumask is full. +/// +/// Equivalent to the kernel's `cpumask_full` API. +#[inline] +pub fn full (&self) ->bool { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_full`. +unsafe { bindings::cpumask_full (self.as_raw ()) } + } + +/// Get weight of the cpumask. +/// +/// Equivalent to the kernel's `cpumask_weight` API. +#[inline] +pub fn weight (&self) ->u32 { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_weight`. +unsafe { bindings::cpumask_weight (self.as_raw ()) } + } + +/// Copy cpumask. +/// +/// Equivalent to the kernel's `cpumask_copy` API. +#[inline] +pub fn copy (&self, dstp: &mut Self ) { +// SAFETY: By the type invariant, `Self::as_raw` is a valid argument to `cpumask_copy`. +unsafe { bindings::cpumask_copy (dstp.as_raw (), self.as_raw ()) }; + } +} + +/// A CPU Mask pointer. +/// +/// Rust abstraction for the C `struct cpumask_var_t`. +/// +/// # Invariants +/// +/// A [`CpumaskVar`] instance always corresponds to a valid C `struct cpumask_var_t`. +/// +/// The callers must ensure that the `struct cpumask_var_t` is valid for access and remains valid +/// for the lifetime of [`CpumaskVar`]. +/// +/// ## Examples +/// +/// The following example demonstrates how to create and update a [`CpumaskVar`]. +/// +/// ``` +/// use kernel::cpumask::CpumaskVar; +/// +/// let mut mask = CpumaskVar::new(GFP_KERNEL).unwrap(); +/// +/// assert!(mask.empty()); +/// mask.set(2); +/// assert!(mask.test(2)); +/// mask.set(3); +/// assert!(mask.test(3)); +/// assert_eq!(mask.weight(), 2); +/// +/// let mask2 = CpumaskVar::try_clone(&mask).unwrap(); +/// assert!(mask2.test(2)); +/// assert!(mask2.test(3)); +/// assert_eq!(mask2.weight(), 2); +/// ``` +pub struct CpumaskVar { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr:NonNull <Cpumask >, +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] + mask:Cpumask , +} + +impl CpumaskVar { +/// Creates an initialized instance of the [`CpumaskVar`]. +pub fn new (_flags:Flags ) ->Result <Self ,AllocError > { +Ok (Self { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr: { +let mut ptr: *mut bindings::cpumask = ptr::null_mut (); + +// SAFETY: Depending on the value of `_flags`, this call may sleep. Other than +// that, it is always safe to call this method. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of +// scope. +unsafe { bindings::zalloc_cpumask_var (&mut ptr, _flags.as_raw ()) }; +NonNull ::new (ptr.cast ()).ok_or (AllocError )? + }, + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +// SAFETY: FFI type is valid to be zero-initialized. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of scope. + mask:unsafe { core::mem::zeroed () }, + }) + } + +/// Creates an uninitialized instance of the [`CpumaskVar`]. +/// +/// # Safety +/// +/// The caller must ensure that the returned [`CpumaskVar`] is properly initialized before +/// getting used. +unsafe fn new_uninit (_flags:Flags ) ->Result <Self ,AllocError > { +Ok (Self { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr: { +let mut ptr: *mut bindings::cpumask = ptr::null_mut (); + +// SAFETY: Depending on the value of `_flags`, this call may sleep. Other than +// that, it is always safe to call this method. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of +// scope. +unsafe { bindings::alloc_cpumask_var (&mut ptr, _flags.as_raw ()) }; +NonNull ::new (ptr.cast ()).ok_or (AllocError )? + }, +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of scope. + mask:unsafe {MaybeUninit ::uninit ().assume_init () }, + }) + } + +/// Creates a mutable reference to an existing `struct cpumask_var_t` pointer. +/// +/// # Safety +/// +/// 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_var_t ) -> &'amut Self { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the +// lifetime of the returned reference. +unsafe { &mut *ptr.cast () } + } + +/// Creates a reference to an existing `struct cpumask_var_t` pointer. +/// +/// # Safety +/// +/// 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_var_t ) -> &'aSelf { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the +// lifetime of the returned reference. +unsafe { &*ptr.cast () } + } + +/// Clones cpumask. +pub fn try_clone (cpumask: &Cpumask ) ->Result <Self > { +// SAFETY: The returned cpumask_box is initialized right after this call. +let mut cpumask_box =unsafe {Self ::new_uninit (GFP_KERNEL ) }?; + + cpumask.copy (&mut cpumask_box); +Ok (cpumask_box) + } +} + +// Make [`CpumaskVar`] behave like a pointer to [`Cpumask`]. +impl Deref for CpumaskVar { +type Target =Cpumask ; + +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +fn deref (&self) -> &Self ::Target { +// SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask. +unsafe { &*self.ptr.as_ptr () } + } + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +fn deref (&self) -> &Self ::Target { + &self.mask + } +} + +impl DerefMut for CpumaskVar { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +fn deref_mut (&mut self) -> &mut Cpumask { +// SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask. +unsafe { self.ptr.as_mut () } + } + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +fn deref_mut (&mut self) -> &mut Cpumask { + &mut self.mask + } +} + +impl Drop for CpumaskVar { +fn drop (&mut self) { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `free_cpumask_var`. +unsafe { + bindings::free_cpumask_var (self.as_raw ()) + }; + } +}
rust/kernel/lib.rs +1 -0
@@ -42,6 +42,7 @@pub mod block;#[doc(hidden)] pub mod build_assert; +pub mod cpumask;pub mod cred;pub mod device;pub mod device_id;
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 4/17 MAINTAINERS: Add entry for Rust cpumask API
In reply to Viresh KumarUpdate the MAINTAINERS file to include the Rust abstractions for cpumask API.
Yury has indicated that he does not wish to maintain the Rust code but would like to be listed as a reviewer.
--- MAINTAINERS | 6 ++++++ 1 file changed, 6 insertions(+)
MAINTAINERS +6 -0
@@ -6237,6 +6237,12 @@ L: [email protected] S: Maintained F: drivers/cpuidle/cpuidle-riscv-sbi.c +CPUMASK API [RUST] +M: Viresh Kumar <[email protected]> +R: Yury Norov <[email protected]> +S: Maintained +F: rust/kernel/cpumask.rs + CRAMFS FILESYSTEM M: Nicolas Pitre <[email protected]> S: Maintained
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 5/17 rust: clk: Add helpers for Rust code
In reply to Viresh KumarNon-trivial C macros and inlined C functions cannot be used directly in the Rust code and are used via functions ("helpers") that wrap those so that they can be called from Rust.
In order to prepare for adding Rust abstractions for the clock APIs, add clock helpers required by the Rust implementation.
--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/clk.c | 66 +++++++++++++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 4 files changed, 69 insertions(+) create mode 100644 rust/helpers/clk.c
MAINTAINERS +1 -0
@@ -5883,6 +5883,7 @@ F: include/dt-bindings/clock/ F: include/linux/clk-pr* F: include/linux/clk/ F: include/linux/of_clk.h +F: rust/helpers/clk.c X: drivers/clk/clkdev.c COMMON INTERNET FILE SYSTEM CLIENT (CIFS and SMB3)
rust/bindings/bindings_helper.h +1 -0
@@ -10,6 +10,7 @@#include <linux/blk-mq.h> #include <linux/blk_types.h> #include <linux/blkdev.h> +#include <linux/clk.h> #include <linux/cpumask.h> #include <linux/cred.h> #include <linux/device/faux.h>
rust/helpers/clk.c new file +66 -0
66 lines not on this page · raw message
rust/helpers/helpers.c +1 -0
@@ -11,6 +11,7 @@#include "bug.c" #include "build_assert.c" #include "build_bug.c" +#include "clk.c" #include "cpumask.c" #include "cred.c" #include "device.c"
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 6/17 rust: clk: Add initial abstractions
In reply to Viresh KumarAdd initial abstractions for the clk APIs. These provide the minimal functionality needed for common use cases, making them straightforward to introduce in the first iteration.
These will be used by Rust based cpufreq / OPP layers to begin with.
--- MAINTAINERS | 1 + rust/kernel/clk.rs | 319 +++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 3 files changed, 322 insertions(+) create mode 100644 rust/kernel/clk.rs
MAINTAINERS +1 -0
@@ -5884,6 +5884,7 @@ F: include/linux/clk-pr* F: include/linux/clk/ F: include/linux/of_clk.h F: rust/helpers/clk.c +F: rust/kernel/clk.rs X: drivers/clk/clkdev.c COMMON INTERNET FILE SYSTEM CLIENT (CIFS and SMB3)
rust/kernel/clk.rs new file +319 -0
319 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -42,6 +42,8 @@pub mod block;#[doc(hidden)] pub mod build_assert; +#[cfg( CONFIG_COMMON_CLK )] +pub mod clk;pub mod cpumask;pub mod cred;pub mod device;
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 7/17 rust: macros: enable use of hyphens in module names
In reply to Viresh KumarFrom: Anisse Astier <[email protected]>
Some modules might need naming that contains hyphens "-" to match the auto-probing by name in the platform devices that comes from the device tree.
But rust identifiers cannot contain hyphens, so replace the module name by an underscore anywhere we'd use it as an identifier.
--- rust/macros/module.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-)
rust/macros/module.rs +12 -8
@@ -185,7 +185,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {let info =ModuleInfo ::parse (&mut it); -let mut modinfo =ModInfoBuilder ::new (info.name.as_ref ()); +/* Rust does not allow hyphens in identifiers, use underscore instead */ +let name_identifier = info.name.replace ('-' ,"_" ); +let mut modinfo =ModInfoBuilder ::new (name_identifier.as_ref ());if let Some (author) = info.author { modinfo.emit ("author" , &author); }
@@ -310,14 +312,15 @@ mod __module_init {{#[doc(hidden)] #[link_section = \"{initcall_section}\"] #[used] - pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init; + pub static __{name_identifier}_initcall: extern \"C\" fn() -> + kernel::ffi::c_int = __{name_identifier}_init; #[cfg(not(MODULE))] #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)] core::arch::global_asm!( r#\".section \"{initcall_section}\", \"a\" - __{name}_initcall: - .long __{name}_init - . + __{name_identifier}_initcall: + .long __{name_identifier}_init - . .previous \"# );
@@ -325,7 +328,7 @@ mod __module_init {{#[cfg(not( MODULE ))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{ + pub extern \"C\" fn __{name_identifier}_init() -> kernel::ffi::c_int {{ // SAFETY: This function is inaccessible to the outside due to the double // module wrapping it. It is called exactly once by the C side via its // placement above in the initcall section.
@@ -335,13 +338,13 @@ mod __module_init {{#[cfg(not( MODULE ))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_exit() {{ + pub extern \"C\" fn __{name_identifier}_exit() {{// SAFETY: // - This function is inaccessible to the outside due to the double // module wrapping it. It is called exactly once by the C side via its // unique name, -// - furthermore it is only called after `__{name}_init` has returned `0` -// (which delegates to `__init`). +// - furthermore it is only called after `__{name_identifier}_init` has +// returned `0` (which delegates to `__init`). unsafe {{__exit () }} }}
@@ -381,6 +384,7 @@ unsafe fn __exit() {{", type_ = info.type_, name = info.name, +name_identifier = name_identifier, modinfo = modinfo.buffer, initcall_section = ".initcall6.init" )
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 8/17 cpufreq: Use enum for cpufreq flags that use BIT()
In reply to Viresh KumarThe BIT() macro is too complex for Rust's bindgen to interpret as integer constants. This results in many of the cpufreq macros being undefined in Rust auto-generated bindings. By replacing the "#define" macros with an "enum", we ensure that bindgen can properly evaluate these values, enabling their seamless use in Rust code.
No intentional functional impact.
--- include/linux/cpufreq.h | 96 ++++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 45 deletions(-)
include/linux/cpufreq.h +51 -45
@@ -298,11 +298,12 @@ static inline void cpufreq_stats_record_transition(struct cpufreq_policy *policy* CPUFREQ DRIVER INTERFACE * *********************************************************************/ -#define CPUFREQ_RELATION_L 0/* lowest frequency at or above target */ -#define CPUFREQ_RELATION_H 1/* highest frequency below or at target */ -#define CPUFREQ_RELATION_C 2/* closest frequency to target */ -/* relation flags */ -#define CPUFREQ_RELATION_E BIT(2)/* Get if possible an efficient frequency */ +enum { +CPUFREQ_RELATION_L =0 ,/* lowest frequency at or above target */ +CPUFREQ_RELATION_H =BIT (0 ),/* highest frequency below or at target */ +CPUFREQ_RELATION_C =BIT (1 ),/* closest frequency to target */ +CPUFREQ_RELATION_E =BIT (2 ),/* Get if possible an efficient frequency */ +};#define CPUFREQ_RELATION_LE (CPUFREQ_RELATION_L | CPUFREQ_RELATION_E)#define CPUFREQ_RELATION_HE (CPUFREQ_RELATION_H | CPUFREQ_RELATION_E)
@@ -424,52 +425,57 @@ struct cpufreq_driver {/* flags */ -/* -* Set by drivers that need to update internal upper and lower boundaries along -* with the target frequency and so the core and governors should also invoke -* the diver if the target frequency does not change, but the policy min or max -* may have changed. -*/ -#define CPUFREQ_NEED_UPDATE_LIMITS BIT(0) +enum { +/* +* Set by drivers that need to update internal upper and lower +* boundaries along with the target frequency and so the core and +* governors should also invoke the diver if the target frequency does +* not change, but the policy min or max may have changed. +*/ +CPUFREQ_NEED_UPDATE_LIMITS =BIT (0 ), -/* loops_per_jiffy or other kernel "constants" aren't affected by frequency transitions */ -#define CPUFREQ_CONST_LOOPS BIT(1) +/* +* loops_per_jiffy or other kernel "constants" aren't affected by +* frequency transitions. +*/ +CPUFREQ_CONST_LOOPS =BIT (1 ), -/* -* Set by drivers that want the core to automatically register the cpufreq -* driver as a thermal cooling device. -*/ -#define CPUFREQ_IS_COOLING_DEV BIT(2) +/* +* Set by drivers that want the core to automatically register the +* cpufreq driver as a thermal cooling device. +*/ +CPUFREQ_IS_COOLING_DEV =BIT (2 ), -/* -* This should be set by platforms having multiple clock-domains, i.e. -* supporting multiple policies. With this sysfs directories of governor would -* be created in cpu/cpu<num>/cpufreq/ directory and so they can use the same -* governor with different tunables for different clusters. -*/ -#define CPUFREQ_HAVE_GOVERNOR_PER_POLICY BIT(3) +/* +* This should be set by platforms having multiple clock-domains, i.e. +* supporting multiple policies. With this sysfs directories of governor +* would be created in cpu/cpu<num>/cpufreq/ directory and so they can +* use the same governor with different tunables for different clusters. +*/ +CPUFREQ_HAVE_GOVERNOR_PER_POLICY =BIT (3 ), -/* -* Driver will do POSTCHANGE notifications from outside of their ->target() -* routine and so must set cpufreq_driver->flags with this flag, so that core -* can handle them specially. -*/ -#define CPUFREQ_ASYNC_NOTIFICATION BIT(4) +/* +* Driver will do POSTCHANGE notifications from outside of their +* ->target() routine and so must set cpufreq_driver->flags with this +* flag, so that core can handle them specially. +*/ +CPUFREQ_ASYNC_NOTIFICATION =BIT (4 ), -/* -* Set by drivers which want cpufreq core to check if CPU is running at a -* frequency present in freq-table exposed by the driver. For these drivers if -* CPU is found running at an out of table freq, we will try to set it to a freq -* from the table. And if that fails, we will stop further boot process by -* issuing a BUG_ON(). -*/ -#define CPUFREQ_NEED_INITIAL_FREQ_CHECK BIT(5) +/* +* Set by drivers which want cpufreq core to check if CPU is running at +* a frequency present in freq-table exposed by the driver. For these +* drivers if CPU is found running at an out of table freq, we will try +* to set it to a freq from the table. And if that fails, we will stop +* further boot process by issuing a BUG_ON(). +*/ +CPUFREQ_NEED_INITIAL_FREQ_CHECK =BIT (5 ), -/* -* Set by drivers to disallow use of governors with "dynamic_switching" flag -* set. -*/ -#define CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING BIT(6) +/* +* Set by drivers to disallow use of governors with "dynamic_switching" +* flag set. +*/ +CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING =BIT (6 ), +};int cpufreq_register_driver (struct cpufreq_driver *driver_data);void cpufreq_unregister_driver (struct cpufreq_driver *driver_data);
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 9/17 rust: cpu: Add from_cpu()
In reply to Viresh KumarThis 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.
--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/cpu.rs | 31 +++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 34 insertions(+) create mode 100644 rust/kernel/cpu.rs
MAINTAINERS +1 -0
@@ -6155,6 +6155,7 @@ F: include/linux/cpuhotplug.h F: include/linux/smpboot.h F: kernel/cpu.c F: kernel/smpboot.* +F: rust/kernel/cpu.rs CPU IDLE TIME MANAGEMENT FRAMEWORK M: "Rafael J. Wysocki" <[email protected]>
rust/bindings/bindings_helper.h +1 -0
@@ -11,6 +11,7 @@#include <linux/blk_types.h> #include <linux/blkdev.h> #include <linux/clk.h> +#include <linux/cpu.h> #include <linux/cpumask.h> #include <linux/cred.h> #include <linux/device/faux.h>
rust/kernel/cpu.rs new file +31 -0
@@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Generic CPU definitions. +//! +//! C header: [`include/linux/cpu.h`](srctree/include/linux/cpu.h) + +use crate ::{bindings, device::Device , error::Result , prelude::ENODEV }; + +/// Creates a new instance of CPU's device. +/// +/// # Safety +/// +/// Reference counting is not implemented for the CPU device in the C code. When a CPU is +/// hot-unplugged, the corresponding CPU device is unregistered, but its associated memory +/// is not freed. +/// +/// Callers must ensure that the CPU device is not used after it has been unregistered. +/// This can be achieved, for example, by registering a CPU hotplug notifier and removing +/// any references to the CPU device within the notifier's callback. +pub unsafe fn from_cpu (cpu:u32 ) ->Result <&'staticDevice > { +// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to +// a `struct device` and is never freed by the C code. +let ptr =unsafe { bindings::get_cpu_device (cpu) }; +if ptr.is_null () { +return Err (ENODEV ); + } + +// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to +// a `struct device` and is never freed by the C code. +Ok (unsafe {Device ::as_ref (ptr) }) +}
rust/kernel/lib.rs +1 -0
@@ -44,6 +44,7 @@pub mod build_assert;#[cfg( CONFIG_COMMON_CLK )] pub mod clk; +pub mod cpu;pub mod cpumask;pub mod cred;pub mod device;
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 10/17 rust: opp: Add initial abstractions for OPP framework
In reply to Viresh KumarIntroduce initial Rust abstractions for the Operating Performance Points (OPP) framework. This includes bindings for struct dev_pm_opp and struct dev_pm_opp_data, laying the groundwork for further OPP integration.
--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 300 ++++++++++++++++++++++++++++++++ 4 files changed, 304 insertions(+) create mode 100644 rust/kernel/opp.rs
MAINTAINERS +1 -0
@@ -18165,6 +18165,7 @@ F: Documentation/devicetree/bindings/opp/ F: Documentation/power/opp.rst F: drivers/opp/ F: include/linux/pm_opp.h +F: rust/kernel/opp.rs OPL4 DRIVER M: Clemens Ladisch <[email protected]>
rust/bindings/bindings_helper.h +1 -0
@@ -30,6 +30,7 @@#include <linux/phy.h> #include <linux/pid_namespace.h> #include <linux/platform_device.h> +#include <linux/pm_opp.h> #include <linux/poll.h> #include <linux/property.h> #include <linux/refcount.h>
rust/kernel/lib.rs +2 -0
@@ -68,6 +68,8 @@#[cfg( CONFIG_NET )] pub mod net;pub mod of; +#[cfg( CONFIG_PM_OPP )] +pub mod opp;pub mod page;#[cfg( CONFIG_PCI )] pub mod pci;
rust/kernel/opp.rs new file +300 -0
300 lines not on this page · raw message
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 11/17 rust: opp: Add abstractions for the OPP table
In reply to Viresh KumarIntroduce Rust abstractions for struct opp_table, enabling access to OPP tables from Rust.
--- rust/kernel/opp.rs | 495 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 494 insertions(+), 1 deletion(-)
rust/kernel/opp.rs +494 -1
@@ -11,8 +11,9 @@use crate ::{ bindings, clk::Hertz , + cpumask::{Cpumask ,CpumaskVar }, device::Device , - error::{code::*, to_result,Result }, + error::{code::*, from_err_ptr, to_result,Error ,Result }, ffi::c_ulong, types::{ARef ,AlwaysRefCounted ,Opaque }, };
@@ -172,6 +173,477 @@ fn freq(&self) -> Hertz { } } +/// [`OPP`] search options. +/// +/// ## Examples +/// +/// Defines how to search for an [`OPP`] in a [`Table`] relative to a frequency. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::error::Result; +/// use kernel::opp::{OPP, SearchType, Table}; +/// use kernel::types::ARef; +/// +/// fn find_opp(table: &Table, freq: Hertz) -> Result<ARef<OPP>> { +/// let opp = table.opp_from_freq(freq, Some(true), None, SearchType::Exact)?; +/// +/// pr_info!("OPP frequency is: {:?}\n", opp.freq(None)); +/// pr_info!("OPP voltage is: {:?}\n", opp.voltage()); +/// pr_info!("OPP level is: {}\n", opp.level()); +/// pr_info!("OPP power is: {:?}\n", opp.power()); +/// +/// Ok(opp) +/// } +/// ``` +#[derive( Copy , Clone , Debug , Eq , PartialEq )] +pub enum SearchType { +/// Match the exact frequency. +Exact , +/// Find the highest frequency less than or equal to the given value. +Floor , +/// Find the lowest frequency greater than or equal to the given value. +Ceil , +} + +/// A reference-counted OPP table. +/// +/// Rust abstraction for the C `struct opp_table`. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of the [`Table`]. +/// +/// Instances of this type are reference-counted. +/// +/// ## Examples +/// +/// The following example demonstrates how to get OPP [`Table`] for a [`Cpumask`] and set its +/// frequency. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::cpumask::Cpumask; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::Table; +/// use kernel::types::ARef; +/// +/// fn get_table(dev: &ARef<Device>, mask: &mut Cpumask, freq: Hertz) -> Result<Table> { +/// let mut opp_table = Table::from_of_cpumask(dev, mask)?; +/// +/// if opp_table.opp_count()? == 0 { +/// return Err(EINVAL); +/// } +/// +/// pr_info!("Max transition latency is: {} ns\n", opp_table.max_transition_latency_ns()); +/// pr_info!("Suspend frequency is: {:?}\n", opp_table.suspend_freq()); +/// +/// opp_table.set_rate(freq)?; +/// Ok(opp_table) +/// } +/// ``` +pub struct Table { + ptr: *mut bindings::opp_table , + dev:ARef <Device >, + em:bool , + of:bool , + cpumask_box:Option <CpumaskVar >, +} + +// SAFETY: It is okay to send ownership of [`Table`] across thread boundaries. +unsafe impl Send for Table {} + +// SAFETY: It is okay to access [`Table`] through shared references from other threads because +// we're either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for Table {} + +impl Table { +/// Creates a new reference-counted [`Table`] from a raw pointer. +/// +/// # Safety +/// +/// Callers must ensure that `ptr` is valid and non-null. +unsafe fn from_raw_table (ptr: *mut bindings::opp_table , dev: &ARef <Device >) ->Self { +// SAFETY: By the safety requirements, ptr is valid and its refcount will be incremented. +// +// INVARIANT: The reference-count is decremented when [`Table`] goes out of scope. +unsafe { bindings::dev_pm_opp_get_opp_table_ref (ptr) }; + +Self { + ptr, + dev: dev.clone (), + em:false , + of:false , + cpumask_box:None , + } + } + +/// Creates a new reference-counted [`Table`] instance for a [`Device`]. +pub fn from_dev (dev: &Device ) ->Result <Self > { +// SAFETY: The requirements are satisfied by the existence of the [`Device`] and its safety +// requirements. +// +// INVARIANT: The reference-count is incremented by the C code and is decremented when +// [`Table`] goes out of scope. +let ptr =from_err_ptr (unsafe { bindings::dev_pm_opp_get_opp_table (dev.as_raw ()) })?; + +Ok (Self { + ptr, + dev: dev.into (), + em:false , + of:false , + cpumask_box:None , + }) + } + +/// Creates a new reference-counted [`Table`] instance for a [`Device`] based on device tree +/// entries. +#[cfg( CONFIG_OF )] +pub fn from_of (dev: &ARef <Device >, index:i32 ) ->Result <Self > { +// SAFETY: The requirements are satisfied by the existence of the [`Device`] and its safety +// requirements. +// +// INVARIANT: The reference-count is incremented by the C code and is decremented when +// [`Table`] goes out of scope. +to_result (unsafe { bindings::dev_pm_opp_of_add_table_indexed (dev.as_raw (), index) })?; + +// Get the newly created [`Table`]. +let mut table =Self ::from_dev (dev)?; + table.of =true ; + +Ok (table) + } + +// Remove device tree based [`Table`]. +#[cfg( CONFIG_OF )] +#[inline] +fn remove_of (&self) { +// SAFETY: The requirements are satisfied by the existence of the [`Device`] and its safety +// requirements. We took the reference from [`from_of`] earlier, it is safe to drop the +// same now. +unsafe { bindings::dev_pm_opp_of_remove_table (self.dev.as_raw ()) }; + } + +/// Creates a new reference-counted [`Table`] instance for a [`Cpumask`] based on device tree +/// entries. +#[cfg( CONFIG_OF )] +pub fn from_of_cpumask (dev: &Device , cpumask: &mut Cpumask ) ->Result <Self > { +// SAFETY: The cpumask is valid and the returned pointer will be owned by the [`Table`] +// instance. +// +// INVARIANT: The reference-count is incremented by the C code and is decremented when +// [`Table`] goes out of scope. +to_result (unsafe { bindings::dev_pm_opp_of_cpumask_add_table (cpumask.as_raw ()) })?; + +// Fetch the newly created table. +let mut table =Self ::from_dev (dev)?; + table.cpumask_box =Some (CpumaskVar ::try_clone (cpumask)?); + +Ok (table) + } + +// Remove device tree based [`Table`] for a [`Cpumask`]. +#[cfg( CONFIG_OF )] +#[inline] +fn remove_of_cpumask (&self, cpumask: &Cpumask ) { +// SAFETY: The cpumask is valid and we took the reference from [`from_of_cpumask`] earlier, +// it is safe to drop the same now. +unsafe { bindings::dev_pm_opp_of_cpumask_remove_table (cpumask.as_raw ()) }; + } + +/// Returns the number of [`OPP`]s in the [`Table`]. +pub fn opp_count (&self) ->Result <u32 > { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +let ret =unsafe { bindings::dev_pm_opp_get_opp_count (self.dev.as_raw ()) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u32 ) + } + } + +/// Returns max clock latency (in nanoseconds) of the [`OPP`]s in the [`Table`]. +#[inline] +pub fn max_clock_latency_ns (&self) ->usize { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +unsafe { bindings::dev_pm_opp_get_max_clock_latency (self.dev.as_raw ()) } + } + +/// Returns max volt latency (in nanoseconds) of the [`OPP`]s in the [`Table`]. +#[inline] +pub fn max_volt_latency_ns (&self) ->usize { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +unsafe { bindings::dev_pm_opp_get_max_volt_latency (self.dev.as_raw ()) } + } + +/// Returns max transition latency (in nanoseconds) of the [`OPP`]s in the [`Table`]. +#[inline] +pub fn max_transition_latency_ns (&self) ->usize { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +unsafe { bindings::dev_pm_opp_get_max_transition_latency (self.dev.as_raw ()) } + } + +/// Returns the suspend [`OPP`]'s frequency. +#[inline] +pub fn suspend_freq (&self) ->Hertz { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +Hertz (unsafe { bindings::dev_pm_opp_get_suspend_opp_freq (self.dev.as_raw ()) }) + } + +/// Synchronizes regulators used by the [`Table`]. +#[inline] +pub fn sync_regulators (&self) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { bindings::dev_pm_opp_sync_regulators (self.dev.as_raw ()) }) + } + +/// Gets sharing CPUs. +#[inline] +pub fn sharing_cpus (dev: &Device , cpumask: &mut Cpumask ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { bindings::dev_pm_opp_get_sharing_cpus (dev.as_raw (), cpumask.as_raw ()) }) + } + +/// Sets sharing CPUs. +pub fn set_sharing_cpus (&mut self, cpumask: &mut Cpumask ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { + bindings::dev_pm_opp_set_sharing_cpus (self.dev.as_raw (), cpumask.as_raw ()) + })?; + +if let Some (mask) = self.cpumask_box.as_mut () { +// Update the cpumask as this will be used while removing the table. + cpumask.copy (mask); + } + +Ok (()) + } + +/// Gets sharing CPUs from device tree. +#[cfg( CONFIG_OF )] +#[inline] +pub fn of_sharing_cpus (dev: &Device , cpumask: &mut Cpumask ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { + bindings::dev_pm_opp_of_get_sharing_cpus (dev.as_raw (), cpumask.as_raw ()) + }) + } + +/// Updates the voltage value for an [`OPP`]. +#[inline] +pub fn adjust_voltage ( + &self, + freq:Hertz , + volt:MicroVolt , + volt_min:MicroVolt , + volt_max:MicroVolt , + ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { + bindings::dev_pm_opp_adjust_voltage ( + self.dev.as_raw (), + freq.into (), + volt.into (), + volt_min.into (), + volt_max.into (), + ) + }) + } + +/// Configures device with [`OPP`] matching the frequency value. +#[inline] +pub fn set_rate (&self, freq:Hertz ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { bindings::dev_pm_opp_set_rate (self.dev.as_raw (), freq.into ()) }) + } + +/// Configures device with [`OPP`]. +#[inline] +pub fn set_opp (&self, opp: &OPP ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { bindings::dev_pm_opp_set_opp (self.dev.as_raw (), opp.as_raw ()) }) + } + +/// Finds [`OPP`] based on frequency. +pub fn opp_from_freq ( + &self, + freq:Hertz , + available:Option <bool >, + index:Option <u32 >, + stype:SearchType , + ) ->Result <ARef <OPP >> { +let raw_dev = self.dev.as_raw (); +let index = index.unwrap_or (0 ); + +let ptr =from_err_ptr (match stype { +SearchType ::Exact => { +if let Some (available) = available { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and +// its safety requirements. The returned pointer will be owned by the new +// [`OPP`] instance. +unsafe { + bindings::dev_pm_opp_find_freq_exact_indexed ( + raw_dev, + freq.into (), + index, + available, + ) + } + }else { +return Err (EINVAL ); + } + } + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Ceil =>unsafe { + bindings::dev_pm_opp_find_freq_ceil_indexed ( + raw_dev, + &mut freq.into ()as *mut usize , + index, + ) + }, + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Floor =>unsafe { + bindings::dev_pm_opp_find_freq_floor_indexed ( + raw_dev, + &mut freq.into ()as *mut usize , + index, + ) + }, + })?; + +// SAFETY: The `ptr` is guaranteed by the C code to be valid. +unsafe {OPP ::from_raw_opp_owned (ptr) } + } + +/// Finds [`OPP`] based on level. +pub fn opp_from_level (&self,mut level:u32 , stype:SearchType ) ->Result <ARef <OPP >> { +let raw_dev = self.dev.as_raw (); + +let ptr =from_err_ptr (match stype { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Exact =>unsafe { bindings::dev_pm_opp_find_level_exact (raw_dev, level) }, + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Ceil =>unsafe { + bindings::dev_pm_opp_find_level_ceil (raw_dev, &mut levelas *mut u32 ) + }, + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Floor =>unsafe { + bindings::dev_pm_opp_find_level_floor (raw_dev, &mut levelas *mut u32 ) + }, + })?; + +// SAFETY: The `ptr` is guaranteed by the C code to be valid. +unsafe {OPP ::from_raw_opp_owned (ptr) } + } + +/// Finds [`OPP`] based on bandwidth. +pub fn opp_from_bw (&self,mut bw:u32 , index:i32 , stype:SearchType ) ->Result <ARef <OPP >> { +let raw_dev = self.dev.as_raw (); + +let ptr =from_err_ptr (match stype { +// The OPP core doesn't support this yet. +SearchType ::Exact =>return Err (EINVAL ), + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Ceil =>unsafe { + bindings::dev_pm_opp_find_bw_ceil (raw_dev, &mut bwas *mut u32 , index) + }, + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The returned pointer will be owned by the new [`OPP`] instance. +SearchType ::Floor =>unsafe { + bindings::dev_pm_opp_find_bw_floor (raw_dev, &mut bwas *mut u32 , index) + }, + })?; + +// SAFETY: The `ptr` is guaranteed by the C code to be valid. +unsafe {OPP ::from_raw_opp_owned (ptr) } + } + +/// Enables the [`OPP`]. +#[inline] +pub fn enable_opp (&self, freq:Hertz ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { bindings::dev_pm_opp_enable (self.dev.as_raw (), freq.into ()) }) + } + +/// Disables the [`OPP`]. +#[inline] +pub fn disable_opp (&self, freq:Hertz ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { bindings::dev_pm_opp_disable (self.dev.as_raw (), freq.into ()) }) + } + +/// Registers with Energy model. +#[cfg( CONFIG_OF )] +pub fn of_register_em (&mut self, cpumask: &mut Cpumask ) ->Result <()> { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { + bindings::dev_pm_opp_of_register_em (self.dev.as_raw (), cpumask.as_raw ()) + })?; + + self.em =true ; +Ok (()) + } + +// Unregisters with Energy model. +#[cfg(all( CONFIG_OF , CONFIG_ENERGY_MODEL ))] +#[inline] +fn of_unregister_em (&self) { +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. We registered with the EM framework earlier, it is safe to unregister now. +unsafe { bindings::em_dev_unregister_perf_domain (self.dev.as_raw ()) }; + } +} + +impl Drop for Table { +fn drop (&mut self) { +// SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe +// to relinquish it now. +unsafe { bindings::dev_pm_opp_put_opp_table (self.ptr) }; + +#[cfg( CONFIG_OF )] + { +#[cfg( CONFIG_ENERGY_MODEL )] +if self.em { + self.of_unregister_em (); + } + +if self.of { + self.remove_of (); + }else if let Some (cpumask) = self.cpumask_box.take () { + self.remove_of_cpumask (&cpumask); + } + } + } +} +/// A reference-counted Operating performance point (OPP). /// /// Rust abstraction for the C `struct dev_pm_opp`.
@@ -185,6 +657,27 @@ fn freq(&self) -> Hertz {/// represents a pointer that owns a reference count on the [`OPP`]. /// /// A reference to the [`OPP`], &[`OPP`], isn't refcounted by the Rust code. +/// +/// ## Examples +/// +/// The following example demonstrates how to get [`OPP`] corresponding to a frequency value and +/// configure the device with it. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::error::Result; +/// use kernel::opp::{SearchType, Table}; +/// +/// fn configure_opp(table: &Table, freq: Hertz) -> Result { +/// let opp = table.opp_from_freq(freq, Some(true), None, SearchType::Exact)?; +/// +/// if opp.freq(None) != freq { +/// return Err(EINVAL); +/// } +/// +/// table.set_opp(&opp) +/// } +/// ``` #[repr(transparent)] pub struct OPP (Opaque <bindings::dev_pm_opp >);
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 12/17 rust: opp: Add abstractions for the configuration options
In reply to Viresh KumarIntroduce Rust abstractions for the OPP core configuration options, enabling safe access to various configurable aspects of the OPP framework.
--- rust/kernel/opp.rs | 295 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 293 insertions(+), 2 deletions(-)
rust/kernel/opp.rs +293 -2
@@ -13,12 +13,29 @@ clk::Hertz, cpumask::{Cpumask, CpumaskVar}, device::Device, - error::{code::*, from_err_ptr, to_result, Error, Result}, + error::{code::*, from_err_ptr, from_result, to_result, Error, Result, VTABLE_DEFAULT_ERROR}, ffi::c_ulong, + prelude::*, + str::CString, types::{ARef, AlwaysRefCounted, Opaque}, }; -use core::ptr; +use core::{marker::PhantomData , ptr}; + +use macros::vtable; + +// Creates a null-terminated slice of pointers to [`Cstring`]s. +fn to_c_str_array (names: &[CString ]) ->Result <KVec <*const u8 >> { +// Allocated a null-terminated vector of pointers. +let mut list =KVec ::with_capacity (names.len () +1 ,GFP_KERNEL )?; + +for namein names.iter () { + list.push (name.as_ptr ()as _ ,GFP_KERNEL )?; + } + + list.push (ptr::null (),GFP_KERNEL )?; +Ok (list) +}/// The voltage unit. ///
@@ -206,6 +223,280 @@ pub enum SearchType { Ceil, } +/// OPP configuration callbacks. +/// +/// Implement this trait to customize OPP clock and regulator setup for your device. +#[vtable] +pub trait ConfigOps { +/// This is typically used to scale clocks when transitioning between OPPs. +#[inline] +fn config_clks (_dev: &Device , _table: &Table , _opp: &OPP , _scaling_down:bool ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// This provides access to the old and new OPPs, allowing for safe regulator adjustments. +#[inline] +fn config_regulators ( + _dev: &Device , + _opp_old: &OPP , + _opp_new: &OPP , + _data: *mut *mut bindings::regulator , + _count:u32 , + ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } +} + +/// OPP configuration token. +/// +/// Returned by the OPP core when configuration is applied to a [`Device`]. The associated +/// configuration is automatically cleared when the token is dropped. +pub struct ConfigToken (i32 ); + +impl Drop for ConfigToken { +fn drop (&mut self) { +// SAFETY: This is the same token value returned by the C code via `dev_pm_opp_set_config`. +unsafe { bindings::dev_pm_opp_clear_config (self.0 ) }; + } +} + +/// OPP configurations. +/// +/// Rust abstraction for the C `struct dev_pm_opp_config`. +/// +/// ## Examples +/// +/// The following example demonstrates how to set OPP property-name configuration for a [`Device`]. +/// +/// ``` +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Config, ConfigOps, ConfigToken}; +/// use kernel::str::CString; +/// use kernel::types::ARef; +/// use kernel::macros::vtable; +/// +/// #[derive(Default)] +/// struct Driver; +/// +/// #[vtable] +/// impl ConfigOps for Driver {} +/// +/// fn configure(dev: &ARef<Device>) -> Result<ConfigToken> { +/// let name = CString::try_from_fmt(fmt!("{}", "slow"))?; +/// +/// // The OPP configuration is cleared once the [`ConfigToken`] goes out of scope. +/// Config::<Driver>::new() +/// .set_prop_name(name)? +/// .set(dev) +/// } +/// ``` +#[derive( Default )] +pub struct Config <T :ConfigOps > +where +T :Default , +{ + clk_names:Option <KVec <CString >>, + prop_name:Option <CString >, + regulator_names:Option <KVec <CString >>, + supported_hw:Option <KVec <u32 >>, + +// Tuple containing (required device, index) + required_dev:Option <(ARef <Device >,u32 )>, + _data:PhantomData <T >, +} + +impl <T :ConfigOps +Default >Config <T > { +/// Creates a new instance of [`Config`]. +#[inline] +pub fn new () ->Self { +Self ::default () + } + +/// Initializes clock names. +pub fn set_clk_names (mut self, names:KVec <CString >) ->Result <Self > { +if self.clk_names.is_some () { +return Err (EBUSY ); + } + +if names.is_empty () { +return Err (EINVAL ); + } + + self.clk_names =Some (names); +Ok (self) + } + +/// Initializes property name. +pub fn set_prop_name (mut self, name:CString ) ->Result <Self > { +if self.prop_name.is_some () { +return Err (EBUSY ); + } + + self.prop_name =Some (name); +Ok (self) + } + +/// Initializes regulator names. +pub fn set_regulator_names (mut self, names:KVec <CString >) ->Result <Self > { +if self.regulator_names.is_some () { +return Err (EBUSY ); + } + +if names.is_empty () { +return Err (EINVAL ); + } + + self.regulator_names =Some (names); + +Ok (self) + } + +/// Initializes required devices. +pub fn set_required_dev (mut self, dev:ARef <Device >, index:u32 ) ->Result <Self > { +if self.required_dev.is_some () { +return Err (EBUSY ); + } + + self.required_dev =Some ((dev, index)); +Ok (self) + } + +/// Initializes supported hardware. +pub fn set_supported_hw (mut self, hw:KVec <u32 >) ->Result <Self > { +if self.supported_hw.is_some () { +return Err (EBUSY ); + } + +if hw.is_empty () { +return Err (EINVAL ); + } + + self.supported_hw =Some (hw); +Ok (self) + } + +/// Sets the configuration with the OPP core. +/// +/// The returned [`ConfigToken`] will remove the configuration when dropped. +pub fn set (self, dev: &Device ) ->Result <ConfigToken > { +let (_clk_list, clk_names) =match &self.clk_names { +Some (x) => { +let list =to_c_str_array (x)?; +let ptr = list.as_ptr (); + (Some (list), ptr) + } +None => (None , ptr::null ()), + }; + +let (_regulator_list, regulator_names) =match &self.regulator_names { +Some (x) => { +let list =to_c_str_array (x)?; +let ptr = list.as_ptr (); + (Some (list), ptr) + } +None => (None , ptr::null ()), + }; + +let prop_name = self + .prop_name + .as_ref () + .map_or (ptr::null (), |p| p.as_char_ptr ()); + +let (supported_hw, supported_hw_count) = self + .supported_hw + .as_ref () + .map_or ((ptr::null (),0 ), |hw| (hw.as_ptr (), hw.len ()as u32 )); + +let (required_dev, required_dev_index) = self + .required_dev + .as_ref () + .map_or ((ptr::null_mut (),0 ), |(dev, idx)| (dev.as_raw (), *idx)); + +let mut config = bindings::dev_pm_opp_config { + clk_names, + config_clks:if T ::HAS_CONFIG_CLKS { +Some (Self ::config_clks) + }else { +None + }, + prop_name, + regulator_names, + config_regulators:if T ::HAS_CONFIG_REGULATORS { +Some (Self ::config_regulators) + }else { +None + }, + supported_hw, + supported_hw_count, + + required_dev, + required_dev_index, + }; + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. The OPP core guarantees not to access fields of [`Config`] after this call +// and so we don't need to save a copy of them for future use. +let ret =unsafe { bindings::dev_pm_opp_set_config (dev.as_raw (), &mut config) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (ConfigToken (ret)) + } + } + +// Config's clk callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn config_clks ( + dev: *mut bindings::device , + opp_table: *mut bindings::opp_table , + opp: *mut bindings::dev_pm_opp , + _data: *mut kernel::ffi::c_void , + scaling_down:bool , + ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: 'dev' is guaranteed by the C code to be valid. +let dev =unsafe {Device ::get_device (dev) }; +T ::config_clks ( + &dev, +// SAFETY: 'opp_table' is guaranteed by the C code to be valid. + &unsafe {Table ::from_raw_table (opp_table, &dev) }, +// SAFETY: 'opp' is guaranteed by the C code to be valid. +unsafe {OPP ::from_raw_opp (opp)? }, + scaling_down, + ) + .map (|()|0 ) + }) + } + +// Config's regulator callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn config_regulators ( + dev: *mut bindings::device , + old_opp: *mut bindings::dev_pm_opp , + new_opp: *mut bindings::dev_pm_opp , + regulators: *mut *mut bindings::regulator , + count: kernel::ffi::c_uint , + ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: 'dev' is guaranteed by the C code to be valid. +let dev =unsafe {Device ::get_device (dev) }; +T ::config_regulators ( + &dev, +// SAFETY: 'old_opp' is guaranteed by the C code to be valid. +unsafe {OPP ::from_raw_opp (old_opp)? }, +// SAFETY: 'new_opp' is guaranteed by the C code to be valid. +unsafe {OPP ::from_raw_opp (new_opp)? }, + regulators, + count, + ) + .map (|()|0 ) + }) + } +} +/// A reference-counted OPP table. /// /// Rust abstraction for the C `struct opp_table`.
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 13/17 rust: cpufreq: Add initial abstractions for cpufreq framework
In reply to Viresh KumarIntroduce initial Rust abstractions for the cpufreq core. This includes basic representations for cpufreq flags, relation types, and the cpufreq table.
--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/cpufreq.c | 10 + rust/helpers/helpers.c | 1 + rust/kernel/cpufreq.rs | 341 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 6 files changed, 356 insertions(+) create mode 100644 rust/helpers/cpufreq.c create mode 100644 rust/kernel/cpufreq.rs
MAINTAINERS +1 -0
@@ -6142,6 +6142,7 @@ F: drivers/cpufreq/ F: include/linux/cpufreq.h F: include/linux/sched/cpufreq.h F: kernel/sched/cpufreq*.c +F: rust/kernel/cpufreq.rs F: tools/testing/selftests/cpufreq/ CPU HOTPLUG
rust/bindings/bindings_helper.h +1 -0
@@ -12,6 +12,7 @@#include <linux/blkdev.h> #include <linux/clk.h> #include <linux/cpu.h> +#include <linux/cpufreq.h> #include <linux/cpumask.h> #include <linux/cred.h> #include <linux/device/faux.h>
rust/helpers/cpufreq.c new file +10 -0
@@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/cpufreq.h> + +#ifdef CONFIG_CPU_FREQ +void rust_helper_cpufreq_register_em_with_opp (struct cpufreq_policy *policy) +{ +cpufreq_register_em_with_opp (policy); +} +#endif
rust/helpers/helpers.c +1 -0
@@ -12,6 +12,7 @@#include "build_assert.c" #include "build_bug.c" #include "clk.c" +#include "cpufreq.c" #include "cpumask.c" #include "cred.c" #include "device.c"
rust/kernel/cpufreq.rs new file +341 -0
341 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -45,6 +45,8 @@#[cfg( CONFIG_COMMON_CLK )] pub mod clk;pub mod cpu; +#[cfg( CONFIG_CPU_FREQ )] +pub mod cpufreq;pub mod cpumask;pub mod cred;pub mod device;
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 14/17 rust: cpufreq: Extend abstractions for policy and driver ops
In reply to Viresh KumarExtend the cpufreq abstractions to include support for policy handling and driver operations.
--- rust/kernel/cpufreq.rs | 455 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 454 insertions(+), 1 deletion(-)
rust/kernel/cpufreq.rs +454 -1
@@ -10,15 +10,24 @@use crate ::{ bindings, - error::{code::*, to_result,Result }, + clk::{Clk ,Hertz }, + cpumask, + device::Device , + error::{code::*, from_err_ptr, to_result,Result ,VTABLE_DEFAULT_ERROR }, ffi::c_ulong, prelude::*, + types::ForeignOwnable , + types::Opaque , };use core::{ + ops::{Deref ,DerefMut }, pin::Pin , + ptr::self, }; +use macros::vtable; +/// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS :u32 = bindings::CPUFREQ_ETERNAL as u32 ;
@@ -339,3 +348,447 @@ pub fn to_table(mut self) -> Result<TableBox> {TableBox ::new (self.entries) } } + +/// CPU frequency policy. +/// +/// Rust abstraction for the C `struct cpufreq_policy`. +/// +/// # Invariants +/// +/// A [`Policy`] instance always corresponds to a valid C `struct cpufreq_policy`. +/// +/// The callers must ensure that the `struct cpufreq_policy` is valid for access and remains valid +/// for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to create a CPU frequency table. +/// +/// ``` +/// use kernel::cpufreq::{ETERNAL_LATENCY_NS, Policy}; +/// +/// fn update_policy(policy: &mut Policy) { +/// policy +/// .set_dvfs_possible_from_any_cpu(true) +/// .set_fast_switch_possible(true) +/// .set_transition_latency_ns(ETERNAL_LATENCY_NS); +/// +/// pr_info!("The policy details are: {:?}\n", (policy.cpu(), policy.cur())); +/// } +/// ``` +#[repr(transparent)] +pub struct Policy (Opaque <bindings::cpufreq_policy >); + +impl Policy { +/// Creates a reference to an existing `struct cpufreq_policy` pointer. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime +/// of the returned reference. +#[inline] +pub unsafe fn from_raw <'a>(ptr: *const bindings::cpufreq_policy ) -> &'aSelf { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the +// lifetime of the returned reference. +unsafe { &*ptr.cast () } + } + +/// Creates a mutable reference to an existing `struct cpufreq_policy` pointer. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime +/// of the returned reference. +#[inline] +pub unsafe fn from_raw_mut <'a>(ptr: *mut bindings::cpufreq_policy ) -> &'amut Self { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the +// lifetime of the returned reference. +unsafe { &mut *ptr.cast () } + } + +// Returns a raw mutable pointer to the C `struct cpufreq_policy`. +#[inline] +fn as_raw (&self) -> *mut bindings::cpufreq_policy { + selfas *const _ as _ + } + +#[inline] +fn as_ref (&self) -> &bindings::cpufreq_policy { +// SAFETY: By the type invariant, the pointer stored in `self` is valid. +unsafe { &*self.as_raw () } + } + +#[inline] +fn as_mut_ref (&mut self) -> &mut bindings::cpufreq_policy { +// SAFETY: By the type invariant, the pointer stored in `self` is valid. +unsafe { &mut *self.as_raw () } + } + +/// Returns the primary CPU for the [`Policy`]. +#[inline] +pub fn cpu (&self) ->u32 { + self.as_ref ().cpu + } + +/// Returns the minimum frequency for the [`Policy`]. +#[inline] +pub fn min (&self) ->Hertz { +Hertz ::from_khz (self.as_ref ().minas usize ) + } + +/// Set the minimum frequency for the [`Policy`]. +#[inline] +pub fn set_min (&mut self, min:Hertz ) -> &mut Self { + self.as_mut_ref ().min = min.as_khz ()as u32 ; + self + } + +/// Returns the maximum frequency for the [`Policy`]. +#[inline] +pub fn max (&self) ->Hertz { +Hertz ::from_khz (self.as_ref ().maxas usize ) + } + +/// Set the maximum frequency for the [`Policy`]. +#[inline] +pub fn set_max (&mut self, max:Hertz ) -> &mut Self { + self.as_mut_ref ().max = max.as_khz ()as u32 ; + self + } + +/// Returns the current frequency for the [`Policy`]. +#[inline] +pub fn cur (&self) ->Hertz { +Hertz ::from_khz (self.as_ref ().curas usize ) + } + +/// Returns the suspend frequency for the [`Policy`]. +#[inline] +pub fn suspend_freq (&self) ->Hertz { +Hertz ::from_khz (self.as_ref ().suspend_freqas usize ) + } + +/// Sets the suspend frequency for the [`Policy`]. +#[inline] +pub fn set_suspend_freq (&mut self, freq:Hertz ) -> &mut Self { + self.as_mut_ref ().suspend_freq = freq.as_khz ()as u32 ; + self + } + +/// Provides a wrapper to the generic suspend routine. +#[inline] +pub fn generic_suspend (&mut self) ->Result <()> { +// SAFETY: By the type invariant, the pointer stored in `self` is valid. +to_result (unsafe { bindings::cpufreq_generic_suspend (self.as_mut_ref ()) }) + } + +/// Provides a wrapper to the generic get routine. +#[inline] +pub fn generic_get (&self) ->Result <u32 > { +// SAFETY: By the type invariant, the pointer stored in `self` is valid. +Ok (unsafe { bindings::cpufreq_generic_get (self.cpu ()) }) + } + +/// Provides a wrapper to the register with energy model using the OPP core. +#[cfg( CONFIG_PM_OPP )] +#[inline] +pub fn register_em_opp (&mut self) { +// SAFETY: By the type invariant, the pointer stored in `self` is valid. +unsafe { bindings::cpufreq_register_em_with_opp (self.as_mut_ref ()) }; + } + +/// Gets [`cpumask::Cpumask`] for a cpufreq [`Policy`]. +#[inline] +pub fn cpus (&mut self) -> &mut cpumask::Cpumask { +// SAFETY: The pointer to `cpus` is valid for writing and remains valid for the lifetime of +// the returned reference. +unsafe { cpumask::CpumaskVar ::from_raw_mut (&mut self.as_mut_ref ().cpus) } + } + +/// Sets clock for the [`Policy`]. +/// +/// # Safety +/// +/// The caller must guarantee that the returned [`Clk`] is not dropped while it is getting used +/// by the C code. +pub unsafe fn set_clk (&mut self, dev: &Device , name:Option <&CStr >) ->Result <Clk > { +let clk =Clk ::get (dev, name)?; + self.as_mut_ref ().clk = clk.as_raw (); +Ok (clk) + } + +/// Allows / disallows frequency switching code to run on any CPU. +#[inline] +pub fn set_dvfs_possible_from_any_cpu (&mut self, val:bool ) -> &mut Self { + self.as_mut_ref ().dvfs_possible_from_any_cpu = val; + self + } + +/// Returns if fast switching of frequencies is possible or not. +#[inline] +pub fn fast_switch_possible (&self) ->bool { + self.as_ref ().fast_switch_possible + } + +/// Enables / disables fast frequency switching. +#[inline] +pub fn set_fast_switch_possible (&mut self, val:bool ) -> &mut Self { + self.as_mut_ref ().fast_switch_possible = val; + self + } + +/// Sets transition latency (in nanoseconds) for the [`Policy`]. +#[inline] +pub fn set_transition_latency_ns (&mut self, latency_ns:u32 ) -> &mut Self { + self.as_mut_ref ().cpuinfo.transition_latency = latency_ns; + self + } + +/// Sets cpuinfo `min_freq`. +#[inline] +pub fn set_cpuinfo_min_freq (&mut self, min_freq:Hertz ) -> &mut Self { + self.as_mut_ref ().cpuinfo.min_freq = min_freq.as_khz ()as u32 ; + self + } + +/// Sets cpuinfo `max_freq`. +#[inline] +pub fn set_cpuinfo_max_freq (&mut self, max_freq:Hertz ) -> &mut Self { + self.as_mut_ref ().cpuinfo.max_freq = max_freq.as_khz ()as u32 ; + self + } + +/// Set `transition_delay_us`, i.e. the minimum time between successive frequency change +/// requests. +#[inline] +pub fn set_transition_delay_us (&mut self, transition_delay_us:u32 ) -> &mut Self { + self.as_mut_ref ().transition_delay_us = transition_delay_us; + self + } + +/// Returns reference to the CPU frequency [`Table`] for the [`Policy`]. +pub fn freq_table (&self) ->Result <&Table > { +if self.as_ref ().freq_table.is_null () { +return Err (EINVAL ); + } + +// SAFETY: The `freq_table` is guaranteed to be valid for reading and remains valid for the +// lifetime of the returned reference. +Ok (unsafe {Table ::from_raw (self.as_ref ().freq_table) }) + } + +/// Sets the CPU frequency [`Table`] for the [`Policy`]. +/// +/// # Safety +/// +/// The caller must guarantee that the [`Table`] is not dropped while it is getting used by the +/// C code. +#[inline] +pub unsafe fn set_freq_table (&mut self, table: &Table ) -> &mut Self { + self.as_mut_ref ().freq_table = table.as_raw (); + self + } + +/// Returns the [`Policy`]'s private data. +pub fn data <T :ForeignOwnable >(&mut self) ->Option <<T >::Borrowed <'_>> { +if self.as_ref ().driver_data.is_null () { +None + }else { +// SAFETY: The data is earlier set from [`set_data`]. +Some (unsafe {T ::borrow (self.as_ref ().driver_data) }) + } + } + +// Sets the private data of the [`Policy`] using a foreign-ownable wrapper. +// +// # Errors +// +// Returns `EBUSY` if private data is already set. +fn set_data <T :ForeignOwnable >(&mut self, data:T ) ->Result <()> { +if self.as_ref ().driver_data.is_null () { +// Transfer the ownership of the data to the foreign interface. + self.as_mut_ref ().driver_data = <T as ForeignOwnable >::into_foreign (data)as _ ; +Ok (()) + }else { +Err (EBUSY ) + } + } + +// Clears and returns ownership of the private data. +fn clear_data <T :ForeignOwnable >(&mut self) ->Option <T > { +if self.as_ref ().driver_data.is_null () { +None + }else { +let data =Some ( +// SAFETY: The data is earlier set by us from [`set_data`]. It is safe to take +// back the ownership of the data from the foreign interface. +unsafe { <T as ForeignOwnable >::from_foreign (self.as_ref ().driver_data) }, + ); + self.as_mut_ref ().driver_data = ptr::null_mut (); + data + } + } +} + +// CPU frequency policy created from a CPU number. +// +// This struct represents the CPU frequency policy obtained for a specific CPU, providing safe +// access to the underlying `cpufreq_policy` and ensuring proper cleanup when the `PolicyCpu` is +// dropped. +struct PolicyCpu <'a>(&'amut Policy ); + +impl <'a>PolicyCpu <'a> { +fn from_cpu (cpu:u32 ) ->Result <Self > { +// SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. +let ptr =from_err_ptr (unsafe { bindings::cpufreq_cpu_get (cpu) })?; + +Ok (Self ( +// SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of +// the returned reference. +unsafe {Policy ::from_raw_mut (ptr) }, + )) + } +} + +impl <'a>Deref for PolicyCpu <'a> { +type Target =Policy ; + +fn deref (&self) -> &Self ::Target { + self.0 + } +} + +impl <'a>DerefMut for PolicyCpu <'a> { +fn deref_mut (&mut self) -> &mut Policy { + self.0 + } +} + +impl <'a>Drop for PolicyCpu <'a> { +fn drop (&mut self) { +// SAFETY: The underlying pointer is guaranteed to be valid for the lifetime of `self`. +unsafe { bindings::cpufreq_cpu_put (self.0 .as_raw ()) }; + } +} + +/// CPU frequency driver. +/// +/// Implement this trait to provide a CPU frequency driver and its callbacks. +/// +/// Reference: <https://docs.kernel.org/cpu-freq/cpu-drivers.html> +#[vtable] +pub trait Driver { +/// Driver specific data. +/// +/// Corresponds to the data retrieved via the kernel's `cpufreq_get_driver_data` function. +/// +/// Require `Data` to implement `ForeignOwnable`. We guarantee to never move the underlying +/// wrapped data structure. +type Data :ForeignOwnable ; + +/// Policy specific data. +/// +/// Require that `PData` implements `ForeignOwnable`. We guarantee to never move the underlying +/// wrapped data structure. +type PData :ForeignOwnable ; + +/// Driver's `init` callback. +fn init (policy: &mut Policy ) ->Result <Self ::PData >; + +/// Driver's `exit` callback. +fn exit (_policy: &mut Policy , _data:Option <Self ::PData >) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `online` callback. +fn online (_policy: &mut Policy ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `offline` callback. +fn offline (_policy: &mut Policy ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `suspend` callback. +fn suspend (_policy: &mut Policy ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `resume` callback. +fn resume (_policy: &mut Policy ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `ready` callback. +fn ready (_policy: &mut Policy ) { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `verify` callback. +fn verify (data: &mut PolicyData ) ->Result <()>; + +/// Driver's `setpolicy` callback. +fn setpolicy (_policy: &mut Policy ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `target` callback. +fn target (_policy: &mut Policy , _target_freq:u32 , _relation:Relation ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `target_index` callback. +fn target_index (_policy: &mut Policy , _index:u32 ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `fast_switch` callback. +fn fast_switch (_policy: &mut Policy , _target_freq:u32 ) ->u32 { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `adjust_perf` callback. +fn adjust_perf (_policy: &mut Policy , _min_perf:usize , _target_perf:usize , _capacity:usize ) { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `get_intermediate` callback. +fn get_intermediate (_policy: &mut Policy , _index:u32 ) ->u32 { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `target_intermediate` callback. +fn target_intermediate (_policy: &mut Policy , _index:u32 ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `get` callback. +fn get (_policy: &mut Policy ) ->Result <u32 > { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `update_limits` callback. +fn update_limits (_policy: &mut Policy ) { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `bios_limit` callback. +fn bios_limit (_policy: &mut Policy , _limit: &mut u32 ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `set_boost` callback. +fn set_boost (_policy: &mut Policy , _state:i32 ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Driver's `register_em` callback. +fn register_em (_policy: &mut Policy ) { +build_error! (VTABLE_DEFAULT_ERROR ) + } +}
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 15/17 rust: cpufreq: Extend abstractions for driver registration
In reply to Viresh KumarExtend the cpufreq abstractions to support driver registration from Rust.
--- rust/kernel/cpufreq.rs | 530 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 528 insertions(+), 2 deletions(-)
rust/kernel/cpufreq.rs +528 -2
@@ -13,7 +13,8 @@ clk::{Clk, Hertz}, cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR}, + devres::Devres, + error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, ffi::c_ulong, prelude::*, types::ForeignOwnable,
@@ -21,9 +22,11 @@ };use core::{ + cell::UnsafeCell , + marker::PhantomData , ops::{Deref ,DerefMut }, pin::Pin , - ptr::self, + ptr, };use macros::vtable;
@@ -792,3 +795,526 @@ fn register_em(_policy: &mut Policy) {build_error! (VTABLE_DEFAULT_ERROR ) } } + +/// CPU frequency driver Registration. +/// +/// ## Examples +/// +/// The following example demonstrates how to register a cpufreq driver. +/// +/// ``` +/// use kernel::{ +/// c_str, +/// cpu, cpufreq, +/// device::Device, +/// macros::vtable, +/// sync::Arc, +/// }; +/// struct FooDevice; +/// +/// #[derive(Default)] +/// struct FooDriver; +/// +/// #[vtable] +/// impl cpufreq::Driver for FooDriver { +/// type Data = (); +/// type PData = Arc<FooDevice>; +/// +/// fn init(policy: &mut cpufreq::Policy) -> Result<Self::PData> { +/// // Initialize here +/// Ok(Arc::new(FooDevice, GFP_KERNEL)?) +/// } +/// +/// fn exit(_policy: &mut cpufreq::Policy, _data: Option<Self::PData>) -> Result<()> { +/// Ok(()) +/// } +/// +/// fn suspend(policy: &mut cpufreq::Policy) -> Result<()> { +/// policy.generic_suspend() +/// } +/// +/// fn verify(data: &mut cpufreq::PolicyData) -> Result<()> { +/// data.generic_verify() +/// } +/// +/// fn target_index(policy: &mut cpufreq::Policy, index: u32) -> Result<()> { +/// // Update CPU frequency +/// Ok(()) +/// } +/// +/// fn get(policy: &mut cpufreq::Policy) -> Result<u32> { +/// policy.generic_get() +/// } +/// } +/// +/// fn foo_probe(dev: &Device) { +/// cpufreq::Registration::<FooDriver>::new_foreign_owned( +/// dev, +/// c_str!("cpufreq-foo"), +/// (), +/// cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV, +/// true, +/// ).unwrap(); +/// } +/// ``` +pub struct Registration <T :Driver > { + drv:KBox <UnsafeCell <bindings::cpufreq_driver >>, + _p:PhantomData <T >, +} + +// SAFETY: `Registration` doesn't offer any methods or access to fields when shared between threads +// or CPUs, so it is safe to share it. +unsafe impl <T :Driver >Sync for Registration <T > {} + +#[allow(clippy::non_send_fields_in_send_ty)] +// SAFETY: Registration with and unregistration from the cpufreq subsystem can happen from any +// thread. Additionally, `T::Data` (which is dropped during unregistration) is `Send`, so it is +// okay to move `Registration` to different threads. +unsafe impl <T :Driver >Send for Registration <T > {} + +impl <T :Driver >Registration <T > { +/// Registers a CPU frequency driver with the cpufreq core. +pub fn new (name: &'staticCStr , data:T ::Data , flags:u16 , boost:bool ) ->Result <Self > { +// Required due to Rust 1.82's stricter handling of `unsafe` in mutable statics. The +// `unsafe` blocks aren't required anymore with later versions. +#![allow(unused_unsafe)] + +let mut drv =KBox ::new ( +UnsafeCell ::new (bindings::cpufreq_driver::default ()), +GFP_KERNEL , + )?; +let drv_ref = drv.get_mut (); + +// Account for the trailing null byte. +let len = name.len () +1 ; +if len > drv_ref.name.len () { +return Err (EINVAL ); + }; + +// SAFETY: `name` is a valid `CStr`, and we are copying it to an array of equal or larger +// size. +let name =unsafe { &*(name.as_bytes_with_nul ()as *const [u8 ]) }; + drv_ref.name[..len].copy_from_slice (name); + + drv_ref.boost_enabled = boost; + drv_ref.flags = flags; + +// Initialize mandatory callbacks. + drv_ref.init =Some (Self ::init_callback); + drv_ref.verify =Some (Self ::verify_callback); + +// Initialize optional callbacks based on the traits of `T`. + drv_ref.setpolicy =if T ::HAS_SETPOLICY { +Some (Self ::setpolicy_callback) + }else { +None + }; + drv_ref.target =if T ::HAS_TARGET { +Some (Self ::target_callback) + }else { +None + }; + drv_ref.target_index =if T ::HAS_TARGET_INDEX { +Some (Self ::target_index_callback) + }else { +None + }; + drv_ref.fast_switch =if T ::HAS_FAST_SWITCH { +Some (Self ::fast_switch_callback) + }else { +None + }; + drv_ref.adjust_perf =if T ::HAS_ADJUST_PERF { +Some (Self ::adjust_perf_callback) + }else { +None + }; + drv_ref.get_intermediate =if T ::HAS_GET_INTERMEDIATE { +Some (Self ::get_intermediate_callback) + }else { +None + }; + drv_ref.target_intermediate =if T ::HAS_TARGET_INTERMEDIATE { +Some (Self ::target_intermediate_callback) + }else { +None + }; + drv_ref.get =if T ::HAS_GET { +Some (Self ::get_callback) + }else { +None + }; + drv_ref.update_limits =if T ::HAS_UPDATE_LIMITS { +Some (Self ::update_limits_callback) + }else { +None + }; + drv_ref.bios_limit =if T ::HAS_BIOS_LIMIT { +Some (Self ::bios_limit_callback) + }else { +None + }; + drv_ref.online =if T ::HAS_ONLINE { +Some (Self ::online_callback) + }else { +None + }; + drv_ref.offline =if T ::HAS_OFFLINE { +Some (Self ::offline_callback) + }else { +None + }; + drv_ref.exit =if T ::HAS_EXIT { +Some (Self ::exit_callback) + }else { +None + }; + drv_ref.suspend =if T ::HAS_SUSPEND { +Some (Self ::suspend_callback) + }else { +None + }; + drv_ref.resume =if T ::HAS_RESUME { +Some (Self ::resume_callback) + }else { +None + }; + drv_ref.ready =if T ::HAS_READY { +Some (Self ::ready_callback) + }else { +None + }; + drv_ref.set_boost =if T ::HAS_SET_BOOST { +Some (Self ::set_boost_callback) + }else { +None + }; + drv_ref.register_em =if T ::HAS_REGISTER_EM { +Some (Self ::register_em_callback) + }else { +None + }; + +// Set driver data before registering the driver, as the cpufreq core calls few callbacks +// before `cpufreq_register_driver` returns. +Self ::set_data (drv_ref, data)?; + +// SAFETY: It is safe to register the driver with the cpufreq core in the kernel C code. +to_result (unsafe { bindings::cpufreq_register_driver (drv_ref) })?; + +Ok (Self { + drv, + _p:PhantomData , + }) + } + +/// Same as [`Registration::new`], but does not return a [`Registration`] instance. +/// +/// Instead the [`Registration`] is owned by [`Devres`] and will be revoked / dropped, once the +/// device is detached. +pub fn new_foreign_owned ( + dev: &Device , + name: &'staticCStr , + data:T ::Data , + flags:u16 , + boost:bool , + ) ->Result <()> { +Devres ::new_foreign_owned (dev,Self ::new (name, data, flags, boost)?,GFP_KERNEL )?; +Ok (()) + } + +// Sets the `Data` for the CPU frequency driver. +fn set_data (drv: &mut bindings::cpufreq_driver , data:T ::Data ) ->Result <()> { +if drv.driver_data.is_null () { +// Transfer the ownership of the data to the C code. + drv.driver_data = <T ::Data as ForeignOwnable >::into_foreign (data)as _ ; +Ok (()) + }else { +Err (EBUSY ) + } + } + +/// Returns borrowed `Data` previously set for the CPU frequency driver. +pub fn data (&mut self) ->Option <<T ::Data as ForeignOwnable >::Borrowed <'static>> { +let drv = self.drv.get_mut (); + +if drv.driver_data.is_null () { +None + }else { +// SAFETY: The data is earlier set by us from `set_data`. +Some (unsafe { <T ::Data as ForeignOwnable >::borrow (drv.driver_data) }) + } + } + +// Clears and returns the `Data` for the CPU frequency driver. +fn clear_data (&mut self) ->Option <T ::Data > { +let drv = self.drv.get_mut (); + +if drv.driver_data.is_null () { +None + }else { +// SAFETY: The data is earlier set by us from `set_data`. +let data =Some (unsafe { <T ::Data as ForeignOwnable >::from_foreign (drv.driver_data) }); + drv.driver_data = ptr::null_mut (); + data + } + } +} + +// CPU frequency driver callbacks. +impl <T :Driver >Registration <T > { +// Driver's `init` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn init_callback (ptr: *mut bindings::cpufreq_policy ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; + +let data =T ::init (policy)?; + policy.set_data (data)?; +Ok (0 ) + }) + } + +// Driver's `exit` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn exit_callback (ptr: *mut bindings::cpufreq_policy ) { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; + +let data = policy.clear_data (); +let _ =T ::exit (policy, data); + } + +// Driver's `online` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn online_callback (ptr: *mut bindings::cpufreq_policy ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::online (policy).map (|()|0 ) + }) + } + +// Driver's `offline` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn offline_callback (ptr: *mut bindings::cpufreq_policy ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::offline (policy).map (|()|0 ) + }) + } + +// Driver's `suspend` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn suspend_callback (ptr: *mut bindings::cpufreq_policy ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::suspend (policy).map (|()|0 ) + }) + } + +// Driver's `resume` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn resume_callback (ptr: *mut bindings::cpufreq_policy ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::resume (policy).map (|()|0 ) + }) + } + +// Driver's `ready` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn ready_callback (ptr: *mut bindings::cpufreq_policy ) { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::ready (policy); + } + +// Driver's `verify` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn verify_callback (ptr: *mut bindings::cpufreq_policy_data ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let data =unsafe {PolicyData ::from_raw_mut (ptr) }; +T ::verify (data).map (|()|0 ) + }) + } + +// Driver's `setpolicy` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn setpolicy_callback (ptr: *mut bindings::cpufreq_policy ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::setpolicy (policy).map (|()|0 ) + }) + } + +// Driver's `target` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn target_callback ( + ptr: *mut bindings::cpufreq_policy , + target_freq:u32 , + relation:u32 , + ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::target (policy, target_freq,Relation ::new (relation)?).map (|()|0 ) + }) + } + +// Driver's `target_index` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn target_index_callback ( + ptr: *mut bindings::cpufreq_policy , + index:u32 , + ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::target_index (policy, index).map (|()|0 ) + }) + } + +// Driver's `fast_switch` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn fast_switch_callback ( + ptr: *mut bindings::cpufreq_policy , + target_freq:u32 , + ) -> kernel::ffi::c_uint { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::fast_switch (policy, target_freq) + } + +// Driver's `adjust_perf` callback. +extern "C" fn adjust_perf_callback ( + cpu:u32 , + min_perf:usize , + target_perf:usize , + capacity:usize , + ) { +if let Ok (mut policy) =PolicyCpu ::from_cpu (cpu) { +T ::adjust_perf (&mut policy, min_perf, target_perf, capacity); + } + } + +// Driver's `get_intermediate` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn get_intermediate_callback ( + ptr: *mut bindings::cpufreq_policy , + index:u32 , + ) -> kernel::ffi::c_uint { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::get_intermediate (policy, index) + } + +// Driver's `target_intermediate` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn target_intermediate_callback ( + ptr: *mut bindings::cpufreq_policy , + index:u32 , + ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::target_intermediate (policy, index).map (|()|0 ) + }) + } + +// Driver's `get` callback. +extern "C" fn get_callback (cpu:u32 ) -> kernel::ffi::c_uint { +PolicyCpu ::from_cpu (cpu).map_or (0 , |mut policy|T ::get (&mut policy).map_or (0 , |f| f)) + } + +// Driver's `update_limit` callback. +extern "C" fn update_limits_callback (cpu:u32 ) { +if let Ok (mut policy) =PolicyCpu ::from_cpu (cpu) { +T ::update_limits (&mut policy); + } + } + +// Driver's `bios_limit` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn bios_limit_callback (cpu:i32 , limit: *mut u32 ) -> kernel::ffi::c_int { +from_result (|| { +let mut policy =PolicyCpu ::from_cpu (cpuas u32 )?; + +// SAFETY: `limit` is guaranteed by the C code to be valid. +T ::bios_limit (&mut policy, &mut (unsafe { *limit })).map (|()|0 ) + }) + } + +// Driver's `set_boost` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn set_boost_callback ( + ptr: *mut bindings::cpufreq_policy , + state:i32 , + ) -> kernel::ffi::c_int { +from_result (|| { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::set_boost (policy, state).map (|()|0 ) + }) + } + +// Driver's `register_em` callback. +// +// SAFETY: Called from C. Inputs must be valid pointers. +extern "C" fn register_em_callback (ptr: *mut bindings::cpufreq_policy ) { +// SAFETY: The `ptr` is guaranteed to be valid by the contract with the C code for the +// lifetime of `policy`. +let policy =unsafe {Policy ::from_raw_mut (ptr) }; +T ::register_em (policy); + } +} + +impl <T :Driver >Drop for Registration <T > { +// Removes the `Registration` from the kernel, if it has initialized successfully earlier. +fn drop (&mut self) { +let drv = self.drv.get_mut (); + +// SAFETY: The driver was earlier registered from `new`. +unsafe { bindings::cpufreq_unregister_driver (drv) }; + +// Free data +drop (self.clear_data ()); + } +}
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 16/17 rust: opp: Extend OPP abstractions with cpufreq support
In reply to Viresh KumarExtend the OPP abstractions to include support for interacting with the cpufreq core, including the ability to retrieve frequency tables from OPP table.
--- rust/kernel/opp.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+)
rust/kernel/opp.rs +67 -0
@@ -20,6 +20,12 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; +#[cfg( CONFIG_CPU_FREQ )] +use crate ::cpufreq; + +#[cfg( CONFIG_CPU_FREQ )] +use core::ops::Deref ; +use core::{marker::PhantomData , ptr};use macros::vtable;
@@ -497,6 +503,60 @@ extern "C" fn config_regulators( } } +/// OPP frequency table. +/// +/// A [`cpufreq::Table`] created from [`Table`]. +#[cfg( CONFIG_CPU_FREQ )] +pub struct FreqTable { + dev:ARef <Device >, + ptr: *mut bindings::cpufreq_frequency_table , +} + +#[cfg( CONFIG_CPU_FREQ )] +impl FreqTable { +/// Creates a new instance of [`FreqTable`] from [`Table`]. +fn new (table: &Table ) ->Result <Self > { +let mut ptr: *mut bindings::cpufreq_frequency_table = ptr::null_mut (); + +// SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety +// requirements. +to_result (unsafe { + bindings::dev_pm_opp_init_cpufreq_table (table.dev.as_raw (), &mut ptr) + })?; + +Ok (Self { + dev: table.dev.clone (), + ptr, + }) + } + +// Returns a reference to the underlying [`cpufreq::Table`]. +#[inline] +fn table (&self) -> &cpufreq::Table { +// SAFETY: The `ptr` is guaranteed by the C code to be valid. +unsafe { cpufreq::Table ::from_raw (self.ptr) } + } +} + +#[cfg( CONFIG_CPU_FREQ )] +impl Deref for FreqTable { +type Target = cpufreq::Table ; + +#[inline] +fn deref (&self) -> &Self ::Target { + self.table () + } +} + +#[cfg( CONFIG_CPU_FREQ )] +impl Drop for FreqTable { +fn drop (&mut self) { +// SAFETY: The pointer was created via `dev_pm_opp_init_cpufreq_table`, and is only freed +// here. +unsafe { bindings::dev_pm_opp_free_cpufreq_table (self.dev.as_raw (), &mut self.as_raw ()) }; + } +} +/// A reference-counted OPP table. /// /// Rust abstraction for the C `struct opp_table`.
@@ -752,6 +812,13 @@ pub fn adjust_voltage( }) } +/// Creates [`FreqTable`] from [`Table`]. +#[cfg( CONFIG_CPU_FREQ )] +#[inline] +pub fn cpufreq_table (&mut self) ->Result <FreqTable > { +FreqTable ::new (self) + } +/// Configures device with [`OPP`] matching the frequency value. #[inline] pub fn set_rate (&self, freq:Hertz ) ->Result <()> {
Signature · 1 line
2.31.1.272.g89b43f80a514
Viresh Kumar
maintainerPATCH v9 17/17 cpufreq: Add Rust-based cpufreq-dt driver
In reply to Viresh KumarIntroduce a Rust-based implementation of the cpufreq-dt driver, covering most of the functionality provided by the existing C version. Some features, such as retrieving platform data from cpufreq-dt-platdev.c, are still pending.
The driver has been tested with QEMU, and frequency scaling works as expected.
--- drivers/cpufreq/Kconfig | 12 ++ drivers/cpufreq/Makefile | 1 + drivers/cpufreq/rcpufreq_dt.rs | 236 +++++++++++++++++++++++++++++++++ 3 files changed, 249 insertions(+) create mode 100644 drivers/cpufreq/rcpufreq_dt.rs
drivers/cpufreq/Kconfig +12 -0
@@ -217,6 +217,18 @@ config CPUFREQ_DT If in doubt, say N. +config CPUFREQ_DT_RUST + tristate "Rust based Generic DT based cpufreq driver" + depends on HAVE_CLK && OF && RUST + select CPUFREQ_DT_PLATDEV + select PM_OPP + help + This adds a Rust based generic DT based cpufreq driver for frequency + management. It supports both uniprocessor (UP) and symmetric + multiprocessor (SMP) systems. + + If in doubt, say N. + config CPUFREQ_VIRT tristate "Virtual cpufreq driver" depends on GENERIC_ARCH_TOPOLOGY
drivers/cpufreq/Makefile +1 -0
@@ -15,6 +15,7 @@ obj-$(CONFIG_CPU_FREQ_GOV_COMMON) += cpufreq_governor.o obj-$(CONFIG_CPU_FREQ_GOV_ATTR_SET) += cpufreq_governor_attr_set.o obj-$(CONFIG_CPUFREQ_DT) += cpufreq-dt.o +obj-$(CONFIG_CPUFREQ_DT_RUST) += rcpufreq_dt.o obj-$(CONFIG_CPUFREQ_DT_PLATDEV) += cpufreq-dt-platdev.o obj-$(CONFIG_CPUFREQ_VIRT) += virtual-cpufreq.o
drivers/cpufreq/rcpufreq_dt.rs new file +236 -0
236 lines not on this page · raw message
Signature · 1 line
2.31.1.272.g89b43f80a514
Danilo Krummrich
reviewerRe: [PATCH V9 15/17] rust: cpufreq: Extend abstractions for driver registration
In reply to Viresh KumarQuoted 8 lines · Viresh Kumar
rust/kernel/cpufreq.rs +8
-0+pub struct Registration <T :Driver > { + drv:KBox <UnsafeCell <bindings::cpufreq_driver >>, + _p:PhantomData <T >, +} + +// SAFETY: `Registration` doesn't offer any methods or access to fields when shared between threads +// or CPUs, so it is safe to share it. +unsafe impl <T :Driver >Sync for Registration <T > {}
rust/kernel/cpufreq.rs fn register_em(_policy: &mut Policy) { · line 877
Quoted 10 lines
rust/kernel/cpufreq.rs +10
-0+ +#[allow(clippy::non_send_fields_in_send_ty)] +// SAFETY: Registration with and unregistration from the cpufreq subsystem can happen from any +// thread. Additionally, `T::Data` (which is dropped during unregistration) is `Send`, so it is +// okay to move `Registration` to different threads. +unsafe impl <T :Driver >Send for Registration <T > {} + +impl <T :Driver >Registration <T > { +/// Registers a CPU frequency driver with the cpufreq core. +pub fn new (name: &'staticCStr , data:T ::Data , flags:u16 , boost:bool ) ->Result <Self > {
Do you really need the private data? It seems to be used by only very few drivers in C either.
If yes, I think you have to split this up into a CpufreqDriver structure and a separate Registration. Otherwise you won't ever get access to the private data again, after Registration::new_foreign_owned().
Note that we typically want Registration::new_foreign_owned(), because it implies the guaranteed "fence" for where we can safely consider a device to be bound. If we'd give out a Registration instance instead, the driver can arbitrarily extend its lifetime across the remove() boundary.
If no, it seems to me that you can even avoid allocating a struct cpufreq_driver dynamically and make it const instead. The fields name, boost_enabled and flags could be required consts in your cpufreq::Driver trait.
Yury Norov
maintainerRe: [PATCH V9 01/17] rust: cpumask: Use non-atomic helpers
In reply to Viresh KumarQuoted 19 lines · Viresh Kumar
The cpumask Rust abstractions don't need the atomic variants of helpers for now. Use the non-atomic helpers instead.
Signed-off-by Viresh Kumar <[email protected]>--- rust/helpers/cpumask.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)rust/helpers/cpumask.c +1
-1@@ -2,14 +2,14 @@#include <linux/cpumask.h> -void rust_helper_cpumask_set_cpu (unsigned int cpu,struct cpumask *dstp) +void rust_helper___cpumask_set_cpu (unsigned int cpu,struct cpumask *dstp) {
rust/helpers/cpumask.c line 13
Quoted 10 lines
rust/helpers/cpumask.c +3
-3-cpumask_set_cpu (cpu, dstp); +__cpumask_set_cpu (cpu, dstp); } -void rust_helper_cpumask_clear_cpu (int cpu,struct cpumask *dstp) +void rust_helper___cpumask_clear_cpu (int cpu,struct cpumask *dstp) { -cpumask_clear_cpu (cpu, dstp); +__cpumask_clear_cpu (cpu, dstp); }
Please just add non-atomic helpers after atomic ones.
Yury Norov
maintainerRe: [PATCH V9 03/17] rust: cpumask: Add initial abstractions
In reply to Viresh KumarQuoted 39 lines · Viresh Kumar
Add initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed.
These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks.
Signed-off-by Viresh Kumar <[email protected]>--- rust/kernel/cpumask.rs | 328 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 329 insertions(+) create mode 100644 rust/kernel/cpumask.rsrust/kernel/cpumask.rs new file +20
-0@@ -0,0 +1,328 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU Mask abstractions. +//! +//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h) + +use crate ::{ + alloc::{AllocError ,Flags }, + bindings, + prelude::*, + types::Opaque , +}; + +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +use core::ptr::{self,NonNull }; + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +use core::mem::MaybeUninit ; + +use core::ops::{Deref ,DerefMut };
rust/kernel/cpumask.rs line 30
Quoted 10 lines
rust/kernel/cpumask.rs new file +10
-0+ +/// A CPU Mask. +/// +/// Rust abstraction for the C `struct cpumask`. +/// +/// # Invariants +/// +/// A [`Cpumask`] instance always corresponds to a valid C `struct cpumask`. +/// +/// The callers must ensure that the `struct cpumask` is valid for access and remains valid for the
This line is too long to me.
Quoted 58 lines
rust/kernel/cpumask.rs new file +58
-0+/// lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to update a [`Cpumask`]. +/// +/// ``` +/// use kernel::bindings; +/// use kernel::cpumask::Cpumask; +/// +/// fn set_clear_cpu(ptr: *mut bindings::cpumask, set_cpu: u32, clear_cpu: i32) { +/// // SAFETY: The `ptr` is valid for writing and remains valid for the lifetime of the +/// // returned reference. +/// let mask = unsafe { Cpumask::from_raw_mut(ptr) }; +/// +/// mask.set(set_cpu); +/// mask.clear(clear_cpu); +/// } +/// ``` +#[repr(transparent)] +pub struct Cpumask (Opaque <bindings::cpumask >); + +impl Cpumask { +/// Creates a mutable reference to an existing `struct cpumask` pointer. +/// +/// # Safety +/// +/// 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 ) -> &'amut Self { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the +// lifetime of the returned reference. +unsafe { &mut *ptr.cast () } + } + +/// Creates a reference to an existing `struct cpumask` pointer. +/// +/// # Safety +/// +/// 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 ) -> &'aSelf { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the +// lifetime of the returned reference. +unsafe { &*ptr.cast () } + } + +/// Obtain the raw `struct cpumask` pointer. +pub fn as_raw (&self) -> *mut bindings::cpumask { + selfas *const _ as _ + } + +/// Set `cpu` in the cpumask. +///
rust/kernel/cpumask.rs line 98
Quoted 10 lines
rust/kernel/cpumask.rs new file +10
-0+/// Equivalent to the kernel's `__cpumask_set_cpu` API. +#[inline] +pub fn set (&mut self, cpu:u32 ) { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `__cpumask_set_cpu`. +unsafe { bindings::__cpumask_set_cpu (cpu, self.as_raw ()) }; + } + +/// Clear `cpu` in the cpumask. +/// +/// Equivalent to the kernel's `__cpumask_clear_cpu` API.
Similarly to bitmaps, can you explain here that this is a non-atomic operation?
Quoted 117 lines
rust/kernel/cpumask.rs new file +117
-0+#[inline] +pub fn clear (&mut self, cpu:i32 ) { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to +// `__cpumask_clear_cpu`. +unsafe { bindings::__cpumask_clear_cpu (cpu, self.as_raw ()) }; + } + +/// Test `cpu` in the cpumask. +/// +/// Equivalent to the kernel's `cpumask_test_cpu` API. +#[inline] +pub fn test (&self, cpu:i32 ) ->bool { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_test_cpu`. +unsafe { bindings::cpumask_test_cpu (cpu, self.as_raw ()) } + } + +/// Set all CPUs in the cpumask. +/// +/// Equivalent to the kernel's `cpumask_setall` API. +#[inline] +pub fn setall (&mut self) { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_setall`. +unsafe { bindings::cpumask_setall (self.as_raw ()) }; + } + +/// Checks if cpumask is empty. +/// +/// Equivalent to the kernel's `cpumask_empty` API. +#[inline] +pub fn empty (&self) ->bool { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_empty`. +unsafe { bindings::cpumask_empty (self.as_raw ()) } + } + +/// Checks if cpumask is full. +/// +/// Equivalent to the kernel's `cpumask_full` API. +#[inline] +pub fn full (&self) ->bool { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_full`. +unsafe { bindings::cpumask_full (self.as_raw ()) } + } + +/// Get weight of the cpumask. +/// +/// Equivalent to the kernel's `cpumask_weight` API. +#[inline] +pub fn weight (&self) ->u32 { +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_weight`. +unsafe { bindings::cpumask_weight (self.as_raw ()) } + } + +/// Copy cpumask. +/// +/// Equivalent to the kernel's `cpumask_copy` API. +#[inline] +pub fn copy (&self, dstp: &mut Self ) { +// SAFETY: By the type invariant, `Self::as_raw` is a valid argument to `cpumask_copy`. +unsafe { bindings::cpumask_copy (dstp.as_raw (), self.as_raw ()) }; + } +} + +/// A CPU Mask pointer. +/// +/// Rust abstraction for the C `struct cpumask_var_t`. +/// +/// # Invariants +/// +/// A [`CpumaskVar`] instance always corresponds to a valid C `struct cpumask_var_t`. +/// +/// The callers must ensure that the `struct cpumask_var_t` is valid for access and remains valid +/// for the lifetime of [`CpumaskVar`]. +/// +/// ## Examples +/// +/// The following example demonstrates how to create and update a [`CpumaskVar`]. +/// +/// ``` +/// use kernel::cpumask::CpumaskVar; +/// +/// let mut mask = CpumaskVar::new(GFP_KERNEL).unwrap(); +/// +/// assert!(mask.empty()); +/// mask.set(2); +/// assert!(mask.test(2)); +/// mask.set(3); +/// assert!(mask.test(3)); +/// assert_eq!(mask.weight(), 2); +/// +/// let mask2 = CpumaskVar::try_clone(&mask).unwrap(); +/// assert!(mask2.test(2)); +/// assert!(mask2.test(3)); +/// assert_eq!(mask2.weight(), 2); +/// ``` +pub struct CpumaskVar { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr:NonNull <Cpumask >, +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] + mask:Cpumask , +} + +impl CpumaskVar { +/// Creates an initialized instance of the [`CpumaskVar`]. +pub fn new (_flags:Flags ) ->Result <Self ,AllocError > { +Ok (Self { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr: { +let mut ptr: *mut bindings::cpumask = ptr::null_mut (); + +// SAFETY: Depending on the value of `_flags`, this call may sleep. Other than +// that, it is always safe to call this method. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of +// scope. +unsafe { bindings::zalloc_cpumask_var (&mut ptr, _flags.as_raw ()) }; +NonNull ::new (ptr.cast ()).ok_or (AllocError )? + },
rust/kernel/cpumask.rs line 225
Quoted 10 lines
rust/kernel/cpumask.rs new file +10
-0+ +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +// SAFETY: FFI type is valid to be zero-initialized. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of scope. + mask: unsafe { core::mem::zeroed() }, + }) + } + +/// Creates an uninitialized instance of the [`CpumaskVar`].
I would do this another way: introduce new() that calls alloc_cpumask_var(), and new_zero() binded to zalloc() version. Your statement here is simply wrong because I can pass GFP_ZERO and 'hack' all your architecture.
rust/kernel/cpumask.rs line 238
Quoted 13 lines
rust/kernel/cpumask.rs new file +13
-0+/// +/// # Safety +/// +/// The caller must ensure that the returned [`CpumaskVar`] is properly initialized before +/// getting used. +unsafe fn new_uninit (_flags:Flags ) ->Result <Self ,AllocError > { +Ok (Self { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr: { +let mut ptr: *mut bindings::cpumask = ptr::null_mut (); + +// SAFETY: Depending on the value of `_flags`, this call may sleep. Other than +// that, it is always safe to call this method.
I'm not sure I understand this sentence. What's wrong with safety when the alloc() function sleeps? Even if something is wrong. If you really want to protect your users, you'd introduce new_sync() version that returns error if user provides sleeping flags.
To that extend, once you write so many flavors of constructors, I bet your users will be happy if you hide the 'flags' entirely:
new_gfp(flags);
new();
new_zero(); // or znew()?
new_sync();Quoted 11 lines
rust/kernel/cpumask.rs new file +11
-0+// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of +// scope. +unsafe { bindings::alloc_cpumask_var (&mut ptr, _flags.as_raw ()) }; +NonNull ::new (ptr.cast ()).ok_or (AllocError )? + }, +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of scope. + mask: unsafe { MaybeUninit::uninit().assume_init() },
rust/kernel/cpumask.rs line 259
Quoted 10 lines
rust/kernel/cpumask.rs new file +10
-0+ }) + } + +/// Creates a mutable reference to an existing `struct cpumask_var_t` pointer. +/// +/// # Safety +/// +/// 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_var_t ) -> &'amut Self {
The 'from' (wrt cpumasks) has a special meaning: search for a cpu starting from a given one. This 'from_raw' may confuse readers. Have you any other name for it in mind?
Quoted 13 lines
rust/kernel/cpumask.rs new file +13
-0+// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the +// lifetime of the returned reference. +unsafe { &mut *ptr.cast () } + } + +/// Creates a reference to an existing `struct cpumask_var_t` pointer. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime +/// of the returned reference.
rust/kernel/cpumask.rs line 282
Quoted 10 lines
rust/kernel/cpumask.rs new file +10
-0+pub unsafe fn from_raw <'a>(ptr: *const bindings::cpumask_var_t ) -> &'aSelf { +// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the +// lifetime of the returned reference. +unsafe { &*ptr.cast () } + } + +/// Clones cpumask. +pub fn try_clone (cpumask: &Cpumask ) ->Result <Self > {
Just clone(), I think.
Quoted 60 lines
rust/kernel/cpumask.rs new file +46
-0+// SAFETY: The returned cpumask_box is initialized right after this call. +let mut cpumask_box =unsafe {Self ::new_uninit (GFP_KERNEL ) }?; + + cpumask.copy (&mut cpumask_box); +Ok (cpumask_box) + } +} + +// Make [`CpumaskVar`] behave like a pointer to [`Cpumask`]. +impl Deref for CpumaskVar { +type Target =Cpumask ; + +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +fn deref (&self) -> &Self ::Target { +// SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask. +unsafe { &*self.ptr.as_ptr () } + } + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +fn deref (&self) -> &Self ::Target { + &self.mask + } +} + +impl DerefMut for CpumaskVar { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +fn deref_mut (&mut self) -> &mut Cpumask { +// SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask. +unsafe { self.ptr.as_mut () } + } + +#[cfg(not( CONFIG_CPUMASK_OFFSTACK ))] +fn deref_mut (&mut self) -> &mut Cpumask { + &mut self.mask + } +} + +impl Drop for CpumaskVar { +fn drop (&mut self) { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] +// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `free_cpumask_var`. +unsafe { + bindings::free_cpumask_var (self.as_raw ()) + }; + } +}rust/kernel/lib.rs +1
-0@@ -42,6 +42,7 @@pub mod block;#[doc(hidden)] pub mod build_assert; +pub mod cpumask;pub mod cred;pub mod device;pub mod device_id;Signature · 1 line
2.31.1.272.g89b43f80a514
Yury Norov
maintainerRe: [PATCH V9 08/17] cpufreq: Use enum for cpufreq flags that use BIT()
In reply to Viresh KumarQuoted 1 line · Viresh Kumar
The
BIT()macro is too complex for Rust's bindgen to interpret as
The BIT() is as simple as '1 << nr'. How that it's so complex for that tool to realize that '1 << 2' is the constant?
Quoted 6 lines
integer constants. This results in many of the cpufreq macros being undefined in Rust auto-generated bindings. By replacing the "#define" macros with an "enum", we ensure that bindgen can properly evaluate these values, enabling their seamless use in Rust code.
No intentional functional impact.
The code you're wiping is perfectly correct. And you clearly state that one of your tools is broken. Please fix your tool or find any other solution.
We don't touch correct code, sorry.
Quoted 128 lines
Suggested-by Alice Ryhl <[email protected]>Signed-off-by Viresh Kumar <[email protected]>--- include/linux/cpufreq.h | 96 ++++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 45 deletions(-)include/linux/cpufreq.h +51
-45@@ -298,11 +298,12 @@ static inline void cpufreq_stats_record_transition(struct cpufreq_policy *policy* CPUFREQ DRIVER INTERFACE * *********************************************************************/ -#define CPUFREQ_RELATION_L 0/* lowest frequency at or above target */ -#define CPUFREQ_RELATION_H 1/* highest frequency below or at target */ -#define CPUFREQ_RELATION_C 2/* closest frequency to target */ -/* relation flags */ -#define CPUFREQ_RELATION_E BIT(2)/* Get if possible an efficient frequency */ +enum { +CPUFREQ_RELATION_L =0 ,/* lowest frequency at or above target */ +CPUFREQ_RELATION_H =BIT (0 ),/* highest frequency below or at target */ +CPUFREQ_RELATION_C =BIT (1 ),/* closest frequency to target */ +CPUFREQ_RELATION_E =BIT (2 ),/* Get if possible an efficient frequency */ +};#define CPUFREQ_RELATION_LE (CPUFREQ_RELATION_L | CPUFREQ_RELATION_E)#define CPUFREQ_RELATION_HE (CPUFREQ_RELATION_H | CPUFREQ_RELATION_E)@@ -424,52 +425,57 @@ struct cpufreq_driver {/* flags */ -/* -* Set by drivers that need to update internal upper and lower boundaries along -* with the target frequency and so the core and governors should also invoke -* the diver if the target frequency does not change, but the policy min or max -* may have changed. -*/ -#define CPUFREQ_NEED_UPDATE_LIMITS BIT(0) +enum { +/* +* Set by drivers that need to update internal upper and lower +* boundaries along with the target frequency and so the core and +* governors should also invoke the diver if the target frequency does +* not change, but the policy min or max may have changed. +*/ +CPUFREQ_NEED_UPDATE_LIMITS =BIT (0 ), -/* loops_per_jiffy or other kernel "constants" aren't affected by frequency transitions */ -#define CPUFREQ_CONST_LOOPS BIT(1) +/* +* loops_per_jiffy or other kernel "constants" aren't affected by +* frequency transitions. +*/ +CPUFREQ_CONST_LOOPS =BIT (1 ), -/* -* Set by drivers that want the core to automatically register the cpufreq -* driver as a thermal cooling device. -*/ -#define CPUFREQ_IS_COOLING_DEV BIT(2) +/* +* Set by drivers that want the core to automatically register the +* cpufreq driver as a thermal cooling device. +*/ +CPUFREQ_IS_COOLING_DEV =BIT (2 ), -/* -* This should be set by platforms having multiple clock-domains, i.e. -* supporting multiple policies. With this sysfs directories of governor would -* be created in cpu/cpu<num>/cpufreq/ directory and so they can use the same -* governor with different tunables for different clusters. -*/ -#define CPUFREQ_HAVE_GOVERNOR_PER_POLICY BIT(3) +/* +* This should be set by platforms having multiple clock-domains, i.e. +* supporting multiple policies. With this sysfs directories of governor +* would be created in cpu/cpu<num>/cpufreq/ directory and so they can +* use the same governor with different tunables for different clusters. +*/ +CPUFREQ_HAVE_GOVERNOR_PER_POLICY =BIT (3 ), -/* -* Driver will do POSTCHANGE notifications from outside of their ->target() -* routine and so must set cpufreq_driver->flags with this flag, so that core -* can handle them specially. -*/ -#define CPUFREQ_ASYNC_NOTIFICATION BIT(4) +/* +* Driver will do POSTCHANGE notifications from outside of their +* ->target() routine and so must set cpufreq_driver->flags with this +* flag, so that core can handle them specially. +*/ +CPUFREQ_ASYNC_NOTIFICATION =BIT (4 ), -/* -* Set by drivers which want cpufreq core to check if CPU is running at a -* frequency present in freq-table exposed by the driver. For these drivers if -* CPU is found running at an out of table freq, we will try to set it to a freq -* from the table. And if that fails, we will stop further boot process by -* issuing a BUG_ON(). -*/ -#define CPUFREQ_NEED_INITIAL_FREQ_CHECK BIT(5) +/* +* Set by drivers which want cpufreq core to check if CPU is running at +* a frequency present in freq-table exposed by the driver. For these +* drivers if CPU is found running at an out of table freq, we will try +* to set it to a freq from the table. And if that fails, we will stop +* further boot process by issuing a BUG_ON(). +*/ +CPUFREQ_NEED_INITIAL_FREQ_CHECK =BIT (5 ), -/* -* Set by drivers to disallow use of governors with "dynamic_switching" flag -* set. -*/ -#define CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING BIT(6) +/* +* Set by drivers to disallow use of governors with "dynamic_switching" +* flag set. +*/ +CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING =BIT (6 ), +};int cpufreq_register_driver (struct cpufreq_driver *driver_data);void cpufreq_unregister_driver (struct cpufreq_driver *driver_data);Signature · 1 line
2.31.1.272.g89b43f80a514
Yury Norov
maintainerRe: [PATCH V9 09/17] rust: cpu: Add from_cpu()
In reply to Viresh KumarQuoted 64 lines · Viresh Kumar
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 <[email protected]>--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/cpu.rs | 31 +++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 34 insertions(+) create mode 100644 rust/kernel/cpu.rsMAINTAINERS +1
-0@@ -6155,6 +6155,7 @@ F: include/linux/cpuhotplug.h F: include/linux/smpboot.h F: kernel/cpu.c F: kernel/smpboot.* +F: rust/kernel/cpu.rs CPU IDLE TIME MANAGEMENT FRAMEWORK M: "Rafael J. Wysocki" <[email protected]>rust/bindings/bindings_helper.h +1
-0@@ -11,6 +11,7 @@#include <linux/blk_types.h> #include <linux/blkdev.h> #include <linux/clk.h> +#include <linux/cpu.h> #include <linux/cpumask.h> #include <linux/cred.h> #include <linux/device/faux.h> rust/kernel/cpu.rs new file +19
-0@@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Generic CPU definitions. +//! +//! C header: [`include/linux/cpu.h`](srctree/include/linux/cpu.h) + +use crate ::{bindings, device::Device , error::Result , prelude::ENODEV }; + +/// Creates a new instance of CPU's device. +/// +/// # Safety +/// +/// Reference counting is not implemented for the CPU device in the C code. When a CPU is +/// hot-unplugged, the corresponding CPU device is unregistered, but its associated memory +/// is not freed. +/// +/// Callers must ensure that the CPU device is not used after it has been unregistered. +/// This can be achieved, for example, by registering a CPU hotplug notifier and removing +/// any references to the CPU device within the notifier's callback.
rust/kernel/cpu.rs line 29
Quoted 10 lines
rust/kernel/cpu.rs new file +10
-0+pub unsafe fn from_cpu (cpu:u32 ) ->Result <&'staticDevice > { +// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to +// a `struct device` and is never freed by the C code. +let ptr =unsafe { bindings::get_cpu_device (cpu) }; +if ptr.is_null () { +return Err (ENODEV ); + } + +// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to +// a `struct device` and is never freed by the C code.
If you think that writing the same thing twice would help in SAFETY department, I'd recommend you to write it for a couple more times.
Quoted 16 lines
rust/kernel/cpu.rs new file +2
-0+Ok (unsafe {Device ::as_ref (ptr) }) +}rust/kernel/lib.rs +1
-0@@ -44,6 +44,7 @@pub mod build_assert;#[cfg( CONFIG_COMMON_CLK )] pub mod clk; +pub mod cpu;pub mod cpumask;pub mod cred;pub mod device;Signature · 1 line
2.31.1.272.g89b43f80a514
Yury Norov
maintainerRe: [PATCH V9 11/17] rust: opp: Add abstractions for the OPP table
In reply to Viresh KumarQuoted 93 lines · Viresh Kumar
Introduce Rust abstractions for
struct opp_table, enabling access to OPP tables from Rust.Signed-off-by Viresh Kumar <[email protected]>--- rust/kernel/opp.rs | 495 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 494 insertions(+), 1 deletion(-)rust/kernel/opp.rs +68
-1@@ -11,8 +11,9 @@use crate ::{ bindings, clk::Hertz , + cpumask::{Cpumask ,CpumaskVar }, device::Device , - error::{code::*, to_result,Result }, + error::{code::*, from_err_ptr, to_result,Error ,Result }, ffi::c_ulong, types::{ARef ,AlwaysRefCounted ,Opaque }, };@@ -172,6 +173,477 @@ fn freq(&self) -> Hertz { } } +/// [`OPP`] search options. +/// +/// ## Examples +/// +/// Defines how to search for an [`OPP`] in a [`Table`] relative to a frequency. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::error::Result; +/// use kernel::opp::{OPP, SearchType, Table}; +/// use kernel::types::ARef; +/// +/// fn find_opp(table: &Table, freq: Hertz) -> Result<ARef<OPP>> { +/// let opp = table.opp_from_freq(freq, Some(true), None, SearchType::Exact)?; +/// +/// pr_info!("OPP frequency is: {:?}\n", opp.freq(None)); +/// pr_info!("OPP voltage is: {:?}\n", opp.voltage()); +/// pr_info!("OPP level is: {}\n", opp.level()); +/// pr_info!("OPP power is: {:?}\n", opp.power()); +/// +/// Ok(opp) +/// } +/// ``` +#[derive( Copy , Clone , Debug , Eq , PartialEq )] +pub enum SearchType { +/// Match the exact frequency. +Exact , +/// Find the highest frequency less than or equal to the given value. +Floor , +/// Find the lowest frequency greater than or equal to the given value. +Ceil , +} + +/// A reference-counted OPP table. +/// +/// Rust abstraction for the C `struct opp_table`. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of the [`Table`]. +/// +/// Instances of this type are reference-counted. +/// +/// ## Examples +/// +/// The following example demonstrates how to get OPP [`Table`] for a [`Cpumask`] and set its +/// frequency. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::cpumask::Cpumask; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::Table; +/// use kernel::types::ARef; +/// +/// fn get_table(dev: &ARef<Device>, mask: &mut Cpumask, freq: Hertz) -> Result<Table> { +/// let mut opp_table = Table::from_of_cpumask(dev, mask)?; +/// +/// if opp_table.opp_count()? == 0 { +/// return Err(EINVAL); +/// } +/// +/// pr_info!("Max transition latency is: {} ns\n", opp_table.max_transition_latency_ns()); +/// pr_info!("Suspend frequency is: {:?}\n", opp_table.suspend_freq()); +///
rust/kernel/opp.rs fn freq(&self) -> Hertz { · line 251
Quoted 10 lines
rust/kernel/opp.rs +10
-0+/// opp_table.set_rate(freq)?; +/// Ok(opp_table) +/// } +/// ``` +pub struct Table { + ptr: *mut bindings::opp_table , + dev:ARef <Device >, + em:bool , + of:bool , + cpumask_box:Option <CpumaskVar >,
The other fields have short names. Maybe just 'cpus' instead of cpumask_box? If you want to put the type of variable into the name, it should be a cpumask_var.
Quoted 1 line
rust/kernel/opp.rs +1
-0+}
Re: [PATCH V9 08/17] cpufreq: Use enum for cpufreq flags that use BIT()
In reply to Yury NorovQuoted 3 lines · Yury Norov
The
BIT()is as simple as '1 << nr'. How that it's so complex for that tool to realize that '1 << 2' is the constant?
It is a C macro which requires evaluating a C expression as the C compiler would.
A solution (a workaround, really) in bindgen is coming, that essentially forces libclang to evaluate it for us, but even if it works perfectly fine already, it will require upgrading the minimum version and so on, so it will take time.
For the moment, either we do something like this (a similar approach was used for some enums in Binder) or the values can be replicated on the Rust side (ideally with a test somewhere to ensure they are in sync). The latter may be best if the values have not changed much over time, i.e. if there is low maintenance required.
I hope that helps.
Cheers,
Miguel
Danilo Krummrich
reviewerRe: [PATCH V9 09/17] rust: cpu: Add from_cpu()
In reply to Yury NorovQuoted 16 lines · Yury Norov
Quoted 5 lines · Viresh Kumar
rust/kernel/cpu.rs new file +5
-0+/// Creates a new instance of CPU's device. +/// +/// # Safety +/// +/// Reference counting is not implemented for the CPU device in the C code. When a CPU is rust/kernel/cpu.rs line 23
Quoted 10 lines
rust/kernel/cpu.rs new file +10
-0+/// hot-unplugged, the corresponding CPU device is unregistered, but its associated memory +/// is not freed. +/// +/// Callers must ensure that the CPU device is not used after it has been unregistered. +/// This can be achieved, for example, by registering a CPU hotplug notifier and removing +/// any references to the CPU device within the notifier's callback. +pub unsafe fn from_cpu (cpu:u32 ) ->Result <&'staticDevice > { +// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to +// a `struct device` and is never freed by the C code. +let ptr =unsafe { bindings::get_cpu_device (cpu) };
You don't need to justify the return value here, you need to justify why cpu is a valid value to call get_cpu_device() with.
Quoted 6 lines
rust/kernel/cpu.rs line 29
Quoted 6 lines
rust/kernel/cpu.rs new file +6
-0+if ptr.is_null () { +return Err (ENODEV ); + } + +// SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to +// a `struct device` and is never freed by the C code.
Here, the comment is good.
Quoted 2 lines
If you think that writing the same thing twice would help in SAFETY department, I'd recommend you to write it for a couple more times.
Fixing the above, should also fix the duplication. :)
Quoted 1 line
Quoted 1 line
+
Ok(unsafe { Device::as_ref(ptr) })
Viresh Kumar
maintainerRe: [PATCH V9 15/17] rust: cpufreq: Extend abstractions for driver registration
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Review
Quoted 3 lines · Viresh Kumar
(quoted diff) +3
-0+impl<T: Driver> Registration<T> { + /// Registers a CPU frequency driver with the cpufreq core. + pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> Result<Self> {Do you really need the private data? It seems to be used by only very few drivers in C either.
Yes, only a few of them are setting it to a value other than pdev. Maybe we can avoid it for the time being and come back to this when a driver really wants it.
Quoted 2 lines
If no, it seems to me that you can even avoid allocating a struct
cpufreq_driverdynamically and make it const instead.
I am not sure if I understood your suggestion. The Registration::new() method still updates the instance of cpufreq_driver before passing it to the C cpufreq core.
I have tried to fix the other issues though.
Signature · 1 line
viresh
drivers/cpufreq/rcpufreq_dt.rs +5 -8
@@ -59,7 +59,10 @@ impl opp::ConfigOps for CPUFreqDTDriver {}#[vtable] impl cpufreq::Driver for CPUFreqDTDriver { -type Data = (); +const NAME : &CStr =c_str! ("cpufreq-dt" ); +const FLAGS :u16 = cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV ; +const BOOST_ENABLED :bool =true ; +type PData =Arc <CPUFreqDTDevice >;fn init (policy: &mut cpufreq::Policy ) ->Result <Self ::PData > {
@@ -213,13 +216,7 @@ fn probe( pdev: &platform::Device<Core>, _id_info: Option<&Self::IdInfo>, ) -> Result<Pin<KBox<Self>>> { - cpufreq::Registration ::<CPUFreqDTDriver >::new_foreign_owned ( - pdev.as_ref (), -c_str! ("cpufreq-dt" ), - (), - cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV , -true , - )?; + cpufreq::Registration ::<CPUFreqDTDriver >::new_foreign_owned (pdev.as_ref ())?;let drvdata =KBox ::new (Self {},GFP_KERNEL )?;
rust/kernel/cpufreq.rs +24 -77
167 lines not on this page · raw message
Danilo Krummrich
reviewerRe: [PATCH V9 15/17] rust: cpufreq: Extend abstractions for driver registration
Quoted 9 lines · Viresh Kumar
Quoted 4 lines · Danilo Krummrich
On Fri, Apr 11, 2025 at 04:25:14PM +0530, Viresh Kumar wrote:
If no, it seems to me that you can even avoid allocating a struct
cpufreq_driverdynamically and make it const instead.I am not sure if I understood your suggestion. The
Registration::new()method still updates the instance ofcpufreq_driverbefore passing it to the C cpufreq core.
See comment in the diff below.
Quoted 53 lines
rust/kernel/cpufreq.rs +13
-10@@ -685,13 +685,14 @@ fn drop(&mut self) {/// Reference: <https://docs.kernel.org/cpu-freq/cpu-drivers.html> #[vtable] pub trait Driver { -/// Driver specific data. -/// -/// Corresponds to the data retrieved via the kernel's `cpufreq_get_driver_data` function. -/// -/// Require `Data` to implement `ForeignOwnable`. We guarantee to never move the underlying -/// wrapped data structure. -type Data :ForeignOwnable ; +/// Driver's name. +const NAME : &'staticCStr ; + +/// Driver's flags. +const FLAGS :u16 ; + +/// Boost support. +const BOOST_ENABLED :bool ;/// Policy specific data. /// @@ -804,8 +805,8 @@ fn register_em(_policy: &mut Policy) {/// /// ``` /// use kernel::{ -/// c_str, /// cpu, cpufreq, +/// c_str, /// device::Device, /// macros::vtable, /// sync::Arc, @@ -817,7 +818,10 @@ fn register_em(_policy: &mut Policy) {/// /// #[vtable] /// impl cpufreq::Driver for FooDriver { -/// type Data = (); +/// const NAME: &'static CStr = c_str!("cpufreq-foo"); +/// const FLAGS: u16 = cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV; +/// const BOOST_ENABLED: bool = true; +/// /// type PData = Arc<FooDevice>; /// /// fn init(policy: &mut cpufreq::Policy) -> Result<Self::PData> { @@ -848,13 +852,7 @@ fn register_em(_policy: &mut Policy) {/// } /// /// fn foo_probe(dev: &Device) { -/// cpufreq::Registration::<FooDriver>::new_foreign_owned(
rust/kernel/cpufreq.rs fn register_em(_policy: &mut Policy) { · line 858
Quoted 10 lines
rust/kernel/cpufreq.rs +1
-6-/// dev, -/// c_str!("cpufreq-foo"), -/// (), -/// cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV, -/// true, -/// ).unwrap(); +/// cpufreq::Registration::<FooDriver>::new_foreign_owned(dev).unwrap(); /// } /// ``` pub struct Registration <T :Driver > {
You could define Registration<T: Driver> as
pub struct Registration<T: Driver>( NonNull<bindings::cpufreq_driver>, PhantomData<T> );
and subsequently...
rust/kernel/cpufreq.rs unsafe impl<T: Driver> Sync for Registration<T> {} · line 872
Quoted 10 lines
rust/kernel/cpufreq.rs +1
-2@@ -868,13 +866,12 @@ unsafe impl<T: Driver> Sync for Registration<T> {}#[allow(clippy::non_send_fields_in_send_ty)] // SAFETY: Registration with and unregistration from the cpufreq subsystem can happen from any -// thread. Additionally, `T::Data` (which is dropped during unregistration) is `Send`, so it is -// okay to move `Registration` to different threads. +// thread. unsafe impl <T :Driver >Send for Registration <T > {}impl <T :Driver >Registration <T > {
...add a new const of type bindings::cpufreq_driver, i.e.
const VTABLE: bindings::cpufreq_driver = bindings::cpufreq_driver {
name: Self::copy_name(T::NAME),
boost_enabled: T::BOOST_ENABLED,
flags: T::FLAGS,
[...]
}
const fn copy_name(name: &'static CStr) -> [kernel::ffi::c_char; CPUFREQ_NAME_LEN] {
let src name.as_bytes_with_nul();
let mut dst = [0; CPUFREQ_NAME_LEN];
build_assert!(name.len() <= dst.len());
let mut i = 0;
while i < dst.len() {
dst[i] = src[i];
i += 1;
}
dst
}You should then be able to store a pointer of Self::VTABLE in your Registration and and hence avoid dynamic allocation of struct cpufreq_driver.
Quoted 107 lines
rust/kernel/cpufreq.rs +9
-59/// Registers a CPU frequency driver with the cpufreq core. -pub fn new (name: &'staticCStr , data:T ::Data , flags:u16 , boost:bool ) ->Result <Self > { +pub fn new () ->Result <Self > {// Required due to Rust 1.82's stricter handling of `unsafe` in mutable statics. The // `unsafe` blocks aren't required anymore with later versions. #![allow(unused_unsafe)] @@ -886,18 +883,18 @@ pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> Resullet drv_ref = drv.get_mut ();// Account for the trailing null byte. -let len = name.len () +1 ; +let len =T ::NAME .len () +1 ;if len > drv_ref.name.len () {return Err (EINVAL ); }; -// SAFETY: `name` is a valid `CStr`, and we are copying it to an array of equal or larger -// size. -let name =unsafe { &*(name.as_bytes_with_nul ()as *const [u8 ]) }; +// SAFETY: `T::NAME` is a valid `CStr`, and we are copying it to an array of equal or +// larger size. +let name =unsafe { &*(T ::NAME .as_bytes_with_nul ()as *const [u8 ]) }; drv_ref.name[..len].copy_from_slice (name); - drv_ref.boost_enabled = boost; - drv_ref.flags = flags; + drv_ref.boost_enabled =T ::BOOST_ENABLED ; + drv_ref.flags =T ::FLAGS ;// Initialize mandatory callbacks. drv_ref.init =Some (Self ::init_callback);@@ -995,10 +992,6 @@ pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> ResulNone }; -// Set driver data before registering the driver, as the cpufreq core calls few callbacks -// before `cpufreq_register_driver` returns. -Self ::set_data (drv_ref, data)?; -// SAFETY: It is safe to register the driver with the cpufreq core in the kernel C code. to_result (unsafe { bindings::cpufreq_register_driver (drv_ref) })?;@@ -1012,53 +1005,10 @@ pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> Resul/// /// Instead the [`Registration`] is owned by [`Devres`] and will be revoked / dropped, once the /// device is detached. -pub fn new_foreign_owned ( - dev: &Device , - name: &'staticCStr , - data:T ::Data , - flags:u16 , - boost:bool , - ) ->Result <()> { -Devres ::new_foreign_owned (dev,Self ::new (name, data, flags, boost)?,GFP_KERNEL )?; +pub fn new_foreign_owned (dev: &Device ) ->Result <()> { +Devres ::new_foreign_owned (dev,Self ::new ()?,GFP_KERNEL )?;Ok (()) } - -// Sets the `Data` for the CPU frequency driver. -fn set_data (drv: &mut bindings::cpufreq_driver , data:T ::Data ) ->Result <()> { -if drv.driver_data.is_null () { -// Transfer the ownership of the data to the C code. - drv.driver_data = <T ::Data as ForeignOwnable >::into_foreign (data)as _ ; -Ok (()) - }else { -Err (EBUSY ) - } - } - -/// Returns borrowed `Data` previously set for the CPU frequency driver. -pub fn data (&mut self) ->Option <<T ::Data as ForeignOwnable >::Borrowed <'static>> { -let drv = self.drv.get_mut (); - -if drv.driver_data.is_null () { -None - }else { -// SAFETY: The data is earlier set by us from `set_data`. -Some (unsafe { <T ::Data as ForeignOwnable >::borrow (drv.driver_data) }) - } - } - -// Clears and returns the `Data` for the CPU frequency driver. -fn clear_data (&mut self) ->Option <T ::Data > { -let drv = self.drv.get_mut (); - -if drv.driver_data.is_null () { -None - }else { -// SAFETY: The data is earlier set by us from `set_data`. -let data =Some (unsafe { <T ::Data as ForeignOwnable >::from_foreign (drv.driver_data) }); - drv.driver_data = ptr::null_mut (); - data - } - } }// CPU frequency driver callbacks. @@ -1313,8 +1263,5 @@ fn drop(&mut self) {// SAFETY: The driver was earlier registered from `new`. unsafe { bindings::cpufreq_unregister_driver (drv) }; - -// Free data -drop (self.clear_data ()); } }
Viresh Kumar
maintainerRe: [PATCH V9 15/17] rust: cpufreq: Extend abstractions for driver registration
Quoted 6 lines · Danilo Krummrich
const VTABLE: bindings::cpufreq_driver = bindings::cpufreq_driver {
name: Self::copy_name(T::NAME),
boost_enabled: T::BOOST_ENABLED,
flags: T::FLAGS,
[...]
}Ahh, thanks for this.
Signature · 1 line
viresh
rust/kernel/cpufreq.rs +79 -78
@@ -9,28 +9,32 @@//! Reference: <https://docs.kernel.org/admin-guide/pm/cpufreq.html> use crate ::{ + alloc::AllocError , bindings, clk::{Clk ,Hertz }, cpumask, device::Device , devres::Devres , error::{code::*, from_err_ptr, from_result, to_result,Result ,VTABLE_DEFAULT_ERROR }, - ffi::c_ulong, + ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable , types::Opaque , };use core::{ - cell::UnsafeCell , marker::PhantomData , + mem::MaybeUninit , ops::{Deref ,DerefMut }, pin::Pin , - ptr, + ptr::{self,NonNull }, };use macros::vtable; +// Maximum length of CPU frequency driver's name. +const CPUFREQ_NAME_LEN :usize = bindings::CPUFREQ_NAME_LEN as usize ; +/// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS :u32 = bindings::CPUFREQ_ETERNAL as u32 ;
@@ -855,10 +859,8 @@ fn register_em(_policy: &mut Policy) {/// cpufreq::Registration::<FooDriver>::new_foreign_owned(dev).unwrap(); /// } /// ``` -pub struct Registration <T :Driver > { - drv:KBox <UnsafeCell <bindings::cpufreq_driver >>, - _p:PhantomData <T >, -} +#[repr(transparent)] +pub struct Registration <T :Driver >(NonNull <bindings::cpufreq_driver >,PhantomData <T >);// SAFETY: `Registration` doesn't offer any methods or access to fields when shared between threads // or CPUs, so it is safe to share it.
@@ -870,135 +872,136 @@ unsafe impl<T: Driver> Sync for Registration<T> {}unsafe impl <T :Driver >Send for Registration <T > {}impl <T :Driver >Registration <T > { -/// Registers a CPU frequency driver with the cpufreq core. -pub fn new () ->Result <Self > { -// Required due to Rust 1.82's stricter handling of `unsafe` in mutable statics. The -// `unsafe` blocks aren't required anymore with later versions. -#![allow(unused_unsafe)] - -let mut drv =KBox ::new ( -UnsafeCell ::new (bindings::cpufreq_driver::default ()), -GFP_KERNEL , - )?; -let drv_ref = drv.get_mut (); - -// Account for the trailing null byte. -let len =T ::NAME .len () +1 ; -if len > drv_ref.name.len () { -return Err (EINVAL ); - }; - -// SAFETY: `T::NAME` is a valid `CStr`, and we are copying it to an array of equal or -// larger size. -let name =unsafe { &*(T ::NAME .as_bytes_with_nul ()as *const [u8 ]) }; - drv_ref.name[..len].copy_from_slice (name); - - drv_ref.boost_enabled =T ::BOOST_ENABLED ; - drv_ref.flags =T ::FLAGS ; +const VTABLE : bindings::cpufreq_driver = bindings::cpufreq_driver { + name:Self ::copy_name (T ::NAME ), + boost_enabled:T ::BOOST_ENABLED , + flags:T ::FLAGS ,// Initialize mandatory callbacks. - drv_ref.init =Some (Self ::init_callback); - drv_ref.verify =Some (Self ::verify_callback); + init:Some (Self ::init_callback), + verify:Some (Self ::verify_callback),// Initialize optional callbacks based on the traits of `T`. - drv_ref.setpolicy =if T ::HAS_SETPOLICY { + setpolicy:if T ::HAS_SETPOLICY {Some (Self ::setpolicy_callback) }else {None - }; - drv_ref.target =if T ::HAS_TARGET { + }, + target:if T ::HAS_TARGET {Some (Self ::target_callback) }else {None - }; - drv_ref.target_index =if T ::HAS_TARGET_INDEX { + }, + target_index:if T ::HAS_TARGET_INDEX {Some (Self ::target_index_callback) }else {None - }; - drv_ref.fast_switch =if T ::HAS_FAST_SWITCH { + }, + fast_switch:if T ::HAS_FAST_SWITCH {Some (Self ::fast_switch_callback) }else {None - }; - drv_ref.adjust_perf =if T ::HAS_ADJUST_PERF { + }, + adjust_perf:if T ::HAS_ADJUST_PERF {Some (Self ::adjust_perf_callback) }else {None - }; - drv_ref.get_intermediate =if T ::HAS_GET_INTERMEDIATE { + }, + get_intermediate:if T ::HAS_GET_INTERMEDIATE {Some (Self ::get_intermediate_callback) }else {None - }; - drv_ref.target_intermediate =if T ::HAS_TARGET_INTERMEDIATE { + }, + target_intermediate:if T ::HAS_TARGET_INTERMEDIATE {Some (Self ::target_intermediate_callback) }else {None - }; - drv_ref.get =if T ::HAS_GET { + }, + get:if T ::HAS_GET {Some (Self ::get_callback) }else {None - }; - drv_ref.update_limits =if T ::HAS_UPDATE_LIMITS { + }, + update_limits:if T ::HAS_UPDATE_LIMITS {Some (Self ::update_limits_callback) }else {None - }; - drv_ref.bios_limit =if T ::HAS_BIOS_LIMIT { + }, + bios_limit:if T ::HAS_BIOS_LIMIT {Some (Self ::bios_limit_callback) }else {None - }; - drv_ref.online =if T ::HAS_ONLINE { + }, + online:if T ::HAS_ONLINE {Some (Self ::online_callback) }else {None - }; - drv_ref.offline =if T ::HAS_OFFLINE { + }, + offline:if T ::HAS_OFFLINE {Some (Self ::offline_callback) }else {None - }; - drv_ref.exit =if T ::HAS_EXIT { + }, + exit:if T ::HAS_EXIT {Some (Self ::exit_callback) }else {None - }; - drv_ref.suspend =if T ::HAS_SUSPEND { + }, + suspend:if T ::HAS_SUSPEND {Some (Self ::suspend_callback) }else {None - }; - drv_ref.resume =if T ::HAS_RESUME { + }, + resume:if T ::HAS_RESUME {Some (Self ::resume_callback) }else {None - }; - drv_ref.ready =if T ::HAS_READY { + }, + ready:if T ::HAS_READY {Some (Self ::ready_callback) }else {None - }; - drv_ref.set_boost =if T ::HAS_SET_BOOST { + }, + set_boost:if T ::HAS_SET_BOOST {Some (Self ::set_boost_callback) }else {None - }; - drv_ref.register_em =if T ::HAS_REGISTER_EM { + }, + register_em:if T ::HAS_REGISTER_EM {Some (Self ::register_em_callback) }else {None - }; + }, +// SAFETY: All zeros is a valid value for `bindings::cpufreq_driver`. + ..unsafe {MaybeUninit ::zeroed ().assume_init () } + }; + +const fn copy_name (name: &'staticCStr ) -> [c_char ;CPUFREQ_NAME_LEN ] { +let src = name.as_bytes_with_nul (); +let mut dst = [0 ;CPUFREQ_NAME_LEN ]; + +build_assert! (src.len () <=CPUFREQ_NAME_LEN ); + +let mut i =0 ; +while i < src.len () { + dst[i] = src[i]; + i +=1 ; + } + + dst + } + +/// Registers a CPU frequency driver with the cpufreq core. +pub fn new () ->Result <Self > { +let drv = &Self ::VTABLE as *const _ as *mut _ ;// SAFETY: It is safe to register the driver with the cpufreq core in the kernel C code. -to_result (unsafe { bindings::cpufreq_register_driver (drv_ref) })?; +to_result (unsafe { bindings::cpufreq_register_driver (drv) })?; -Ok (Self { - drv, - _p:PhantomData , - }) +Ok (Self ( +NonNull ::new (drv.cast ()).ok_or (AllocError )?, +PhantomData , + )) }/// Same as [`Registration::new`], but does not return a [`Registration`] instance.
@@ -1259,9 +1262,7 @@ extern "C" fn register_em_callback(ptr: *mut bindings::cpufreq_policy) {impl <T :Driver >Drop for Registration <T > {// Removes the `Registration` from the kernel, if it has initialized successfully earlier. fn drop (&mut self) { -let drv = self.drv.get_mut (); -// SAFETY: The driver was earlier registered from `new`. -unsafe { bindings::cpufreq_unregister_driver (drv) }; +unsafe { bindings::cpufreq_unregister_driver (self.0 .as_ptr ()) }; } }
Viresh Kumar
maintainerRe: [PATCH V9 03/17] rust: cpumask: Add initial abstractions
In reply to Yury NorovQuoted 10 lines · Yury Norov
rust/kernel/cpumask.rs line 238
Quoted 8 lines · Viresh Kumar
rust/kernel/cpumask.rs new file +8
-0+unsafe fn new_uninit (_flags:Flags ) ->Result <Self ,AllocError > { +Ok (Self { +#[cfg( CONFIG_CPUMASK_OFFSTACK )] + ptr: { +let mut ptr: *mut bindings::cpumask = ptr::null_mut (); + +// SAFETY: Depending on the value of `_flags`, this call may sleep. Other than +// that, it is always safe to call this method.
Quoted 4 lines
I'm not sure I understand this sentence. What's wrong with safety when the
alloc()function sleeps? Even if something is wrong. If you really want to protect your users, you'd introducenew_sync()version that returns error if user provides sleeping flags.
I borrowed this SAFETY comment from similar allocation done in page.rs, I think we can skip it though. Here is the delta so far:
@@ -27,8 +27,8 @@
///
/// A [Cpumask] instance always corresponds to a valid C struct cpumask.
///
-/// The callers must ensure that the struct cpumask is valid for access and remains valid for the -/// lifetime of the returned reference.
+/// The callers must ensure that the struct cpumask is valid for access and
+/// remains valid for the lifetime of the returned reference.
///
/// ## Examples
///
@@ -86,7 +86,9 @@ pub fn as_raw(&self) -> *mut bindings::cpumask {
/// Set `cpu` in the cpumask.
///
- /// Equivalent to the kernel's `__cpumask_set_cpu` API.
+ /// ATTENTION: Contrary to C, this Rust `set()` method is non-atomic.
+ /// This mismatches kernel naming convention and corresponds to the C
+ /// function `__cpumask_set_cpu()`.
#[inline]
pub fn set(&mut self, cpu: u32) {
// SAFETY: By the type invariant, `self.as_raw` is a valid argument to `__cpumask_set_cpu`.@@ -95,7 +97,9 @@ pub fn set(&mut self, cpu: u32) {
/// Clear `cpu` in the cpumask.
///
- /// Equivalent to the kernel's `__cpumask_clear_cpu` API.
+ /// ATTENTION: Contrary to C, this Rust `clear()` method is non-atomic.
+ /// This mismatches kernel naming convention and corresponds to the C
+ /// function `__cpumask_clear_cpu()`.
#[inline]
pub fn clear(&mut self, cpu: i32) {
// SAFETY: By the type invariant, `self.as_raw` is a valid argument to@@ -198,15 +202,14 @@ pub struct CpumaskVar {
}
impl CpumaskVar {
- /// Creates an initialized instance of the [`CpumaskVar`].
- pub fn new(_flags: Flags) -> Result<Self, AllocError> {
+ /// Creates a zero-initialized instance of the [`CpumaskVar`].
+ pub fn new_zero(_flags: Flags) -> Result<Self, AllocError> {
Ok(Self {
#[cfg(CONFIG_CPUMASK_OFFSTACK)]
ptr: {
let mut ptr: *mut bindings::cpumask = ptr::null_mut();- // SAFETY: Depending on the value of `_flags`, this call may sleep. Other than
- // that, it is always safe to call this method.
+ // SAFETY: It is safe to call this method as the reference to `ptr` is valid.
//
// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of
// scope.
@@ -222,20 +225,19 @@ pub fn new(_flags: Flags) -> Result<Self, AllocError> {
})
}- /// Creates an uninitialized instance of the [CpumaskVar].
+ /// Creates an instance of the [CpumaskVar].
///
/// # Safety
///
/// The caller must ensure that the returned [`CpumaskVar`] is properly initialized before
/// getting used.
- unsafe fn new_uninit(_flags: Flags) -> Result<Self, AllocError> {
+ unsafe fn new(_flags: Flags) -> Result<Self, AllocError> {
Ok(Self {
#[cfg(CONFIG_CPUMASK_OFFSTACK)]
ptr: {
let mut ptr: *mut bindings::cpumask = ptr::null_mut();- // SAFETY: Depending on the value of `_flags`, this call may sleep. Other than
- // that, it is always safe to call this method.
+ // SAFETY: It is safe to call this method as the reference to `ptr` is valid.
//
// INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of
// scope.Quoted 11 lines
rust/kernel/cpumask.rs line 259
Quoted 7 lines
rust/kernel/cpumask.rs new file +7
-0+/// Creates a mutable reference to an existing `struct cpumask_var_t` pointer. +/// +/// # Safety +/// +/// 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_var_t ) -> &'amut Self {The 'from' (wrt cpumasks) has a special meaning: search for a cpu starting from a given one. This '
from_raw' may confuse readers. Have you any other name for it in mind?
'from_raw' is widely used in Rust for similar methods, though I do understand your concerns.
Danilo / Miguel, what do you suggest I rename these to ?
Quoted 10 lines
rust/kernel/cpumask.rs line 282
Quoted 8 lines
rust/kernel/cpumask.rs new file +8
-0+// SAFETY: Guaranteed by the safety requirements of the function. +// +// INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the +// lifetime of the returned reference. +unsafe { &mut *ptr.cast () } + } +/// Clones cpumask. +pub fn try_clone (cpumask: &Cpumask ) ->Result <Self > {Just
clone(), I think.
The method 'clone()' is already used by the 'Clone' trait [1], and that's what I wanted to use initially. But 'clone' doesn't return a 'Result'.
Signature · 3 lines
viresh [1] https://doc.rust-lang.org/std/clone/trait.Clone.html
Danilo Krummrich
reviewerRe: [PATCH V9 15/17] rust: cpufreq: Extend abstractions for driver registration
In reply to Viresh KumarQuoted 9 lines · Viresh Kumar
Quoted 6 lines · Danilo Krummrich
const VTABLE: bindings::cpufreq_driver = bindings::cpufreq_driver { name: Self::copy_name(T::NAME), boost_enabled: T::BOOST_ENABLED, flags: T::FLAGS, [...] }Ahh, thanks for this.
The diff below looks good!
One nit below.
Quoted 232 lines
rust/kernel/cpufreq.rs +63
-70@@ -9,28 +9,32 @@//! Reference: <https://docs.kernel.org/admin-guide/pm/cpufreq.html> use crate ::{ + alloc::AllocError , bindings, clk::{Clk ,Hertz }, cpumask, device::Device , devres::Devres , error::{code::*, from_err_ptr, from_result, to_result,Result ,VTABLE_DEFAULT_ERROR }, - ffi::c_ulong, + ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable , types::Opaque , };use core::{ - cell::UnsafeCell , marker::PhantomData , + mem::MaybeUninit , ops::{Deref ,DerefMut }, pin::Pin , - ptr, + ptr::{self,NonNull }, };use macros::vtable; +// Maximum length of CPU frequency driver's name. +const CPUFREQ_NAME_LEN :usize = bindings::CPUFREQ_NAME_LEN as usize ; +/// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS :u32 = bindings::CPUFREQ_ETERNAL as u32 ;@@ -855,10 +859,8 @@ fn register_em(_policy: &mut Policy) {/// cpufreq::Registration::<FooDriver>::new_foreign_owned(dev).unwrap(); /// } /// ``` -pub struct Registration <T :Driver > { - drv:KBox <UnsafeCell <bindings::cpufreq_driver >>, - _p:PhantomData <T >, -} +#[repr(transparent)] +pub struct Registration <T :Driver >(NonNull <bindings::cpufreq_driver >,PhantomData <T >);// SAFETY: `Registration` doesn't offer any methods or access to fields when shared between threads // or CPUs, so it is safe to share it. @@ -870,135 +872,136 @@ unsafe impl<T: Driver> Sync for Registration<T> {}unsafe impl <T :Driver >Send for Registration <T > {}impl <T :Driver >Registration <T > { -/// Registers a CPU frequency driver with the cpufreq core. -pub fn new () ->Result <Self > { -// Required due to Rust 1.82's stricter handling of `unsafe` in mutable statics. The -// `unsafe` blocks aren't required anymore with later versions. -#![allow(unused_unsafe)] - -let mut drv =KBox ::new ( -UnsafeCell ::new (bindings::cpufreq_driver::default ()), -GFP_KERNEL , - )?; -let drv_ref = drv.get_mut (); - -// Account for the trailing null byte. -let len =T ::NAME .len () +1 ; -if len > drv_ref.name.len () { -return Err (EINVAL ); - }; - -// SAFETY: `T::NAME` is a valid `CStr`, and we are copying it to an array of equal or -// larger size. -let name =unsafe { &*(T ::NAME .as_bytes_with_nul ()as *const [u8 ]) }; - drv_ref.name[..len].copy_from_slice (name); - - drv_ref.boost_enabled =T ::BOOST_ENABLED ; - drv_ref.flags =T ::FLAGS ; +const VTABLE : bindings::cpufreq_driver = bindings::cpufreq_driver { + name:Self ::copy_name (T ::NAME ), + boost_enabled:T ::BOOST_ENABLED , + flags:T ::FLAGS ,// Initialize mandatory callbacks. - drv_ref.init =Some (Self ::init_callback); - drv_ref.verify =Some (Self ::verify_callback); + init:Some (Self ::init_callback), + verify:Some (Self ::verify_callback),// Initialize optional callbacks based on the traits of `T`. - drv_ref.setpolicy =if T ::HAS_SETPOLICY { + setpolicy:if T ::HAS_SETPOLICY {Some (Self ::setpolicy_callback) }else {None - }; - drv_ref.target =if T ::HAS_TARGET { + }, + target:if T ::HAS_TARGET {Some (Self ::target_callback) }else {None - }; - drv_ref.target_index =if T ::HAS_TARGET_INDEX { + }, + target_index:if T ::HAS_TARGET_INDEX {Some (Self ::target_index_callback) }else {None - }; - drv_ref.fast_switch =if T ::HAS_FAST_SWITCH { + }, + fast_switch:if T ::HAS_FAST_SWITCH {Some (Self ::fast_switch_callback) }else {None - }; - drv_ref.adjust_perf =if T ::HAS_ADJUST_PERF { + }, + adjust_perf:if T ::HAS_ADJUST_PERF {Some (Self ::adjust_perf_callback) }else {None - }; - drv_ref.get_intermediate =if T ::HAS_GET_INTERMEDIATE { + }, + get_intermediate:if T ::HAS_GET_INTERMEDIATE {Some (Self ::get_intermediate_callback) }else {None - }; - drv_ref.target_intermediate =if T ::HAS_TARGET_INTERMEDIATE { + }, + target_intermediate:if T ::HAS_TARGET_INTERMEDIATE {Some (Self ::target_intermediate_callback) }else {None - }; - drv_ref.get =if T ::HAS_GET { + }, + get:if T ::HAS_GET {Some (Self ::get_callback) }else {None - }; - drv_ref.update_limits =if T ::HAS_UPDATE_LIMITS { + }, + update_limits:if T ::HAS_UPDATE_LIMITS {Some (Self ::update_limits_callback) }else {None - }; - drv_ref.bios_limit =if T ::HAS_BIOS_LIMIT { + }, + bios_limit:if T ::HAS_BIOS_LIMIT {Some (Self ::bios_limit_callback) }else {None - }; - drv_ref.online =if T ::HAS_ONLINE { + }, + online:if T ::HAS_ONLINE {Some (Self ::online_callback) }else {None - }; - drv_ref.offline =if T ::HAS_OFFLINE { + }, + offline:if T ::HAS_OFFLINE {Some (Self ::offline_callback) }else {None - }; - drv_ref.exit =if T ::HAS_EXIT { + }, + exit:if T ::HAS_EXIT {Some (Self ::exit_callback) }else {None - }; - drv_ref.suspend =if T ::HAS_SUSPEND { + }, + suspend:if T ::HAS_SUSPEND {Some (Self ::suspend_callback) }else {None - }; - drv_ref.resume =if T ::HAS_RESUME { + }, + resume:if T ::HAS_RESUME {Some (Self ::resume_callback) }else {None - }; - drv_ref.ready =if T ::HAS_READY { + }, + ready:if T ::HAS_READY {Some (Self ::ready_callback) }else {None - }; - drv_ref.set_boost =if T ::HAS_SET_BOOST { + }, + set_boost:if T ::HAS_SET_BOOST {Some (Self ::set_boost_callback) }else {None - }; - drv_ref.register_em =if T ::HAS_REGISTER_EM { + }, + register_em:if T ::HAS_REGISTER_EM {Some (Self ::register_em_callback) }else {None - }; + }, +// SAFETY: All zeros is a valid value for `bindings::cpufreq_driver`. + ..unsafe {MaybeUninit ::zeroed ().assume_init () } + }; + +const fn copy_name (name: &'staticCStr ) -> [c_char ;CPUFREQ_NAME_LEN ] { +let src = name.as_bytes_with_nul (); +let mut dst = [0 ;CPUFREQ_NAME_LEN ]; + +build_assert! (src.len () <=CPUFREQ_NAME_LEN ); + +let mut i =0 ; +while i < src.len () {
rust/kernel/cpufreq.rs unsafe impl<T: Driver> Sync for Registration<T> {} · line 996
Quoted 10 lines
rust/kernel/cpufreq.rs +10
-0+ dst[i] = src[i]; + i +=1 ; + } + + dst + } + +/// Registers a CPU frequency driver with the cpufreq core. +pub fn new () ->Result <Self > { +let drv = &Self ::VTABLE as *const _ as *mut _ ;
Hm, I didn't think of that, maybe it's better to store a *const directly instead of a NonNull, given that VTABLE can't be altered.
Tamir is trying to clean up 'as' casts in [1]. So, I'd write this as
let drv: *const bindings::cpufreq_driver = &Self::VTABLE;
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Quoted 27 lines
rust/kernel/cpufreq.rs +6
-8// SAFETY: It is safe to register the driver with the cpufreq core in the kernel C code. -to_result (unsafe { bindings::cpufreq_register_driver (drv_ref) })?; +to_result (unsafe { bindings::cpufreq_register_driver (drv) })?; -Ok (Self { - drv, - _p:PhantomData , - }) +Ok (Self ( +NonNull ::new (drv.cast ()).ok_or (AllocError )?, +PhantomData , + )) }/// Same as [`Registration::new`], but does not return a [`Registration`] instance. @@ -1259,9 +1262,7 @@ extern "C" fn register_em_callback(ptr: *mut bindings::cpufreq_policy) {impl <T :Driver >Drop for Registration <T > {// Removes the `Registration` from the kernel, if it has initialized successfully earlier. fn drop (&mut self) { -let drv = self.drv.get_mut (); -// SAFETY: The driver was earlier registered from `new`. -unsafe { bindings::cpufreq_unregister_driver (drv) }; +unsafe { bindings::cpufreq_unregister_driver (self.0 .as_ptr ()) }; } }