* [PATCH v6 0/3] Rust: add runtime PM support
@ 2026-11-24 11:34 Beata Michalska
2026-11-24 11:34 ` [PATCH v6 1/3] rust: " Beata Michalska
` (2 more replies)
0 siblings, 3 replies; 6+ messages in thread
From: Beata Michalska @ 2026-11-24 11:34 UTC (permalink / raw)
To: ojeda, dakr, gregkh, rafael, aliceryhl
Cc: boqun, gary, bjorn3_gh, lossin, a.hindborg, tmgross,
daniel.almeida, boris.brezillon, work, samitolvanen, acourbot,
rust-for-linux, driver-core, linux-kernel, linux-pm
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 `Scope`s
- 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 (samitolvanen@google.com),
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
--
2.43.0
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH v6 1/3] rust: add runtime PM support
2026-11-24 11:34 [PATCH v6 0/3] Rust: add runtime PM support Beata Michalska
@ 2026-11-24 11:34 ` Beata Michalska
2026-11-27 20:08 ` Rafael J. Wysocki (Intel)
2026-11-24 11:34 ` [PATCH v6 2/3] rust: platform: wire runtime PM callbacks Beata Michalska
2026-11-24 11:34 ` [PATCH v6 3/3 DO NOT MERGE] drm/tyr: enable runtime PM Beata Michalska
2 siblings, 1 reply; 6+ messages in thread
From: Beata Michalska @ 2026-11-24 11:34 UTC (permalink / raw)
To: ojeda, dakr, gregkh, rafael, aliceryhl
Cc: boqun, gary, bjorn3_gh, lossin, a.hindborg, tmgross,
daniel.almeida, boris.brezillon, work, samitolvanen, acourbot,
rust-for-linux, driver-core, linux-kernel, linux-pm
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.
Signed-off-by: Beata Michalska <beata.michalska@arm.com>
---
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
diff --git a/drivers/base/base.h b/drivers/base/base.h
index 866b2beb6baa..bc91d873318f 100644
--- a/drivers/base/base.h
+++ b/drivers/base/base.h
@@ -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) \
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 3791af0aadc7..a630213039d9 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -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>
diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
index d62c7be1ca7b..2cfd0ee83ac1 100644
--- a/rust/helpers/helpers.c
+++ b/rust/helpers/helpers.c
@@ -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"
diff --git a/rust/helpers/pm_runtime.c b/rust/helpers/pm_runtime.c
new file mode 100644
index 000000000000..890cdc8d5c90
--- /dev/null
+++ b/rust/helpers/pm_runtime.c
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/pm_runtime.h>
+
+__rust_helper
+void rust_helper_pm_runtime_get_noresume(struct device *dev)
+{
+ pm_runtime_get_noresume(dev);
+}
+
+__rust_helper
+void rust_helper_pm_runtime_put_noidle(struct device *dev)
+{
+ pm_runtime_put_noidle(dev);
+}
+
+__rust_helper
+void rust_helper_pm_runtime_mark_last_busy(struct device *dev)
+{
+ pm_runtime_mark_last_busy(dev);
+}
+
+__rust_helper
+bool rust_helper_pm_runtime_active(struct device *dev)
+{
+ return pm_runtime_active(dev);
+}
+
+__rust_helper
+bool rust_helper_pm_runtime_suspended(struct device *dev)
+{
+ return pm_runtime_suspended(dev);
+}
+
+__rust_helper
+void rust_helper_pm_suspend_ignore_children(struct device *dev, bool enable)
+{
+ pm_suspend_ignore_children(dev, enable);
+}
+
+__rust_helper
+int rust_helper_pm_runtime_set_active(struct device *dev)
+{
+ return pm_runtime_set_active(dev);
+}
+
+__rust_helper
+int rust_helper_pm_runtime_set_suspended(struct device *dev)
+{
+ return pm_runtime_set_suspended(dev);
+}
+
+__rust_helper
+bool rust_helper_pm_runtime_enabled(struct device *dev)
+{
+ return pm_runtime_enabled(dev);
+}
+
+__rust_helper
+bool rust_helper_pm_runtime_is_irq_safe(struct device *dev)
+{
+ return pm_runtime_is_irq_safe(dev);
+}
+
+#ifndef CONFIG_PM
+__rust_helper
+int rust_helper___pm_runtime_resume(struct device *dev, int rpmflags)
+{
+ return __pm_runtime_resume(dev, rpmflags);
+}
+
+__rust_helper
+int rust_helper___pm_runtime_idle(struct device *dev, int rpmflags)
+{
+ return __pm_runtime_idle(dev, rpmflags);
+}
+
+__rust_helper
+int rust_helper___pm_runtime_suspend(struct device *dev, int rpmflags)
+{
+ return __pm_runtime_suspend(dev, rpmflags);
+}
+
+__rust_helper
+int rust_helper_pm_runtime_get_if_active(struct device *dev)
+{
+ return pm_runtime_get_if_active(dev);
+}
+
+__rust_helper void rust_helper_pm_runtime_enable(struct device *dev) {}
+__rust_helper void rust_helper___pm_runtime_disable(struct device *dev, bool c) {}
+__rust_helper void rust_helper_pm_runtime_barrier(struct device *dev) {}
+__rust_helper void rust_helper_pm_runtime_no_callbacks(struct device *dev) {}
+__rust_helper void rust_helper_pm_runtime_irq_safe(struct device *dev) {}
+__rust_helper
+void rust_helper___pm_runtime_use_autosuspend(struct device *dev, bool use)
+{}
+__rust_helper
+void rust_helper_pm_runtime_set_autosuspend_delay(struct device *dev, int delay)
+{}
+#endif /* CONFIG_PM */
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 2291d85b6849..7edcc6941deb 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -19,6 +19,7 @@
ptr, //
};
+pub mod pm;
pub mod property;
/// The core representation of a device in the kernel's driver model.
diff --git a/rust/kernel/device/pm.rs b/rust/kernel/device/pm.rs
new file mode 100644
index 000000000000..9abf5efe48fe
--- /dev/null
+++ b/rust/kernel/device/pm.rs
@@ -0,0 +1,1187 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust Runtime Power Management abstraction.
+//!
+//! C header: [`include/linux/pm_runtime.h`](srctree/include/linux/pm_runtime.h)
+
+use crate::{
+ bindings,
+ bits::bit_u32,
+ device::{
+ Device,
+ Bound,
+ Core,
+ AsBusDevice, //
+ },
+ driver,
+ error::{
+ to_result,
+ VTABLE_DEFAULT_ERROR, //
+ },
+ prelude::*,
+ sync::atomic::{
+ ordering,
+ Atomic,
+ AtomicFlag,
+ AtomicType, //
+ },
+ sync::Srcu,
+ sync::srcu::new_srcu, //
+};
+
+use core::{
+ cell::UnsafeCell,
+ marker::PhantomData,
+ mem::ManuallyDrop,
+ ptr::NonNull, //
+};
+
+kernel::impl_flags! {
+ /// Runtime Power Management modes that determine how a particular PM
+ /// transition is to be carried out.
+ /// Corresponds to C Runtime PM flag argument bits:
+ /// - `RPM_ASYNC`
+ /// - `RPM_NOWAIT`
+ /// - `RPM_GET_PUT`
+ /// - `RPM_AUTO`
+ /// Synchronous mode is represented as `Mode::empty()`,
+ /// which is the default mode.
+ #[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
+ pub struct Mode(u32);
+
+ /// Single RPM mode
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
+ pub enum ModeFlag {
+ /// Allow asynchronous PM operations.
+ Async = bindings::RPM_ASYNC,
+ /// Do not wait for any pending requests to finish.
+ Nowait = bindings::RPM_NOWAIT,
+ /// Acquire a runtime-PM usage reference.
+ Acquire = bindings::RPM_GET_PUT,
+ /// Use autosuspend.
+ Auto = bindings::RPM_AUTO,
+ /// Additional mode for devices supporting idle states.
+ /// No counterpart.
+ Idle = bit_u32(16),
+ }
+}
+
+impl From<Mode> for c_int {
+ #[inline]
+ fn from(mode: Mode) -> c_int {
+ mode.0 as c_int
+ }
+}
+
+/// Device's runtime power management status
+#[derive(Copy,Clone)]
+#[repr(i32)]
+pub enum RuntimePMState {
+ /// The device is expected to be runtime active and in its normal operating state
+ Active = bindings::rpm_status_RPM_ACTIVE,
+ /// The device is expected to be suspended, unavailable for normal operations
+ Suspended = bindings::rpm_status_RPM_SUSPENDED,
+}
+
+/// Device's scoped runtime-resumed state
+pub struct Scope<'a, Tag> {
+ dev: &'a Device<Bound>,
+ mode: Mode,
+ _tag: PhantomData<Tag>,
+}
+
+/// Device resumed without incrementing the device's usage count
+struct Resume;
+/// Device resumed with the device's usage count being incremented
+struct Awake;
+/// Device with increased usage reference count
+struct Retain;
+
+/// Resumes the device without acquiring the usage reference.
+/// Note: This does not guarantee the device will be kept active
+/// for the lifetime of the scope due to potential pending/incoming
+/// suspend requests.
+/// Successfully obtaining the scope guard does not guarantee the device
+/// has been resumed: subject to the requested mode:
+/// `ModeFlag::Async` and `ModeFlag::Nowait`
+///
+/// On drop:
+/// - If `ModeFlag::Idle`, calls `__pm_runtime_idle()`:
+/// triggers idle notification before attempting to suspend
+/// - If `ModeFlag::Auto`, marks last busy then calls `__pm_runtime_suspend()`.
+/// - Otherwise calls `__pm_runtime_suspend()`.
+///
+/// The guard must be dropped from a context matching the requested transition
+/// mode: sync vs async.
+#[must_use = "dropping this guard issues the matching runtime PM release request"]
+pub struct ResumeScope<'a>(Scope<'a, Resume>);
+
+/// Acquires a runtime-PM usage reference and keeps the device powered.
+/// Successfully obtaining the scope guard does not guarantee the device
+/// has been resumed: subject to the requested mode:
+/// `ModeFlag::Async` and `ModeFlag::Nowait`.
+///
+/// Requires `ModeFlag::Acquire`.
+/// Drop behavior matches `ResumeScope`.
+///
+/// The guard must be dropped from a context matching the requested transition
+/// mode: sync vs async.
+#[must_use = "dropping this guard releases its runtime PM hold"]
+pub struct AwakeScope<'a>(Scope<'a, Awake>);
+
+/// Prevents the device from getting suspended by holding the usage reference
+/// count.
+///
+/// On drop, calls `pm_runtime_put_noidle()`.
+#[must_use = "dropping this guard releases its runtime PM hold"]
+pub struct RetainScope<'a>(Scope<'a, Retain>);
+
+impl<'a> ResumeScope<'a> {
+ fn new(dev: &'a 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 off before passing further
+ match Request::resume(dev, mode & !ModeFlag::Idle) {
+ Ok(()) => {}
+ // if ModeFlag::Async is set, -EINPROGRESS signals ongoing resume,
+ // with ModeFlag::Nowait -> ongoing suspend with delayed resume
+ // being queued
+ Err(e) if e == EINPROGRESS && mode.contains_any(ModeFlag::Async| ModeFlag::Nowait) => {}
+ Err(e) => return Err(e),
+ }
+
+ Ok(Self(Scope::<Resume> {
+ dev,
+ mode,
+ _tag: PhantomData,
+ }))
+ }
+
+ fn release_inner(&self) -> Result {
+ if !cfg!(CONFIG_PM) {
+ return Ok(())
+ }
+
+ let mode = self.0.mode;
+ let scope_mode = mode & !ModeFlag::Idle;
+
+ if mode.contains(ModeFlag::Auto) {
+ Request::mark_last_busy(self.0.dev);
+ }
+
+ match self.0.mode {
+ mode if mode.contains(ModeFlag::Idle) => Request::idle(self.0.dev, scope_mode),
+ _ => Request::suspend(self.0.dev, scope_mode),
+ }
+ }
+
+ /// Explicitly release the scope
+ ///
+ /// This should be used in favor of regular drop when error handling is
+ /// required.
+ pub fn release(self) -> Result {
+ let result = self.release_inner();
+ core::mem::forget(self);
+ result
+ }
+}
+
+impl<'a> Drop for ResumeScope<'a> {
+ fn drop(&mut self) {
+ let _ = self.release_inner();
+ }
+}
+
+impl<'a> AwakeScope<'a> {
+ fn new(dev: &'a Device<Bound>, mode: Mode) -> Result<Self> {
+ if !mode.contains(ModeFlag::Acquire) {
+ return Err(EINVAL);
+ }
+ // ModeFlag::Idle is internal so strip it off before passing further
+ match Request::resume(dev, mode & !ModeFlag::Idle) {
+ Ok(()) => {}
+ // For async/nowait requests, `EINPROGRESS` means the resume is
+ // either in flight or pending.
+ 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 {
+ if !cfg!(CONFIG_PM) {
+ return Ok(())
+ }
+
+ let mode = self.0.mode;
+ let scope_mode = mode & !ModeFlag::Idle;
+
+ if mode.contains(ModeFlag::Auto) {
+ Request::mark_last_busy(self.0.dev);
+ }
+
+ match self.0.mode {
+ mode if mode.contains(ModeFlag::Idle) => Request::idle(self.0.dev, scope_mode),
+ _ => Request::suspend(self.0.dev, scope_mode),
+ }
+ }
+
+ /// Explicitly release the scope
+ ///
+ /// This should be used in favor of regular drop when error handling is
+ /// required.
+ pub fn release(self) -> Result {
+ let result = self.release_inner();
+ core::mem::forget(self);
+ result
+ }
+}
+
+impl<'a> Drop for AwakeScope<'a> {
+ fn drop(&mut self) {
+ let _ = self.release_inner();
+ }
+}
+
+impl<'a> RetainScope<'a> {
+ fn new(dev: &'a Device<Bound>) -> Result<Self> {
+ Request::get_noresume(dev);
+ Ok(Self(Scope::<Retain> {
+ dev,
+ mode: Mode::empty(),
+ _tag: PhantomData,
+ }))
+ }
+
+ fn try_new(dev: &'a Device<Bound>) -> Result<Self> {
+ Request::get_if_active(dev)?;
+ Ok(Self(Scope::<Retain> {
+ dev,
+ mode: Mode(u32::from(Mode::empty())),
+ _tag: PhantomData,
+ }))
+ }
+
+ fn release_inner(&self) {
+ Request::put_noidle(self.0.dev);
+ }
+
+ /// Explicitly release the scope
+ ///
+ /// This should be used in favor of regular drop when error handling is
+ /// required.
+ pub fn release(self) -> Result {
+ self.release_inner();
+ core::mem::forget(self);
+ Ok(())
+ }
+}
+
+impl<'a> Drop for RetainScope<'a> {
+ fn drop(&mut self) {
+ self.release_inner();
+ }
+}
+
+/// Private entry points to the C runtime PM API.
+///
+/// Provides a centralized location for both, the C calls themsleves,
+/// as well as for their safety requirements.
+///
+/// # Safety
+///
+/// Each method takes `&Device<Bound>`. `Device` guarantees that `as_raw()`
+/// points to a valid `struct device` during the call. `Bound` guarantees that
+/// the driver remains attached while the PM core may invoke callbacks using
+/// driver-owned data. For requests completed later, [`Registration`] keeps
+/// callback data alive and drains pending callbacks before dropping it.
+struct Request;
+
+impl Request {
+ #[inline]
+ fn active(dev: &Device<Bound>) -> bool {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_active(dev.as_raw()) }
+ }
+
+ #[inline]
+ fn suspended(dev: &Device<Bound>) -> bool {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_suspended(dev.as_raw()) }
+ }
+
+ #[inline]
+ fn resume(dev: &Device<Bound>, mode: Mode) -> Result {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ to_result(unsafe { bindings::__pm_runtime_resume(dev.as_raw(), mode.into()) })
+ }
+
+ #[inline]
+ fn suspend(dev: &Device<Bound>, mode: Mode) -> Result {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ to_result(unsafe { bindings::__pm_runtime_suspend(dev.as_raw(), mode.into()) })
+ }
+
+ #[inline]
+ fn get_noresume(dev: &Device<Bound>) {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_get_noresume(dev.as_raw()) };
+ }
+
+ #[inline]
+ fn get_if_active(dev: &Device<Bound>) -> Result {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ match unsafe { bindings::pm_runtime_get_if_active(dev.as_raw()) } {
+ ret if ret < 0 => Err(Error::from_errno(ret)),
+ 0 => Err(EAGAIN),
+ _ => Ok(()),
+ }
+ }
+
+ #[inline]
+ fn idle(dev: &Device<Bound>, mode: Mode) -> Result {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ to_result(unsafe { bindings::__pm_runtime_idle(dev.as_raw(), mode.into()) })
+ }
+
+ #[inline]
+ fn put_noidle(dev: &Device<Bound>) {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_put_noidle(dev.as_raw()) };
+ }
+
+ #[inline]
+ fn mark_active(dev: &Device<Bound>) -> Result {
+ to_result(
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_set_active(dev.as_raw()) },
+ )
+ }
+
+ #[inline]
+ fn mark_suspended(dev: &Device<Bound>) -> Result {
+ to_result(
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_set_suspended(dev.as_raw()) },
+ )
+ }
+
+ #[inline]
+ fn mark_last_busy(dev: &Device<Bound>) {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe {
+ bindings::pm_runtime_mark_last_busy(dev.as_raw());
+ }
+ }
+
+ #[inline]
+ fn runtime_enable(dev: &Device<Bound>) {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::pm_runtime_enable(dev.as_raw()) }
+ }
+
+ #[inline]
+ fn runtime_disable(dev: &Device<Bound>) {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe { bindings::__pm_runtime_disable(dev.as_raw(), true) };
+ }
+
+ #[inline]
+ fn barrier(dev: &Device<Bound>) {
+ // SAFETY: `dev` satisfies safety requirements documented on `Request`.
+ unsafe {
+ bindings::pm_runtime_barrier(dev.as_raw());
+ }
+ }
+}
+
+/// Common runtime PM callback entry point.
+///
+/// Invokes a runtime PM callback with its registration data and current payload.
+///
+/// # Safety
+///
+/// The generated extern "C" callbacks call into this helper with the raw
+/// `struct device *` provided by the PM core. As such, it is guaranteed that
+/// the `struct device` remains valid throughout the calls.
+#[cfg(CONFIG_PM)]
+unsafe fn with_registration_data<T, F>(dev: *mut bindings::device, cb: F) -> Result
+where
+ T: PMOps,
+ F: for <'a>FnOnce(
+ &'a <T as PMOps>::DeviceType,
+ &'a <T as PMOps>::RegistrationData<'a>,
+ RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>
+ ) -> PMCallbackResult<RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>,
+ RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>>,
+{
+ // SAFETY: `dev` is provided by the PM core and remains valid
+ // for the duration of the callback.
+ let dev: &Device = unsafe { Device::from_raw(dev) };
+ // SAFETY: The runtime PM callback can only be triggered for a bound device.
+ let dev: &Device<Bound> = unsafe { dev.as_bound() };
+ let pm_dev: &T::DeviceType =
+ // SAFETY: The generated `dev_pm_ops` for `T` is installed on devices whose
+ // bus-specific type is `T::DeviceType`. Therefore the base `Device<Bound>`
+ // passed by the PM core is embedded in a valid `T::DeviceType`; the
+ // `AsBusDevice` implementation supplies the correct offset for this cast.
+ unsafe { T::DeviceType::from_device(dev) };
+ // SAFETY: The `RegistrationData` must have been successfully installed
+ // for a device and it is guaranteed that it reamins valid at least until
+ // the last PM callback finishes.
+ let ptr = unsafe { (*(*dev.as_raw()).p).rust.pm_registration_data };
+ // SAFETY: `Registration::new` stores a pointer to its initialized, pinned
+ // `RegistrationData<T>` before enabling runtime PM. These callbacks
+ // belong to the same `T`. Registration teardown disables runtime PM and
+ // drains callbacks before clearing the pointer and dropping the data, so
+ // it remains valid for this callback
+ let reg_data = unsafe { &*ptr.cast::<RegistrationData<'_, T>>() };
+
+ let _guard = reg_data.payload.acquire()?;
+ // SAFETY: This callback alone acquired `in_flight`; it has exclusive
+ // access to the payload slot until `_guard` is dropped.
+ let slot = unsafe { &mut *reg_data.payload.inner.get() };
+ // SAFETY: `_guard` gives this callback exclusive access to `slot`, which
+ // contains an initialized payload. Both callback outcomes provide a payload
+ // that is written back into `slot` before `_guard` is released.
+ let payload = unsafe { ManuallyDrop::take(slot) };
+
+ let (next, result) = match cb(pm_dev, ®_data.data, payload) {
+ Ok(next) => (next, Ok(())),
+ Err((current, err)) => (current, Err(err)),
+ };
+
+ *slot = ManuallyDrop::new(next);
+ result
+}
+
+/// Runtime resume PM callback.
+///
+/// # Safety
+///
+/// `dev` is a valid `struct device *` supplied by the PM core for a device
+/// whose runtime PM callbacks and PM registration data were both created
+/// for `T`.
+#[cfg(CONFIG_PM)]
+unsafe extern "C" fn runtime_resume_callback<T>(dev: *mut bindings::device) -> c_int
+where
+ T: PMOps,
+{
+ // SAFETY: The callback's safety contract guarantees that `dev` remains
+ // valid for this call and has PM registration data created for `T`.
+ // These are the preconditions of `with_registration_data`.
+ unsafe {
+ with_registration_data::<T, _>(dev,
+ |pm_dev, data, payload| {
+ match payload {
+ RuntimeStatePayload::Suspended(payload_data) => {
+ T::runtime_resume(pm_dev, data, payload_data)
+ .map(RuntimeStatePayload::Active)
+ .map_err(|(prev, err)| (RuntimeStatePayload::Suspended(prev), err))
+ },
+ other => Err((other, EINVAL)),
+ }
+ })
+ .map(|()| 0)
+ .unwrap_or_else(|e| e.to_errno())
+ }
+}
+/// Runtime suspend PM callback.
+///
+/// # Safety
+///
+/// `dev` is a valid `struct device *` supplied by the PM core for a device
+/// whose runtime PM callbacks and PM registration data were both created
+/// for `T`.
+#[cfg(CONFIG_PM)]
+unsafe extern "C" fn runtime_suspend_callback<T>(dev: *mut bindings::device) -> c_int
+where
+ T: PMOps,
+{
+ // SAFETY: The callback's safety contract guarantees that `dev` remains
+ // valid for this call and has PM registration data created for `T`.
+ // These are the preconditions of `with_registration_data`.
+ unsafe {
+ with_registration_data::<T, _>(dev,
+ |pm_dev, data, payload| {
+ match payload {
+ RuntimeStatePayload::Active(payload_data) => {
+ T::runtime_suspend(pm_dev, data, payload_data)
+ .map(RuntimeStatePayload::Suspended)
+ .map_err(|(prev, err)| (RuntimeStatePayload::Active(prev), err))
+ },
+ other => Err((other, EINVAL)),
+ }
+ })
+ .map(|()| 0)
+ .unwrap_or_else(|e| e.to_errno())
+ }
+}
+
+/// Default empty Runtime PM ops
+pub const PMOPS_NONE: bindings::dev_pm_ops =
+ // 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
+ //
+ unsafe { core::mem::MaybeUninit::<bindings::dev_pm_ops>::zeroed().assume_init() };
+
+/// Typed reference to a driver's runtime PM ops.
+///
+/// Instances of this type are generated from static [`Ops`]
+/// and are used by bus registration code to install the matching
+/// C `dev_pm_ops` pointer into the driver object.
+/// The `A` parameter identifies the bus adapter that is allowed
+/// to install the table.
+pub struct AdapterOpsRef<'a, A> {
+ #[cfg_attr(not(CONFIG_PM), allow(unused))]
+ ops: &'a bindings::dev_pm_ops,
+ _p: PhantomData<fn() -> *const A>,
+}
+
+/// Conveniance type alias
+pub type OpsRef<T> = AdapterOpsRef<'static, <T as PMOps>::Adapter>;
+
+// SAFETY: `AdapterOpsRef` only contains a shared reference to an immutable
+// `dev_pm_ops` table and a type marker. Sharing it between threads cannot
+// introduce mutation or aliasing of Rust-owned state.
+unsafe impl<A> Sync for AdapterOpsRef<'_, A> {}
+
+impl<A> AdapterOpsRef<'_, A> {
+ #[cfg_attr(not(CONFIG_PM), allow(unused))]
+ #[inline]
+ pub(crate) const fn as_raw(&self) -> *const bindings::dev_pm_ops {
+ self.ops
+ }
+}
+
+/// Runtime PM ops for a driver.
+///
+/// Intended to be constructed by bus-specific helpers, allowing
+/// the bus to ensure that the callback device type matches the device
+/// supplied by the C driver core.
+pub struct Ops<T: PMOps> {
+ raw: bindings::dev_pm_ops,
+ _p: PhantomData<fn() -> T>,
+}
+
+impl<T: PMOps> Ops<T> {
+ /// Creates a typed runtime PM ops.
+ ///
+ /// # Safety
+ ///
+ /// The caller must guarantee that `T::Adapter` is the bus adapter that
+ /// will install this ops into the C driver object for `T`, and
+ /// that `T::DeviceType` is the bus device type corresponding to
+ /// that adapter. Safe bus-specific constructors should wrap this
+ /// function with those bounds.
+ pub(crate) const unsafe fn new_unchecked(raw: bindings::dev_pm_ops) -> Self {
+ const_assert!(
+ T::HAS_RUNTIME_RESUME == T::HAS_RUNTIME_SUSPEND,
+ "runtime suspend and resume callbacks should be implemented together"
+ );
+ Self {
+ raw,
+ _p: PhantomData,
+ }
+ }
+
+ /// Provides a typed reference to this runtime PM ops
+ ///
+ /// Bus registration code uses the returned value to install
+ /// the ops into the corresponding C driver object.
+ /// The returned reference is tied to `T::Adapter`.
+ pub const fn pm_ops(&'static self) -> OpsRef<T> {
+ AdapterOpsRef {
+ ops: &self.raw,
+ _p: PhantomData,
+ }
+ }
+
+ /// Returns the raw C runtime PM operations table.
+ #[inline]
+ pub const fn as_raw(&'static self) -> *const bindings::dev_pm_ops {
+ &self.raw
+ }
+}
+
+/// Result type returned by runtime PM callbacks.
+pub type PMCallbackResult<New, Current> = Result<New, (Current, Error)>;
+
+/// Runtime PM callbacks implemented by a driver.
+///
+/// Defines the [`PMOps`] trait and its corresponding [`bindings::dev_pm_ops`].
+///
+/// The Adapter associated type identifies the bus adapter that installs
+/// the generated PM ops.
+/// Implementations should normally be enabled through a
+/// bus-specific constructor for [`Ops`], which constrains
+/// [`Self::DeviceType`] to the correct bound device type for that bus.
+#[vtable]
+pub trait PMOps: Sized {
+ /// The bus adapter that installs the generated PM ops.
+ type Adapter: driver::DriverLayout + 'static;
+
+ /// Type of the bound bus device passed to runtime PM callbacks.
+ type DeviceType: AsBusDevice<Bound>;
+
+ /// Data associated with the `Registration`, tied to its lifetime.
+ type RegistrationData<'a>: Send + Sync + 'a;
+
+ /// Driver's specific data associated with suspended PM device state
+ type SuspendedPayload<'a>: Send + 'a;
+ /// Driver's specific data associated with active PM device states
+ type ActivePayload<'a>: Send + 'a;
+
+ /// Runtime resume callback.
+ fn runtime_resume<'a>(
+ _dev: &'a Self::DeviceType,
+ _reg_data: &'a Self::RegistrationData<'a>,
+ _payload: Self::SuspendedPayload<'a>,
+ ) -> PMCallbackResult<Self::ActivePayload<'a>, Self::SuspendedPayload<'a>> {
+ build_error!(VTABLE_DEFAULT_ERROR)
+ }
+
+ /// Runtime suspend callback.
+ fn runtime_suspend<'a>(
+ _dev: &'a Self::DeviceType,
+ _reg_data: &'a Self::RegistrationData<'a>,
+ _payload: Self::ActivePayload<'a>,
+ ) -> PMCallbackResult<Self::SuspendedPayload<'a>, Self::ActivePayload<'a>> {
+ build_error!(VTABLE_DEFAULT_ERROR)
+ }
+}
+
+/// RAII guard for ongoing runtime PM payload transition.
+///
+/// For most of the callbacks this guard is not necessarily needed as
+/// the callbacks themselves are being serialized by the runtime PM C code.
+/// Still, some like runtime_idle are exempt from that.
+#[cfg_attr(not(CONFIG_PM), allow(unused))]
+struct PayloadGuard<'a> {
+ busy: &'a AtomicFlag,
+}
+
+impl Drop for PayloadGuard<'_> {
+ fn drop(&mut self) {
+ self.busy.store(false, ordering::Release);
+ }
+}
+
+/// Payload associated with the given runtime power state of a device.
+#[cfg_attr(not(CONFIG_PM), allow(unused))]
+pub enum RuntimeStatePayload<Active, Suspended> {
+ /// Payload associated with the runtime active PM state of a device
+ Active(Active),
+ /// Payload associated with the runtime suspended PM state of a device
+ Suspended(Suspended),
+}
+
+#[cfg_attr(not(CONFIG_PM), allow(unused))]
+struct Payload<'a, T:PMOps> {
+ in_flight: AtomicFlag,
+ inner: UnsafeCell<ManuallyDrop<RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>>>,
+}
+
+#[cfg_attr(not(CONFIG_PM), allow(unused))]
+impl<'a, T:PMOps> Payload<'a, T> {
+ /// Attempts to acquire exclusive access to the runtime PM payload.
+ ///
+ /// Returns `EBUSY` if another runtime PM callback is already transitioning the
+ /// payload.
+ fn acquire(&self) -> Result<PayloadGuard<'_>> {
+ self.in_flight
+ .cmpxchg(false, true, ordering::Acquire)
+ .map_err(|_| EBUSY)?;
+ Ok(PayloadGuard {
+ busy: &self.in_flight,
+ })
+ }
+}
+
+impl<T:PMOps> Drop for Payload<'_, T> {
+ fn drop(&mut self) {
+ // SAFETY: teardown drained PM callbacks and the slot holds a `P`
+ unsafe {
+ ManuallyDrop::drop(self.inner.get_mut());
+ }
+ }
+}
+
+// SAFETY: Although Payload's `inner` is an `UnsafeCell`, it is only accessed
+// after `in_flight` has been acquired. The AtomicFlag flag serializes all mutable
+// access to the payload, and `PayloadGuard` clears the flag when the access ends.
+unsafe impl<T:PMOps> Sync for Payload<'_, T> {}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(i32)]
+enum PMContextState {
+ /// The PM registration is alive, but runtime PM has not been enabled.
+ Disabled = 0,
+ /// Enabling runtime PM has been initiated but has not completed just yet
+ Enabling = 1,
+ /// The runtime PM has been enabled. Intended to be balanced by
+ /// `disable()` or `Registration::drop()`
+ Enabled = 2,
+ /// Disabling runtime PM has been initiated but has not completed just yet
+ Disabling = 3,
+ /// The owning `Registration` is being dropped or has been dropped.
+ /// Stale cloned `PMContext`s may still exist, but once this state is
+ /// visible, runtime PM cannot be re-enabled.
+ Closing = 4,
+}
+
+// SAFETY: `PMContextState` has the same size and alignment as `i32`, and all
+// values written through `Atomic<PMContextState>` are valid `PMContextState`
+// discriminants.
+unsafe impl AtomicType for PMContextState {
+ type Repr = i32;
+}
+
+#[pin_data]
+struct PMContextInner<'a, T: PMOps> {
+ dev: &'a Device<Bound>,
+ /// State owned by the runtime PM registration
+ state: Atomic<PMContextState>,
+ /// A synchronization point for all pending callbacks to finish.
+ #[pin]
+ guard: Srcu,
+ /// Optional driver-selected runtime PM request PMProfiles.
+ ///
+ /// Set of runtime PM predefined PMProfiles that can be used by the driver
+ /// when requesting a PM transition. This might be useful when a driver
+ /// has several different PM usage patterns.
+ /// See [PMProfile] for more details.
+ profiles: KVec<PMProfile>,
+ /// Set of PM config options applied for associated device.
+ configs: KVec<PMConfig>,
+ _marker: PhantomData<fn() -> T>,
+}
+
+/// Runtime PM context tied to a device.
+///
+/// Needs to be dropped from sleepable context.
+#[pin_data]
+pub struct PMContext<'r, 'a, T: PMOps> {
+ inner: &'r PMContextInner<'a, T>,
+}
+
+impl<'r, 'a, T: PMOps> PMContext<'r, 'a, 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, its registration data
+ /// 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.
+ #[cfg(CONFIG_PM)]
+ pub(crate) const PM_OPS: bindings::dev_pm_ops = bindings::dev_pm_ops {
+ runtime_resume: if T::HAS_RUNTIME_RESUME {
+ Some(runtime_resume_callback::<T>)
+ } else {
+ None
+ },
+ runtime_suspend: if T::HAS_RUNTIME_SUSPEND {
+ Some(runtime_suspend_callback::<T>)
+ } else {
+ None
+ },
+ ..PMOPS_NONE
+ };
+
+ #[cfg(not(CONFIG_PM))]
+ pub(crate) const PM_OPS: bindings::dev_pm_ops = PMOPS_NONE;
+
+ #[inline]
+ fn state_transition(&self, expected: PMContextState, new: PMContextState) -> Result
+ {
+ self.inner.state.cmpxchg(expected, new, ordering::Full)
+ .map(|_| ())
+ .map_err(|actual| match (expected, actual) {
+ (_, PMContextState::Closing) => ENODEV,
+ (PMContextState::Disabled, PMContextState::Disabling)
+ | (PMContextState::Enabled, PMContextState::Enabling) => EBUSY,
+ _ => EINVAL,
+ })
+ }
+
+ /// Enable runtime PM
+ pub fn enable(&self, state: RuntimePMState) -> Result {
+ let _transition_guard = self.inner.guard.read_lock();
+ self.state_transition(PMContextState::Disabled, PMContextState::Enabling)?;
+ Self::apply_config(self.inner.dev, &self.inner.configs);
+
+ match state {
+ RuntimePMState::Active => Request::mark_active(self.inner.dev),
+ RuntimePMState::Suspended => Request::mark_suspended(self.inner.dev),
+ }
+ .inspect_err(|_| {
+ Self::reset_config(self.inner.dev, &self.inner.configs);
+ let _ = self.state_transition(
+ PMContextState::Enabling,
+ PMContextState::Disabled,
+ );
+ })?;
+
+ Request::runtime_enable(self.inner.dev);
+ self.state_transition(
+ PMContextState::Enabling,
+ PMContextState::Enabled,
+ ).inspect_err(|e| {
+ if *e == ENODEV {
+ Request::runtime_disable(self.inner.dev);
+ Self::reset_config(self.inner.dev, &self.inner.configs);
+ }
+ })?;
+ Ok(())
+ }
+
+ /// Disable runtime PM
+ pub fn disable(&self) -> Result {
+ let _transition_guard = self.inner.guard.read_lock();
+ self.state_transition(
+ PMContextState::Enabled,
+ PMContextState::Disabling,
+ )?;
+
+ Request::runtime_disable(self.inner.dev);
+ Self::reset_config(self.inner.dev, &self.inner.configs);
+
+ let _ = self.state_transition(
+ PMContextState::Disabling,
+ PMContextState::Disabled
+ );
+ Ok(())
+ }
+
+ /// Returns whether the runtime PM state is active.
+ #[inline]
+ pub fn active(&self) -> bool {
+ Request::active(self.inner.dev)
+ }
+
+ /// Returns whether the runtime PM state is suspended.
+ #[inline]
+ pub fn suspended(&self) -> bool {
+ Request::suspended(self.inner.dev)
+ }
+
+ /// Creates a `ResumeScope` for the given PMProfile.
+ /// Note that for ASYNC/NOWAIT request this does not guarantee
+ /// the device has been resumed at the time this function returns.
+ #[inline]
+ pub fn resume(&self, profile: PMProfile) -> Result<ResumeScope<'r>> {
+ ResumeScope::new(self.inner.dev, profile.0)
+ }
+
+ /// Creates an `AwakeScope` for the given PMProfile.
+ /// Note that for ASYNC/NOWAIT request this does not guarantee
+ /// the device has been resumed at the time this function returns.
+ #[inline]
+ pub fn get(&self, profile: PMProfile) -> Result<AwakeScope<'r>> {
+ AwakeScope::new(self.inner.dev, profile.0 | ModeFlag::Acquire)
+ }
+
+ /// Creates a `RetainScope` for this device.
+ pub fn hold(&self) -> Result<RetainScope<'r>> {
+ RetainScope::new(self.inner.dev)
+ }
+
+ /// Creates a `RetainScope` for an active device.
+ pub fn try_hold_active(&self) -> Result<RetainScope<'r>> {
+ RetainScope::try_new(self.inner.dev)
+ }
+
+ /// Runs a closure while holding a `ResumeScope`.
+ pub fn with_resume<R>(&self, profile: PMProfile, f: impl FnOnce() -> Result<R>) -> Result<R> {
+ if profile.0.contains_any(ModeFlag::Async| ModeFlag::Nowait) {
+ return Err(EINVAL);
+ }
+ let _scope = self.resume(profile)?;
+ f()
+ }
+ /// 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_any(ModeFlag::Async | ModeFlag::Nowait) {
+ return Err(EINVAL);
+ }
+ let _scope = self.get(profile)?;
+ f()
+ }
+
+ /// Runs a closure while holding a `RetainScope`.
+ pub fn with_hold<R>(&self, f: impl FnOnce() -> Result<R>) -> Result<R> {
+ let _scope = self.hold()?;
+ f()
+ }
+
+ /// Applies runtime PM configuration options.
+ ///
+ /// Options are applied in the order provided. The currently supported
+ /// options do not report per-option failures.
+ fn apply_config(dev: &Device<Bound>, opts: &[PMConfig]) {
+ for opt in opts {
+ match opt {
+ // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
+ // yields a valid pointer to `struct device` for the duration of this call.
+ PMConfig::IgnoreChildren(v) => unsafe {
+ bindings::pm_suspend_ignore_children(dev.as_raw(), *v)
+ },
+ // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
+ // yields a valid pointer to `struct device` for the duration of this call.
+ PMConfig::NoCallbacks => unsafe { bindings::pm_runtime_no_callbacks(dev.as_raw()) },
+ // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
+ // yields a valid pointer to `struct device` for the duration of this call.
+ PMConfig::IrqSafe => unsafe {
+ // Do not attempt to call that more than once
+ if !bindings::pm_runtime_is_irq_safe(dev.as_raw()) {
+ bindings::pm_runtime_irq_safe(dev.as_raw());
+ }
+ },
+ // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
+ // yields a valid pointer to `struct device` for the duration of this call.
+ PMConfig::AutoSuspend(v) => unsafe {
+ bindings::__pm_runtime_use_autosuspend(dev.as_raw(), *v);
+ },
+ // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
+ // yields a valid pointer to `struct device` for the duration of this call.
+ PMConfig::AutoSuspendDelay(v) => unsafe {
+ bindings::pm_runtime_set_autosuspend_delay(dev.as_raw(), *v);
+ bindings::__pm_runtime_use_autosuspend(dev.as_raw(), true);
+ },
+ }
+ }
+ }
+
+ fn reset_config(dev: &Device<Bound>, opts: &[PMConfig]) {
+ if opts.iter().any(|opt| {
+ matches!(opt, PMConfig::AutoSuspend(_) | PMConfig::AutoSuspendDelay(_))
+ }) {
+ // SAFETY: `dev` remains bound and valid for this call
+ unsafe { bindings::__pm_runtime_use_autosuspend(dev.as_raw(), false) };
+ }
+
+ if opts.iter().any(|opt| {
+ matches!(opt, PMConfig::IgnoreChildren(_))
+ }) {
+ // SAFETY: `dev` remains bound and valid for this call
+ unsafe { bindings::pm_suspend_ignore_children(dev.as_raw(), false) };
+ }
+ }
+
+ /// Get a borrowed reference to PM profiles associated with the PM context
+ pub fn profiles(&self) -> &[PMProfile] {
+ &self.inner.profiles
+ }
+
+ /// Get a borrowed reference to PM configs associated with the PM context
+ pub fn configs(&self) -> &[PMConfig] {
+ &self.inner.configs
+ }
+}
+
+/// Runtime PM request profile.
+#[derive(Copy, Clone)]
+pub struct PMProfile(Mode);
+
+impl PMProfile {
+ /// Creates a PMProfile with default SYNC mode set.
+ pub const fn new() -> Self {
+ Self(Mode::empty())
+ }
+ /// Enables async PM operations for this PMProfile.
+ pub const fn r#async(self) -> Self {
+ Self(Mode(self.0 .0 | ModeFlag::Async as u32))
+ }
+ /// Use autosuspend
+ pub const fn auto(self) -> Self {
+ Self(Mode(self.0 .0 | ModeFlag::Auto as u32))
+ }
+ /// Requests idle handling for this PMProfile.
+ pub const fn idle(self) -> Self {
+ Self(Mode(self.0 .0 | ModeFlag::Idle as u32))
+ }
+ /// Do not wait for concurrent requests to finish.
+ pub const fn nowait(self) -> Self {
+ Self(Mode(self.0 .0 | ModeFlag::Nowait as u32))
+ }
+}
+
+impl Default for PMProfile {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Configuration knobs for runtime PM.
+pub enum PMConfig {
+ /// Ignore child devices when suspending.
+ IgnoreChildren(bool),
+ /// Disable runtime PM callbacks.
+ NoCallbacks,
+ /// Mark device as IRQ-safe for runtime PM.
+ /// Runtime PM callbacks run with local interrupts
+ /// disabled and must not sleep
+ IrqSafe,
+ /// Enable or disable autosuspend.
+ AutoSuspend(bool),
+ /// Set autosuspend delay (milliseconds).
+ AutoSuspendDelay(i32),
+}
+
+/// Runtime PM data stored within the `struct device_private` during
+/// runtime PM registration.
+///
+#[repr(C)]
+#[pin_data]
+struct RegistrationData<'a, T: PMOps> {
+ payload: Payload<'a, T>,
+ #[cfg_attr(not(CONFIG_PM), allow(dead_code))]
+ #[pin]
+ data: T::RegistrationData<'a>,
+ _marker: PhantomData<&'a mut T>,
+}
+
+/// Runtime PM registration for a device.
+///
+/// A `Registration` installs the `RegistrationData` alonw with the runtime
+/// payload, used by the generated [`PMOps`] callbacks and owns
+/// the corresponding teardown.
+///
+/// Dropping the registration disables runtime PM, waits for in-flight runtime PM
+/// callbacks to complete, and then removes the stored registration data.
+#[pin_data(PinnedDrop)]
+pub struct Registration<'a, T>
+where
+ T:PMOps,
+{
+ ctx: PMContext<'inner, 'a, T>,
+ #[pin]
+ inner: PMContextInner<'a, T>,
+ #[pin]
+ data: RegistrationData<'a, T>,
+}
+
+impl<'a, T: PMOps> Registration<'a, T> {
+ /// Creates a runtime PM registration for `dev`.
+ ///
+ /// The provided profiles and configuration are stored in the associated
+ /// [`PMContext`]. The `initial_payload` is expected to reflect current
+ /// power state of the device.
+ ///
+ /// The device must use the callback represented by `ops`, generated
+ /// for the same bus adapter and driver pair `(D, T)`.
+ ///
+ /// # Safety
+ ///
+ /// The returned [`Registration`] object cannot be mem::forgotten,
+ /// or it's [`Drop`] implementation cannot be skipped in any way.
+ ///
+ pub unsafe fn new<E>(
+ dev: &'a Device<Core<'_>>,
+ ops: &'static Ops<T>,
+ profiles: Option<KVec<PMProfile>>,
+ configs: Option<KVec<PMConfig>>,
+ data: impl PinInit<<T as PMOps>::RegistrationData<'a>, E> + 'a,
+ initial_payload: RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>,
+ ) -> impl PinInit<Self, Error> + 'a
+ where
+ Error: From<E>,
+ {
+ let dev: &'a Device<Bound> = dev;
+
+ try_pin_init!(Self {
+ _: {
+ // SAFETY: For the duration of this call, `dev` is a valid `Device<Core>`,
+ // and so is its raw `struct device` pointer.
+ let pm = unsafe { (*(*dev.as_raw()).driver).pm };
+ if pm != ops.as_raw() && (cfg!(CONFIG_PM) || !pm.is_null()) {
+ return Err(EINVAL);
+ }
+ // SAFETY: Construction has exclusive access to this slot.
+ if !unsafe {
+ (*(*dev.as_raw()).p).rust.pm_registration_data
+ }.is_null() {
+ return Err(EBUSY);
+ }
+ },
+ inner <- try_pin_init!(PMContextInner {
+ dev,
+ state: Atomic::new(PMContextState::Disabled),
+ guard <- new_srcu!("rpm"),
+ profiles: profiles.unwrap_or_default(),
+ configs: configs.unwrap_or_default(),
+ _marker: PhantomData,
+ }),
+ ctx : PMContext { inner: inner.get_ref(), },
+ data <- try_pin_init!(RegistrationData {
+ data <- data,
+ payload: Payload {in_flight: AtomicFlag::new(false), inner: UnsafeCell::new(ManuallyDrop::new(initial_payload))},
+ _marker: PhantomData
+ }? E),
+ _: {
+ let ptr: NonNull<RegistrationData<'a, T>> =
+ NonNull::from(data.as_ref().get_ref());
+ // SAFETY: The device is not yet registered, and neither is
+ // the runtime pm beingenabled - as such, there is no
+ // cuncurency here
+ unsafe {
+ (*(*dev.as_raw()).p).rust.pm_registration_data =
+ ptr.cast::<core::ffi::c_void>().as_ptr();
+ };
+
+ }
+ })
+
+ }
+ /// Returns the runtime PM context associated with this registration.
+ pub fn get_ctx(&self) -> PMContext<'_, 'a, T> {
+ PMContext{ inner: &self.inner }
+ }
+}
+
+#[pinned_drop]
+impl<'a, T: PMOps> PinnedDrop for Registration<'a, T> {
+ fn drop(self: Pin<&mut Self>) {
+ // `self.inner.dev` is the device this registration was
+ // created for. Runtime PM is disabled first, and `pm_runtime_barrier`
+ // waits for pending runtime PM work/callbacks before the callback data
+ // is removed below.
+ // Furthermore, prevent any stale `PMContext`s from re-enabling runtime
+ // PM after teardown starts.
+ let prev = self.inner.state.xchg(PMContextState::Closing, ordering::Full);
+
+ self.inner.guard.synchronize();
+
+ if prev == PMContextState::Enabled {
+ Request::runtime_disable(self.inner.dev);
+ PMContext::<T>::reset_config(self.inner.dev, &self.inner.configs);
+ }
+
+ Request::barrier(self.inner.dev);
+
+ // SAFETY: The pointer was stored by `Registration::new`.
+ // Runtime PM has been disabled and drained above, so generated
+ // callbacks can no longer borrow this data.
+ unsafe {
+ (*(*self.inner.dev.as_raw()).p).rust.pm_registration_data = core::ptr::null_mut();
+ }
+ }
+}
--
2.43.0
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH v6 2/3] rust: platform: wire runtime PM callbacks
2026-11-24 11:34 [PATCH v6 0/3] Rust: add runtime PM support Beata Michalska
2026-11-24 11:34 ` [PATCH v6 1/3] rust: " Beata Michalska
@ 2026-11-24 11:34 ` Beata Michalska
2026-11-24 11:34 ` [PATCH v6 3/3 DO NOT MERGE] drm/tyr: enable runtime PM Beata Michalska
2 siblings, 0 replies; 6+ messages in thread
From: Beata Michalska @ 2026-11-24 11:34 UTC (permalink / raw)
To: ojeda, dakr, gregkh, rafael, aliceryhl
Cc: boqun, gary, bjorn3_gh, lossin, a.hindborg, tmgross,
daniel.almeida, boris.brezillon, work, samitolvanen, acourbot,
rust-for-linux, driver-core, linux-kernel, linux-pm
Allow 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.
Signed-off-by: Beata Michalska <beata.michalska@arm.com>
---
rust/kernel/platform.rs | 35 +++++++++++++++++++++++++++++++++--
1 file changed, 33 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index ac0a012ae1bb..c9f2bd3d9aad 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -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) }
+ }
+}
--
2.43.0
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH v6 3/3 DO NOT MERGE] drm/tyr: enable runtime PM
2026-11-24 11:34 [PATCH v6 0/3] Rust: add runtime PM support Beata Michalska
2026-11-24 11:34 ` [PATCH v6 1/3] rust: " Beata Michalska
2026-11-24 11:34 ` [PATCH v6 2/3] rust: platform: wire runtime PM callbacks Beata Michalska
@ 2026-11-24 11:34 ` Beata Michalska
2 siblings, 0 replies; 6+ messages in thread
From: Beata Michalska @ 2026-11-24 11:34 UTC (permalink / raw)
To: ojeda, dakr, gregkh, rafael, aliceryhl
Cc: boqun, gary, bjorn3_gh, lossin, a.hindborg, tmgross,
daniel.almeida, boris.brezillon, work, samitolvanen, acourbot,
rust-for-linux, driver-core, linux-kernel, linux-pm
Add 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.
Signed-off-by: Beata Michalska <beata.michalska@arm.com>
---
drivers/gpu/drm/tyr/driver.rs | 220 +++++++++++++++++++++++++---------
drivers/gpu/drm/tyr/file.rs | 7 +-
2 files changed, 169 insertions(+), 58 deletions(-)
diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs
index c2b99d67369f..c82f31e2d2b4 100644
--- a/drivers/gpu/drm/tyr/driver.rs
+++ b/drivers/gpu/drm/tyr/driver.rs
@@ -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: &'pm TyrHW<'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: &'drm TyrHW<'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: &'a Self::DeviceType,
+ _reg_data: &'a Self::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: &'a Self::DeviceType,
+ _reg_data: &'a Self::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)
+ }
+}
diff --git a/drivers/gpu/drm/tyr/file.rs b/drivers/gpu/drm/tyr/file.rs
index 9f60a90d4948..28a78ed17e5a 100644
--- a/drivers/gpu/drm/tyr/file.rs
+++ b/drivers/gpu/drm/tyr/file.rs
@@ -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)
}
--
2.43.0
^ permalink raw reply [flat|nested] 6+ messages in thread
* Re: [PATCH v6 1/3] rust: add runtime PM support
2026-11-24 11:34 ` [PATCH v6 1/3] rust: " Beata Michalska
@ 2026-11-27 20:08 ` Rafael J. Wysocki (Intel)
2026-11-28 0:37 ` Danilo Krummrich
0 siblings, 1 reply; 6+ messages in thread
From: Rafael J. Wysocki (Intel) @ 2026-11-27 20:08 UTC (permalink / raw)
To: Beata Michalska
Cc: ojeda, dakr, gregkh, rafael, aliceryhl, boqun, gary, bjorn3_gh,
lossin, a.hindborg, tmgross, daniel.almeida, boris.brezillon,
work, samitolvanen, acourbot, rust-for-linux, driver-core,
linux-kernel, linux-pm
On Tue, Nov 24, 2026 at 12:36 PM Beata Michalska
<beata.michalska@arm.com> wrote:
>
> 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.
I need to understand what happens here, but unfortunately my general
experience with Rust is quite limited (let alone Rust in the kernel).
> Runtime PM is managed through a registration object tied to the device
> lifetime. The registration stores the callback payload and 'ensures'
What is the callback payload?
> 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.
So the "do not outlive the device" part is not super-precise I think.
They actually cannot outlive driver unbinding, can they?
> 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.
So `AwakeScope` and `RetainScope` are kind of similar to the
pm_runtime_active and pm_runtime_noresume guards in C, if I understand
this correctly.
I'm not sure why `ResumeScope` is needed though, especially for
autosuspending devices.
> 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.
So it would be good to say something about how the above are supposed
to be used.
> Signed-off-by: Beata Michalska <beata.michalska@arm.com>
> ---
> 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
>
> diff --git a/drivers/base/base.h b/drivers/base/base.h
> index 866b2beb6baa..bc91d873318f 100644
> --- a/drivers/base/base.h
> +++ b/drivers/base/base.h
> @@ -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;
This doesn't match the "rust_private" documented above (and a space
seems to be missing).
> +#endif
> u8 dead:1;
> };
> #define to_device_private_parent(obj) \
> diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
> index 3791af0aadc7..a630213039d9 100644
> --- a/rust/bindings/bindings_helper.h
> +++ b/rust/bindings/bindings_helper.h
> @@ -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>
> diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
> index d62c7be1ca7b..2cfd0ee83ac1 100644
> --- a/rust/helpers/helpers.c
> +++ b/rust/helpers/helpers.c
> @@ -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"
> diff --git a/rust/helpers/pm_runtime.c b/rust/helpers/pm_runtime.c
> new file mode 100644
> index 000000000000..890cdc8d5c90
> --- /dev/null
> +++ b/rust/helpers/pm_runtime.c
> @@ -0,0 +1,101 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +#include <linux/pm_runtime.h>
> +
> +__rust_helper
> +void rust_helper_pm_runtime_get_noresume(struct device *dev)
> +{
> + pm_runtime_get_noresume(dev);
> +}
> +
> +__rust_helper
> +void rust_helper_pm_runtime_put_noidle(struct device *dev)
> +{
> + pm_runtime_put_noidle(dev);
> +}
> +
> +__rust_helper
> +void rust_helper_pm_runtime_mark_last_busy(struct device *dev)
> +{
> + pm_runtime_mark_last_busy(dev);
> +}
> +
> +__rust_helper
> +bool rust_helper_pm_runtime_active(struct device *dev)
> +{
> + return pm_runtime_active(dev);
> +}
> +
> +__rust_helper
> +bool rust_helper_pm_runtime_suspended(struct device *dev)
> +{
> + return pm_runtime_suspended(dev);
> +}
> +
> +__rust_helper
> +void rust_helper_pm_suspend_ignore_children(struct device *dev, bool enable)
> +{
> + pm_suspend_ignore_children(dev, enable);
> +}
> +
> +__rust_helper
> +int rust_helper_pm_runtime_set_active(struct device *dev)
> +{
> + return pm_runtime_set_active(dev);
> +}
> +
> +__rust_helper
> +int rust_helper_pm_runtime_set_suspended(struct device *dev)
> +{
> + return pm_runtime_set_suspended(dev);
> +}
> +
> +__rust_helper
> +bool rust_helper_pm_runtime_enabled(struct device *dev)
> +{
> + return pm_runtime_enabled(dev);
> +}
> +
> +__rust_helper
> +bool rust_helper_pm_runtime_is_irq_safe(struct device *dev)
> +{
> + return pm_runtime_is_irq_safe(dev);
> +}
> +
> +#ifndef CONFIG_PM
> +__rust_helper
> +int rust_helper___pm_runtime_resume(struct device *dev, int rpmflags)
> +{
> + return __pm_runtime_resume(dev, rpmflags);
> +}
> +
> +__rust_helper
> +int rust_helper___pm_runtime_idle(struct device *dev, int rpmflags)
> +{
> + return __pm_runtime_idle(dev, rpmflags);
> +}
> +
> +__rust_helper
> +int rust_helper___pm_runtime_suspend(struct device *dev, int rpmflags)
> +{
> + return __pm_runtime_suspend(dev, rpmflags);
> +}
> +
> +__rust_helper
> +int rust_helper_pm_runtime_get_if_active(struct device *dev)
> +{
> + return pm_runtime_get_if_active(dev);
> +}
> +
> +__rust_helper void rust_helper_pm_runtime_enable(struct device *dev) {}
> +__rust_helper void rust_helper___pm_runtime_disable(struct device *dev, bool c) {}
> +__rust_helper void rust_helper_pm_runtime_barrier(struct device *dev) {}
> +__rust_helper void rust_helper_pm_runtime_no_callbacks(struct device *dev) {}
> +__rust_helper void rust_helper_pm_runtime_irq_safe(struct device *dev) {}
> +__rust_helper
> +void rust_helper___pm_runtime_use_autosuspend(struct device *dev, bool use)
> +{}
> +__rust_helper
> +void rust_helper_pm_runtime_set_autosuspend_delay(struct device *dev, int delay)
> +{}
How do these empty __rust_helper functions work? Or what are they for
(if that is a better question)?
> +#endif /* CONFIG_PM */
> diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
> index 2291d85b6849..7edcc6941deb 100644
> --- a/rust/kernel/device.rs
> +++ b/rust/kernel/device.rs
> @@ -19,6 +19,7 @@
> ptr, //
> };
>
> +pub mod pm;
> pub mod property;
>
> /// The core representation of a device in the kernel's driver model.
> diff --git a/rust/kernel/device/pm.rs b/rust/kernel/device/pm.rs
> new file mode 100644
> index 000000000000..9abf5efe48fe
> --- /dev/null
> +++ b/rust/kernel/device/pm.rs
> @@ -0,0 +1,1187 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! Rust Runtime Power Management abstraction.
> +//!
> +//! C header: [`include/linux/pm_runtime.h`](srctree/include/linux/pm_runtime.h)
> +
> +use crate::{
> + bindings,
> + bits::bit_u32,
> + device::{
> + Device,
> + Bound,
> + Core,
> + AsBusDevice, //
> + },
> + driver,
> + error::{
> + to_result,
> + VTABLE_DEFAULT_ERROR, //
> + },
> + prelude::*,
> + sync::atomic::{
> + ordering,
> + Atomic,
> + AtomicFlag,
> + AtomicType, //
> + },
> + sync::Srcu,
> + sync::srcu::new_srcu, //
> +};
> +
> +use core::{
> + cell::UnsafeCell,
> + marker::PhantomData,
> + mem::ManuallyDrop,
> + ptr::NonNull, //
> +};
> +
> +kernel::impl_flags! {
> + /// Runtime Power Management modes that determine how a particular PM
> + /// transition is to be carried out.
> + /// Corresponds to C Runtime PM flag argument bits:
> + /// - `RPM_ASYNC`
> + /// - `RPM_NOWAIT`
> + /// - `RPM_GET_PUT`
> + /// - `RPM_AUTO`
Why do you need these flags at the Rust level? The API users are not
supposed to pass them directly.
> + /// Synchronous mode is represented as `Mode::empty()`,
> + /// which is the default mode.
> + #[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
> + pub struct Mode(u32);
> +
> + /// Single RPM mode
> + #[derive(Clone, Copy, PartialEq, Eq, Debug)]
> + pub enum ModeFlag {
> + /// Allow asynchronous PM operations.
> + Async = bindings::RPM_ASYNC,
> + /// Do not wait for any pending requests to finish.
> + Nowait = bindings::RPM_NOWAIT,
> + /// Acquire a runtime-PM usage reference.
> + Acquire = bindings::RPM_GET_PUT,
> + /// Use autosuspend.
> + Auto = bindings::RPM_AUTO,
> + /// Additional mode for devices supporting idle states.
What do you mean by "supporting idle states"?
> + /// No counterpart.
> + Idle = bit_u32(16),
> + }
> +}
> +
> +impl From<Mode> for c_int {
> + #[inline]
> + fn from(mode: Mode) -> c_int {
> + mode.0 as c_int
> + }
> +}
Well, you need to tell me what the above means and does.
> +
> +/// Device's runtime power management status
> +#[derive(Copy,Clone)]
> +#[repr(i32)]
> +pub enum RuntimePMState {
> + /// The device is expected to be runtime active and in its normal operating state
> + Active = bindings::rpm_status_RPM_ACTIVE,
> + /// The device is expected to be suspended, unavailable for normal operations
> + Suspended = bindings::rpm_status_RPM_SUSPENDED,
> +}
> +
> +/// Device's scoped runtime-resumed state
> +pub struct Scope<'a, Tag> {
> + dev: &'a Device<Bound>,
> + mode: Mode,
> + _tag: PhantomData<Tag>,
> +}
And same here.
> +
> +/// Device resumed without incrementing the device's usage count
> +struct Resume;
> +/// Device resumed with the device's usage count being incremented
> +struct Awake;
> +/// Device with increased usage reference count
> +struct Retain;
> +
> +/// Resumes the device without acquiring the usage reference.
> +/// Note: This does not guarantee the device will be kept active
> +/// for the lifetime of the scope due to potential pending/incoming
> +/// suspend requests.
> +/// Successfully obtaining the scope guard does not guarantee the device
> +/// has been resumed: subject to the requested mode:
> +/// `ModeFlag::Async` and `ModeFlag::Nowait`
RPM_NOWAIT is strictly internal, it should not be used outside
drivers/base/power/runtime.c.
> +///
> +/// On drop:
> +/// - If `ModeFlag::Idle`, calls `__pm_runtime_idle()`:
> +/// triggers idle notification before attempting to suspend
> +/// - If `ModeFlag::Auto`, marks last busy then calls `__pm_runtime_suspend()`.
> +/// - Otherwise calls `__pm_runtime_suspend()`.
First, why do you need to refer to the __pm_runtime_*() functions at
all? There are wrappers around them defined already, what would be
wrong with using them?
Second, I'd recommend using pm_runtime_put() always unless you want to
bypass the autosuspend delay, in which case you can use
pm_runtime_put_sync_suspend() (with no async variant), especially
after very recent runtime PM core changes:
https://web.git.kernel.org/pub/scm/linux/kernel/git/rafael/linux-pm.git/commit/?h=linux-next&id=26236a3e8803f7e1ace104020d7f006edb220116
https://lore.kernel.org/linux-pm/4779892.LvFx2qVVIh@rafael.j.wysocki/
With the `ResumeScope` thing you can use pm_request_idle() most of the
time and pm_runtime_suspend() if you want to bypass the autosuspend
delay (but I'm still kind of unsure why you need that).
> +///
> +/// The guard must be dropped from a context matching the requested transition
> +/// mode: sync vs async.
> +#[must_use = "dropping this guard issues the matching runtime PM release request"]
> +pub struct ResumeScope<'a>(Scope<'a, Resume>);
Do I remember correctly that this defines a struct type based on Scope
and with the lifetime of 'a?
> +
> +/// Acquires a runtime-PM usage reference and keeps the device powered.
> +/// Successfully obtaining the scope guard does not guarantee the device
> +/// has been resumed: subject to the requested mode:
> +/// `ModeFlag::Async` and `ModeFlag::Nowait`.
> +///
> +/// Requires `ModeFlag::Acquire`.
> +/// Drop behavior matches `ResumeScope`.
> +///
> +/// The guard must be dropped from a context matching the requested transition
> +/// mode: sync vs async.
> +#[must_use = "dropping this guard releases its runtime PM hold"]
> +pub struct AwakeScope<'a>(Scope<'a, Awake>);
> +
> +/// Prevents the device from getting suspended by holding the usage reference
> +/// count.
> +///
> +/// On drop, calls `pm_runtime_put_noidle()`.
> +#[must_use = "dropping this guard releases its runtime PM hold"]
> +pub struct RetainScope<'a>(Scope<'a, Retain>);
> +
> +impl<'a> ResumeScope<'a> {
> + fn new(dev: &'a 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 off before passing further
> + match Request::resume(dev, mode & !ModeFlag::Idle) {
> + Ok(()) => {}
> + // if ModeFlag::Async is set, -EINPROGRESS signals ongoing resume,
> + // with ModeFlag::Nowait -> ongoing suspend with delayed resume
> + // being queued
> + Err(e) if e == EINPROGRESS && mode.contains_any(ModeFlag::Async| ModeFlag::Nowait) => {}
> + Err(e) => return Err(e),
> + }
> +
> + Ok(Self(Scope::<Resume> {
> + dev,
> + mode,
> + _tag: PhantomData,
> + }))
> + }
> +
> + fn release_inner(&self) -> Result {
> + if !cfg!(CONFIG_PM) {
> + return Ok(())
> + }
> +
> + let mode = self.0.mode;
> + let scope_mode = mode & !ModeFlag::Idle;
> +
> + if mode.contains(ModeFlag::Auto) {
> + Request::mark_last_busy(self.0.dev);
This may not be necessary after the core changes mentioned above.
> + }
> +
> + match self.0.mode {
> + mode if mode.contains(ModeFlag::Idle) => Request::idle(self.0.dev, scope_mode),
> + _ => Request::suspend(self.0.dev, scope_mode),
> + }
> + }
> +
> + /// Explicitly release the scope
> + ///
> + /// This should be used in favor of regular drop when error handling is
> + /// required.
> + pub fn release(self) -> Result {
> + let result = self.release_inner();
> + core::mem::forget(self);
> + result
> + }
> +}
> +
> +impl<'a> Drop for ResumeScope<'a> {
> + fn drop(&mut self) {
> + let _ = self.release_inner();
> + }
> +}
> +
> +impl<'a> AwakeScope<'a> {
> + fn new(dev: &'a Device<Bound>, mode: Mode) -> Result<Self> {
> + if !mode.contains(ModeFlag::Acquire) {
> + return Err(EINVAL);
> + }
> + // ModeFlag::Idle is internal so strip it off before passing further
> + match Request::resume(dev, mode & !ModeFlag::Idle) {
> + Ok(()) => {}
> + // For async/nowait requests, `EINPROGRESS` means the resume is
> + // either in flight or pending.
> + 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 {
> + if !cfg!(CONFIG_PM) {
> + return Ok(())
> + }
> +
> + let mode = self.0.mode;
> + let scope_mode = mode & !ModeFlag::Idle;
> +
> + if mode.contains(ModeFlag::Auto) {
> + Request::mark_last_busy(self.0.dev);
> + }
> +
> + match self.0.mode {
> + mode if mode.contains(ModeFlag::Idle) => Request::idle(self.0.dev, scope_mode),
> + _ => Request::suspend(self.0.dev, scope_mode),
> + }
> + }
> +
> + /// Explicitly release the scope
> + ///
> + /// This should be used in favor of regular drop when error handling is
> + /// required.
> + pub fn release(self) -> Result {
> + let result = self.release_inner();
> + core::mem::forget(self);
> + result
> + }
> +}
> +
> +impl<'a> Drop for AwakeScope<'a> {
> + fn drop(&mut self) {
> + let _ = self.release_inner();
> + }
> +}
> +
> +impl<'a> RetainScope<'a> {
> + fn new(dev: &'a Device<Bound>) -> Result<Self> {
> + Request::get_noresume(dev);
> + Ok(Self(Scope::<Retain> {
> + dev,
> + mode: Mode::empty(),
> + _tag: PhantomData,
> + }))
> + }
> +
> + fn try_new(dev: &'a Device<Bound>) -> Result<Self> {
> + Request::get_if_active(dev)?;
> + Ok(Self(Scope::<Retain> {
> + dev,
> + mode: Mode(u32::from(Mode::empty())),
> + _tag: PhantomData,
> + }))
> + }
> +
> + fn release_inner(&self) {
> + Request::put_noidle(self.0.dev);
> + }
> +
> + /// Explicitly release the scope
> + ///
> + /// This should be used in favor of regular drop when error handling is
> + /// required.
> + pub fn release(self) -> Result {
> + self.release_inner();
> + core::mem::forget(self);
> + Ok(())
> + }
> +}
> +
> +impl<'a> Drop for RetainScope<'a> {
> + fn drop(&mut self) {
> + self.release_inner();
> + }
> +}
> +
> +/// Private entry points to the C runtime PM API.
> +///
> +/// Provides a centralized location for both, the C calls themsleves,
> +/// as well as for their safety requirements.
> +///
> +/// # Safety
> +///
> +/// Each method takes `&Device<Bound>`. `Device` guarantees that `as_raw()`
> +/// points to a valid `struct device` during the call. `Bound` guarantees that
> +/// the driver remains attached while the PM core may invoke callbacks using
> +/// driver-owned data. For requests completed later, [`Registration`] keeps
> +/// callback data alive and drains pending callbacks before dropping it.
> +struct Request;
> +
> +impl Request {
> + #[inline]
> + fn active(dev: &Device<Bound>) -> bool {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_active(dev.as_raw()) }
> + }
> +
> + #[inline]
> + fn suspended(dev: &Device<Bound>) -> bool {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_suspended(dev.as_raw()) }
> + }
> +
> + #[inline]
> + fn resume(dev: &Device<Bound>, mode: Mode) -> Result {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + to_result(unsafe { bindings::__pm_runtime_resume(dev.as_raw(), mode.into()) })
> + }
> +
> + #[inline]
> + fn suspend(dev: &Device<Bound>, mode: Mode) -> Result {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + to_result(unsafe { bindings::__pm_runtime_suspend(dev.as_raw(), mode.into()) })
> + }
> +
> + #[inline]
> + fn get_noresume(dev: &Device<Bound>) {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_get_noresume(dev.as_raw()) };
> + }
> +
> + #[inline]
> + fn get_if_active(dev: &Device<Bound>) -> Result {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + match unsafe { bindings::pm_runtime_get_if_active(dev.as_raw()) } {
> + ret if ret < 0 => Err(Error::from_errno(ret)),
> + 0 => Err(EAGAIN),
> + _ => Ok(()),
> + }
> + }
> +
> + #[inline]
> + fn idle(dev: &Device<Bound>, mode: Mode) -> Result {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + to_result(unsafe { bindings::__pm_runtime_idle(dev.as_raw(), mode.into()) })
> + }
> +
> + #[inline]
> + fn put_noidle(dev: &Device<Bound>) {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_put_noidle(dev.as_raw()) };
> + }
> +
> + #[inline]
> + fn mark_active(dev: &Device<Bound>) -> Result {
> + to_result(
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_set_active(dev.as_raw()) },
> + )
> + }
> +
> + #[inline]
> + fn mark_suspended(dev: &Device<Bound>) -> Result {
> + to_result(
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_set_suspended(dev.as_raw()) },
> + )
> + }
> +
> + #[inline]
> + fn mark_last_busy(dev: &Device<Bound>) {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe {
> + bindings::pm_runtime_mark_last_busy(dev.as_raw());
> + }
> + }
> +
> + #[inline]
> + fn runtime_enable(dev: &Device<Bound>) {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::pm_runtime_enable(dev.as_raw()) }
> + }
> +
> + #[inline]
> + fn runtime_disable(dev: &Device<Bound>) {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe { bindings::__pm_runtime_disable(dev.as_raw(), true) };
> + }
> +
> + #[inline]
> + fn barrier(dev: &Device<Bound>) {
> + // SAFETY: `dev` satisfies safety requirements documented on `Request`.
> + unsafe {
> + bindings::pm_runtime_barrier(dev.as_raw());
> + }
> + }
> +}
> +
I think I know what's going on above this point (except for the places
where I said I needed help), but the part below escapes me, more or
less.
Which is unfortunate because I need to understand it so I can tell you
whether or not it all makes sense IMV.
So how can we get there? I'm not sure.
> +/// Common runtime PM callback entry point.
> +///
> +/// Invokes a runtime PM callback with its registration data and current payload.
> +///
> +/// # Safety
> +///
> +/// The generated extern "C" callbacks call into this helper with the raw
> +/// `struct device *` provided by the PM core. As such, it is guaranteed that
> +/// the `struct device` remains valid throughout the calls.
> +#[cfg(CONFIG_PM)]
> +unsafe fn with_registration_data<T, F>(dev: *mut bindings::device, cb: F) -> Result
> +where
> + T: PMOps,
> + F: for <'a>FnOnce(
> + &'a <T as PMOps>::DeviceType,
> + &'a <T as PMOps>::RegistrationData<'a>,
> + RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>
> + ) -> PMCallbackResult<RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>,
> + RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>>,
> +{
> + // SAFETY: `dev` is provided by the PM core and remains valid
> + // for the duration of the callback.
> + let dev: &Device = unsafe { Device::from_raw(dev) };
> + // SAFETY: The runtime PM callback can only be triggered for a bound device.
> + let dev: &Device<Bound> = unsafe { dev.as_bound() };
> + let pm_dev: &T::DeviceType =
> + // SAFETY: The generated `dev_pm_ops` for `T` is installed on devices whose
> + // bus-specific type is `T::DeviceType`. Therefore the base `Device<Bound>`
> + // passed by the PM core is embedded in a valid `T::DeviceType`; the
> + // `AsBusDevice` implementation supplies the correct offset for this cast.
> + unsafe { T::DeviceType::from_device(dev) };
> + // SAFETY: The `RegistrationData` must have been successfully installed
> + // for a device and it is guaranteed that it reamins valid at least until
> + // the last PM callback finishes.
> + let ptr = unsafe { (*(*dev.as_raw()).p).rust.pm_registration_data };
> + // SAFETY: `Registration::new` stores a pointer to its initialized, pinned
> + // `RegistrationData<T>` before enabling runtime PM. These callbacks
> + // belong to the same `T`. Registration teardown disables runtime PM and
> + // drains callbacks before clearing the pointer and dropping the data, so
> + // it remains valid for this callback
> + let reg_data = unsafe { &*ptr.cast::<RegistrationData<'_, T>>() };
> +
> + let _guard = reg_data.payload.acquire()?;
> + // SAFETY: This callback alone acquired `in_flight`; it has exclusive
> + // access to the payload slot until `_guard` is dropped.
> + let slot = unsafe { &mut *reg_data.payload.inner.get() };
> + // SAFETY: `_guard` gives this callback exclusive access to `slot`, which
> + // contains an initialized payload. Both callback outcomes provide a payload
> + // that is written back into `slot` before `_guard` is released.
> + let payload = unsafe { ManuallyDrop::take(slot) };
> +
> + let (next, result) = match cb(pm_dev, ®_data.data, payload) {
> + Ok(next) => (next, Ok(())),
> + Err((current, err)) => (current, Err(err)),
> + };
> +
> + *slot = ManuallyDrop::new(next);
> + result
> +}
> +
> +/// Runtime resume PM callback.
> +///
> +/// # Safety
> +///
> +/// `dev` is a valid `struct device *` supplied by the PM core for a device
> +/// whose runtime PM callbacks and PM registration data were both created
> +/// for `T`.
> +#[cfg(CONFIG_PM)]
> +unsafe extern "C" fn runtime_resume_callback<T>(dev: *mut bindings::device) -> c_int
> +where
> + T: PMOps,
> +{
> + // SAFETY: The callback's safety contract guarantees that `dev` remains
> + // valid for this call and has PM registration data created for `T`.
> + // These are the preconditions of `with_registration_data`.
> + unsafe {
> + with_registration_data::<T, _>(dev,
> + |pm_dev, data, payload| {
> + match payload {
> + RuntimeStatePayload::Suspended(payload_data) => {
> + T::runtime_resume(pm_dev, data, payload_data)
> + .map(RuntimeStatePayload::Active)
> + .map_err(|(prev, err)| (RuntimeStatePayload::Suspended(prev), err))
> + },
> + other => Err((other, EINVAL)),
> + }
> + })
> + .map(|()| 0)
> + .unwrap_or_else(|e| e.to_errno())
> + }
> +}
> +/// Runtime suspend PM callback.
> +///
> +/// # Safety
> +///
> +/// `dev` is a valid `struct device *` supplied by the PM core for a device
> +/// whose runtime PM callbacks and PM registration data were both created
> +/// for `T`.
> +#[cfg(CONFIG_PM)]
> +unsafe extern "C" fn runtime_suspend_callback<T>(dev: *mut bindings::device) -> c_int
> +where
> + T: PMOps,
> +{
> + // SAFETY: The callback's safety contract guarantees that `dev` remains
> + // valid for this call and has PM registration data created for `T`.
> + // These are the preconditions of `with_registration_data`.
> + unsafe {
> + with_registration_data::<T, _>(dev,
> + |pm_dev, data, payload| {
> + match payload {
> + RuntimeStatePayload::Active(payload_data) => {
> + T::runtime_suspend(pm_dev, data, payload_data)
> + .map(RuntimeStatePayload::Suspended)
> + .map_err(|(prev, err)| (RuntimeStatePayload::Active(prev), err))
> + },
> + other => Err((other, EINVAL)),
> + }
> + })
> + .map(|()| 0)
> + .unwrap_or_else(|e| e.to_errno())
> + }
> +}
> +
> +/// Default empty Runtime PM ops
> +pub const PMOPS_NONE: bindings::dev_pm_ops =
> + // 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
> + //
> + unsafe { core::mem::MaybeUninit::<bindings::dev_pm_ops>::zeroed().assume_init() };
> +
> +/// Typed reference to a driver's runtime PM ops.
> +///
> +/// Instances of this type are generated from static [`Ops`]
> +/// and are used by bus registration code to install the matching
> +/// C `dev_pm_ops` pointer into the driver object.
> +/// The `A` parameter identifies the bus adapter that is allowed
> +/// to install the table.
> +pub struct AdapterOpsRef<'a, A> {
> + #[cfg_attr(not(CONFIG_PM), allow(unused))]
> + ops: &'a bindings::dev_pm_ops,
> + _p: PhantomData<fn() -> *const A>,
> +}
> +
> +/// Conveniance type alias
> +pub type OpsRef<T> = AdapterOpsRef<'static, <T as PMOps>::Adapter>;
> +
> +// SAFETY: `AdapterOpsRef` only contains a shared reference to an immutable
> +// `dev_pm_ops` table and a type marker. Sharing it between threads cannot
> +// introduce mutation or aliasing of Rust-owned state.
> +unsafe impl<A> Sync for AdapterOpsRef<'_, A> {}
> +
> +impl<A> AdapterOpsRef<'_, A> {
> + #[cfg_attr(not(CONFIG_PM), allow(unused))]
> + #[inline]
> + pub(crate) const fn as_raw(&self) -> *const bindings::dev_pm_ops {
> + self.ops
> + }
> +}
> +
> +/// Runtime PM ops for a driver.
> +///
> +/// Intended to be constructed by bus-specific helpers, allowing
> +/// the bus to ensure that the callback device type matches the device
> +/// supplied by the C driver core.
> +pub struct Ops<T: PMOps> {
> + raw: bindings::dev_pm_ops,
> + _p: PhantomData<fn() -> T>,
> +}
> +
> +impl<T: PMOps> Ops<T> {
> + /// Creates a typed runtime PM ops.
> + ///
> + /// # Safety
> + ///
> + /// The caller must guarantee that `T::Adapter` is the bus adapter that
> + /// will install this ops into the C driver object for `T`, and
> + /// that `T::DeviceType` is the bus device type corresponding to
> + /// that adapter. Safe bus-specific constructors should wrap this
> + /// function with those bounds.
> + pub(crate) const unsafe fn new_unchecked(raw: bindings::dev_pm_ops) -> Self {
> + const_assert!(
> + T::HAS_RUNTIME_RESUME == T::HAS_RUNTIME_SUSPEND,
> + "runtime suspend and resume callbacks should be implemented together"
> + );
> + Self {
> + raw,
> + _p: PhantomData,
> + }
> + }
> +
> + /// Provides a typed reference to this runtime PM ops
> + ///
> + /// Bus registration code uses the returned value to install
> + /// the ops into the corresponding C driver object.
> + /// The returned reference is tied to `T::Adapter`.
> + pub const fn pm_ops(&'static self) -> OpsRef<T> {
> + AdapterOpsRef {
> + ops: &self.raw,
> + _p: PhantomData,
> + }
> + }
> +
> + /// Returns the raw C runtime PM operations table.
> + #[inline]
> + pub const fn as_raw(&'static self) -> *const bindings::dev_pm_ops {
> + &self.raw
> + }
> +}
> +
> +/// Result type returned by runtime PM callbacks.
> +pub type PMCallbackResult<New, Current> = Result<New, (Current, Error)>;
> +
> +/// Runtime PM callbacks implemented by a driver.
> +///
> +/// Defines the [`PMOps`] trait and its corresponding [`bindings::dev_pm_ops`].
> +///
> +/// The Adapter associated type identifies the bus adapter that installs
> +/// the generated PM ops.
> +/// Implementations should normally be enabled through a
> +/// bus-specific constructor for [`Ops`], which constrains
> +/// [`Self::DeviceType`] to the correct bound device type for that bus.
> +#[vtable]
> +pub trait PMOps: Sized {
> + /// The bus adapter that installs the generated PM ops.
> + type Adapter: driver::DriverLayout + 'static;
> +
> + /// Type of the bound bus device passed to runtime PM callbacks.
> + type DeviceType: AsBusDevice<Bound>;
> +
> + /// Data associated with the `Registration`, tied to its lifetime.
> + type RegistrationData<'a>: Send + Sync + 'a;
> +
> + /// Driver's specific data associated with suspended PM device state
> + type SuspendedPayload<'a>: Send + 'a;
> + /// Driver's specific data associated with active PM device states
> + type ActivePayload<'a>: Send + 'a;
> +
> + /// Runtime resume callback.
> + fn runtime_resume<'a>(
> + _dev: &'a Self::DeviceType,
> + _reg_data: &'a Self::RegistrationData<'a>,
> + _payload: Self::SuspendedPayload<'a>,
> + ) -> PMCallbackResult<Self::ActivePayload<'a>, Self::SuspendedPayload<'a>> {
> + build_error!(VTABLE_DEFAULT_ERROR)
> + }
> +
> + /// Runtime suspend callback.
> + fn runtime_suspend<'a>(
> + _dev: &'a Self::DeviceType,
> + _reg_data: &'a Self::RegistrationData<'a>,
> + _payload: Self::ActivePayload<'a>,
> + ) -> PMCallbackResult<Self::SuspendedPayload<'a>, Self::ActivePayload<'a>> {
> + build_error!(VTABLE_DEFAULT_ERROR)
> + }
> +}
> +
> +/// RAII guard for ongoing runtime PM payload transition.
> +///
> +/// For most of the callbacks this guard is not necessarily needed as
> +/// the callbacks themselves are being serialized by the runtime PM C code.
> +/// Still, some like runtime_idle are exempt from that.
> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
> +struct PayloadGuard<'a> {
> + busy: &'a AtomicFlag,
> +}
> +
> +impl Drop for PayloadGuard<'_> {
> + fn drop(&mut self) {
> + self.busy.store(false, ordering::Release);
> + }
> +}
> +
> +/// Payload associated with the given runtime power state of a device.
> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
> +pub enum RuntimeStatePayload<Active, Suspended> {
> + /// Payload associated with the runtime active PM state of a device
> + Active(Active),
> + /// Payload associated with the runtime suspended PM state of a device
> + Suspended(Suspended),
> +}
> +
> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
> +struct Payload<'a, T:PMOps> {
> + in_flight: AtomicFlag,
> + inner: UnsafeCell<ManuallyDrop<RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>>>,
> +}
> +
> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
> +impl<'a, T:PMOps> Payload<'a, T> {
> + /// Attempts to acquire exclusive access to the runtime PM payload.
> + ///
> + /// Returns `EBUSY` if another runtime PM callback is already transitioning the
> + /// payload.
> + fn acquire(&self) -> Result<PayloadGuard<'_>> {
> + self.in_flight
> + .cmpxchg(false, true, ordering::Acquire)
> + .map_err(|_| EBUSY)?;
> + Ok(PayloadGuard {
> + busy: &self.in_flight,
> + })
> + }
> +}
> +
> +impl<T:PMOps> Drop for Payload<'_, T> {
> + fn drop(&mut self) {
> + // SAFETY: teardown drained PM callbacks and the slot holds a `P`
> + unsafe {
> + ManuallyDrop::drop(self.inner.get_mut());
> + }
> + }
> +}
> +
> +// SAFETY: Although Payload's `inner` is an `UnsafeCell`, it is only accessed
> +// after `in_flight` has been acquired. The AtomicFlag flag serializes all mutable
> +// access to the payload, and `PayloadGuard` clears the flag when the access ends.
> +unsafe impl<T:PMOps> Sync for Payload<'_, T> {}
> +
> +#[derive(Clone, Copy, PartialEq, Eq)]
> +#[repr(i32)]
> +enum PMContextState {
> + /// The PM registration is alive, but runtime PM has not been enabled.
> + Disabled = 0,
> + /// Enabling runtime PM has been initiated but has not completed just yet
> + Enabling = 1,
> + /// The runtime PM has been enabled. Intended to be balanced by
> + /// `disable()` or `Registration::drop()`
> + Enabled = 2,
> + /// Disabling runtime PM has been initiated but has not completed just yet
> + Disabling = 3,
> + /// The owning `Registration` is being dropped or has been dropped.
> + /// Stale cloned `PMContext`s may still exist, but once this state is
> + /// visible, runtime PM cannot be re-enabled.
> + Closing = 4,
> +}
> +
> +// SAFETY: `PMContextState` has the same size and alignment as `i32`, and all
> +// values written through `Atomic<PMContextState>` are valid `PMContextState`
> +// discriminants.
> +unsafe impl AtomicType for PMContextState {
> + type Repr = i32;
> +}
> +
> +#[pin_data]
> +struct PMContextInner<'a, T: PMOps> {
> + dev: &'a Device<Bound>,
> + /// State owned by the runtime PM registration
> + state: Atomic<PMContextState>,
> + /// A synchronization point for all pending callbacks to finish.
> + #[pin]
> + guard: Srcu,
> + /// Optional driver-selected runtime PM request PMProfiles.
> + ///
> + /// Set of runtime PM predefined PMProfiles that can be used by the driver
> + /// when requesting a PM transition. This might be useful when a driver
> + /// has several different PM usage patterns.
> + /// See [PMProfile] for more details.
> + profiles: KVec<PMProfile>,
> + /// Set of PM config options applied for associated device.
> + configs: KVec<PMConfig>,
> + _marker: PhantomData<fn() -> T>,
> +}
> +
> +/// Runtime PM context tied to a device.
> +///
> +/// Needs to be dropped from sleepable context.
> +#[pin_data]
> +pub struct PMContext<'r, 'a, T: PMOps> {
> + inner: &'r PMContextInner<'a, T>,
> +}
> +
> +impl<'r, 'a, T: PMOps> PMContext<'r, 'a, 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, its registration data
> + /// 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.
> + #[cfg(CONFIG_PM)]
> + pub(crate) const PM_OPS: bindings::dev_pm_ops = bindings::dev_pm_ops {
> + runtime_resume: if T::HAS_RUNTIME_RESUME {
> + Some(runtime_resume_callback::<T>)
> + } else {
> + None
> + },
> + runtime_suspend: if T::HAS_RUNTIME_SUSPEND {
> + Some(runtime_suspend_callback::<T>)
> + } else {
> + None
> + },
> + ..PMOPS_NONE
> + };
> +
> + #[cfg(not(CONFIG_PM))]
> + pub(crate) const PM_OPS: bindings::dev_pm_ops = PMOPS_NONE;
> +
> + #[inline]
> + fn state_transition(&self, expected: PMContextState, new: PMContextState) -> Result
> + {
> + self.inner.state.cmpxchg(expected, new, ordering::Full)
> + .map(|_| ())
> + .map_err(|actual| match (expected, actual) {
> + (_, PMContextState::Closing) => ENODEV,
> + (PMContextState::Disabled, PMContextState::Disabling)
> + | (PMContextState::Enabled, PMContextState::Enabling) => EBUSY,
> + _ => EINVAL,
> + })
> + }
> +
> + /// Enable runtime PM
> + pub fn enable(&self, state: RuntimePMState) -> Result {
> + let _transition_guard = self.inner.guard.read_lock();
> + self.state_transition(PMContextState::Disabled, PMContextState::Enabling)?;
> + Self::apply_config(self.inner.dev, &self.inner.configs);
> +
> + match state {
> + RuntimePMState::Active => Request::mark_active(self.inner.dev),
> + RuntimePMState::Suspended => Request::mark_suspended(self.inner.dev),
> + }
> + .inspect_err(|_| {
> + Self::reset_config(self.inner.dev, &self.inner.configs);
> + let _ = self.state_transition(
> + PMContextState::Enabling,
> + PMContextState::Disabled,
> + );
> + })?;
> +
> + Request::runtime_enable(self.inner.dev);
> + self.state_transition(
> + PMContextState::Enabling,
> + PMContextState::Enabled,
> + ).inspect_err(|e| {
> + if *e == ENODEV {
> + Request::runtime_disable(self.inner.dev);
> + Self::reset_config(self.inner.dev, &self.inner.configs);
> + }
> + })?;
> + Ok(())
> + }
> +
> + /// Disable runtime PM
> + pub fn disable(&self) -> Result {
> + let _transition_guard = self.inner.guard.read_lock();
> + self.state_transition(
> + PMContextState::Enabled,
> + PMContextState::Disabling,
> + )?;
> +
> + Request::runtime_disable(self.inner.dev);
> + Self::reset_config(self.inner.dev, &self.inner.configs);
> +
> + let _ = self.state_transition(
> + PMContextState::Disabling,
> + PMContextState::Disabled
> + );
> + Ok(())
> + }
> +
> + /// Returns whether the runtime PM state is active.
> + #[inline]
> + pub fn active(&self) -> bool {
> + Request::active(self.inner.dev)
> + }
> +
> + /// Returns whether the runtime PM state is suspended.
> + #[inline]
> + pub fn suspended(&self) -> bool {
> + Request::suspended(self.inner.dev)
> + }
> +
> + /// Creates a `ResumeScope` for the given PMProfile.
> + /// Note that for ASYNC/NOWAIT request this does not guarantee
> + /// the device has been resumed at the time this function returns.
> + #[inline]
> + pub fn resume(&self, profile: PMProfile) -> Result<ResumeScope<'r>> {
> + ResumeScope::new(self.inner.dev, profile.0)
> + }
> +
> + /// Creates an `AwakeScope` for the given PMProfile.
> + /// Note that for ASYNC/NOWAIT request this does not guarantee
> + /// the device has been resumed at the time this function returns.
> + #[inline]
> + pub fn get(&self, profile: PMProfile) -> Result<AwakeScope<'r>> {
> + AwakeScope::new(self.inner.dev, profile.0 | ModeFlag::Acquire)
> + }
> +
> + /// Creates a `RetainScope` for this device.
> + pub fn hold(&self) -> Result<RetainScope<'r>> {
> + RetainScope::new(self.inner.dev)
> + }
> +
> + /// Creates a `RetainScope` for an active device.
> + pub fn try_hold_active(&self) -> Result<RetainScope<'r>> {
> + RetainScope::try_new(self.inner.dev)
> + }
> +
> + /// Runs a closure while holding a `ResumeScope`.
> + pub fn with_resume<R>(&self, profile: PMProfile, f: impl FnOnce() -> Result<R>) -> Result<R> {
> + if profile.0.contains_any(ModeFlag::Async| ModeFlag::Nowait) {
> + return Err(EINVAL);
> + }
> + let _scope = self.resume(profile)?;
> + f()
> + }
> + /// 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_any(ModeFlag::Async | ModeFlag::Nowait) {
> + return Err(EINVAL);
> + }
> + let _scope = self.get(profile)?;
> + f()
> + }
> +
> + /// Runs a closure while holding a `RetainScope`.
> + pub fn with_hold<R>(&self, f: impl FnOnce() -> Result<R>) -> Result<R> {
> + let _scope = self.hold()?;
> + f()
> + }
> +
> + /// Applies runtime PM configuration options.
> + ///
> + /// Options are applied in the order provided. The currently supported
> + /// options do not report per-option failures.
> + fn apply_config(dev: &Device<Bound>, opts: &[PMConfig]) {
> + for opt in opts {
> + match opt {
> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
> + // yields a valid pointer to `struct device` for the duration of this call.
> + PMConfig::IgnoreChildren(v) => unsafe {
> + bindings::pm_suspend_ignore_children(dev.as_raw(), *v)
> + },
> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
> + // yields a valid pointer to `struct device` for the duration of this call.
> + PMConfig::NoCallbacks => unsafe { bindings::pm_runtime_no_callbacks(dev.as_raw()) },
> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
> + // yields a valid pointer to `struct device` for the duration of this call.
> + PMConfig::IrqSafe => unsafe {
> + // Do not attempt to call that more than once
> + if !bindings::pm_runtime_is_irq_safe(dev.as_raw()) {
> + bindings::pm_runtime_irq_safe(dev.as_raw());
> + }
> + },
> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
> + // yields a valid pointer to `struct device` for the duration of this call.
> + PMConfig::AutoSuspend(v) => unsafe {
> + bindings::__pm_runtime_use_autosuspend(dev.as_raw(), *v);
> + },
> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
> + // yields a valid pointer to `struct device` for the duration of this call.
> + PMConfig::AutoSuspendDelay(v) => unsafe {
> + bindings::pm_runtime_set_autosuspend_delay(dev.as_raw(), *v);
> + bindings::__pm_runtime_use_autosuspend(dev.as_raw(), true);
> + },
> + }
> + }
> + }
> +
> + fn reset_config(dev: &Device<Bound>, opts: &[PMConfig]) {
> + if opts.iter().any(|opt| {
> + matches!(opt, PMConfig::AutoSuspend(_) | PMConfig::AutoSuspendDelay(_))
> + }) {
> + // SAFETY: `dev` remains bound and valid for this call
> + unsafe { bindings::__pm_runtime_use_autosuspend(dev.as_raw(), false) };
> + }
> +
> + if opts.iter().any(|opt| {
> + matches!(opt, PMConfig::IgnoreChildren(_))
> + }) {
> + // SAFETY: `dev` remains bound and valid for this call
> + unsafe { bindings::pm_suspend_ignore_children(dev.as_raw(), false) };
> + }
> + }
> +
> + /// Get a borrowed reference to PM profiles associated with the PM context
> + pub fn profiles(&self) -> &[PMProfile] {
> + &self.inner.profiles
> + }
> +
> + /// Get a borrowed reference to PM configs associated with the PM context
> + pub fn configs(&self) -> &[PMConfig] {
> + &self.inner.configs
> + }
> +}
> +
> +/// Runtime PM request profile.
> +#[derive(Copy, Clone)]
> +pub struct PMProfile(Mode);
> +
> +impl PMProfile {
> + /// Creates a PMProfile with default SYNC mode set.
> + pub const fn new() -> Self {
> + Self(Mode::empty())
> + }
> + /// Enables async PM operations for this PMProfile.
> + pub const fn r#async(self) -> Self {
> + Self(Mode(self.0 .0 | ModeFlag::Async as u32))
> + }
> + /// Use autosuspend
> + pub const fn auto(self) -> Self {
> + Self(Mode(self.0 .0 | ModeFlag::Auto as u32))
> + }
> + /// Requests idle handling for this PMProfile.
> + pub const fn idle(self) -> Self {
> + Self(Mode(self.0 .0 | ModeFlag::Idle as u32))
> + }
> + /// Do not wait for concurrent requests to finish.
> + pub const fn nowait(self) -> Self {
> + Self(Mode(self.0 .0 | ModeFlag::Nowait as u32))
> + }
> +}
> +
> +impl Default for PMProfile {
> + fn default() -> Self {
> + Self::new()
> + }
> +}
> +
> +/// Configuration knobs for runtime PM.
> +pub enum PMConfig {
> + /// Ignore child devices when suspending.
> + IgnoreChildren(bool),
> + /// Disable runtime PM callbacks.
> + NoCallbacks,
> + /// Mark device as IRQ-safe for runtime PM.
> + /// Runtime PM callbacks run with local interrupts
> + /// disabled and must not sleep
> + IrqSafe,
> + /// Enable or disable autosuspend.
> + AutoSuspend(bool),
> + /// Set autosuspend delay (milliseconds).
> + AutoSuspendDelay(i32),
> +}
> +
> +/// Runtime PM data stored within the `struct device_private` during
> +/// runtime PM registration.
> +///
> +#[repr(C)]
> +#[pin_data]
> +struct RegistrationData<'a, T: PMOps> {
> + payload: Payload<'a, T>,
> + #[cfg_attr(not(CONFIG_PM), allow(dead_code))]
> + #[pin]
> + data: T::RegistrationData<'a>,
> + _marker: PhantomData<&'a mut T>,
> +}
> +
> +/// Runtime PM registration for a device.
> +///
> +/// A `Registration` installs the `RegistrationData` alonw with the runtime
> +/// payload, used by the generated [`PMOps`] callbacks and owns
> +/// the corresponding teardown.
> +///
> +/// Dropping the registration disables runtime PM, waits for in-flight runtime PM
> +/// callbacks to complete, and then removes the stored registration data.
> +#[pin_data(PinnedDrop)]
> +pub struct Registration<'a, T>
> +where
> + T:PMOps,
> +{
> + ctx: PMContext<'inner, 'a, T>,
> + #[pin]
> + inner: PMContextInner<'a, T>,
> + #[pin]
> + data: RegistrationData<'a, T>,
> +}
> +
> +impl<'a, T: PMOps> Registration<'a, T> {
> + /// Creates a runtime PM registration for `dev`.
> + ///
> + /// The provided profiles and configuration are stored in the associated
> + /// [`PMContext`]. The `initial_payload` is expected to reflect current
> + /// power state of the device.
> + ///
> + /// The device must use the callback represented by `ops`, generated
> + /// for the same bus adapter and driver pair `(D, T)`.
> + ///
> + /// # Safety
> + ///
> + /// The returned [`Registration`] object cannot be mem::forgotten,
> + /// or it's [`Drop`] implementation cannot be skipped in any way.
> + ///
> + pub unsafe fn new<E>(
> + dev: &'a Device<Core<'_>>,
> + ops: &'static Ops<T>,
> + profiles: Option<KVec<PMProfile>>,
> + configs: Option<KVec<PMConfig>>,
> + data: impl PinInit<<T as PMOps>::RegistrationData<'a>, E> + 'a,
> + initial_payload: RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>,
> + ) -> impl PinInit<Self, Error> + 'a
> + where
> + Error: From<E>,
> + {
> + let dev: &'a Device<Bound> = dev;
> +
> + try_pin_init!(Self {
> + _: {
> + // SAFETY: For the duration of this call, `dev` is a valid `Device<Core>`,
> + // and so is its raw `struct device` pointer.
> + let pm = unsafe { (*(*dev.as_raw()).driver).pm };
> + if pm != ops.as_raw() && (cfg!(CONFIG_PM) || !pm.is_null()) {
> + return Err(EINVAL);
> + }
> + // SAFETY: Construction has exclusive access to this slot.
> + if !unsafe {
> + (*(*dev.as_raw()).p).rust.pm_registration_data
> + }.is_null() {
> + return Err(EBUSY);
> + }
> + },
> + inner <- try_pin_init!(PMContextInner {
> + dev,
> + state: Atomic::new(PMContextState::Disabled),
> + guard <- new_srcu!("rpm"),
> + profiles: profiles.unwrap_or_default(),
> + configs: configs.unwrap_or_default(),
> + _marker: PhantomData,
> + }),
> + ctx : PMContext { inner: inner.get_ref(), },
> + data <- try_pin_init!(RegistrationData {
> + data <- data,
> + payload: Payload {in_flight: AtomicFlag::new(false), inner: UnsafeCell::new(ManuallyDrop::new(initial_payload))},
> + _marker: PhantomData
> + }? E),
> + _: {
> + let ptr: NonNull<RegistrationData<'a, T>> =
> + NonNull::from(data.as_ref().get_ref());
> + // SAFETY: The device is not yet registered, and neither is
> + // the runtime pm beingenabled - as such, there is no
> + // cuncurency here
> + unsafe {
> + (*(*dev.as_raw()).p).rust.pm_registration_data =
> + ptr.cast::<core::ffi::c_void>().as_ptr();
> + };
> +
> + }
> + })
> +
> + }
> + /// Returns the runtime PM context associated with this registration.
> + pub fn get_ctx(&self) -> PMContext<'_, 'a, T> {
> + PMContext{ inner: &self.inner }
> + }
> +}
> +
> +#[pinned_drop]
> +impl<'a, T: PMOps> PinnedDrop for Registration<'a, T> {
> + fn drop(self: Pin<&mut Self>) {
> + // `self.inner.dev` is the device this registration was
> + // created for. Runtime PM is disabled first, and `pm_runtime_barrier`
> + // waits for pending runtime PM work/callbacks before the callback data
> + // is removed below.
> + // Furthermore, prevent any stale `PMContext`s from re-enabling runtime
> + // PM after teardown starts.
> + let prev = self.inner.state.xchg(PMContextState::Closing, ordering::Full);
> +
> + self.inner.guard.synchronize();
> +
> + if prev == PMContextState::Enabled {
> + Request::runtime_disable(self.inner.dev);
> + PMContext::<T>::reset_config(self.inner.dev, &self.inner.configs);
> + }
> +
> + Request::barrier(self.inner.dev);
> +
> + // SAFETY: The pointer was stored by `Registration::new`.
> + // Runtime PM has been disabled and drained above, so generated
> + // callbacks can no longer borrow this data.
> + unsafe {
> + (*(*self.inner.dev.as_raw()).p).rust.pm_registration_data = core::ptr::null_mut();
> + }
> + }
> +}
> --
^ permalink raw reply [flat|nested] 6+ messages in thread
* Re: [PATCH v6 1/3] rust: add runtime PM support
2026-11-27 20:08 ` Rafael J. Wysocki (Intel)
@ 2026-11-28 0:37 ` Danilo Krummrich
0 siblings, 0 replies; 6+ messages in thread
From: Danilo Krummrich @ 2026-11-28 0:37 UTC (permalink / raw)
To: Rafael J. Wysocki (Intel)
Cc: Beata Michalska, ojeda, gregkh, aliceryhl, boqun, gary,
bjorn3_gh, lossin, a.hindborg, tmgross, daniel.almeida,
boris.brezillon, work, samitolvanen, acourbot, rust-for-linux,
driver-core, linux-kernel, linux-pm
On Fri Nov 27, 2026 at 9:08 PM CET, Rafael J. Wysocki (Intel) wrote:
> I think I know what's going on above this point (except for the places
> where I said I needed help), but the part below escapes me, more or
> less.
>
> Which is unfortunate because I need to understand it so I can tell you
> whether or not it all makes sense IMV.
>
> So how can we get there? I'm not sure.
Most of the code below is for integration into the desgin of how the driver
lifecycle model is implemented in Rust.
I've given a talk about this topic this year at Kernel Recipes [1], with some
continuation in my LPC talk later this year [2].
In the following I will try to summarize the fundamentals of how this works in
Rust, and then try to tie it back to the PM code below, as it follows those core
principles.
(If you want I think it could make sense to schedule a call where we can walk
through the code and discuss the details. Of course I can't speak for Beata
though.)
One common source of bugs when writing C drivers is getting the ordering and
lifetime constraints of acquiring resources and initializing asynchronous
contexts (such as IRQs, class device, workqueues, etc.) and sharing resources
with such scope right.
For instance, when registering an IRQ in probe(), drivers have to make sure that
all (the relevant) fields of the driver's bus device private data are properly
initialized before an IRQ can fire an access the driver's bus device private
data.
Similar ordering constraints apply on teardown on either remove() or
devres_release_all(), depending on which model has been chosen by the driver
(and hopefully the driver didn't mix them up :).
(Of course you know all that, but I need an introduction. :)
In Rust we can basically break this down into three core mechanics to ensure
correct ordering and make lifecycle guarantees:
(1) Use Rust's core principles about ownership, borrowing and lifetimes.
(2) Use pin-init to expand the principles from (1) to allow them for
self-referencial, in-memory pinned structures.
(3) Give asynchronous contexts their own object representation, and - through
(1) and (2) - allow them to borrow from sibling fields within their entire
storage container (which typically is the driver's bus device private data).
The object representation of (3) is typically called "Registration", for
instance there is an irq::Registration type, whose existance (or lifetime)
describes the scope in which a driver has an IRQ registered for its bound
device.
Since this is probably a bit abstract, let's have a look at a concrete example.
Let's say this is a driver's bus device private data:
struct DriverData<'bound> {
pdev: &'bound pci::Device<Bound>,
_enable: pci::DeviceEnableGuard<'bound>,
#[pin]
irq_handler: irq::Registration<'irq_vec, IrqHandler<'irq_vec>>,
irq_vec: pci::IrqVectorRegistration<'bound>,
bar: pci::Bar<'bound>,
}
The first thing to notice is the 'bound lifetime annotation; semanically this is
the lifetime of the driver being bound to the device.
For instance, Rust allows us to store a pci::Device<Bound> (i.e. a PCI device
that has the type state guarantee to be bound) inside of this container, as the
container trivially statisfies its lifetime requirement. It could also be stored
in something that is shorter lived, but it can't be stored in a container that
is longer lived (as this would violate the 'Bound' type state).
(Most) Registration types, such as irq::Registration, require to be shorter
lived than 'bound, such that is guaranteed that their destructor is called
before 'bound expires, i.e. before the driver is unbound.
They also receive their own storage container; in the case above the
irq::Registration's private data is IrqHandler.
Note that this storage container is still part of the allocation of the driver's
bus device private data, i.e. DriverData. There's no separate allocation.
The lifetime it captures only means that pci::IrqVectorRegistration must be
longer lived than irq::Registration, because we can't free PCI IRQ vectors
before we free the IRQ itself.
You can't see it from the struct definition, but this ordering is enforced at
compile time, if the order would be changed it wouldn't compile.
Let's have a look at the storage container of irq::Registration now.
struct IrqHandler<'handler> {
pdev: &'handler pci::Device<Bound>,
bar: &'handler pci::Bar<'handler>,
}
The IrqHandler also stores a reference to the pci::Device<Bound>, which is valid
as the compiler ensures it can't outlive 'bound. And it also stores a reference
to the pci::Bar owned by DriverData, which it borrows from.
The point of this exercise is that with this it becomes impossible for the
driver to register and prime the IRQ first and then map the pci::Bar, which the
IRQ handler could access concurrently. It is guaranteed that pci::Bar is
constructed before the irq::Registration.
We can easily see this from probe():
impl Driver {
fn probe<'bound>(
pdev: &'bound pci::Device<Core<'_>>,
_id_info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
try_pin_init!(DriverData {
_enable: pdev.enable_device()
.inspect(|_| pdev.set_master())?,
Here we create the pci::DeviceEnableGuard first and set bus mastering and store
it in DriverData.
bar: pdev.iomap_region_sized::<{ regs::END }>(
0, c"rust_driver_edu",
)?,
Here we map the pci::Bar and store it in DriverData as bar.
irq_vec: pdev.alloc_irq_vectors(
1, 1, IrqTypes::default().with(pci::IrqType::Msi),
)?,
Here we create the pci::IrqVectorRegistration and store it in DriverData as irq_vec.
irq_handler <- irq::Registration::new(
irq_vec.index(0)?.into(),
Constructing irq::Registration requires the PCI IRQ vector index as Linux IRQ
number (the conversion happens through the into() call).
The resulting IrqRequest type, that captures the Linux IRQ number also captures
the lifetime from irq_vec, which establishes the relationship I explained above.
It also ensures correct initialization order, as there is a data dependency:
irq::Registration can't be constructed without pci::IrqVectorRegistration being
initialized in-place before.
Flags::TRIGGER_NONE,
c"rust_edu_irq",
try_pin_init!(IrqHandler {
bar,
pdev,
}),
Here we pass the private data of the irq::Registration; bar is a borrow of the
in-place initialized fields above. Through the data dependency the order is
guaranteed.
The driver core ensures that the destructor of DriverData runs on driver unbind,
which causes all fields to drop. The drop order is reverse of initialization
order (declaration order) which is guaranteed through pin-init. Those are all
compile time guarantees.
),
pdev,
})
}
}
Finally to the runtime PM code. :)
It pretty much follows the same pattern, analogous to irq::Registration, there
is a pm::Registration type that serves as the container for private data that is
accessible to runtime_resume() and runtime_suspend().
This is also what the pm_registration_data pointer is used for; it helps us to
find the offset of the pm::Registration data container within the driver's bus
device private data.
You can think of pm::Registration as pretty much the same as
devm_pm_runtime_enable(), except that the lifetime management isn't done by
devres, but by Rust's ownership and lifetime model.
Of course, this doesn't work for all buses, but only for buses where drivers
should use devm_pm_runtime_enable(), or pm_runtime_{enable,disable}().
(I missed this part in my previous review; pm::Registration should only work for
buses where this pattern is supported, e.g. platform. So, there should probably
be a platform::pm::Registration that takes a platform::Device<Bound>.
pci::pm::Registration needs to be slightly different and should probably use
pm_runtime_get_noresume() and pm_runtime_put_noidle() etc. instead.)
Now, let's have a look at how the PM callbacks work in this patch.
impl PMOps for MyPlatformDriver {
type Adapter = platform::Adapter<MyPlatformDriver>;
type DeviceType = platform::Device<Bound>;
type RegistrationData<'a> = MyPMRegistrationData<'a>;
This is the pm::Registration data container that can e.g. borrow resources owned
by the driver's bus device private data.
type ActivePayload<'a> = MyActivePayload;
This type represents data that only lives as long as the driver is not
suspended. It is currently constructed in when pm::Registration is constructed
and passed by value to runtime_suspend() do the driver can either drop it or
retain it via SuspendedPayload.
This type can be useful to allow drivers to change the type state of a type that
represents a resource.
For instance, it could contain a Regulator<Enabled>. runtime_suspend() gets the
container by value, takes out the Regulator<Enabled>, converts it to a
Regulator<Disabled> and stores it in SuspendedPayload.
Note that Regulator<Enabled> and Regulator<Disabled> are different types and
hence having different container types, i.e. ActivePayload and SuspendedPayload
make sense.
type SuspendedPayload<'a> = MySuspendPayload;
This has mostly been covered above, but obvious SuspendedPayload only lives as
long as the device is suspended and it is constructed by runtime_suspend() and
consumed by value by runtime_resume().
fn runtime_suspend<'a>(
_dev: &'a Self::DeviceType,
_reg_data: &'a Self::RegistrationData<'a>,
payload: Self::ActivePayload<'a>,
) -> Result<Self::SuspendedPayload<'a>, (Self::ActivePayload<'a>, Error)> {
The runtime_suspend() callback received the RegistrationData (i.e. the container
that can borrow from the driver's device private data) and the initial
ActivePayload, both passed to pm::Registration::new().
It can deconstruct ActivePayload and returns a SuspendedPayload, on failure it
returns an error and the original ActivePayload.
...
Ok(payload)
}
fn runtime_resume<'a>(
_dev: &'a Self::DeviceType,
_reg_data: &'a Self::RegistrationData<'a>,
payload: Self::SuspendedPayload<'a>,
) -> Result<Self::ActivePayload<'a>, (Self::SuspendedPayload<'a>, Error)> {
As one would expect, the runtime_resume() callback works pretty much the same,
just in reverse.
...
Ok(payload)
}
}
Both ActivePayload and SuspendedPayload can borrow from the RegistrationData and
allow drivers to use proper guard types and type states rather than needing
"manual calls" to switch between enabled/disabled states or balance reference
counts.
A lot of the code below is dealing with juggling ActivePayload and
SuspendedPayload around for this purpose. Functions like
with_registration_data() are accessors e.g. dealing with lifetime variance [3].
[1] https://kernel-recipes.org/en/2026/schedule/enforcing-device-driver-lifecycle-rules-at-compile-time/
[2] https://youtu.be/3A2vGbc_rxs?t=668
[3] https://doc.rust-lang.org/nomicon/subtyping.html#variance
>> +/// Common runtime PM callback entry point.
>> +///
>> +/// Invokes a runtime PM callback with its registration data and current payload.
>> +///
>> +/// # Safety
>> +///
>> +/// The generated extern "C" callbacks call into this helper with the raw
>> +/// `struct device *` provided by the PM core. As such, it is guaranteed that
>> +/// the `struct device` remains valid throughout the calls.
>> +#[cfg(CONFIG_PM)]
>> +unsafe fn with_registration_data<T, F>(dev: *mut bindings::device, cb: F) -> Result
>> +where
>> + T: PMOps,
>> + F: for <'a>FnOnce(
>> + &'a <T as PMOps>::DeviceType,
>> + &'a <T as PMOps>::RegistrationData<'a>,
>> + RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>
>> + ) -> PMCallbackResult<RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>,
>> + RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>>,
>> +{
>> + // SAFETY: `dev` is provided by the PM core and remains valid
>> + // for the duration of the callback.
>> + let dev: &Device = unsafe { Device::from_raw(dev) };
>> + // SAFETY: The runtime PM callback can only be triggered for a bound device.
>> + let dev: &Device<Bound> = unsafe { dev.as_bound() };
>> + let pm_dev: &T::DeviceType =
>> + // SAFETY: The generated `dev_pm_ops` for `T` is installed on devices whose
>> + // bus-specific type is `T::DeviceType`. Therefore the base `Device<Bound>`
>> + // passed by the PM core is embedded in a valid `T::DeviceType`; the
>> + // `AsBusDevice` implementation supplies the correct offset for this cast.
>> + unsafe { T::DeviceType::from_device(dev) };
>> + // SAFETY: The `RegistrationData` must have been successfully installed
>> + // for a device and it is guaranteed that it reamins valid at least until
>> + // the last PM callback finishes.
>> + let ptr = unsafe { (*(*dev.as_raw()).p).rust.pm_registration_data };
>> + // SAFETY: `Registration::new` stores a pointer to its initialized, pinned
>> + // `RegistrationData<T>` before enabling runtime PM. These callbacks
>> + // belong to the same `T`. Registration teardown disables runtime PM and
>> + // drains callbacks before clearing the pointer and dropping the data, so
>> + // it remains valid for this callback
>> + let reg_data = unsafe { &*ptr.cast::<RegistrationData<'_, T>>() };
>> +
>> + let _guard = reg_data.payload.acquire()?;
>> + // SAFETY: This callback alone acquired `in_flight`; it has exclusive
>> + // access to the payload slot until `_guard` is dropped.
>> + let slot = unsafe { &mut *reg_data.payload.inner.get() };
>> + // SAFETY: `_guard` gives this callback exclusive access to `slot`, which
>> + // contains an initialized payload. Both callback outcomes provide a payload
>> + // that is written back into `slot` before `_guard` is released.
>> + let payload = unsafe { ManuallyDrop::take(slot) };
>> +
>> + let (next, result) = match cb(pm_dev, ®_data.data, payload) {
>> + Ok(next) => (next, Ok(())),
>> + Err((current, err)) => (current, Err(err)),
>> + };
>> +
>> + *slot = ManuallyDrop::new(next);
>> + result
>> +}
>> +
>> +/// Runtime resume PM callback.
>> +///
>> +/// # Safety
>> +///
>> +/// `dev` is a valid `struct device *` supplied by the PM core for a device
>> +/// whose runtime PM callbacks and PM registration data were both created
>> +/// for `T`.
>> +#[cfg(CONFIG_PM)]
>> +unsafe extern "C" fn runtime_resume_callback<T>(dev: *mut bindings::device) -> c_int
>> +where
>> + T: PMOps,
>> +{
>> + // SAFETY: The callback's safety contract guarantees that `dev` remains
>> + // valid for this call and has PM registration data created for `T`.
>> + // These are the preconditions of `with_registration_data`.
>> + unsafe {
>> + with_registration_data::<T, _>(dev,
>> + |pm_dev, data, payload| {
>> + match payload {
>> + RuntimeStatePayload::Suspended(payload_data) => {
>> + T::runtime_resume(pm_dev, data, payload_data)
>> + .map(RuntimeStatePayload::Active)
>> + .map_err(|(prev, err)| (RuntimeStatePayload::Suspended(prev), err))
>> + },
>> + other => Err((other, EINVAL)),
>> + }
>> + })
>> + .map(|()| 0)
>> + .unwrap_or_else(|e| e.to_errno())
>> + }
>> +}
>> +/// Runtime suspend PM callback.
>> +///
>> +/// # Safety
>> +///
>> +/// `dev` is a valid `struct device *` supplied by the PM core for a device
>> +/// whose runtime PM callbacks and PM registration data were both created
>> +/// for `T`.
>> +#[cfg(CONFIG_PM)]
>> +unsafe extern "C" fn runtime_suspend_callback<T>(dev: *mut bindings::device) -> c_int
>> +where
>> + T: PMOps,
>> +{
>> + // SAFETY: The callback's safety contract guarantees that `dev` remains
>> + // valid for this call and has PM registration data created for `T`.
>> + // These are the preconditions of `with_registration_data`.
>> + unsafe {
>> + with_registration_data::<T, _>(dev,
>> + |pm_dev, data, payload| {
>> + match payload {
>> + RuntimeStatePayload::Active(payload_data) => {
>> + T::runtime_suspend(pm_dev, data, payload_data)
>> + .map(RuntimeStatePayload::Suspended)
>> + .map_err(|(prev, err)| (RuntimeStatePayload::Active(prev), err))
>> + },
>> + other => Err((other, EINVAL)),
>> + }
>> + })
>> + .map(|()| 0)
>> + .unwrap_or_else(|e| e.to_errno())
>> + }
>> +}
>> +
>> +/// Default empty Runtime PM ops
>> +pub const PMOPS_NONE: bindings::dev_pm_ops =
>> + // 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
>> + //
>> + unsafe { core::mem::MaybeUninit::<bindings::dev_pm_ops>::zeroed().assume_init() };
>> +
>> +/// Typed reference to a driver's runtime PM ops.
>> +///
>> +/// Instances of this type are generated from static [`Ops`]
>> +/// and are used by bus registration code to install the matching
>> +/// C `dev_pm_ops` pointer into the driver object.
>> +/// The `A` parameter identifies the bus adapter that is allowed
>> +/// to install the table.
>> +pub struct AdapterOpsRef<'a, A> {
>> + #[cfg_attr(not(CONFIG_PM), allow(unused))]
>> + ops: &'a bindings::dev_pm_ops,
>> + _p: PhantomData<fn() -> *const A>,
>> +}
>> +
>> +/// Conveniance type alias
>> +pub type OpsRef<T> = AdapterOpsRef<'static, <T as PMOps>::Adapter>;
>> +
>> +// SAFETY: `AdapterOpsRef` only contains a shared reference to an immutable
>> +// `dev_pm_ops` table and a type marker. Sharing it between threads cannot
>> +// introduce mutation or aliasing of Rust-owned state.
>> +unsafe impl<A> Sync for AdapterOpsRef<'_, A> {}
>> +
>> +impl<A> AdapterOpsRef<'_, A> {
>> + #[cfg_attr(not(CONFIG_PM), allow(unused))]
>> + #[inline]
>> + pub(crate) const fn as_raw(&self) -> *const bindings::dev_pm_ops {
>> + self.ops
>> + }
>> +}
>> +
>> +/// Runtime PM ops for a driver.
>> +///
>> +/// Intended to be constructed by bus-specific helpers, allowing
>> +/// the bus to ensure that the callback device type matches the device
>> +/// supplied by the C driver core.
>> +pub struct Ops<T: PMOps> {
>> + raw: bindings::dev_pm_ops,
>> + _p: PhantomData<fn() -> T>,
>> +}
>> +
>> +impl<T: PMOps> Ops<T> {
>> + /// Creates a typed runtime PM ops.
>> + ///
>> + /// # Safety
>> + ///
>> + /// The caller must guarantee that `T::Adapter` is the bus adapter that
>> + /// will install this ops into the C driver object for `T`, and
>> + /// that `T::DeviceType` is the bus device type corresponding to
>> + /// that adapter. Safe bus-specific constructors should wrap this
>> + /// function with those bounds.
>> + pub(crate) const unsafe fn new_unchecked(raw: bindings::dev_pm_ops) -> Self {
>> + const_assert!(
>> + T::HAS_RUNTIME_RESUME == T::HAS_RUNTIME_SUSPEND,
>> + "runtime suspend and resume callbacks should be implemented together"
>> + );
>> + Self {
>> + raw,
>> + _p: PhantomData,
>> + }
>> + }
>> +
>> + /// Provides a typed reference to this runtime PM ops
>> + ///
>> + /// Bus registration code uses the returned value to install
>> + /// the ops into the corresponding C driver object.
>> + /// The returned reference is tied to `T::Adapter`.
>> + pub const fn pm_ops(&'static self) -> OpsRef<T> {
>> + AdapterOpsRef {
>> + ops: &self.raw,
>> + _p: PhantomData,
>> + }
>> + }
>> +
>> + /// Returns the raw C runtime PM operations table.
>> + #[inline]
>> + pub const fn as_raw(&'static self) -> *const bindings::dev_pm_ops {
>> + &self.raw
>> + }
>> +}
>> +
>> +/// Result type returned by runtime PM callbacks.
>> +pub type PMCallbackResult<New, Current> = Result<New, (Current, Error)>;
>> +
>> +/// Runtime PM callbacks implemented by a driver.
>> +///
>> +/// Defines the [`PMOps`] trait and its corresponding [`bindings::dev_pm_ops`].
>> +///
>> +/// The Adapter associated type identifies the bus adapter that installs
>> +/// the generated PM ops.
>> +/// Implementations should normally be enabled through a
>> +/// bus-specific constructor for [`Ops`], which constrains
>> +/// [`Self::DeviceType`] to the correct bound device type for that bus.
>> +#[vtable]
>> +pub trait PMOps: Sized {
>> + /// The bus adapter that installs the generated PM ops.
>> + type Adapter: driver::DriverLayout + 'static;
>> +
>> + /// Type of the bound bus device passed to runtime PM callbacks.
>> + type DeviceType: AsBusDevice<Bound>;
>> +
>> + /// Data associated with the `Registration`, tied to its lifetime.
>> + type RegistrationData<'a>: Send + Sync + 'a;
>> +
>> + /// Driver's specific data associated with suspended PM device state
>> + type SuspendedPayload<'a>: Send + 'a;
>> + /// Driver's specific data associated with active PM device states
>> + type ActivePayload<'a>: Send + 'a;
>> +
>> + /// Runtime resume callback.
>> + fn runtime_resume<'a>(
>> + _dev: &'a Self::DeviceType,
>> + _reg_data: &'a Self::RegistrationData<'a>,
>> + _payload: Self::SuspendedPayload<'a>,
>> + ) -> PMCallbackResult<Self::ActivePayload<'a>, Self::SuspendedPayload<'a>> {
>> + build_error!(VTABLE_DEFAULT_ERROR)
>> + }
>> +
>> + /// Runtime suspend callback.
>> + fn runtime_suspend<'a>(
>> + _dev: &'a Self::DeviceType,
>> + _reg_data: &'a Self::RegistrationData<'a>,
>> + _payload: Self::ActivePayload<'a>,
>> + ) -> PMCallbackResult<Self::SuspendedPayload<'a>, Self::ActivePayload<'a>> {
>> + build_error!(VTABLE_DEFAULT_ERROR)
>> + }
>> +}
>> +
>> +/// RAII guard for ongoing runtime PM payload transition.
>> +///
>> +/// For most of the callbacks this guard is not necessarily needed as
>> +/// the callbacks themselves are being serialized by the runtime PM C code.
>> +/// Still, some like runtime_idle are exempt from that.
>> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
>> +struct PayloadGuard<'a> {
>> + busy: &'a AtomicFlag,
>> +}
>> +
>> +impl Drop for PayloadGuard<'_> {
>> + fn drop(&mut self) {
>> + self.busy.store(false, ordering::Release);
>> + }
>> +}
>> +
>> +/// Payload associated with the given runtime power state of a device.
>> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
>> +pub enum RuntimeStatePayload<Active, Suspended> {
>> + /// Payload associated with the runtime active PM state of a device
>> + Active(Active),
>> + /// Payload associated with the runtime suspended PM state of a device
>> + Suspended(Suspended),
>> +}
>> +
>> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
>> +struct Payload<'a, T:PMOps> {
>> + in_flight: AtomicFlag,
>> + inner: UnsafeCell<ManuallyDrop<RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>>>,
>> +}
>> +
>> +#[cfg_attr(not(CONFIG_PM), allow(unused))]
>> +impl<'a, T:PMOps> Payload<'a, T> {
>> + /// Attempts to acquire exclusive access to the runtime PM payload.
>> + ///
>> + /// Returns `EBUSY` if another runtime PM callback is already transitioning the
>> + /// payload.
>> + fn acquire(&self) -> Result<PayloadGuard<'_>> {
>> + self.in_flight
>> + .cmpxchg(false, true, ordering::Acquire)
>> + .map_err(|_| EBUSY)?;
>> + Ok(PayloadGuard {
>> + busy: &self.in_flight,
>> + })
>> + }
>> +}
>> +
>> +impl<T:PMOps> Drop for Payload<'_, T> {
>> + fn drop(&mut self) {
>> + // SAFETY: teardown drained PM callbacks and the slot holds a `P`
>> + unsafe {
>> + ManuallyDrop::drop(self.inner.get_mut());
>> + }
>> + }
>> +}
>> +
>> +// SAFETY: Although Payload's `inner` is an `UnsafeCell`, it is only accessed
>> +// after `in_flight` has been acquired. The AtomicFlag flag serializes all mutable
>> +// access to the payload, and `PayloadGuard` clears the flag when the access ends.
>> +unsafe impl<T:PMOps> Sync for Payload<'_, T> {}
>> +
>> +#[derive(Clone, Copy, PartialEq, Eq)]
>> +#[repr(i32)]
>> +enum PMContextState {
>> + /// The PM registration is alive, but runtime PM has not been enabled.
>> + Disabled = 0,
>> + /// Enabling runtime PM has been initiated but has not completed just yet
>> + Enabling = 1,
>> + /// The runtime PM has been enabled. Intended to be balanced by
>> + /// `disable()` or `Registration::drop()`
>> + Enabled = 2,
>> + /// Disabling runtime PM has been initiated but has not completed just yet
>> + Disabling = 3,
>> + /// The owning `Registration` is being dropped or has been dropped.
>> + /// Stale cloned `PMContext`s may still exist, but once this state is
>> + /// visible, runtime PM cannot be re-enabled.
>> + Closing = 4,
>> +}
>> +
>> +// SAFETY: `PMContextState` has the same size and alignment as `i32`, and all
>> +// values written through `Atomic<PMContextState>` are valid `PMContextState`
>> +// discriminants.
>> +unsafe impl AtomicType for PMContextState {
>> + type Repr = i32;
>> +}
>> +
>> +#[pin_data]
>> +struct PMContextInner<'a, T: PMOps> {
>> + dev: &'a Device<Bound>,
>> + /// State owned by the runtime PM registration
>> + state: Atomic<PMContextState>,
>> + /// A synchronization point for all pending callbacks to finish.
>> + #[pin]
>> + guard: Srcu,
>> + /// Optional driver-selected runtime PM request PMProfiles.
>> + ///
>> + /// Set of runtime PM predefined PMProfiles that can be used by the driver
>> + /// when requesting a PM transition. This might be useful when a driver
>> + /// has several different PM usage patterns.
>> + /// See [PMProfile] for more details.
>> + profiles: KVec<PMProfile>,
>> + /// Set of PM config options applied for associated device.
>> + configs: KVec<PMConfig>,
>> + _marker: PhantomData<fn() -> T>,
>> +}
>> +
>> +/// Runtime PM context tied to a device.
>> +///
>> +/// Needs to be dropped from sleepable context.
>> +#[pin_data]
>> +pub struct PMContext<'r, 'a, T: PMOps> {
>> + inner: &'r PMContextInner<'a, T>,
>> +}
>> +
>> +impl<'r, 'a, T: PMOps> PMContext<'r, 'a, 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, its registration data
>> + /// 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.
>> + #[cfg(CONFIG_PM)]
>> + pub(crate) const PM_OPS: bindings::dev_pm_ops = bindings::dev_pm_ops {
>> + runtime_resume: if T::HAS_RUNTIME_RESUME {
>> + Some(runtime_resume_callback::<T>)
>> + } else {
>> + None
>> + },
>> + runtime_suspend: if T::HAS_RUNTIME_SUSPEND {
>> + Some(runtime_suspend_callback::<T>)
>> + } else {
>> + None
>> + },
>> + ..PMOPS_NONE
>> + };
>> +
>> + #[cfg(not(CONFIG_PM))]
>> + pub(crate) const PM_OPS: bindings::dev_pm_ops = PMOPS_NONE;
>> +
>> + #[inline]
>> + fn state_transition(&self, expected: PMContextState, new: PMContextState) -> Result
>> + {
>> + self.inner.state.cmpxchg(expected, new, ordering::Full)
>> + .map(|_| ())
>> + .map_err(|actual| match (expected, actual) {
>> + (_, PMContextState::Closing) => ENODEV,
>> + (PMContextState::Disabled, PMContextState::Disabling)
>> + | (PMContextState::Enabled, PMContextState::Enabling) => EBUSY,
>> + _ => EINVAL,
>> + })
>> + }
>> +
>> + /// Enable runtime PM
>> + pub fn enable(&self, state: RuntimePMState) -> Result {
>> + let _transition_guard = self.inner.guard.read_lock();
>> + self.state_transition(PMContextState::Disabled, PMContextState::Enabling)?;
>> + Self::apply_config(self.inner.dev, &self.inner.configs);
>> +
>> + match state {
>> + RuntimePMState::Active => Request::mark_active(self.inner.dev),
>> + RuntimePMState::Suspended => Request::mark_suspended(self.inner.dev),
>> + }
>> + .inspect_err(|_| {
>> + Self::reset_config(self.inner.dev, &self.inner.configs);
>> + let _ = self.state_transition(
>> + PMContextState::Enabling,
>> + PMContextState::Disabled,
>> + );
>> + })?;
>> +
>> + Request::runtime_enable(self.inner.dev);
>> + self.state_transition(
>> + PMContextState::Enabling,
>> + PMContextState::Enabled,
>> + ).inspect_err(|e| {
>> + if *e == ENODEV {
>> + Request::runtime_disable(self.inner.dev);
>> + Self::reset_config(self.inner.dev, &self.inner.configs);
>> + }
>> + })?;
>> + Ok(())
>> + }
>> +
>> + /// Disable runtime PM
>> + pub fn disable(&self) -> Result {
>> + let _transition_guard = self.inner.guard.read_lock();
>> + self.state_transition(
>> + PMContextState::Enabled,
>> + PMContextState::Disabling,
>> + )?;
>> +
>> + Request::runtime_disable(self.inner.dev);
>> + Self::reset_config(self.inner.dev, &self.inner.configs);
>> +
>> + let _ = self.state_transition(
>> + PMContextState::Disabling,
>> + PMContextState::Disabled
>> + );
>> + Ok(())
>> + }
>> +
>> + /// Returns whether the runtime PM state is active.
>> + #[inline]
>> + pub fn active(&self) -> bool {
>> + Request::active(self.inner.dev)
>> + }
>> +
>> + /// Returns whether the runtime PM state is suspended.
>> + #[inline]
>> + pub fn suspended(&self) -> bool {
>> + Request::suspended(self.inner.dev)
>> + }
>> +
>> + /// Creates a `ResumeScope` for the given PMProfile.
>> + /// Note that for ASYNC/NOWAIT request this does not guarantee
>> + /// the device has been resumed at the time this function returns.
>> + #[inline]
>> + pub fn resume(&self, profile: PMProfile) -> Result<ResumeScope<'r>> {
>> + ResumeScope::new(self.inner.dev, profile.0)
>> + }
>> +
>> + /// Creates an `AwakeScope` for the given PMProfile.
>> + /// Note that for ASYNC/NOWAIT request this does not guarantee
>> + /// the device has been resumed at the time this function returns.
>> + #[inline]
>> + pub fn get(&self, profile: PMProfile) -> Result<AwakeScope<'r>> {
>> + AwakeScope::new(self.inner.dev, profile.0 | ModeFlag::Acquire)
>> + }
>> +
>> + /// Creates a `RetainScope` for this device.
>> + pub fn hold(&self) -> Result<RetainScope<'r>> {
>> + RetainScope::new(self.inner.dev)
>> + }
>> +
>> + /// Creates a `RetainScope` for an active device.
>> + pub fn try_hold_active(&self) -> Result<RetainScope<'r>> {
>> + RetainScope::try_new(self.inner.dev)
>> + }
>> +
>> + /// Runs a closure while holding a `ResumeScope`.
>> + pub fn with_resume<R>(&self, profile: PMProfile, f: impl FnOnce() -> Result<R>) -> Result<R> {
>> + if profile.0.contains_any(ModeFlag::Async| ModeFlag::Nowait) {
>> + return Err(EINVAL);
>> + }
>> + let _scope = self.resume(profile)?;
>> + f()
>> + }
>> + /// 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_any(ModeFlag::Async | ModeFlag::Nowait) {
>> + return Err(EINVAL);
>> + }
>> + let _scope = self.get(profile)?;
>> + f()
>> + }
>> +
>> + /// Runs a closure while holding a `RetainScope`.
>> + pub fn with_hold<R>(&self, f: impl FnOnce() -> Result<R>) -> Result<R> {
>> + let _scope = self.hold()?;
>> + f()
>> + }
>> +
>> + /// Applies runtime PM configuration options.
>> + ///
>> + /// Options are applied in the order provided. The currently supported
>> + /// options do not report per-option failures.
>> + fn apply_config(dev: &Device<Bound>, opts: &[PMConfig]) {
>> + for opt in opts {
>> + match opt {
>> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
>> + // yields a valid pointer to `struct device` for the duration of this call.
>> + PMConfig::IgnoreChildren(v) => unsafe {
>> + bindings::pm_suspend_ignore_children(dev.as_raw(), *v)
>> + },
>> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
>> + // yields a valid pointer to `struct device` for the duration of this call.
>> + PMConfig::NoCallbacks => unsafe { bindings::pm_runtime_no_callbacks(dev.as_raw()) },
>> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
>> + // yields a valid pointer to `struct device` for the duration of this call.
>> + PMConfig::IrqSafe => unsafe {
>> + // Do not attempt to call that more than once
>> + if !bindings::pm_runtime_is_irq_safe(dev.as_raw()) {
>> + bindings::pm_runtime_irq_safe(dev.as_raw());
>> + }
>> + },
>> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
>> + // yields a valid pointer to `struct device` for the duration of this call.
>> + PMConfig::AutoSuspend(v) => unsafe {
>> + bindings::__pm_runtime_use_autosuspend(dev.as_raw(), *v);
>> + },
>> + // SAFETY: The `Device<Bound>` reference guarantees that `dev.as_raw()`
>> + // yields a valid pointer to `struct device` for the duration of this call.
>> + PMConfig::AutoSuspendDelay(v) => unsafe {
>> + bindings::pm_runtime_set_autosuspend_delay(dev.as_raw(), *v);
>> + bindings::__pm_runtime_use_autosuspend(dev.as_raw(), true);
>> + },
>> + }
>> + }
>> + }
>> +
>> + fn reset_config(dev: &Device<Bound>, opts: &[PMConfig]) {
>> + if opts.iter().any(|opt| {
>> + matches!(opt, PMConfig::AutoSuspend(_) | PMConfig::AutoSuspendDelay(_))
>> + }) {
>> + // SAFETY: `dev` remains bound and valid for this call
>> + unsafe { bindings::__pm_runtime_use_autosuspend(dev.as_raw(), false) };
>> + }
>> +
>> + if opts.iter().any(|opt| {
>> + matches!(opt, PMConfig::IgnoreChildren(_))
>> + }) {
>> + // SAFETY: `dev` remains bound and valid for this call
>> + unsafe { bindings::pm_suspend_ignore_children(dev.as_raw(), false) };
>> + }
>> + }
>> +
>> + /// Get a borrowed reference to PM profiles associated with the PM context
>> + pub fn profiles(&self) -> &[PMProfile] {
>> + &self.inner.profiles
>> + }
>> +
>> + /// Get a borrowed reference to PM configs associated with the PM context
>> + pub fn configs(&self) -> &[PMConfig] {
>> + &self.inner.configs
>> + }
>> +}
>> +
>> +/// Runtime PM request profile.
>> +#[derive(Copy, Clone)]
>> +pub struct PMProfile(Mode);
>> +
>> +impl PMProfile {
>> + /// Creates a PMProfile with default SYNC mode set.
>> + pub const fn new() -> Self {
>> + Self(Mode::empty())
>> + }
>> + /// Enables async PM operations for this PMProfile.
>> + pub const fn r#async(self) -> Self {
>> + Self(Mode(self.0 .0 | ModeFlag::Async as u32))
>> + }
>> + /// Use autosuspend
>> + pub const fn auto(self) -> Self {
>> + Self(Mode(self.0 .0 | ModeFlag::Auto as u32))
>> + }
>> + /// Requests idle handling for this PMProfile.
>> + pub const fn idle(self) -> Self {
>> + Self(Mode(self.0 .0 | ModeFlag::Idle as u32))
>> + }
>> + /// Do not wait for concurrent requests to finish.
>> + pub const fn nowait(self) -> Self {
>> + Self(Mode(self.0 .0 | ModeFlag::Nowait as u32))
>> + }
>> +}
>> +
>> +impl Default for PMProfile {
>> + fn default() -> Self {
>> + Self::new()
>> + }
>> +}
>> +
>> +/// Configuration knobs for runtime PM.
>> +pub enum PMConfig {
>> + /// Ignore child devices when suspending.
>> + IgnoreChildren(bool),
>> + /// Disable runtime PM callbacks.
>> + NoCallbacks,
>> + /// Mark device as IRQ-safe for runtime PM.
>> + /// Runtime PM callbacks run with local interrupts
>> + /// disabled and must not sleep
>> + IrqSafe,
>> + /// Enable or disable autosuspend.
>> + AutoSuspend(bool),
>> + /// Set autosuspend delay (milliseconds).
>> + AutoSuspendDelay(i32),
>> +}
>> +
>> +/// Runtime PM data stored within the `struct device_private` during
>> +/// runtime PM registration.
>> +///
>> +#[repr(C)]
>> +#[pin_data]
>> +struct RegistrationData<'a, T: PMOps> {
>> + payload: Payload<'a, T>,
>> + #[cfg_attr(not(CONFIG_PM), allow(dead_code))]
>> + #[pin]
>> + data: T::RegistrationData<'a>,
>> + _marker: PhantomData<&'a mut T>,
>> +}
>> +
>> +/// Runtime PM registration for a device.
>> +///
>> +/// A `Registration` installs the `RegistrationData` alonw with the runtime
>> +/// payload, used by the generated [`PMOps`] callbacks and owns
>> +/// the corresponding teardown.
>> +///
>> +/// Dropping the registration disables runtime PM, waits for in-flight runtime PM
>> +/// callbacks to complete, and then removes the stored registration data.
>> +#[pin_data(PinnedDrop)]
>> +pub struct Registration<'a, T>
>> +where
>> + T:PMOps,
>> +{
>> + ctx: PMContext<'inner, 'a, T>,
>> + #[pin]
>> + inner: PMContextInner<'a, T>,
>> + #[pin]
>> + data: RegistrationData<'a, T>,
>> +}
>> +
>> +impl<'a, T: PMOps> Registration<'a, T> {
>> + /// Creates a runtime PM registration for `dev`.
>> + ///
>> + /// The provided profiles and configuration are stored in the associated
>> + /// [`PMContext`]. The `initial_payload` is expected to reflect current
>> + /// power state of the device.
>> + ///
>> + /// The device must use the callback represented by `ops`, generated
>> + /// for the same bus adapter and driver pair `(D, T)`.
>> + ///
>> + /// # Safety
>> + ///
>> + /// The returned [`Registration`] object cannot be mem::forgotten,
>> + /// or it's [`Drop`] implementation cannot be skipped in any way.
>> + ///
>> + pub unsafe fn new<E>(
>> + dev: &'a Device<Core<'_>>,
>> + ops: &'static Ops<T>,
>> + profiles: Option<KVec<PMProfile>>,
>> + configs: Option<KVec<PMConfig>>,
>> + data: impl PinInit<<T as PMOps>::RegistrationData<'a>, E> + 'a,
>> + initial_payload: RuntimeStatePayload<T::ActivePayload<'a>, T::SuspendedPayload<'a>>,
>> + ) -> impl PinInit<Self, Error> + 'a
>> + where
>> + Error: From<E>,
>> + {
>> + let dev: &'a Device<Bound> = dev;
>> +
>> + try_pin_init!(Self {
>> + _: {
>> + // SAFETY: For the duration of this call, `dev` is a valid `Device<Core>`,
>> + // and so is its raw `struct device` pointer.
>> + let pm = unsafe { (*(*dev.as_raw()).driver).pm };
>> + if pm != ops.as_raw() && (cfg!(CONFIG_PM) || !pm.is_null()) {
>> + return Err(EINVAL);
>> + }
>> + // SAFETY: Construction has exclusive access to this slot.
>> + if !unsafe {
>> + (*(*dev.as_raw()).p).rust.pm_registration_data
>> + }.is_null() {
>> + return Err(EBUSY);
>> + }
>> + },
>> + inner <- try_pin_init!(PMContextInner {
>> + dev,
>> + state: Atomic::new(PMContextState::Disabled),
>> + guard <- new_srcu!("rpm"),
>> + profiles: profiles.unwrap_or_default(),
>> + configs: configs.unwrap_or_default(),
>> + _marker: PhantomData,
>> + }),
>> + ctx : PMContext { inner: inner.get_ref(), },
>> + data <- try_pin_init!(RegistrationData {
>> + data <- data,
>> + payload: Payload {in_flight: AtomicFlag::new(false), inner: UnsafeCell::new(ManuallyDrop::new(initial_payload))},
>> + _marker: PhantomData
>> + }? E),
>> + _: {
>> + let ptr: NonNull<RegistrationData<'a, T>> =
>> + NonNull::from(data.as_ref().get_ref());
>> + // SAFETY: The device is not yet registered, and neither is
>> + // the runtime pm beingenabled - as such, there is no
>> + // cuncurency here
>> + unsafe {
>> + (*(*dev.as_raw()).p).rust.pm_registration_data =
>> + ptr.cast::<core::ffi::c_void>().as_ptr();
>> + };
>> +
>> + }
>> + })
>> +
>> + }
>> + /// Returns the runtime PM context associated with this registration.
>> + pub fn get_ctx(&self) -> PMContext<'_, 'a, T> {
>> + PMContext{ inner: &self.inner }
>> + }
>> +}
>> +
>> +#[pinned_drop]
>> +impl<'a, T: PMOps> PinnedDrop for Registration<'a, T> {
>> + fn drop(self: Pin<&mut Self>) {
>> + // `self.inner.dev` is the device this registration was
>> + // created for. Runtime PM is disabled first, and `pm_runtime_barrier`
>> + // waits for pending runtime PM work/callbacks before the callback data
>> + // is removed below.
>> + // Furthermore, prevent any stale `PMContext`s from re-enabling runtime
>> + // PM after teardown starts.
>> + let prev = self.inner.state.xchg(PMContextState::Closing, ordering::Full);
>> +
>> + self.inner.guard.synchronize();
>> +
>> + if prev == PMContextState::Enabled {
>> + Request::runtime_disable(self.inner.dev);
>> + PMContext::<T>::reset_config(self.inner.dev, &self.inner.configs);
>> + }
>> +
>> + Request::barrier(self.inner.dev);
>> +
>> + // SAFETY: The pointer was stored by `Registration::new`.
>> + // Runtime PM has been disabled and drained above, so generated
>> + // callbacks can no longer borrow this data.
>> + unsafe {
>> + (*(*self.inner.dev.as_raw()).p).rust.pm_registration_data = core::ptr::null_mut();
>> + }
>> + }
>> +}
>> --
^ permalink raw reply [flat|nested] 6+ messages in thread
end of thread, other threads:[~2026-11-28 0:37 UTC | newest]
Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-24 11:34 [PATCH v6 0/3] Rust: add runtime PM support Beata Michalska
2026-11-24 11:34 ` [PATCH v6 1/3] rust: " Beata Michalska
2026-11-27 20:08 ` Rafael J. Wysocki (Intel)
2026-11-28 0:37 ` Danilo Krummrich
2026-11-24 11:34 ` [PATCH v6 2/3] rust: platform: wire runtime PM callbacks Beata Michalska
2026-11-24 11:34 ` [PATCH v6 3/3 DO NOT MERGE] drm/tyr: enable runtime PM Beata Michalska
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®