Rust: add runtime PM support
Subsystems (5)
v3 cover Rust: add runtime PM support
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.
It is based on Danilo's drm/file branch [1]
---
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
---
[1] https://git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=drm/file
Beata Michalska (3):
rust: add runtime PM support
rust: platform: wire runtime PM callbacks
drm/tyr: enable runtime PM
drivers/base/base.h | 3 + drivers/gpu/drm/tyr/driver.rs | 123 +++- drivers/gpu/drm/tyr/file.rs | 3 + rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/pm_runtime.c | 44 ++ rust/kernel/error.rs | 1 + rust/kernel/lib.rs | 1 + rust/kernel/platform.rs | 30 + rust/kernel/pm.rs | 1079 +++++++++++++++++++++++++++++++ 10 files changed, 1262 insertions(+), 24 deletions(-) create mode 100644 rust/helpers/pm_runtime.c create mode 100644 rust/kernel/pm.rs
Signature · 1 line
2.43.0
PATCH v3 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 | 3 + rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/pm_runtime.c | 44 ++ rust/kernel/error.rs | 1 + rust/kernel/lib.rs | 1 + rust/kernel/pm.rs | 1058 +++++++++++++++++++++++++++++++ 7 files changed, 1109 insertions(+) create mode 100644 rust/helpers/pm_runtime.c create mode 100644 rust/kernel/pm.rs
drivers/base/base.h +3 -0
@@ -119,6 +119,9 @@ struct device_private {const struct device_driver *async_driver;char *deferred_probe_reason;struct device *device; +#ifdef CONFIG_RUST +void *rust_private; +#endif u8 dead:1; };#define to_device_private_parent (obj) \
rust/bindings/bindings_helper.h +1 -0
@@ -77,6 +77,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
@@ -77,6 +77,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 +44 -0
44 lines not on this page · raw message
rust/kernel/error.rs +1 -0
@@ -67,6 +67,7 @@ macro_rules! declare_err {declare_err! (EOVERFLOW ,"Value too large for defined data type." );declare_err! (EMSGSIZE ,"Message too long." );declare_err! (ETIMEDOUT ,"Connection timed out." ); +declare_err! (EINPROGRESS ,"Operation now in progress." );declare_err! (ERESTARTSYS ,"Restart the system call." );declare_err! (ERESTARTNOINTR ,"System call was interrupted by a signal and will be restarted." );declare_err! (ERESTARTNOHAND ,"Restart if no handler." );
rust/kernel/lib.rs +1 -0
@@ -109,6 +109,7 @@pub mod pci;pub mod pid_namespace;pub mod platform; +pub mod pm;pub mod prelude;pub mod print;pub mod processor;
rust/kernel/pm.rs new file +1058 -0
1,058 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v3 1/3] rust: add runtime PM support
Hi Beata,
rust/kernel/error.rs macro_rules! declare_err { · line 70
Quoted 9 lines · Beata Michalska
rust/kernel/error.rs +1
-0@@ -67,6 +67,7 @@ macro_rules! declare_err {declare_err! (EOVERFLOW ,"Value too large for defined data type." );declare_err! (EMSGSIZE ,"Message too long." );declare_err! (ETIMEDOUT ,"Connection timed out." ); +declare_err! (EINPROGRESS ,"Operation now in progress." );
Looks like this is already upstream since commit b93fb6e76ec1.
rust/kernel/error.rs macro_rules! declare_err {
Quoted 6 lines
rust/kernel/error.rs +6
-0+/// Device's runtime power management status +#[repr( i32 )] +pub enum RuntimePMState { +/// Runtime PM has not been initialized for this device yet. +UNKNOWN = bindings::rpm_status_RPM_INVALID, +/// The device is expected to be runtime active and in it's normal operating state
Nit: it's -> its.
rust/kernel/error.rs
Quoted 3 lines
rust/kernel/error.rs +3
-0+ RESUMED = bindings::rpm_status_RPM_ACTIVE, +/// The device is expected to be suspended, unavailable for normal operations + SUSPENDED = bindings::rpm_status_RPM_SUSPENDED,
Should the enum variant names use CamelCase?
rust/kernel/error.rs
Quoted 9 lines
rust/kernel/error.rs +9
-0+impl <'a>ResumeScope <'a> { +fn new (dev: &'a device::Device <device::Bound >, mode:Mode ) ->Result <Self > { +if mode.contains (ModeFlag ::Acquire ) { +// ModeFlag::Acquire is intended to be used with Awake scope +// Avoid mixing the modes. +return Err (EINVAL ); + } + +// ModeFlag::Idle is internal so strip it of before passing further
Nit: of -> off. Also in the identical comment below.
Quoted 24 lines
rust/kernel/error.rs +24
-0+impl <'a>AwakeScope <'a> { +fn new (dev: &'a device::Device <device::Bound >, mode:Mode ) ->Result <Self > { +if !mode.contains (ModeFlag ::Acquire ) { +return Err (EINVAL ); + } +// ModeFlag::Idle is internal so strip it of before passing further +match Request ::resume (dev, mode & !ModeFlag ::Idle ) { +Ok (()) => {} +// For async/nowait requests, `EINPROGRESS` means the resume is in +// flight and the usage reference already keeps the device active. +Err (e)if e ==EINPROGRESS && mode.contains_any (ModeFlag ::Async |ModeFlag ::Nowait ) => { + } +Err (e) => { +Request ::put_noidle (dev); +return Err (e); + } + } + +Ok (Self (Scope ::<Awake > { + dev, + mode, + _tag:PhantomData , + })) + }
rust/kernel/error.rs
Quoted 10 lines
rust/kernel/error.rs +10
-0+ +fn release_inner (&self) ->Result { +let scope_mode = self.0 .mode & !ModeFlag ::Idle ; +match self.0 .mode { + modeif mode.contains (ModeFlag ::Idle ) =>Request ::idle (self.0 .dev, scope_mode), + modeif mode.contains (ModeFlag ::Auto ) => { +Request ::mark_last_busy (self.0 .dev); +Request ::suspend (self.0 .dev, scope_mode) + } + _ =>Request ::suspend (self.0 .dev, scope_mode),
In v2 you had Request::idle in the default arm. I didn't see a note about this in the changelog. Was the change in behavior intentional?
Quoted 11 lines
rust/kernel/error.rs +11
-0+impl <'a>RetainScope <'a> { +fn new (dev: &'a device::Device <device::Bound >) ->Result <Self > { +Request ::get_noresume (dev); +Ok (Self (Scope ::<Retain > { + dev, + mode:Mode (ModeFlag ::Sync as u32 ), + _tag:PhantomData , + })) + } + +fn try_new (dev: &'a device::Device <device::Bound >) ->Result <Self > {
rust/kernel/error.rs
Quoted 10 lines
rust/kernel/error.rs +10
-0+Request ::get_if_active (dev)?; +Ok (Self (Scope ::<Retain > { + dev, + mode:Mode (ModeFlag ::Sync as u32 ), + _tag:PhantomData , + })) + } + +fn release_inner (&self) { +Request ::put_noidle (self.0 .dev);
What's the reason for using put_noidle here? It doesn't queue autosuspend, so wouldn't the try_hold_active pattern (i.e. grab if active, do something, drop) leave the device active until something else triggers a suspend?
rust/kernel/error.rs
Quoted 7 lines
rust/kernel/error.rs +7
-0+/// SAFETY: +/// bindings::dev_pm_ops is #[repr(C)], implements Default +/// and the struct itself is all nullable function pointers. +/// There is no padding and all zero bit-pattern is valid +/// +pub const PMOPS_NONE : bindings::dev_pm_ops = +unsafe { core::mem::MaybeUninit ::<bindings::dev_pm_ops >::zeroed ().assume_init () };
The safety comment shouldn't be a doc comment.
rust/kernel/error.rs
Quoted 5 lines
rust/kernel/error.rs +5
-0+/// Runtime PM context tied to a device. +pub struct PMContext <'a,D : driver::DriverLayout ,T :PMOps <D >> { +// Preferably, PMContext could be shared via borrowed reference over +// a pm Registration's lifetime but that bares complications on its own +// when the context needs to be shared across different Registration types.
Nit: bares -> bears. Also in the identical comment below.
Quoted 26 lines
rust/kernel/error.rs +26
-0+impl <'a,D : driver::DriverLayout ,T :PMOps <D >>PMContext <'a,D ,T > { +/// Driver-provided runtime PM operations. +/// +/// A driver implements this trait to handle runtime PM +/// transitions for its device type. +/// +/// Each callback receives the device and the current payload. +/// On success, it returns the payload to keep for the next +/// transition. On failure, it returns the payload together +/// with the error so the previous, or otherwise sane state +/// can be preserved. +pub const PM_OPS : bindings::dev_pm_ops = bindings::dev_pm_ops { + runtime_resume:if T ::HAS_RUNTIME_RESUME { +Some (runtime_resume_callback ::<D ,T >) + }else { +None + }, + runtime_suspend:if T ::HAS_RUNTIME_SUSPEND { +Some (runtime_suspend_callback ::<D ,T >) + }else { +None + }, + ..PMOPS_NONE + }; + +/// Enable runtime PM
rust/kernel/error.rs
Quoted 10 lines
rust/kernel/error.rs +10
-0+pub fn enable (&self, state:RuntimePMState ) ->Result { +if self.inner.enabled.cmpxchg (false ,true , ordering::Full ).is_err () { +return Err (EBUSY ); + } +Self ::apply_config (self.inner.dev, &self.inner.configs); +match state { +RuntimePMState ::RESUMED =>Request ::mark_active (self.inner.dev), +RuntimePMState ::SUSPENDED =>Request ::mark_suspended (self.inner.dev), + _ =>Err (EINVAL ), + }.inspect_err (|_| self.inner.enabled.store (false , ordering::Release ))?;
This always applies the config even if state is invalid. Should we validate the state before making changes?
rust/kernel/error.rs
Quoted 8 lines
rust/kernel/error.rs +8
-0+/// Runs a closure while holding an `AwakeScope`. +pub fn with_get <R >(&self, profile:PMProfile , f:impl FnOnce () ->Result <R >) ->Result <R > { +if profile.0 .contains (ModeFlag ::Async ) { +return Err (EINVAL ); + } +let _scope = self.get (profile)?; +f () + }
Shouldn't this reject NoWait too to make sure the device will actually be powered when the closure is executed?
Sami
Re: [PATCH v3 1/3] rust: add runtime PM support
Hi Sami,
Quoted 14 lines · Sami Tolvanen
Hi Beata,
rust/kernel/error.rs macro_rules! declare_err { · line 70
Quoted 9 lines · Beata Michalska
rust/kernel/error.rs +1
-0@@ -67,6 +67,7 @@ macro_rules! declare_err {declare_err! (EOVERFLOW ,"Value too large for defined data type." );declare_err! (EMSGSIZE ,"Message too long." );declare_err! (ETIMEDOUT ,"Connection timed out." ); +declare_err! (EINPROGRESS ,"Operation now in progress." );Looks like this is already upstream since commit
b93fb6e76ec1.
Missed that.
Quoted 9 lines
rust/kernel/error.rs macro_rules! declare_err {
Quoted 7 lines
rust/kernel/error.rs +6
-0+/// Device's runtime power management status +#[repr( i32 )] +pub enum RuntimePMState { +/// Runtime PM has not been initialized for this device yet. +UNKNOWN = bindings::rpm_status_RPM_INVALID, +/// The device is expected to be runtime active and in it's normal operating state Nit: it's -> its.
Fixed for v4 (across all style-related comments: spelling, documentation formatting, naming/CamelCase, etc.).
Quoted 48 lines
rust/kernel/error.rs
Quoted 4 lines
rust/kernel/error.rs +3
-0+ RESUMED = bindings::rpm_status_RPM_ACTIVE, +/// The device is expected to be suspended, unavailable for normal operations + SUSPENDED = bindings::rpm_status_RPM_SUSPENDED,Should the enum variant names use CamelCase?
rust/kernel/error.rs
Quoted 9 lines
rust/kernel/error.rs +9
-0+impl <'a>ResumeScope <'a> { +fn new (dev: &'a device::Device <device::Bound >, mode:Mode ) ->Result <Self > { +if mode.contains (ModeFlag ::Acquire ) { +// ModeFlag::Acquire is intended to be used with Awake scope +// Avoid mixing the modes. +return Err (EINVAL ); + } + +// ModeFlag::Idle is internal so strip it of before passing further Nit: of -> off. Also in the identical comment below.
Quoted 29 lines
rust/kernel/error.rs +29
-0+impl <'a>AwakeScope <'a> { +fn new (dev: &'a device::Device <device::Bound >, mode:Mode ) ->Result <Self > { +if !mode.contains (ModeFlag ::Acquire ) { +return Err (EINVAL ); + } +// ModeFlag::Idle is internal so strip it of before passing further +match Request ::resume (dev, mode & !ModeFlag ::Idle ) { +Ok (()) => {} +// For async/nowait requests, `EINPROGRESS` means the resume is in +// flight and the usage reference already keeps the device active. +Err (e)if e ==EINPROGRESS && mode.contains_any (ModeFlag ::Async |ModeFlag ::Nowait ) => { + } +Err (e) => { +Request ::put_noidle (dev); +return Err (e); + } + } + +Ok (Self (Scope ::<Awake > { + dev, + mode, + _tag:PhantomData , + })) + } + +fn release_inner (&self) ->Result { +let scope_mode = self.0 .mode & !ModeFlag ::Idle ; +match self.0 .mode { + modeif mode.contains (ModeFlag ::Idle ) =>Request ::idle (self.0 .dev, scope_mode),
Quoted 8 lines
rust/kernel/error.rs
Quoted 5 lines
rust/kernel/error.rs +5
-0+ mode if mode.contains(ModeFlag::Auto) => { + Request::mark_last_busy(self.0.dev); + Request::suspend(self.0.dev, scope_mode) + } + _ => Request::suspend(self.0.dev, scope_mode),In v2 you had
Request::idlein the default arm. I didn't see a note about this in the changelog. Was the change in behavior intentional?
This is intentional to match the resume request. Idle has a separate case. Missed that from the changelog.
Quoted 19 lines
Quoted 19 lines
rust/kernel/error.rs +18
-0+impl <'a>RetainScope <'a> { +fn new (dev: &'a device::Device <device::Bound >) ->Result <Self > { +Request ::get_noresume (dev); +Ok (Self (Scope ::<Retain > { + dev, + mode:Mode (ModeFlag ::Sync as u32 ), + _tag:PhantomData , + })) + } + +fn try_new (dev: &'a device::Device <device::Bound >) ->Result <Self > { +Request ::get_if_active (dev)?; +Ok (Self (Scope ::<Retain > { + dev, + mode:Mode (ModeFlag ::Sync as u32 ), + _tag:PhantomData , + })) + }
Quoted 8 lines
rust/kernel/error.rs
Quoted 3 lines
rust/kernel/error.rs +3
-0+ +fn release_inner (&self) { +Request ::put_noidle (self.0 .dev);What's the reason for using
put_noidlehere? It doesn't queue autosuspend, so wouldn't thetry_hold_activepattern (i.e. grab if active, do something, drop) leave the device active until something else triggers a suspend?
You are right. This should call put.
Quoted 50 lines
rust/kernel/error.rs
Quoted 8 lines
rust/kernel/error.rs +7
-0+/// SAFETY: +/// bindings::dev_pm_ops is #[repr(C)], implements Default +/// and the struct itself is all nullable function pointers. +/// There is no padding and all zero bit-pattern is valid +/// +pub const PMOPS_NONE : bindings::dev_pm_ops = +unsafe { core::mem::MaybeUninit ::<bindings::dev_pm_ops >::zeroed ().assume_init () };The safety comment shouldn't be a doc comment.
rust/kernel/error.rs
Quoted 5 lines
rust/kernel/error.rs +5
-0+/// Runtime PM context tied to a device. +pub struct PMContext <'a,D : driver::DriverLayout ,T :PMOps <D >> { +// Preferably, PMContext could be shared via borrowed reference over +// a pm Registration's lifetime but that bares complications on its own +// when the context needs to be shared across different Registration types. Nit: bares -> bears. Also in the identical comment below.
Quoted 31 lines
rust/kernel/error.rs +31
-0+impl <'a,D : driver::DriverLayout ,T :PMOps <D >>PMContext <'a,D ,T > { +/// Driver-provided runtime PM operations. +/// +/// A driver implements this trait to handle runtime PM +/// transitions for its device type. +/// +/// Each callback receives the device and the current payload. +/// On success, it returns the payload to keep for the next +/// transition. On failure, it returns the payload together +/// with the error so the previous, or otherwise sane state +/// can be preserved. +pub const PM_OPS : bindings::dev_pm_ops = bindings::dev_pm_ops { + runtime_resume:if T ::HAS_RUNTIME_RESUME { +Some (runtime_resume_callback ::<D ,T >) + }else { +None + }, + runtime_suspend:if T ::HAS_RUNTIME_SUSPEND { +Some (runtime_suspend_callback ::<D ,T >) + }else { +None + }, + ..PMOPS_NONE + }; + +/// Enable runtime PM +pub fn enable (&self, state:RuntimePMState ) ->Result { +if self.inner.enabled.cmpxchg (false ,true , ordering::Full ).is_err () { +return Err (EBUSY ); + } +Self ::apply_config (self.inner.dev, &self.inner.configs);
Quoted 8 lines
rust/kernel/error.rs
Quoted 5 lines
rust/kernel/error.rs +5
-0+match state { +RuntimePMState ::RESUMED =>Request ::mark_active (self.inner.dev), +RuntimePMState ::SUSPENDED =>Request ::mark_suspended (self.inner.dev), + _ =>Err (EINVAL ), + }.inspect_err (|_| self.inner.enabled.store (false , ordering::Release ))?;This always applies the config even if state is invalid. Should we validate the state before making changes?
We could but that should not be strictly necessary. Those should not have any effect when rpm is not enabled.
Quoted 10 lines
rust/kernel/error.rs
Quoted 9 lines
rust/kernel/error.rs +8
-0+/// Runs a closure while holding an `AwakeScope`. +pub fn with_get <R >(&self, profile:PMProfile , f:impl FnOnce () ->Result <R >) ->Result <R > { +if profile.0 .contains (ModeFlag ::Async ) { +return Err (EINVAL ); + } +let _scope = self.get (profile)?; +f () + }
Quoted 2 lines
Shouldn't this reject NoWait too to make sure the device will actually be powered when the closure is executed?
We should. Thanks for catching this.
Thank you for your feedback.\
---
BR
Beata
Quoted 2 lines
Sami
Alice Ryhl
maintainerRe: [PATCH v3 1/3] rust: add runtime PM support
In reply to Beata Michalskarust/kernel/pm.rs line 581
Quoted 2 lines · Beata Michalska
rust/kernel/pm.rs new file +2
-0+/// Result type returned by runtime PM callbacks. +pub type PMCallbackResult <T > =Result <Option <T >, (Option <T >,Error )>;
So I think my number one feedback is that it would be really nice to get rid of this Option.
Quoted 1 line
+/// Runtime PM data stored within the `struct
device_private' during
Should be ... rather than ' to render correctly in html docs.
Alice
Re: [PATCH v3 1/3] rust: add runtime PM support
Quoted 6 lines · Alice Ryhl
rust/kernel/pm.rs line 581
Quoted 2 lines · Beata Michalska
rust/kernel/pm.rs new file +2
-0+/// Result type returned by runtime PM callbacks. +pub type PMCallbackResult <T > =Result <Option <T >, (Option <T >,Error )>;So I think my number one feedback is that it would be really nice to get rid of this Option.
Guess this can be done. And I'm assuming that's for both Options here (?)
---
BR
Beata
Quoted 6 lines
Quoted 2 lines
+/// Runtime PM data stored within the `struct
device_private' duringShould be
...rather than ' to render correctly in html docs.Alice
Alice Ryhl
maintainerRe: [PATCH v3 1/3] rust: add runtime PM support
Quoted 9 lines · Beata Michalska
Quoted 6 lines · Alice Ryhl
rust/kernel/pm.rs line 581
Quoted 2 lines · Beata Michalska
rust/kernel/pm.rs new file +2
-0+/// Result type returned by runtime PM callbacks. +pub type PMCallbackResult <T > =Result <Option <T >, (Option <T >,Error )>;So I think my number one feedback is that it would be really nice to get rid of this Option.
Guess this can be done. And I'm assuming that's for both Options here (?)
Yeah. I'm thinking that one approach could be to use the AtomicFlag to track whether a value is stored in the container, and possible change the Option to ManuallyDrop. Then in drop of that type, you check the AtomicFlag and only if it's false you drop the value. That way, you can take the value in/out of the ManuallyDrop so that you can transfer ownership to/from the storage.
Alice
PATCH v3 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::DevPMOps 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 | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)
rust/kernel/platform.rs +30 -0
@@ -72,6 +72,10 @@ unsafe fn register( None => core::ptr::null(), }; +let pm_ops =T ::dev_pm_ops () + .map (|ops| ops.as_raw ()) + .unwrap_or (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 +83,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`.
@@ -195,6 +200,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); ///
@@ -224,6 +230,14 @@ 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. +fn dev_pm_ops () ->Option <crate ::pm::DevPMOps <Adapter <Self >,Self >> +where +Self :Sized , + { +None + } +/// Platform driver probe. /// /// Called when a new platform device is added or discovered.
@@ -571,3 +585,19 @@ 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 >crate ::pm::DevPMOps <Adapter <T >,T > +where +T :Driver +crate ::pm::PMOps <Adapter <T >,DeviceType =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. +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 {crate ::pm::DevPMOps ::new_unchecked () } + } +}
Signature · 1 line
2.43.0
PATCH v3 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 | 123 +++++++++++++++++++++++++++------- drivers/gpu/drm/tyr/file.rs | 3 + 2 files changed, 102 insertions(+), 24 deletions(-)
drivers/gpu/drm/tyr/driver.rs +99 -24
@@ -21,17 +21,15 @@ poll, Io, // }, - new_mutex, of, platform, + pm, + pm::*, prelude::*, regulator, regulator::Regulator, sizes::SZ_2M, - sync::{ - Arc, - Mutex, // - }, + sync::Arc, time, types::CovariantForLt, // };
@@ -58,6 +56,10 @@#[pin_data( PinnedDrop )] pub (crate )struct TyrPlatformDriverData <'bound> { _reg: drm::Registration <'bound,TyrDrmDriver >, +// This needs to be dropped after drm::Registration as that one +// borrows PMContext. +pub (crate ) pm: + pm::Registration <'bound, platform::Adapter <TyrPlatformDriver >,TyrPlatformDriver >, }/// Data owned by the DRM [`Registration`].
@@ -72,11 +74,8 @@ pub(crate) struct TyrDrmRegistrationData<'drm> {/// Firmware sections. pub(crate) fw: Firmware<'drm>, -#[pin] - clks: Mutex<Clocks>, - -#[pin] - regulators: Mutex<Regulators>, +/// Runtime PM context owned by the PM Registration + pub(crate) pm: PMContext<'drm, platform::Adapter<TyrPlatformDriver>, TyrPlatformDriver>,/// GPU MMIO register mapping. pub(crate) iomem: Arc<IoMem<'drm>>,
@@ -114,6 +113,10 @@ impl platform::Driver for TyrPlatformDriver {type Data <'bound> =TyrPlatformDriverData <'bound>;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE ); +fn dev_pm_ops () ->Option <pm::DevPMOps <platform::Adapter <Self >,Self >> { +Some (pm::DevPMOps ::<platform::Adapter <Self >,Self >::new ()) + } +fn probe <'bound>( pdev: &'bound platform::Device <Core <'_>>, _info: Option<&'bound Self::IdInfo>,
@@ -129,6 +132,32 @@ 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 pm_registration = pm::Registration ::new ( + pdev.as_ref (), + pm::DevPMOps ::<platform::Adapter <Self >,Self >::new (), +None , +Some (pm_configs), +Some (runtime_payload), + )?; + +let pm_context = pm_registration.ctx ().clone (); +let request = pdev.io_request_by_index (0 ).ok_or (ENODEV )?;let iomem =Arc ::new (request.iomap_sized ::<SZ_2M >()?,GFP_KERNEL )?;
@@ -162,27 +191,23 @@ fn probe<'bound>( firmware.boot ()?;let reg_data =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, + pdev, + fw: firmware, + pm: pm_context, + iomem, + gpu_info, });// SAFETY: `reg` is stored in `TyrPlatformDriverData` and dropped when the driver is // unbound; it is never forgotten. let reg =unsafe { drm::Registration ::new (pdev.as_ref (), unreg_dev, reg_data,0 )? }; -let driver =TyrPlatformDriverData { _reg: reg }; +let driver =TyrPlatformDriverData { + _reg: reg, + pm: pm_registration, + }; + driver.pm.ctx ().enable (RuntimePMState ::RESUMED )?;dev_dbg! (pdev,"Tyr initialized correctly." );Ok (driver) }
@@ -237,3 +262,53 @@ struct Regulators { _mali: Regulator<regulator::Enabled>, _sram: Regulator<regulator::Enabled>, } + +pub (crate )struct TyrRuntimePMPayload { + clks:Clocks , + _regulators:Regulators , +} + +#[vtable] +impl PMOps <platform::Adapter <TyrPlatformDriver >>for TyrPlatformDriver { +type DeviceType = platform::Device <kernel::device::Bound >; +type RuntimePayloadType =TyrRuntimePMPayload ; + +fn runtime_suspend <'a>( + _dev: &'aSelf ::DeviceType , + payload:Option <TyrRuntimePMPayload >, + ) ->Result <Option <TyrRuntimePMPayload >, (Option <TyrRuntimePMPayload >,Error )> { +let Some (payload) = payloadelse { +return Err ((None ,EINVAL )); + }; + + payload.clks.coregroup.disable_unprepare (); + payload.clks.stacks.disable_unprepare (); + payload.clks.core.disable_unprepare (); +Ok (Some (payload)) + } +fn runtime_resume <'a>( + _dev: &'aSelf ::DeviceType , + payload:Option <TyrRuntimePMPayload >, + ) ->Result <Option <TyrRuntimePMPayload >, (Option <TyrRuntimePMPayload >,Error )> { +let Some (payload) = payloadelse { +return Err ((None ,EINVAL )); + }; + +if let Err (e) = payload.clks.core.prepare_enable () { +return Err ((Some (payload), e)); + } + +if let Err (e) = payload.clks.stacks.prepare_enable () { + payload.clks.core.disable_unprepare (); +return Err ((Some (payload), e)); + } + +if let Err (e) = payload.clks.coregroup.prepare_enable () { + payload.clks.stacks.disable_unprepare (); + payload.clks.core.disable_unprepare (); +return Err ((Some (payload), e)); + } + +Ok (Some (payload)) + } +}
drivers/gpu/drm/tyr/file.rs +3 -0
@@ -5,6 +5,7 @@ self, Registered, // }, + pm::PMProfile, prelude::*, uaccess::UserSlice, uapi, //
@@ -40,6 +41,8 @@ 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 => {
Signature · 1 line
2.43.0