Rust: add runtime PM support
Subsystems (5)
v6 cover Rust: add runtime PM support
Hi All,
This series adds initial Rust support for Linux runtime PM.
The concept for Rust abstraction gets introduced in the first patch. It provides callback registration, PM callback dispatch through PMOps trait, scoped request helpers for common runtime PM operations and configuration helpers.
The abstraction intends to keep the request semantics aligned with the C runtime PM core.
Second patch integrates dev_pm_ops into the Rust platform driver abstraction, enabling drivers to register PM callbacks with the core.
The last in the series is provided for demonstrative purposes (not intended to be an actual merge material).
This has been lightly tested with the Tyr driver.
Based on drm-next.
---
v6:
- Moved the runtime PM API from rust/kernel/pm.rs to rust/kernel/device/pm.rs
- Reworked Registration::new() to initialize pinned registration data and return a PinInit; replaced the cloned, Arc-backed PMContext with one borrowed from the registration.
- Replaced the single 'static runtime payload type with separate active and suspended payload types, plus registration data passed to callbacks
- Tied PM request scopes to the registration lifetime instead of device's one
- Added SRCU synchronization and intermediate enable/disable states so registration teardown waits for those operations to finish.
- Fixed ResumeScope and AwakeScope handling of EINPROGRESS for ASYNC and NOWAIT requests; rejected NOWAIT in the synchronous closure helpers.
- Changed enable ordering to apply PM configuration before marking the initial device state. Reset autosuspend and ignore-children settings on failure, disable and teardown.
- Updated naming, comments and documentation for the revised API and according to review suggestions.
- Removed the zero-valued Sync mode in favor of Mode::empty(), renamed RuntimePMState::Resumed to Active, and updated the PM ops type names.
- Reworked the Tyr example to use pinned hardware, PM and DRM registration data with explicit lifetime and drop ordering.
v5:
- Added doc comment for rust_private
- Dropped the RuntimePMState::Unknown as that was no longer needed
- Dropped masking the RPM mode in ResumeScope::release_inner as that is not necessary and brings in only confusion
- Fixed the behaviour of AwakeScope::new when the Request::resume returns EINPROGRESS.
- Note on RetainScope: the pairing of:
Request::get_noresume ->Request::put_noidle
is intentional to avoid mixing the expected behaviour of Scopes
- Cleaned up all the CONFIG_PM guards
- Switched the PMPayload to use ManuallyDrop<> instead of Option<>
- Apply the PMConfig only after successfully marking the devices devices PM state
- Dropped #[pin_data] for RegistrationData
- Registration::new() is now usafe to with the safety requirement that the Registration cannot be mem::forgotten
- Overall cleanup for attributes and formatting
- The platform::Driver trait is now sized to enable making the DevPMOps an associated constant.
v4:
- Simplified the PMOps/DevPMOps type model by making the bus adapter an associated type of PMOps, so DevPMOps is now parameterized only by the driver PM implementation type.
- Added DevPMOpsRef to pass typed, adapter-scoped dev_pm_ops references through bus registration code.
- Made DevPMOps own the generated dev_pm_ops table and require a static DevPMOps instance for Registration::new().
- Made the runtime PM payload mandatory.
- Replaced the PMContext enabled flag with an explicit Disabled/Enabled/Dead state machine to prevent re-enabling through stale PMContext clones during teardown.
- Updated with_get() to reject NOWAIT profiles in addition to ASYNC profiles.
- Changed AutoSuspendDelay to i32 to match the C runtime PM API.
- Renamed RuntimePMState variants to Rust-style names.
- Dropped the local EINPROGRESS error addition: already available
- Updated the platform PM wiring and Tyr example to the new DevPMOpsRef/static DevPMOps model.
- Cleaned up comments, docs, and minor typos.
v3:
- Dropped macros in favour of plain encoding of the PM callbacks
- Moved Mode to use kernel::impl_flags
- Generated PM callbacks, the stored payload, and the device cast are all monomorphized for the same (Adapter<T>, T) pair,
with the registration sealing the contract by validating installed dev_pm_ops
- Platform PM wiring should be type-safe now
- Tracking runtime enable/disable state
- Few fixes for issues pointed out by Sami Tolvanen ([email protected]), like making the registration teardown respecting the CONFIG_PM settings or fixing AwakeScope for async/no wait calls; Sami is also the person behind adding get_if_active variant (much appreciated)
- Changed base branch
v2:
- Moving away from the old PMContext<T, Dormant/Active> type-state design
- Introducing an explicit Registration<'a, T> object.
- PMContext now carries a lifetime and is derived from the registration
- Callback data is no longer recovered through driver data
- Simplified PMOps
- Runtime payload handling change
- Request helpers slightly extended
Beata Michalska (3):
rust: add runtime PM support
rust: platform: wire runtime PM callbacks
drm/tyr: enable runtime PM
drivers/base/base.h | 6 + drivers/gpu/drm/tyr/driver.rs | 220 ++++-- drivers/gpu/drm/tyr/file.rs | 7 +- rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/pm_runtime.c | 101 +++ rust/kernel/device.rs | 1 + rust/kernel/device/pm.rs | 1187 +++++++++++++++++++++++++++++++ rust/kernel/platform.rs | 35 +- 9 files changed, 1499 insertions(+), 60 deletions(-) create mode 100644 rust/helpers/pm_runtime.c create mode 100644 rust/kernel/device/pm.rs
Signature · 1 line
2.43.0
PATCH v6 1/3 rust: add runtime PM support
Add a Rust abstraction for Linux runtime PM, allowing Rust drivers to register runtime PM callbacks and use scoped runtime PM requests while retaining the behavior and guarantees of the underlying C PM core.
Runtime PM is managed through a registration object tied to the device lifetime. The registration stores the callback payload and 'ensures' that the registration, its PMContext, and the payload do not outlive the device. All that while PMContext holds a lifetime-annotated device reference so that runtime PM requests are made only while the device remains bound.
Drivers define runtime PM callbacks through the PMOps trait. The generated dev_pm_ops callbacks take the stored payload, pass ownership to the corresponding Rust callback, and store the returned payload for the next invocation. Each callback must return a valid payload, regardless of whether the power transition succeeds or not.
PMContext provides scoped helpers for common runtime PM operations:
- ResumeScope resumes the device for the lifetime of the scope.
- AwakeScope resumes the device and holds a runtime PM usage reference.
- RetainScope increments the runtime PM usage count without resuming the device.
Each scope performs the corresponding inverse operation when dropped, according to the selected driver-defined profile.
The abstraction does not change the semantics of the C runtime PM API. Asynchronous requests may only queue work, non-waiting requests may fail instead of sleeping, and callbacks remain subject to the existing driver core rules.
--- drivers/base/base.h | 6 + rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/pm_runtime.c | 101 +++ rust/kernel/device.rs | 1 + rust/kernel/device/pm.rs | 1187 +++++++++++++++++++++++++++++++ 6 files changed, 1297 insertions(+) create mode 100644 rust/helpers/pm_runtime.c create mode 100644 rust/kernel/device/pm.rs
drivers/base/base.h +6 -0
@@ -105,6 +105,7 @@ struct driver_private {* dev_err_probe() for later retrieval via debugfs * @device: pointer back to the struct device that this structure is * associated with. +* @rust_private: private data used exclusively by the Rust driver core * @dead: This device is currently either in the process of or has been * removed from the system. Any asynchronous events scheduled for this * device should exit without taking any action.
@@ -121,6 +122,11 @@ struct device_private {const struct device_driver *async_driver;char *deferred_probe_reason;struct device *device; +#ifdef CONFIG_RUST +struct { +void *pm_registration_data; + }rust; +#endif u8 dead:1; };#define to_device_private_parent (obj) \
rust/bindings/bindings_helper.h +1 -0
@@ -79,6 +79,7 @@#include <linux/pid_namespace.h> #include <linux/platform_device.h> #include <linux/pm_opp.h> +#include <linux/pm_runtime.h> #include <linux/poll.h> #include <linux/property.h> #include <linux/pwm.h>
rust/helpers/helpers.c +1 -0
@@ -83,6 +83,7 @@#include "pci.c" #include "pid_namespace.c" #include "platform.c" +#include "pm_runtime.c" #include "poll.c" #include "processor.c" #include "property.c"
rust/helpers/pm_runtime.c new file +101 -0
101 lines not on this page · raw message
rust/kernel/device.rs +1 -0
@@ -19,6 +19,7 @@ ptr, // }; +pub mod pm;pub mod property;/// The core representation of a device in the kernel's driver model.
rust/kernel/device/pm.rs new file +1187 -0
1,187 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v6 2/3 rust: platform: wire runtime PM callbacks
In reply to Beata MichalskaAllow platform drivers to provide Rust runtime PM callbacks by exposing typed dev_pm_ops through the platform driver trait and installing them via the generated platform_driver.
Add a platform-specific constructor for pm::Ops that ties the PM callbacks to platform::Adapter<T> and requires callbacks to use a bound platform device. This keeps the unsafe generic PM ops constructor internal while letting platform drivers opt into runtime PM without affecting drivers that do not use it.
The platform glue only wires the callback table into the C driver model; ownership of the callback payload and runtime PM teardown remain with the pm module.
--- rust/kernel/platform.rs | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-)
rust/kernel/platform.rs +33 -2
@@ -10,7 +10,8 @@ container_of, device::{ self, - Bound, // + Bound, + pm, // }, driver, error::{
@@ -72,6 +73,11 @@ unsafe fn register( None => core::ptr::null(), }; +#[cfg( CONFIG_PM )] +let pm_ops =T ::DEV_PM_OPS .map_or (core::ptr::null (), |ops| ops.as_raw ()); +#[cfg(not( CONFIG_PM ))] +let pm_ops = core::ptr::null (); +// SAFETY: It's safe to set the fields of `struct platform_driver` on initialization. unsafe { (*pdrv.get ()).driver.name = name.as_char_ptr ();
@@ -79,6 +85,7 @@ unsafe fn register( (*pdrv.get ()).remove =Some (Self ::remove_callback); (*pdrv.get ()).driver.of_match_table = of_table; (*pdrv.get ()).driver.acpi_match_table = acpi_table; + (*pdrv.get ()).driver.pm = pm_ops; }// SAFETY: `pdrv` is guaranteed to be a valid `DriverType`.
@@ -194,6 +201,7 @@ macro_rules! module_platform_driver {/// impl platform::Driver for MyDriver { /// type IdInfo = (); /// type Data<'bound> = Self; +/// /// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); /// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE); ///
@@ -205,7 +213,7 @@ macro_rules! module_platform_driver {/// } /// } ///``` -pub trait Driver { +pub trait Driver :Sized {/// The type holding driver private data about each device id supported by the driver. // TODO: Use associated_type_defaults once stabilized: //
@@ -223,6 +231,9 @@ pub trait Driver {/// The table of ACPI device ids supported by the driver. const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =None ; +/// Provides driver's PM callbacks, if any. +const DEV_PM_OPS :Option <pm::AdapterOpsRef <'static,Adapter <Self >>> =None ; +/// Platform driver probe. /// /// Called when a new platform device is added or discovered.
@@ -587,3 +598,23 @@ unsafe impl Sync for Device {}// SAFETY: Same as `Device<Normal>` -- the underlying `struct platform_device` is the same; // `Bound` is a zero-sized type-state marker that does not affect thread safety. unsafe impl Sync for Device <device::Bound > {} + +#[allow(clippy::new_without_default)] +impl <T > pm::Ops <T > +where +T :Driver + pm::PMOps < +Adapter =Adapter <T >, +DeviceType =crate ::platform::Device <device::Bound >, + >, +{ +/// Creates a platform driver's runtime PM callbacks for `T`. +/// +/// This constructor is available only when `T` is a platform driver and +/// its runtime PM callbacks accept a bound platform device. +#[inline] +pub const fn new () ->Self { +// SAFETY: `Adapter<T>` is the platform bus adapter for `T`, and the +// bound above forces PM callbacks to receive a platform bound device. +unsafe { pm::Ops ::new_unchecked (pm::PMContext ::<T >::PM_OPS ) } + } +}
Signature · 1 line
2.43.0
PATCH v6 3/3 drm/tyr: enable runtime PM
In reply to Beata MichalskaAdd runtime PM support to the Tyr platform driver. Move the clocks and regulators used by runtime suspend and resume into the PM payload, register the PM callbacks, configure autosuspend, and let DRM paths take a PM usage reference while querying device state.
--- drivers/gpu/drm/tyr/driver.rs | 220 +++++++++++++++++++++++++--------- drivers/gpu/drm/tyr/file.rs | 7 +- 2 files changed, 169 insertions(+), 58 deletions(-)
drivers/gpu/drm/tyr/driver.rs +164 -56
@@ -9,7 +9,11 @@ Bound, Core, Device, - DeviceContext, // + DeviceContext, + pm:: { + self, + *, + }, // }, dma::{ Device as DmaDevice,
@@ -21,17 +25,13 @@ poll, Io, // }, - new_mutex, of, platform, prelude::*, regulator, regulator::Regulator, sizes::SZ_2M, - sync::{ - Arc, - Mutex, // - }, + sync::Arc, time, // };
@@ -55,35 +55,59 @@pub (crate )struct TyrPlatformDriver ; +#[pin_data] +pub (crate )struct TyrHW <'bound> { +/// Firmware sections. +pub (crate ) fw:Firmware <'bound>, + +/// GPU MMIO register mapping. +pub (crate ) iomem:Arc <IoMem <'bound>>, + +/// GPU information read from hardware during probe. +pub (crate ) gpu_info:GpuInfo , +} + +#[pin_data( PinnedDrop )] pub (crate )struct TyrPlatformDriverData <'bound> {#[pin] - _reg: drm::Registration <'bound,TyrDrmDriver >, +#[uses('pm: invariant, 'hw)] + _reg: drm::Registration <'pm,TyrDrmDriver >, +// This needs to be dropped after drm::Registration as that one +// borrows PMContext. +#[pin] +#[uses('hw: invariant)] +pub (crate ) pm: pm::Registration <'hw,TyrPlatformDriver >, +#[pin] + hw:TyrHW <'bound>, +} + +#[pin_data] +pub (crate )struct TyrPMRegistrationData <'pm> +where +exists <'bound>: 'pm, +{ +#[uses('bound: invariant)] +pub (crate ) hw: &'pmTyrHW <'bound>, } +/// Data owned by the DRM [`Registration`]. /// /// This data can have references tied to the parent platform device binding scope /// and is accessible only while the DRM device is registered with userspace. #[pin_data] -pub (crate )struct TyrDrmRegistrationData <'drm> { +pub (crate )struct TyrDrmRegistrationData <'drm> +where +exists <'bound>: 'drm, +{/// Parent platform device. pub (crate ) pdev: &'drm platform::Device <Bound >, -/// Firmware sections. -pub (crate ) fw:Firmware <'drm>, - -#[pin] - clks:Mutex <Clocks >, - -#[pin] - regulators:Mutex <Regulators >, - -/// GPU MMIO register mapping. -pub (crate ) iomem:Arc <IoMem <'drm>>, - -/// GPU information read from hardware during probe. -pub (crate ) gpu_info:GpuInfo , +/// Runtime PM context owned by the PM Registration +pub (crate ) pm:PMContext <'drm, 'drm,TyrPlatformDriver >, +#[uses('bound: invariant)] +pub (crate ) hw: &'drmTyrHW <'bound>, }fn issue_soft_reset (dev: &Device , iomem: &IoMem <'_>) ->Result {
@@ -113,6 +137,7 @@ impl platform::Driver for TyrPlatformDriver {type IdInfo = ();type Data <'bound> =TyrPlatformDriverData <'bound>;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE ); +const DEV_PM_OPS :Option <pm::OpsRef <Self >> =Some (TYR_PM_OPS .pm_ops ());fn probe <'bound>( pdev: &'bound platform::Device<Core<'_>>,
@@ -130,6 +155,22 @@ fn probe<'bound>(let mali_regulator =Regulator ::<regulator::Enabled >::get (pdev.as_ref (),c"mali" )?;let sram_regulator =Regulator ::<regulator::Enabled >::get (pdev.as_ref (),c"sram" )?; +let runtime_payload =TyrRuntimePMPayload { + clks:Clocks { + core: core_clk, + stacks: stacks_clk, + coregroup: coregroup_clk, + }, + _regulators:Regulators { + _mali: mali_regulator, + _sram: sram_regulator, + }, + }; + +let mut pm_configs =KVec ::<PMConfig >::with_capacity (2 ,GFP_KERNEL )?; + pm_configs.push (PMConfig ::AutoSuspend (true ),GFP_KERNEL )?; + pm_configs.push (PMConfig ::AutoSuspendDelay (300 ),GFP_KERNEL )?; +let request = pdev.io_request_by_index (0 ).ok_or (ENODEV )?;let iomem =Arc ::new (request.iomap_sized ::<SZ_2M >()?,GFP_KERNEL )?;
@@ -150,41 +191,59 @@ fn probe<'bound>(let unreg_dev = drm::UnregisteredDevice ::<TyrDrmDriver >::new (pdev,Ok (()))?; -let mmu =Mmu ::new (pdev.as_ref (), iomem.as_arc_borrow (), &gpu_info)?; - -let firmware =Firmware ::new ( - pdev.as_ref (), - iomem.clone (), - &unreg_dev, - mmu.as_arc_borrow (), - &gpu_info, - )?; - - firmware.boot ()?; -Ok (try_pin_init! (TyrPlatformDriverData { -// SAFETY: `_reg` is stored in `TyrPlatformDriverData` and dropped when the -// driver is unbound; it is never forgotten. - _reg <-unsafe { drm::Registration ::new ( - pdev.as_ref (), - unreg_dev, -pin_init! (TyrDrmRegistrationData { - pdev, - fw: firmware, - clks <-new_mutex! (Clocks { - core: core_clk, - stacks: stacks_clk, - coregroup: coregroup_clk, - }), - regulators <-new_mutex! (Regulators { - _mali: mali_regulator, - _sram: sram_regulator, - }), - iomem, - gpu_info, - }), - )}, -_ : { dev_dbg!(pdev,"Tyr initialized correctly." ) }, + hw <- { +let mmu =Mmu ::new (pdev.as_ref (), iomem.as_arc_borrow (), &gpu_info)?; + +let firmware =Firmware ::new ( + pdev.as_ref (), + iomem.clone (), + &unreg_dev, + mmu.as_arc_borrow (), + &gpu_info, + )?; + + firmware.boot ()?; + +pin_init! (TyrHW { + fw: firmware, + iomem, + gpu_info + }) + }, + pm <- { +// SAFETY: `pm` is owned by the driver data and remains accounted for +unsafe { + pm::Registration ::new ( + pdev.as_ref (), + &TYR_PM_OPS , +None , +Some (pm_configs), +pin_init! (TyrPMRegistrationData {hw: hw.get_ref ()}), + pm::RuntimeStatePayload ::Active (runtime_payload) + ) + } + }, + + _reg <- { +// SAFETY: `_reg` is owned by the driver data and is not forgotten. +unsafe { + drm::Registration ::new ( + pdev.as_ref (), + unreg_dev, +pin_init! (TyrDrmRegistrationData { + pdev, + pm: pm.get_ref ().get_ctx (), + hw: hw.get_ref (), + }), + ) + } + }, + + _: { + pm.get_ctx ().enable (RuntimePMState ::Active )?; +dev_dbg! (pdev,"Tyr initialized correctly." ); + }, })) }) }
@@ -239,3 +298,52 @@ struct Regulators { _mali: Regulator<regulator::Enabled>, _sram: Regulator<regulator::Enabled>, } + +pub (crate )struct TyrRuntimePMPayload { + clks:Clocks , + _regulators:Regulators , +} + +static TYR_PM_OPS : pm::Ops <TyrPlatformDriver > = pm::Ops ::new (); + +#[vtable] +impl PMOps for TyrPlatformDriver { +type Adapter = platform::Adapter <TyrPlatformDriver >; +type DeviceType = platform::Device <kernel::device::Bound >; +type RegistrationData <'a> =TyrPMRegistrationData <'a>; +type ActivePayload <'a> =TyrRuntimePMPayload ; +type SuspendedPayload <'a> =TyrRuntimePMPayload ; + +fn runtime_suspend <'a>( + _dev: &'aSelf ::DeviceType , + _reg_data: &'aSelf ::RegistrationData <'a>, + payload:Self ::ActivePayload <'a>, + ) ->Result <Self ::SuspendedPayload <'a>, (Self ::ActivePayload <'a>,Error )> { + payload.clks.coregroup.disable_unprepare (); + payload.clks.stacks.disable_unprepare (); + payload.clks.core.disable_unprepare (); +Ok (payload) + } +fn runtime_resume <'a>( + _dev: &'aSelf ::DeviceType , + _reg_data: &'aSelf ::RegistrationData <'a>, + payload:Self ::SuspendedPayload <'a>, + ) ->Result <Self ::ActivePayload <'a>, (Self ::SuspendedPayload <'a>,Error )> { +if let Err (e) = payload.clks.core.prepare_enable () { +return Err ((payload, e)); + } + +if let Err (e) = payload.clks.stacks.prepare_enable () { + payload.clks.core.disable_unprepare (); +return Err ((payload, e)); + } + +if let Err (e) = payload.clks.coregroup.prepare_enable () { + payload.clks.stacks.disable_unprepare (); + payload.clks.core.disable_unprepare (); +return Err ((payload, e)); + } + +Ok (payload) + } +}
drivers/gpu/drm/tyr/file.rs +5 -2
@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-2.0 or MIT use kernel::{ + device::pm::PMProfile , drm::{ self,Registered ,//
@@ -37,10 +38,12 @@ pub(crate) fn dev_query( devquery: &mut uapi::drm_panthor_dev_query, _file: &TyrDrmFile, ) -> Result<u32> { +// Runtime suspend called when pm_scope gets dropped +let _pm_scope = reg_data.pm.get (PMProfile ::new ())?;if devquery.pointer ==0 {match devquery.type_ { uapi::drm_panthor_dev_query_type_DRM_PANTHOR_DEV_QUERY_GPU_INFO => { - devquery.size = core::mem::size_of_val (®_data.gpu_info)as u32 ; + devquery.size = core::mem::size_of_val (®_data.with_hw (|hw| hw.gpu_info))as u32 ;Ok (0 ) } _ =>Err (EINVAL ),
@@ -54,7 +57,7 @@ pub(crate) fn dev_query( ) .writer(); - writer.write (®_data.gpu_info)?; + writer.write (®_data.with_hw (|hw| hw.gpu_info))?;Ok (0 ) }
Signature · 1 line
2.43.0