Skip to contentSkip to conversation

rust: device: Higher-Ranked Lifetime Types for device drivers

PATCH Superseded Danilo Krummrich 4 participants 33 messages May 6 – May 11

Subsystems (18)
DRM drivers USB PCI Driver core +14 more subsystems

v2 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

v2 cover rust: device: Higher-Ranked Lifetime Types for device drivers

Currently, Rust device drivers access device resources such as PCI BAR mappings and I/O memory regions through Devres<T>.

Devres::access() provides zero-overhead access by taking a &Device<Bound> reference as proof that the device is still bound. Since a &Device<Bound> is available in almost all contexts by design, Devres is mostly a type-system level proof that the resource is valid, but it can also be used from scopes without this guarantee through its try_access() accessor.

This works well in general, but has a few limitations:

- Every access to a device resource goes through Devres::access(), which despite zero cost, adds boilerplate to every access site.

- Destructors do not receive a &Device<Bound>, so they must use try_access(), which can fail. In practice the access succeeds if teardown ordering is correct, but the type system can't express this, forcing drivers to handle a failure path that should never be taken.

- Sharing a resource across components (e.g. passing a BAR to a sub-component) requires Arc<Devres<T>>.

- Device references must be stored as ARef<Device> rather than plain &Device borrows.

These limitations stem from the driver's bus device private data being 'static -- the driver struct cannot borrow from the device reference it receives in probe(), even though it structurally cannot outlive the device binding.

This series introduces Higher-Ranked Lifetime Types (HRT) for Rust device drivers. An HRT is a type that is generic over a lifetime -- it does not have a fixed lifetime, but can be instantiated with any lifetime chosen by the caller.

Rust does not directly support types that are generic over a lifetime as type parameters; the ForLt trait (contributed by Gary Guo) encodes this internally.

The module_*_driver! macros handle the wrapping, so driver authors just write struct MyDriver<'a> and impl Driver<'a>.

With HRT, driver structs carry a lifetime parameter tied to the device binding scope -- the interval of a bus device being bound to a driver. Device resources like pci::Bar<'a> and IoMem<'a> are handed out with this lifetime, so the compiler enforces at build time that they do not escape the binding scope.

Before:

	struct MyDriver {
	    pdev: ARef<pci::Device>,
	    bar: Devres<pci::Bar<BAR_SIZE>>,
	}

	let io = self.bar.access(dev)?;
	io.read32(OFFSET);

After:

	struct MyDriver<'a> {
	    pdev: &'a pci::Device,
	    bar: pci::Bar<'a, BAR_SIZE>,
	}

	self.bar.read32(OFFSET);

Lifetime-parameterized device resources can be put into a Devres at any point via Bar::into_devres() / IoMem::into_devres(), providing the exact same semantics as before. This is useful for resources shared across subsystem boundaries where revocation is needed.

This also synergizes with the upcoming self-referential initialization support in pin-init, which allows one field of the driver struct to borrow another during initialization without unsafe code.

The same pattern is applied to auxiliary device registration data as a first example beyond bus device private data. Registration<F: ForLt> can hold lifetime-parameterized data tied to the parent driver's binding scope. Since the auxiliary bus guarantees that the parent remains bound while the auxiliary device is registered, the registration data can safely borrow the parent's device resources.

More generally, binding resource lifetimes to a registration scope applies to every registration that is scoped to a driver binding -- auxiliary devices, class devices, IRQ handlers, workqueues.

A follow-up series extends this to class device registrations, starting with DRM, so that class device callbacks (IOCTLs, etc.) can safely access device resources through the separate registration data bound to the registration's lifetime without Devres indirection.

The series contains a few driver patches for reference, indicated by the REF suffix.

Thanks to Gary for coming up with the ForLt implementation; thanks to Alice for the early discussions around lifetime-parameterized private data that helped shape the direction of this work.

This series depends on [1].

[1] https://lore.kernel.org/driver-core/[email protected]/

Changes in v2:
- Add 'a bound to ForLt::Of<'a> and WithLt::Of, making the lifetime bound inherent to the trait; remove all F::Of<'static>: 'static where clauses
- Drop "rust: devres: add ForLt support to Devres"; Devres itself stays unchanged -- ForLt-aware access is introduced later through DevresLt in a separate series
- Use 'bound instead of 'a; add patches to consistently use 'bound for pre-existing 'a

Danilo Krummrich (24):
rust: driver core: drop drvdata before devres release
rust: device: generalize drvdata methods over ForLt
rust: driver: make Adapter trait lifetime-parameterized
rust: pci: implement Sync for Device<Bound>
rust: platform: implement Sync for Device<Bound>
rust: auxiliary: implement Sync for Device<Bound>
rust: usb: implement Sync for Device<Bound>
rust: device: implement Sync for Device<Bound>
rust: pci: make Driver trait lifetime-parameterized
rust: platform: make Driver trait lifetime-parameterized
rust: auxiliary: make Driver trait lifetime-parameterized
rust: auxiliary: generalize Registration over ForLt
samples: rust: rust_driver_auxiliary: showcase lifetime-bound
registration data
rust: usb: make Driver trait lifetime-parameterized
rust: i2c: make Driver trait lifetime-parameterized
rust: pci: make Bar lifetime-parameterized
rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
samples: rust: rust_driver_pci: use HRT lifetime for Bar
rust: driver-core: rename 'a lifetime to 'bound
gpu: nova-core: rename 'a lifetime to 'bound
gpu: nova-core: use HRT lifetime for Bar
gpu: nova-core: unregister sysmem flush page from Drop
gpu: nova-core: replace ARef<Device> with &'bound Device in
SysmemFlush
gpu: drm: tyr: use HRT lifetime for IoMem

Gary Guo (1):
rust: types: add ForLt trait for higher-ranked lifetime support

 drivers/base/dd.c                        |   2 +-
 drivers/cpufreq/rcpufreq_dt.rs           |  10 +-
 drivers/gpu/drm/nova/driver.rs           |   9 +-
 drivers/gpu/drm/tyr/driver.rs            |  24 ++-
 drivers/gpu/drm/tyr/gpu.rs               |  62 +++---
 drivers/gpu/drm/tyr/regs.rs              |  21 +-
 drivers/gpu/nova-core/driver.rs          |  48 ++---
 drivers/gpu/nova-core/fb.rs              |  31 ++-
 drivers/gpu/nova-core/firmware/gsp.rs    |   8 +-
 drivers/gpu/nova-core/gpu.rs             |  38 ++--
 drivers/gpu/nova-core/gsp/commands.rs    |  10 +-
 drivers/gpu/nova-core/gsp/fw/commands.rs |   4 +-
 drivers/gpu/nova-core/nova_core.rs       |   4 +-
 drivers/pwm/pwm_th1520.rs                |  14 +-
 include/linux/device/driver.h            |   4 +-
 rust/Makefile                            |   1 +
 rust/kernel/auxiliary.rs                 | 132 +++++++++----
 rust/kernel/cpufreq.rs                   |   8 +-
 rust/kernel/device.rs                    |  79 +++++---
 rust/kernel/devres.rs                    |  16 +-
 rust/kernel/driver.rs                    |  44 +++--
 rust/kernel/i2c.rs                       | 130 +++++++-----
 rust/kernel/io/mem.rs                    | 131 ++++++------
 rust/kernel/pci.rs                       |  89 ++++++---
 rust/kernel/pci/io.rs                    |  68 ++++---
 rust/kernel/pci/irq.rs                   |  38 ++--
 rust/kernel/platform.rs                  | 120 +++++++----
 rust/kernel/types.rs                     |   4 +
 rust/kernel/types/for_lt.rs              | 117 +++++++++++
 rust/kernel/usb.rs                       |  94 +++++----
 rust/macros/for_lt.rs                    | 242 +++++++++++++++++++++++
 rust/macros/lib.rs                       |  12 ++
 samples/rust/rust_debugfs.rs             |  10 +-
 samples/rust/rust_dma.rs                 |   9 +-
 samples/rust/rust_driver_auxiliary.rs    |  53 +++--
 samples/rust/rust_driver_i2c.rs          |  18 +-
 samples/rust/rust_driver_pci.rs          |  93 ++++-----
 samples/rust/rust_driver_platform.rs     |  12 +-
 samples/rust/rust_driver_usb.rs          |  14 +-
 samples/rust/rust_i2c_client.rs          |  12 +-
 samples/rust/rust_soc.rs                 |  12 +-
 41 files changed, 1220 insertions(+), 627 deletions(-)
 create mode 100644 rust/kernel/types/for_lt.rs
 create mode 100644 rust/macros/for_lt.rs
Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH v2 1/25 rust: driver core: drop drvdata before devres release

Move the post_unbind_rust callback before devres_release_all() in device_unbind_cleanup().

With drvdata() removed, the driver's bus device private data is only accessible by the owning driver itself. It is hence safe to drop the driver's bus device private data before devres actions are released.

This reordering is the key enabler for Higher-Ranked Lifetime Types (HRT) in Rust device drivers -- it allows driver structs to hold direct references to devres-managed resources, because the bus device private data (and with it all such references) is guaranteed to be dropped while the underlying devres resources are still alive.

Without this change, devres resources would be freed first, leaving the driver's bus device private data with dangling references during its destructor.

---
 drivers/base/dd.c             | 2 +-
 include/linux/device/driver.h | 4 ++--
 rust/kernel/driver.rs         | 4 ++--
 3 files changed, 5 insertions(+), 5 deletions(-)
drivers/base/dd.c +1 -1
index 5799a60fd058..be59d2e13a15 100644
@@ -593,9 +593,9 @@ static DEVICE_ATTR_RW(state_synced);
 
 static void device_unbind_cleanup(struct device *dev)
 {
-	devres_release_all(dev);
 	if (dev->driver->p_cb.post_unbind_rust)
 		dev->driver->p_cb.post_unbind_rust(dev);
+	devres_release_all(dev);
 	arch_teardown_dma_ops(dev);
 	kfree(dev->dma_range_map);
 	dev->dma_range_map = NULL;
include/linux/device/driver.h +2 -2
index bbc67ec513ed..38e9a4679447 100644
@@ -123,8 +123,8 @@ struct device_driver {
 	struct driver_private *p;
 	struct {
 		/*
-		 * Called after remove() and after all devres entries have been
-		 * processed. This is a Rust only callback.
+		 * Called after remove() but before devres entries are released.
+		 * This is a Rust only callback.
 		 */
 		void (*post_unbind_rust)(struct device *dev);
 	} p_cb;
rust/kernel/driver.rs +2 -2
index 93e5dd6ae371..bb53035a1017 100644
@@ -189,8 +189,8 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::device) {
         // INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`.
         let dev = unsafe { &*dev.cast::<device::Device<device::CoreInternal>>() };
 
-        // `remove()` and all devres callbacks have been completed at this point, hence drop the
-        // driver's device private data.
+        // `remove()` has been completed at this point; devres resources are still valid and will
+        // be released after the driver's bus device private data is dropped.
         //
         // SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the
         // driver's device private data type.
Signature · 1 line
2.54.0
author maintainer
#2 lore raw

PATCH v2 2/25 rust: types: add `ForLt` trait for higher-ranked lifetime support

In reply to Danilo Krummrich

From: Gary Guo <[email protected]>

There are a few cases, e.g. when dealing with data referencing each other, one might want to write code that are generic over lifetimes. For example, if you want take a function that takes &'a Foo and gives Bar<'a>, you can write:

    f: impl for<'a> FnOnce(&'a Foo) -> Bar<'a>,

However, it becomes tricky when you want that function to not have a fixed Bar, but have it be generic again. In this case, one needs something that is generic over types that are themselves generic over lifetimes.

ForLt provides such support. It provides a trait ForLt which describes a type generic over lifetime. One may use ForLt::Of<'a> to get an instance of a type for a specific lifetime.

For the case of cross referencing, one would almost always want the lifetime to be covariant. Therefore this is also made a requirement for the ForLt trait, so functions with ForLt trait bound can assume covariance.

A macro ForLt!() is provided to be able to obtain a type that implements ForLt. For example, ForLt!(for<'a> Bar<'a>) would yield a type that <TheType as ForLt>::Of<'a> is Bar<'a>. This also works with lifetime elision, e.g. ForLt!(Bar<'_>) or for types without lifetime at all, e.g. ForLt!(u32).

The API design draws inspiration from the higher-kinded-types [1] crate, however different design decision has been taken (e.g. covariance requirement) and the implementation is independent.

License headers use "Apache-2.0 OR MIT" because I anticipate this to be used in pin-init crate too which is licensed as such.

---
 rust/Makefile               |   1 +
 rust/kernel/types.rs        |   4 +
 rust/kernel/types/for_lt.rs | 117 +++++++++++++++++
 rust/macros/for_lt.rs       | 242 ++++++++++++++++++++++++++++++++++++
 rust/macros/lib.rs          |  12 ++
 5 files changed, 376 insertions(+)
 create mode 100644 rust/kernel/types/for_lt.rs
 create mode 100644 rust/macros/for_lt.rs
rust/Makefile +1 -0
index b361bfedfdf0..c5a9a3339416 100644
@@ -110,6 +110,7 @@ syn-cfgs := \
     feature="parsing" \
     feature="printing" \
     feature="proc-macro" \
+    feature="visit" \
     feature="visit-mut"
 
 syn-flags := \
rust/kernel/types.rs +4 -0
index 4329d3c2c2e5..3119401dcb9f 100644
@@ -11,6 +11,10 @@
 };
 use pin_init::{PinInit, Wrapper, Zeroable};
 
+#[doc(hidden)]
+pub mod for_lt;
+pub use for_lt::ForLt;
+
 /// Used to transfer ownership to and from foreign (non-Rust) languages.
 ///
 /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and
rust/kernel/types/for_lt.rs new file +117 -0

117 lines not on this page · raw message

rust/macros/for_lt.rs new file +242 -0

242 lines not on this page · raw message

rust/macros/lib.rs +12 -0
index 2cfd59e0f9e7..e5f6f8318112 100644
@@ -17,6 +17,7 @@
 mod concat_idents;
 mod export;
 mod fmt;
+mod for_lt;
 mod helpers;
 mod kunit;
 mod module;
@@ -489,3 +490,14 @@ pub fn kunit_tests(attr: TokenStream, input: TokenStream) -> TokenStream {
         .unwrap_or_else(|e| e.into_compile_error())
         .into()
 }
+
+/// Obtain a type that implements `ForLt` for the given higher-ranked type.
+///
+/// Please refer to the documentation of [`ForLt`] trait.
+///
+/// [`ForLt`]: trait.ForLt.html
+#[proc_macro]
+#[allow(non_snake_case)] // The macro shares the name with the trait.
+pub fn ForLt(input: TokenStream) -> TokenStream {
+    for_lt::for_lt(parse_macro_input!(input)).into()
+}
Signature · 1 line
2.54.0
author maintainer
#4 lore raw

PATCH v2 3/25 rust: device: generalize drvdata methods over ForLt

In reply to Danilo Krummrich

Generalize set_drvdata(), drvdata_obtain() and drvdata_borrow() to take
F: ForLt, enabling Higher-Ranked Lifetime Types (HRT) for device private data.

The data is initialized as F::Of<'bound> and stored as F::Of<'static>; ForLt guarantees covariance, making it sound to shorten the stored 'static lifetime to the borrow lifetime of &self.

---
 rust/kernel/auxiliary.rs |  7 ++--
 rust/kernel/device.rs    | 75 ++++++++++++++++++++++++++++------------
 rust/kernel/driver.rs    | 15 +++++---
 rust/kernel/i2c.rs       | 13 ++++---
 rust/kernel/pci.rs       | 11 +++---
 rust/kernel/platform.rs  | 11 +++---
 rust/kernel/usb.rs       | 11 +++---
 7 files changed, 96 insertions(+), 47 deletions(-)
rust/kernel/auxiliary.rs +4 -3
index 19aec94aa95b..37690fa14891 100644
@@ -20,6 +20,7 @@
     },
     prelude::*,
     types::{
+        ForLt,
         ForeignOwnable,
         Opaque, //
     },
@@ -46,7 +47,7 @@
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
 unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
     type DriverType = bindings::auxiliary_driver;
-    type DriverData = T;
+    type DriverData = ForLt!(T);
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
@@ -97,7 +98,7 @@ extern "C" fn probe_callback(
         from_result(|| {
             let data = T::probe(adev, info);
 
-            adev.as_ref().set_drvdata(data)?;
+            adev.as_ref().set_drvdata::<ForLt!(T)>(data)?;
             Ok(0)
         })
     }
@@ -112,7 +113,7 @@ extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {
         // SAFETY: `remove_callback` is only ever called after a successful call to
         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
         // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { adev.as_ref().drvdata_borrow::<T>() };
+        let data = unsafe { adev.as_ref().drvdata_borrow::<ForLt!(T)>() };
 
         T::unbind(adev, data);
     }
rust/kernel/device.rs +53 -22

124 lines not on this page · raw message

rust/kernel/driver.rs +10 -5
index bb53035a1017..2ab3c0050117 100644
@@ -99,7 +99,10 @@
     device,
     of,
     prelude::*,
-    types::Opaque,
+    types::{
+        ForLt,
+        Opaque, //
+    },
     ThisModule, //
 };
 
@@ -112,14 +115,16 @@
 ///
 /// Implementors must guarantee that:
 /// - `DriverType` is `repr(C)`,
-/// - `DriverData` is the type of the driver's device private data.
+/// - `DriverData` is the [`ForLt`] encoding of the driver's device private data type.
 /// - `DriverType` embeds a valid `struct device_driver` at byte offset `DEVICE_DRIVER_OFFSET`.
+///
+/// [`ForLt`]: trait@ForLt
 pub unsafe trait DriverLayout {
     /// The specific driver type embedding a `struct device_driver`.
     type DriverType: Default;
 
-    /// The type of the driver's device private data.
-    type DriverData;
+    /// The [`ForLt`](trait@ForLt) encoding of the driver's device private data type.
+    type DriverData: ForLt;
 
     /// Byte offset of the embedded `struct device_driver` within `DriverType`.
     ///
@@ -193,7 +198,7 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::device) {
         // be released after the driver's bus device private data is dropped.
         //
         // SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the
-        // driver's device private data type.
+        // ForLt encoding of the driver's device private data type.
         drop(unsafe { dev.drvdata_obtain::<T::DriverData>() });
     }
 
rust/kernel/i2c.rs +8 -5
index 7b908f0c5a58..cde3dd7a6cc7 100644
@@ -20,7 +20,10 @@
         ARef,
         AlwaysRefCounted, //
     },
-    types::Opaque, //
+    types::{
+        ForLt,
+        Opaque, //
+    }, //
 };
 
 use core::{
@@ -98,7 +101,7 @@ macro_rules! i2c_device_table {
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
 unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
     type DriverType = bindings::i2c_driver;
-    type DriverData = T;
+    type DriverData = ForLt!(T);
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
@@ -165,7 +168,7 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_
         from_result(|| {
             let data = T::probe(idev, info);
 
-            idev.as_ref().set_drvdata(data)?;
+            idev.as_ref().set_drvdata::<ForLt!(T)>(data)?;
             Ok(0)
         })
     }
@@ -177,7 +180,7 @@ extern "C" fn remove_callback(idev: *mut bindings::i2c_client) {
         // SAFETY: `remove_callback` is only ever called after a successful call to
         // `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called
         // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { idev.as_ref().drvdata_borrow::<T>() };
+        let data = unsafe { idev.as_ref().drvdata_borrow::<ForLt!(T)>() };
 
         T::unbind(idev, data);
     }
@@ -189,7 +192,7 @@ extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {
         // SAFETY: `shutdown_callback` is only ever called after a successful call to
         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
         // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { idev.as_ref().drvdata_borrow::<T>() };
+        let data = unsafe { idev.as_ref().drvdata_borrow::<ForLt!(T)>() };
 
         T::shutdown(idev, data);
     }
rust/kernel/pci.rs +7 -4
index af74ddff6114..fe5148f41d8b 100644
@@ -19,7 +19,10 @@
     },
     prelude::*,
     str::CStr,
-    types::Opaque,
+    types::{
+        ForLt,
+        Opaque, //
+    },
     ThisModule, //
 };
 use core::{
@@ -64,7 +67,7 @@
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
 unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
     type DriverType = bindings::pci_driver;
-    type DriverData = T;
+    type DriverData = ForLt!(T);
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
@@ -115,7 +118,7 @@ extern "C" fn probe_callback(
         from_result(|| {
             let data = T::probe(pdev, info);
 
-            pdev.as_ref().set_drvdata(data)?;
+            pdev.as_ref().set_drvdata::<ForLt!(T)>(data)?;
             Ok(0)
         })
     }
@@ -130,7 +133,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {
         // SAFETY: `remove_callback` is only ever called after a successful call to
         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
         // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { pdev.as_ref().drvdata_borrow::<T>() };
+        let data = unsafe { pdev.as_ref().drvdata_borrow::<ForLt!(T)>() };
 
         T::unbind(pdev, data);
     }
rust/kernel/platform.rs +7 -4
index 8917d4ee499f..7ff69e3eea90 100644
@@ -27,7 +27,10 @@
     },
     of,
     prelude::*,
-    types::Opaque,
+    types::{
+        ForLt,
+        Opaque, //
+    },
     ThisModule, //
 };
 
@@ -50,7 +53,7 @@
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
 unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
     type DriverType = bindings::platform_driver;
-    type DriverData = T;
+    type DriverData = ForLt!(T);
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
@@ -103,7 +106,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff
         from_result(|| {
             let data = T::probe(pdev, info);
 
-            pdev.as_ref().set_drvdata(data)?;
+            pdev.as_ref().set_drvdata::<ForLt!(T)>(data)?;
             Ok(0)
         })
     }
@@ -118,7 +121,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
         // SAFETY: `remove_callback` is only ever called after a successful call to
         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
         // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { pdev.as_ref().drvdata_borrow::<T>() };
+        let data = unsafe { pdev.as_ref().drvdata_borrow::<ForLt!(T)>() };
 
         T::unbind(pdev, data);
     }
rust/kernel/usb.rs +7 -4
index 9c17a672cd27..9b9d3ae41087 100644
@@ -19,7 +19,10 @@
     },
     prelude::*,
     sync::aref::AlwaysRefCounted,
-    types::Opaque,
+    types::{
+        ForLt,
+        Opaque, //
+    },
     ThisModule, //
 };
 use core::{
@@ -41,7 +44,7 @@
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
 unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
     type DriverType = bindings::usb_driver;
-    type DriverData = T;
+    type DriverData = ForLt!(T);
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
@@ -93,7 +96,7 @@ extern "C" fn probe_callback(
             let data = T::probe(intf, id, info);
 
             let dev: &device::Device<device::CoreInternal> = intf.as_ref();
-            dev.set_drvdata(data)?;
+            dev.set_drvdata::<ForLt!(T)>(data)?;
             Ok(0)
         })
     }
@@ -110,7 +113,7 @@ extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) {
         // SAFETY: `disconnect_callback` is only ever called after a successful call to
         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
         // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { dev.drvdata_borrow::<T>() };
+        let data = unsafe { dev.drvdata_borrow::<ForLt!(T)>() };
 
         T::disconnect(intf, data);
     }
Signature · 1 line
2.54.0
author maintainer
#7 lore raw

PATCH v2 4/25 rust: driver: make Adapter trait lifetime-parameterized

In reply to Danilo Krummrich

Parameterize the Adapter trait with a lifetime, changing the id_info(), of_id_info() and acpi_id_info() methods to take &'bound Device<Bound> and return &'bound Self::IdInfo instead of &'static.

This is needed for the ForLt conversion of bus driver traits. Once Driver becomes lifetime-parameterized, its IdInfo associated type may depend on the lifetime parameter. With Adapter<'bound>, the impl can set IdInfo = <F::Of<'bound> as Driver<'bound>>::IdInfo and the lifetime flows through naturally, avoiding the need for transmute.

For the current non-lifetime-parameterized Driver trait, this is a no-op type relaxation; IdInfo is 'static and &'static coerces to &'bound.

---
 rust/kernel/driver.rs   | 16 ++++++++++------
 rust/kernel/i2c.rs      | 10 +++++-----
 rust/kernel/platform.rs |  4 ++--
 3 files changed, 17 insertions(+), 13 deletions(-)
rust/kernel/driver.rs +10 -6
index 2ab3c0050117..e462535f545d 100644
@@ -96,7 +96,11 @@
 
 use crate::{
     acpi,
-    device,
+    device::{
+        self,
+        Bound,
+        Device, //
+    },
     of,
     prelude::*,
     types::{
@@ -192,7 +196,7 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::device) {
         // a `struct device`.
         //
         // INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`.
-        let dev = unsafe { &*dev.cast::<device::Device<device::CoreInternal>>() };
+        let dev = unsafe { &*dev.cast::<Device<device::CoreInternal>>() };
 
         // `remove()` has been completed at this point; devres resources are still valid and will
         // be released after the driver's bus device private data is dropped.
@@ -309,7 +313,7 @@ unsafe fn acpi_of_match_device(
 /// of a device and a driver.
 ///
 /// It provides bus independent functions for device / driver interactions.
-pub trait Adapter {
+pub trait Adapter<'bound> {
     /// The type holding driver private data about each device id supported by the driver.
     type IdInfo: 'static;
 
@@ -319,7 +323,7 @@ pub trait Adapter {
     /// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.
     ///
     /// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].
-    fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
+    fn acpi_id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
         #[cfg(not(CONFIG_ACPI))]
         {
             let _ = dev;
@@ -353,7 +357,7 @@ fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
     /// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.
     ///
     /// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].
-    fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
+    fn of_id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
         let table = Self::of_id_table()?;
 
         #[cfg(not(any(CONFIG_OF, CONFIG_ACPI)))]
@@ -417,7 +421,7 @@ fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
     ///
     /// If this returns `None`, it means that there is no match in any of the ID tables directly
     /// associated with a [`device::Device`].
-    fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
+    fn id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
         let id = Self::acpi_id_info(dev);
         if id.is_some() {
             return id;
rust/kernel/i2c.rs +5 -5
index cde3dd7a6cc7..208c73aa3ce3 100644
@@ -162,8 +162,8 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_
         // INVARIANT: `idev` is valid for the duration of `probe_callback()`.
         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };
 
-        let info =
-            Self::i2c_id_info(idev).or_else(|| <Self as driver::Adapter>::id_info(idev.as_ref()));
+        let info = Self::i2c_id_info(idev)
+            .or_else(|| <Self as driver::Adapter<'_>>::id_info(idev.as_ref()));
 
         from_result(|| {
             let data = T::probe(idev, info);
@@ -198,14 +198,14 @@ extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {
     }
 
     /// The [`i2c::IdTable`] of the corresponding driver.
-    fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter>::IdInfo>> {
+    fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter<'static>>::IdInfo>> {
         T::I2C_ID_TABLE
     }
 
     /// Returns the driver's private data from the matching entry in the [`i2c::IdTable`], if any.
     ///
     /// If this returns `None`, it means there is no match with an entry in the [`i2c::IdTable`].
-    fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::IdInfo> {
+    fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter<'static>>::IdInfo> {
         let table = Self::i2c_id_table()?;
 
         // SAFETY:
@@ -225,7 +225,7 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::Id
     }
 }
 
-impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
+impl<'bound, T: Driver + 'static> driver::Adapter<'bound> for Adapter<T> {
     type IdInfo = T::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
rust/kernel/platform.rs +2 -2
index 7ff69e3eea90..506731a648c2 100644
@@ -101,7 +101,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff
         //
         // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
         let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
-        let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
+        let info = <Self as driver::Adapter<'_>>::id_info(pdev.as_ref());
 
         from_result(|| {
             let data = T::probe(pdev, info);
@@ -127,7 +127,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
     }
 }
 
-impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
+impl<'bound, T: Driver + 'static> driver::Adapter<'bound> for Adapter<T> {
     type IdInfo = T::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
Signature · 1 line
2.54.0
author maintainer
#10 lore raw

PATCH v2 5/25 rust: pci: implement Sync for Device<Bound>

In reply to Danilo Krummrich

Implement Sync for Device<Bound> in addition to Device<Normal>. The underlying struct pci_dev is the same; Bound is a zero-sized type-state marker that does not affect thread safety.

This is needed for pci::Bar to hold &'bound Device<Bound> (required for Bar::into_devres()) while remaining Send.

---
 rust/kernel/pci.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/pci.rs +4 -0
index fe5148f41d8b..6f82f2e6c74f 100644
@@ -526,3 +526,7 @@ unsafe impl Send for Device {}
 // SAFETY: `Device` can be shared among threads because all methods of `Device`
 // (i.e. `Device<Normal>) are thread safe.
 unsafe impl Sync for Device {}
+
+// SAFETY: Same as `Device<Normal>` -- the underlying `struct pci_dev` is the same;
+// `Bound` is a zero-sized type-state marker that does not affect thread safety.
+unsafe impl Sync for Device<device::Bound> {}
Signature · 1 line
2.54.0
author maintainer
#11 lore raw

PATCH v2 6/25 rust: platform: implement Sync for Device<Bound>

In reply to Danilo Krummrich

Device<Bound> uses the same underlying struct platform_device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.

This is needed for drivers to store &'bound platform::Device<Bound> in their HRT private data while remaining Send.

---
 rust/kernel/platform.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/platform.rs +4 -0
index 506731a648c2..aec26307ae68 100644
@@ -564,3 +564,7 @@ unsafe impl Send for Device {}
 // SAFETY: `Device` can be shared among threads because all methods of `Device`
 // (i.e. `Device<Normal>) are thread safe.
 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> {}
Signature · 1 line
2.54.0
author maintainer
#12 lore raw

PATCH v2 7/25 rust: auxiliary: implement Sync for Device<Bound>

In reply to Danilo Krummrich

Device<Bound> uses the same underlying struct auxiliary_device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.

This is needed for drivers to store &'bound auxiliary::Device<Bound> in their HRT private data while remaining Send.

---
 rust/kernel/auxiliary.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/auxiliary.rs +4 -0
index 37690fa14891..e193ba5b7167 100644
@@ -366,6 +366,10 @@ unsafe impl Send for Device {}
 // (i.e. `Device<Normal>) are thread safe.
 unsafe impl Sync for Device {}
 
+// SAFETY: Same as `Device<Normal>` -- the underlying `struct auxiliary_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> {}
+
 /// Wrapper that stores a [`TypeId`] alongside the registration data for runtime type checking.
 #[repr(C)]
 #[pin_data]
Signature · 1 line
2.54.0
author maintainer
#13 lore raw

PATCH v2 8/25 rust: usb: implement Sync for Device<Bound>

In reply to Danilo Krummrich

Device<Bound> uses the same underlying struct usb_device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.

This is needed for drivers to store &'bound usb::Device<Bound> in their HRT private data while remaining Send.

---
 rust/kernel/usb.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/usb.rs +4 -0
index 9b9d3ae41087..442e456fd2d3 100644
@@ -467,6 +467,10 @@ unsafe impl Send for Device {}
 // allow any mutation through a shared reference.
 unsafe impl Sync for Device {}
 
+// SAFETY: Same as `Device<Normal>` -- the underlying `struct usb_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> {}
+
 /// Declares a kernel module that exposes a single USB driver.
 ///
 /// # Examples
Signature · 1 line
2.54.0
author maintainer
#14 lore raw

PATCH v2 9/25 rust: device: implement Sync for Device<Bound>

In reply to Danilo Krummrich

The underlying struct device is the same for all device contexts; Bound is a zero-sized type-state marker that does not affect thread safety. Implement Sync for Device<Bound> with the same safety argument as the existing Device<Normal> implementation.

This is needed for types that hold &'bound Device<Bound>, such as io::mem::IoMem, to be Send.

---
 rust/kernel/device.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/device.rs +4 -0
index cee61638b08c..fbbb297cf2a9 100644
@@ -498,6 +498,10 @@ unsafe impl Send for Device {}
 // synchronization in `struct device`.
 unsafe impl Sync for Device {}
 
+// SAFETY: Same as `Device<Normal>` -- the underlying `struct device` is the same; `Bound` is a
+// zero-sized type-state marker that does not affect thread safety.
+unsafe impl Sync for Device<Bound> {}
+
 /// Marker trait for the context or scope of a bus specific device.
 ///
 /// [`DeviceContext`] is a marker trait for types representing the context of a bus specific
Signature · 1 line
2.54.0
author maintainer
#15 lore raw

PATCH v2 10/25 rust: pci: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

Make pci::Driver take a lifetime parameter 'bound that ties device resources to the binding scope.

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a HRTB bound for<'bound> F::Of<'bound>: Driver<'bound>; module_pci_driver! wraps the driver type in ForLt!() so drivers don't have to.

---
 drivers/gpu/nova-core/driver.rs       |  9 ++-
 drivers/gpu/nova-core/nova_core.rs    |  4 +-
 rust/kernel/pci.rs                    | 80 +++++++++++++++++++--------
 samples/rust/rust_dma.rs              |  9 ++-
 samples/rust/rust_driver_auxiliary.rs | 13 +++--
 samples/rust/rust_driver_pci.rs       | 11 ++--
 6 files changed, 87 insertions(+), 39 deletions(-)
drivers/gpu/nova-core/driver.rs +6 -3
index 8fe484d357f6..d0ccfbc8d0ea 100644
@@ -50,7 +50,7 @@ pub(crate) struct NovaCore {
 kernel::pci_device_table!(
     PCI_TABLE,
     MODULE_PCI_TABLE,
-    <NovaCore as pci::Driver>::IdInfo,
+    <NovaCore as pci::Driver<'_>>::IdInfo,
     [
         // Modern NVIDIA GPUs will show up as either VGA or 3D controllers.
         (
@@ -72,11 +72,14 @@ pub(crate) struct NovaCore {
     ]
 );
 
-impl pci::Driver for NovaCore {
+impl<'bound> pci::Driver<'bound> for NovaCore {
     type IdInfo = ();
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
-    fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> {
+    fn probe(
+        pdev: &'bound pci::Device<Core>,
+        _info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         pin_init::pin_init_scope(move || {
             dev_dbg!(pdev, "Probe Nova Core GPU driver.\n");
 
drivers/gpu/nova-core/nova_core.rs +3 -1
index 04a1fa6b25f8..49c093a0cb42 100644
@@ -7,6 +7,7 @@
     driver::Registration,
     pci,
     prelude::*,
+    types::ForLt,
     InPlaceModule, //
 };
 
@@ -46,8 +47,9 @@ fn drop(&mut self) {
 struct NovaCoreModule {
     // Fields are dropped in declaration order, so `_driver` is dropped first,
     // then `_debugfs_guard` clears `DEBUGFS_ROOT`.
+    #[allow(clippy::type_complexity)]
     #[pin]
-    _driver: Registration<pci::Adapter<driver::NovaCore>>,
+    _driver: Registration<pci::Adapter<ForLt!(driver::NovaCore)>>,
     _debugfs_guard: DebugfsRootGuard,
 }
 
rust/kernel/pci.rs +56 -24

178 lines not on this page · raw message

samples/rust/rust_dma.rs +6 -3
index 129bb4b39c04..e8b3e2e799f3 100644
@@ -52,15 +52,18 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}
 kernel::pci_device_table!(
     PCI_TABLE,
     MODULE_PCI_TABLE,
-    <DmaSampleDriver as pci::Driver>::IdInfo,
+    <DmaSampleDriver as pci::Driver<'_>>::IdInfo,
     [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
 );
 
-impl pci::Driver for DmaSampleDriver {
+impl<'bound> pci::Driver<'bound> for DmaSampleDriver {
     type IdInfo = ();
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
-    fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> {
+    fn probe(
+        pdev: &'bound pci::Device<Core>,
+        _info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         pin_init::pin_init_scope(move || {
             dev_info!(pdev, "Probe DMA test driver.\n");
 
samples/rust/rust_driver_auxiliary.rs +9 -4
index 319ef734c02b..a1b42d30580e 100644
@@ -14,6 +14,7 @@
     driver,
     pci,
     prelude::*,
+    types::ForLt,
     InPlaceModule, //
 };
 
@@ -59,16 +60,19 @@ struct ParentDriver {
 kernel::pci_device_table!(
     PCI_TABLE,
     MODULE_PCI_TABLE,
-    <ParentDriver as pci::Driver>::IdInfo,
+    <ParentDriver as pci::Driver<'_>>::IdInfo,
     [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
 );
 
-impl pci::Driver for ParentDriver {
+impl<'bound> pci::Driver<'bound> for ParentDriver {
     type IdInfo = ();
 
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
-    fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> {
+    fn probe(
+        pdev: &'bound pci::Device<Core>,
+        _info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         Ok(Self {
             _reg0: auxiliary::Registration::new(
                 pdev.as_ref(),
@@ -116,7 +120,8 @@ fn connect(adev: &auxiliary::Device<Bound>) -> Result {
 #[pin_data]
 struct SampleModule {
     #[pin]
-    _pci_driver: driver::Registration<pci::Adapter<ParentDriver>>,
+    #[allow(clippy::type_complexity)]
+    _pci_driver: driver::Registration<pci::Adapter<ForLt!(ParentDriver)>>,
     #[pin]
     _aux_driver: driver::Registration<auxiliary::Adapter<AuxiliaryDriver>>,
 }
samples/rust/rust_driver_pci.rs +7 -4
index 47d3e84fab63..794311691d1e 100644
@@ -77,7 +77,7 @@ struct SampleDriver {
 kernel::pci_device_table!(
     PCI_TABLE,
     MODULE_PCI_TABLE,
-    <SampleDriver as pci::Driver>::IdInfo,
+    <SampleDriver as pci::Driver<'_>>::IdInfo,
     [(
         pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5),
         TestIndex::NO_EVENTFD
@@ -138,12 +138,15 @@ fn config_space(pdev: &pci::Device<Bound>) {
     }
 }
 
-impl pci::Driver for SampleDriver {
+impl<'bound> pci::Driver<'bound> for SampleDriver {
     type IdInfo = TestIndex;
 
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
-    fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Error> {
+    fn probe(
+        pdev: &'bound pci::Device<Core>,
+        info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         pin_init::pin_init_scope(move || {
             let vendor = pdev.vendor_id();
             dev_dbg!(
@@ -174,7 +177,7 @@ fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Er
         })
     }
 
-    fn unbind(pdev: &pci::Device<Core>, this: Pin<&Self>) {
+    fn unbind(pdev: &'bound pci::Device<Core>, this: Pin<&'bound Self>) {
         if let Ok(bar) = this.bar.access(pdev.as_ref()) {
             // Reset pci-testdev by writing a new test index.
             bar.write_reg(regs::TEST::zeroed().with_index(this.index));
Signature · 1 line
2.54.0
author maintainer
#16 lore raw

PATCH v2 11/25 rust: platform: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

Make platform::Driver take a lifetime parameter 'bound that ties device resources to the binding scope.

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a bound for<'bound> F::Of<'bound>: Driver<'bound>; module_platform_driver! wraps the driver type in ForLt!() so drivers don't have to.

---
 drivers/cpufreq/rcpufreq_dt.rs       | 10 +--
 drivers/gpu/drm/tyr/driver.rs        | 10 +--
 drivers/pwm/pwm_th1520.rs            | 10 +--
 rust/kernel/cpufreq.rs               |  8 +--
 rust/kernel/driver.rs                |  9 ++-
 rust/kernel/io/mem.rs                | 16 ++---
 rust/kernel/platform.rs              | 93 ++++++++++++++++++----------
 samples/rust/rust_debugfs.rs         | 10 +--
 samples/rust/rust_driver_platform.rs | 12 ++--
 samples/rust/rust_i2c_client.rs      | 12 ++--
 samples/rust/rust_soc.rs             | 12 ++--
 11 files changed, 117 insertions(+), 85 deletions(-)
drivers/cpufreq/rcpufreq_dt.rs +5 -5
index f17bf64c22e2..f0ad2d115cf3 100644
@@ -195,18 +195,18 @@ fn register_em(policy: &mut cpufreq::Policy) {
 kernel::of_device_table!(
     OF_TABLE,
     MODULE_OF_TABLE,
-    <CPUFreqDTDriver as platform::Driver>::IdInfo,
+    <CPUFreqDTDriver as platform::Driver<'_>>::IdInfo,
     [(of::DeviceId::new(c"operating-points-v2"), ())]
 );
 
-impl platform::Driver for CPUFreqDTDriver {
+impl<'bound> platform::Driver<'bound> for CPUFreqDTDriver {
     type IdInfo = ();
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
 
     fn probe(
-        pdev: &platform::Device<Core>,
-        _id_info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<Core>,
+        _id_info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         cpufreq::Registration::<CPUFreqDTDriver>::new_foreign_owned(pdev.as_ref())?;
         Ok(Self {})
     }
drivers/gpu/drm/tyr/driver.rs +5 -5
index 279710b36a10..96d83605e4b9 100644
@@ -82,21 +82,21 @@ fn issue_soft_reset(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result {
 kernel::of_device_table!(
     OF_TABLE,
     MODULE_OF_TABLE,
-    <TyrPlatformDriverData as platform::Driver>::IdInfo,
+    <TyrPlatformDriverData as platform::Driver<'_>>::IdInfo,
     [
         (of::DeviceId::new(c"rockchip,rk3588-mali"), ()),
         (of::DeviceId::new(c"arm,mali-valhall-csf"), ())
     ]
 );
 
-impl platform::Driver for TyrPlatformDriverData {
+impl<'bound> platform::Driver<'bound> for TyrPlatformDriverData {
     type IdInfo = ();
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
 
     fn probe(
-        pdev: &platform::Device<Core>,
-        _info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<Core>,
+        _info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         let core_clk = Clk::get(pdev.as_ref(), Some(c"core"))?;
         let stacks_clk = OptionalClk::get(pdev.as_ref(), Some(c"stacks"))?;
         let coregroup_clk = OptionalClk::get(pdev.as_ref(), Some(c"coregroup"))?;
drivers/pwm/pwm_th1520.rs +5 -5
index ddd44a5ce497..a7831b4ebe00 100644
@@ -310,18 +310,18 @@ fn drop(self: Pin<&mut Self>) {
 kernel::of_device_table!(
     OF_TABLE,
     MODULE_OF_TABLE,
-    <Th1520PwmPlatformDriver as platform::Driver>::IdInfo,
+    <Th1520PwmPlatformDriver as platform::Driver<'_>>::IdInfo,
     [(of::DeviceId::new(c"thead,th1520-pwm"), ())]
 );
 
-impl platform::Driver for Th1520PwmPlatformDriver {
+impl<'bound> platform::Driver<'bound> for Th1520PwmPlatformDriver {
     type IdInfo = ();
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
 
     fn probe(
-        pdev: &platform::Device<Core>,
-        _id_info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<Core>,
+        _id_info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         let dev = pdev.as_ref();
         let request = pdev.io_request_by_index(0).ok_or(ENODEV)?;
 
rust/kernel/cpufreq.rs +4 -4
index d8d26870bea2..ac59cdfd633c 100644
@@ -886,14 +886,14 @@ fn register_em(_policy: &mut Policy) {
 ///     }
 /// }
 ///
-/// impl platform::Driver for SampleDriver {
+/// impl<'a> platform::Driver<'a> for SampleDriver {
 ///     type IdInfo = ();
 ///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
 ///
 ///     fn probe(
-///         pdev: &platform::Device<Core>,
-///         _id_info: Option<&Self::IdInfo>,
-///     ) -> impl PinInit<Self, Error> {
+///         pdev: &'a platform::Device<Core>,
+///         _id_info: Option<&'a Self::IdInfo>,
+///     ) -> impl PinInit<Self, Error> + 'a {
 ///         cpufreq::Registration::<SampleDriver>::new_foreign_owned(pdev.as_ref())?;
 ///         Ok(Self {})
 ///     }
rust/kernel/driver.rs +6 -3
index e462535f545d..7c5148772697 100644
@@ -13,7 +13,7 @@
 //! The main driver interface is defined by a bus specific driver trait. For instance:
 //!
 //! ```ignore
-//! pub trait Driver: Send {
+//! pub trait Driver<'bound>: Send {
 //!     /// The type holding information about each device ID supported by the driver.
 //!     type IdInfo: 'static;
 //!
@@ -24,10 +24,13 @@
 //!     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
 //!
 //!     /// Driver probe.
-//!     fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> impl PinInit<Self, Error>;
+//!     fn probe(
+//!         dev: &'bound Device<device::Core>,
+//!         id_info: &'bound Self::IdInfo,
+//!     ) -> impl PinInit<Self, Error> + 'bound;
 //!
 //!     /// Driver unbind (optional).
-//!     fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
+//!     fn unbind(dev: &'bound Device<device::Core>, this: Pin<&'bound Self>) {
 //!         let _ = (dev, this);
 //!     }
 //! }
rust/kernel/io/mem.rs +8 -8
index 7dc78d547f7a..fd5292df5870 100644
@@ -60,13 +60,13 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S
     /// };
     /// struct SampleDriver;
     ///
-    /// impl platform::Driver for SampleDriver {
+    /// impl<'bound> platform::Driver<'bound> for SampleDriver {
     ///    # type IdInfo = ();
     ///
     ///    fn probe(
-    ///       pdev: &platform::Device<Core>,
-    ///       info: Option<&Self::IdInfo>,
-    ///    ) -> impl PinInit<Self, Error> {
+    ///       pdev: &'bound platform::Device<Core>,
+    ///       info: Option<&'bound Self::IdInfo>,
+    ///    ) -> impl PinInit<Self, Error> + 'bound {
     ///       let offset = 0; // Some offset.
     ///
     ///       // If the size is known at compile time, use [`Self::iomap_sized`].
@@ -124,13 +124,13 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(
     /// };
     /// struct SampleDriver;
     ///
-    /// impl platform::Driver for SampleDriver {
+    /// impl<'bound> platform::Driver<'bound> for SampleDriver {
     ///    # type IdInfo = ();
     ///
     ///    fn probe(
-    ///       pdev: &platform::Device<Core>,
-    ///       info: Option<&Self::IdInfo>,
-    ///    ) -> impl PinInit<Self, Error> {
+    ///       pdev: &'bound platform::Device<Core>,
+    ///       info: Option<&'bound Self::IdInfo>,
+    ///    ) -> impl PinInit<Self, Error> + 'bound {
     ///       let offset = 0; // Some offset.
     ///
     ///       // Unlike [`Self::iomap_sized`], here the size of the memory region
rust/kernel/platform.rs +61 -32

200 lines not on this page · raw message

samples/rust/rust_debugfs.rs +5 -5
index 0963efe19f93..ca73c0ef4a79 100644
@@ -111,19 +111,19 @@ fn from_str(s: &str) -> Result<Self> {
 kernel::acpi_device_table!(
     ACPI_TABLE,
     MODULE_ACPI_TABLE,
-    <RustDebugFs as platform::Driver>::IdInfo,
+    <RustDebugFs as platform::Driver<'_>>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), ())]
 );
 
-impl platform::Driver for RustDebugFs {
+impl<'bound> platform::Driver<'bound> for RustDebugFs {
     type IdInfo = ();
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
 
     fn probe(
-        pdev: &platform::Device<Core>,
-        _info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<Core>,
+        _info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         RustDebugFs::new(pdev).pin_chain(|this| {
             this.counter.store(91, Relaxed);
             {
samples/rust/rust_driver_platform.rs +6 -6
index f2229d176fb9..5b7037eb4b3f 100644
@@ -88,26 +88,26 @@ struct SampleDriver {
 kernel::of_device_table!(
     OF_TABLE,
     MODULE_OF_TABLE,
-    <SampleDriver as platform::Driver>::IdInfo,
+    <SampleDriver as platform::Driver<'_>>::IdInfo,
     [(of::DeviceId::new(c"test,rust-device"), Info(42))]
 );
 
 kernel::acpi_device_table!(
     ACPI_TABLE,
     MODULE_ACPI_TABLE,
-    <SampleDriver as platform::Driver>::IdInfo,
+    <SampleDriver as platform::Driver<'_>>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), Info(0))]
 );
 
-impl platform::Driver for SampleDriver {
+impl<'bound> platform::Driver<'bound> for SampleDriver {
     type IdInfo = Info;
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
 
     fn probe(
-        pdev: &platform::Device<Core>,
-        info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<Core>,
+        info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         let dev = pdev.as_ref();
 
         dev_dbg!(dev, "Probe Rust Platform driver sample.\n");
samples/rust/rust_i2c_client.rs +6 -6
index 8d2c12e535b0..e21595a4376e 100644
@@ -88,14 +88,14 @@ struct SampleDriver {
 kernel::of_device_table!(
     OF_TABLE,
     MODULE_OF_TABLE,
-    <SampleDriver as platform::Driver>::IdInfo,
+    <SampleDriver as platform::Driver<'_>>::IdInfo,
     [(of::DeviceId::new(c"test,rust-device"), ())]
 );
 
 kernel::acpi_device_table!(
     ACPI_TABLE,
     MODULE_ACPI_TABLE,
-    <SampleDriver as platform::Driver>::IdInfo,
+    <SampleDriver as platform::Driver<'_>>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), ())]
 );
 
@@ -104,15 +104,15 @@ struct SampleDriver {
 const BOARD_INFO: i2c::I2cBoardInfo =
     i2c::I2cBoardInfo::new(c"rust_driver_i2c", SAMPLE_I2C_CLIENT_ADDR);
 
-impl platform::Driver for SampleDriver {
+impl<'bound> platform::Driver<'bound> for SampleDriver {
     type IdInfo = ();
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
 
     fn probe(
-        pdev: &platform::Device<device::Core>,
-        _info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<device::Core>,
+        _info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         dev_info!(
             pdev.as_ref(),
             "Probe Rust I2C Client registration sample.\n"
samples/rust/rust_soc.rs +6 -6
index 8079c1c48416..356d093bc8dd 100644
@@ -24,26 +24,26 @@ struct SampleSocDriver {
 kernel::of_device_table!(
     OF_TABLE,
     MODULE_OF_TABLE,
-    <SampleSocDriver as platform::Driver>::IdInfo,
+    <SampleSocDriver as platform::Driver<'_>>::IdInfo,
     [(of::DeviceId::new(c"test,rust-device"), ())]
 );
 
 kernel::acpi_device_table!(
     ACPI_TABLE,
     MODULE_ACPI_TABLE,
-    <SampleSocDriver as platform::Driver>::IdInfo,
+    <SampleSocDriver as platform::Driver<'_>>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), ())]
 );
 
-impl platform::Driver for SampleSocDriver {
+impl<'bound> platform::Driver<'bound> for SampleSocDriver {
     type IdInfo = ();
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
 
     fn probe(
-        pdev: &platform::Device<Core>,
-        _info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        pdev: &'bound platform::Device<Core>,
+        _info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         dev_dbg!(pdev, "Probe Rust SoC driver sample.\n");
 
         let pdev = pdev.into();
Signature · 1 line
2.54.0
author maintainer
#17 lore raw

PATCH v2 12/25 rust: auxiliary: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

Make auxiliary::Driver take a lifetime parameter 'bound that ties device resources to the binding scope.

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a bound for<'bound> F::Of<'bound>: Driver<'bound>; module_auxiliary_driver! wraps the driver type in ForLt!() so drivers don't have to.

---
 drivers/gpu/drm/nova/driver.rs        |  9 ++--
 rust/kernel/auxiliary.rs              | 60 ++++++++++++++++++---------
 samples/rust/rust_driver_auxiliary.rs | 12 ++++--
 3 files changed, 55 insertions(+), 26 deletions(-)
drivers/gpu/drm/nova/driver.rs +6 -3
index b1af0a099551..8e28ccad0575 100644
@@ -42,18 +42,21 @@ pub(crate) struct NovaData {
 kernel::auxiliary_device_table!(
     AUX_TABLE,
     MODULE_AUX_TABLE,
-    <NovaDriver as auxiliary::Driver>::IdInfo,
+    <NovaDriver as auxiliary::Driver<'_>>::IdInfo,
     [(
         auxiliary::DeviceId::new(NOVA_CORE_MODULE_NAME, AUXILIARY_NAME),
         ()
     )]
 );
 
-impl auxiliary::Driver for NovaDriver {
+impl<'bound> auxiliary::Driver<'bound> for NovaDriver {
     type IdInfo = ();
     const ID_TABLE: auxiliary::IdTable<Self::IdInfo> = &AUX_TABLE;
 
-    fn probe(adev: &auxiliary::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> {
+    fn probe(
+        adev: &'bound auxiliary::Device<Core>,
+        _info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         let data = try_pin_init!(NovaData { adev: adev.into() });
 
         let drm = drm::Device::<Self>::new(adev.as_ref(), data)?;
rust/kernel/auxiliary.rs +41 -19

129 lines not on this page · raw message

samples/rust/rust_driver_auxiliary.rs +8 -4
index a1b42d30580e..6baeb1dde5da 100644
@@ -26,16 +26,19 @@
 kernel::auxiliary_device_table!(
     AUX_TABLE,
     MODULE_AUX_TABLE,
-    <AuxiliaryDriver as auxiliary::Driver>::IdInfo,
+    <AuxiliaryDriver as auxiliary::Driver<'_>>::IdInfo,
     [(auxiliary::DeviceId::new(MODULE_NAME, AUXILIARY_NAME), ())]
 );
 
-impl auxiliary::Driver for AuxiliaryDriver {
+impl<'bound> auxiliary::Driver<'bound> for AuxiliaryDriver {
     type IdInfo = ();
 
     const ID_TABLE: auxiliary::IdTable<Self::IdInfo> = &AUX_TABLE;
 
-    fn probe(adev: &auxiliary::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> {
+    fn probe(
+        adev: &'bound auxiliary::Device<Core>,
+        _info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         dev_info!(
             adev,
             "Probing auxiliary driver for auxiliary device with id={}\n",
@@ -123,7 +126,8 @@ struct SampleModule {
     #[allow(clippy::type_complexity)]
     _pci_driver: driver::Registration<pci::Adapter<ForLt!(ParentDriver)>>,
     #[pin]
-    _aux_driver: driver::Registration<auxiliary::Adapter<AuxiliaryDriver>>,
+    #[allow(clippy::type_complexity)]
+    _aux_driver: driver::Registration<auxiliary::Adapter<ForLt!(AuxiliaryDriver)>>,
 }
 
 impl InPlaceModule for SampleModule {
Signature · 1 line
2.54.0
author maintainer
#18 lore raw

PATCH v2 13/25 rust: auxiliary: generalize Registration over ForLt

In reply to Danilo Krummrich

Generalize Registration<T> to Registration<F: ForLt> and Device::registration_data<F: ForLt>() to return Pin<&F::Of<'_>>.

The stored 'static lifetime is shortened to the borrow lifetime of &self via ForLt::cast_ref; ForLt's covariance guarantee makes this sound.

---
 drivers/gpu/nova-core/driver.rs       |  4 +-
 rust/kernel/auxiliary.rs              | 67 +++++++++++++++++----------
 samples/rust/rust_driver_auxiliary.rs |  7 +--
 3 files changed, 50 insertions(+), 28 deletions(-)
drivers/gpu/nova-core/driver.rs +3 -1
index d0ccfbc8d0ea..ed154cd93fa8 100644
@@ -21,6 +21,7 @@
         },
         Arc,
     },
+    types::ForLt,
 };
 
 use crate::gpu::Gpu;
@@ -32,7 +33,8 @@
 pub(crate) struct NovaCore {
     #[pin]
     pub(crate) gpu: Gpu,
-    _reg: Devres<auxiliary::Registration<()>>,
+    #[allow(clippy::type_complexity)]
+    _reg: Devres<auxiliary::Registration<ForLt!(())>>,
 }
 
 const BAR0_SIZE: usize = SZ_16M;
rust/kernel/auxiliary.rs +43 -24

144 lines not on this page · raw message

samples/rust/rust_driver_auxiliary.rs +4 -3
index 6baeb1dde5da..de44ba901967 100644
@@ -55,9 +55,10 @@ struct Data {
     index: u32,
 }
 
+#[allow(clippy::type_complexity)]
 struct ParentDriver {
-    _reg0: Devres<auxiliary::Registration<Data>>,
-    _reg1: Devres<auxiliary::Registration<Data>>,
+    _reg0: Devres<auxiliary::Registration<ForLt!(Data)>>,
+    _reg1: Devres<auxiliary::Registration<ForLt!(Data)>>,
 }
 
 kernel::pci_device_table!(
@@ -100,7 +101,7 @@ fn connect(adev: &auxiliary::Device<Bound>) -> Result {
         let dev = adev.parent();
         let pdev: &pci::Device<Bound> = dev.try_into()?;
 
-        let data = adev.registration_data::<Data>()?;
+        let data = adev.registration_data::<ForLt!(Data)>()?;
 
         dev_info!(
             dev,
Signature · 1 line
2.54.0
author maintainer
#19 lore raw

PATCH v2 14/25 samples: rust: rust_driver_auxiliary: showcase lifetime-bound registration data

In reply to Danilo Krummrich

Make the Data struct lifetime-parameterized, storing a reference to the parent pci::Device<Bound>. This demonstrates that registration data can hold device resources tied to the parent driver's lifetime.

In connect(), retrieve the parent PCI device from the registration data rather than casting through adev.parent().

---
 samples/rust/rust_driver_auxiliary.rs | 27 ++++++++++++++++-----------
 1 file changed, 16 insertions(+), 11 deletions(-)
samples/rust/rust_driver_auxiliary.rs +16 -11
index de44ba901967..da445c4cc910 100644
@@ -51,14 +51,15 @@ fn probe(
     }
 }
 
-struct Data {
+struct Data<'bound> {
     index: u32,
+    parent: &'bound pci::Device<Bound>,
 }
 
 #[allow(clippy::type_complexity)]
 struct ParentDriver {
-    _reg0: Devres<auxiliary::Registration<ForLt!(Data)>>,
-    _reg1: Devres<auxiliary::Registration<ForLt!(Data)>>,
+    _reg0: Devres<auxiliary::Registration<ForLt!(Data<'_>)>>,
+    _reg1: Devres<auxiliary::Registration<ForLt!(Data<'_>)>>,
 }
 
 kernel::pci_device_table!(
@@ -83,14 +84,20 @@ fn probe(
                 AUXILIARY_NAME,
                 0,
                 MODULE_NAME,
-                Data { index: 0 },
+                Data {
+                    index: 0,
+                    parent: pdev,
+                },
             )?,
             _reg1: auxiliary::Registration::new(
                 pdev.as_ref(),
                 AUXILIARY_NAME,
                 1,
                 MODULE_NAME,
-                Data { index: 1 },
+                Data {
+                    index: 1,
+                    parent: pdev,
+                },
             )?,
         })
     }
@@ -98,13 +105,11 @@ fn probe(
 
 impl ParentDriver {
     fn connect(adev: &auxiliary::Device<Bound>) -> Result {
-        let dev = adev.parent();
-        let pdev: &pci::Device<Bound> = dev.try_into()?;
-
-        let data = adev.registration_data::<ForLt!(Data)>()?;
+        let data = adev.registration_data::<ForLt!(Data<'_>)>()?;
+        let pdev = data.parent;
 
         dev_info!(
-            dev,
+            pdev,
             "Connect auxiliary {} with parent: VendorID={}, DeviceID={:#x}\n",
             adev.id(),
             pdev.vendor_id(),
@@ -112,7 +117,7 @@ fn connect(adev: &auxiliary::Device<Bound>) -> Result {
         );
 
         dev_info!(
-            dev,
+            pdev,
             "Connected to auxiliary device with index {}.\n",
             data.index
         );
Signature · 1 line
2.54.0
author maintainer
#20 lore raw

PATCH v2 15/25 rust: usb: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

Make usb::Driver take a lifetime parameter 'bound that ties device resources to the binding scope.

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a bound for<'bound> F::Of<'bound>: Driver<'bound>; module_usb_driver! wraps the driver type in ForLt!() so drivers don't have to.

---
 rust/kernel/usb.rs              | 85 ++++++++++++++++++++-------------
 samples/rust/rust_driver_usb.rs | 14 +++---
 2 files changed, 59 insertions(+), 40 deletions(-)
rust/kernel/usb.rs +52 -33
index 442e456fd2d3..450be2b7c542 100644
@@ -35,22 +35,35 @@
 };
 
 /// An adapter for the registration of USB drivers.
-pub struct Adapter<T: Driver>(T);
+///
+/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver's device
+/// private data type, i.e. `F::Of<'bound>` is the driver struct
+/// parameterized by `'bound`. The macro `module_usb_driver!` generates
+/// this automatically via `ForLt!()`.
+pub struct Adapter<F>(PhantomData<F>);
 
 // SAFETY:
 // - `bindings::usb_driver` is a C type declared as `repr(C)`.
-// - `T` is the type of the driver's device private data.
+// - `F::Of<'static>` is the stored type of the driver's device private data.
 // - `struct usb_driver` embeds a `struct device_driver`.
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
-unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
+unsafe impl<F> driver::DriverLayout for Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
+{
     type DriverType = bindings::usb_driver;
-    type DriverData = ForLt!(T);
+    type DriverData = F;
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
 // SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
 // a preceding call to `register` has been successful.
-unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
+unsafe impl<F> driver::RegistrationOps for Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
+{
     unsafe fn register(
         udrv: &Opaque<Self::DriverType>,
         name: &'static CStr,
@@ -61,7 +74,7 @@ unsafe fn register(
             (*udrv.get()).name = name.as_char_ptr();
             (*udrv.get()).probe = Some(Self::probe_callback);
             (*udrv.get()).disconnect = Some(Self::disconnect_callback);
-            (*udrv.get()).id_table = T::ID_TABLE.as_ptr();
+            (*udrv.get()).id_table = <F::Of<'static> as Driver<'static>>::ID_TABLE.as_ptr();
         }
 
         // SAFETY: `udrv` is guaranteed to be a valid `DriverType`.
@@ -76,7 +89,11 @@ unsafe fn unregister(udrv: &Opaque<Self::DriverType>) {
     }
 }
 
-impl<T: Driver + 'static> Adapter<T> {
+impl<F> Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
+{
     extern "C" fn probe_callback(
         intf: *mut bindings::usb_interface,
         id: *const bindings::usb_device_id,
@@ -87,16 +104,16 @@ extern "C" fn probe_callback(
         // INVARIANT: `intf` is valid for the duration of `probe_callback()`.
         let intf = unsafe { &*intf.cast::<Interface<device::CoreInternal>>() };
 
-        from_result(|| {
-            // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct usb_device_id` and
-            // does not add additional invariants, so it's safe to transmute.
-            let id = unsafe { &*id.cast::<DeviceId>() };
+        // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct usb_device_id` and
+        // does not add additional invariants, so it's safe to transmute.
+        let id = unsafe { &*id.cast::<DeviceId>() };
 
-            let info = T::ID_TABLE.info(id.index());
-            let data = T::probe(intf, id, info);
+        from_result(|| {
+            let info = <F::Of<'_> as Driver<'_>>::ID_TABLE.info(id.index());
+            let data = <F::Of<'_> as Driver<'_>>::probe(intf, id, info);
 
             let dev: &device::Device<device::CoreInternal> = intf.as_ref();
-            dev.set_drvdata::<ForLt!(T)>(data)?;
+            dev.set_drvdata::<F>(data)?;
             Ok(0)
         })
     }
@@ -111,11 +128,10 @@ extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) {
         let dev: &device::Device<device::CoreInternal> = intf.as_ref();
 
         // SAFETY: `disconnect_callback` is only ever called after a successful call to
-        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
-        // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { dev.drvdata_borrow::<ForLt!(T)>() };
+        // `probe_callback`, hence it's guaranteed that drvdata has been set.
+        let data = unsafe { dev.drvdata_borrow::<F>() };
 
-        T::disconnect(intf, data);
+        <F::Of<'_> as Driver<'_>>::disconnect(intf, data);
     }
 }
 
@@ -281,29 +297,29 @@ macro_rules! usb_device_table {
 /// kernel::usb_device_table!(
 ///     USB_TABLE,
 ///     MODULE_USB_TABLE,
-///     <MyDriver as usb::Driver>::IdInfo,
+///     <MyDriver as usb::Driver<'_>>::IdInfo,
 ///     [
 ///         (usb::DeviceId::from_id(0x1234, 0x5678), ()),
 ///         (usb::DeviceId::from_id(0xabcd, 0xef01), ()),
 ///     ]
 /// );
 ///
-/// impl usb::Driver for MyDriver {
+/// impl<'bound> usb::Driver<'bound> for MyDriver {
 ///     type IdInfo = ();
 ///     const ID_TABLE: usb::IdTable<Self::IdInfo> = &USB_TABLE;
 ///
 ///     fn probe(
-///         _interface: &usb::Interface<Core>,
-///         _id: &usb::DeviceId,
-///         _info: &Self::IdInfo,
-///     ) -> impl PinInit<Self, Error> {
+///         _interface: &'bound usb::Interface<Core>,
+///         _id: &'bound usb::DeviceId,
+///         _info: &'bound Self::IdInfo,
+///     ) -> impl PinInit<Self, Error> + 'bound {
 ///         Err(ENODEV)
 ///     }
 ///
-///     fn disconnect(_interface: &usb::Interface<Core>, _data: Pin<&Self>) {}
+///     fn disconnect(_interface: &'bound usb::Interface<Core>, _data: Pin<&'bound Self>) {}
 /// }
 ///```
-pub trait Driver {
+pub trait Driver<'bound> {
     /// The type holding information about each one of the device ids supported by the driver.
     type IdInfo: 'static;
 
@@ -315,15 +331,15 @@ pub trait Driver {
     /// Called when a new USB interface is bound to this driver.
     /// Implementers should attempt to initialize the interface here.
     fn probe(
-        interface: &Interface<device::Core>,
-        id: &DeviceId,
-        id_info: &Self::IdInfo,
-    ) -> impl PinInit<Self, Error>;
+        interface: &'bound Interface<device::Core>,
+        id: &'bound DeviceId,
+        id_info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound;
 
     /// USB driver disconnect.
     ///
     /// Called when the USB interface is about to be unbound from this driver.
-    fn disconnect(interface: &Interface<device::Core>, data: Pin<&Self>);
+    fn disconnect(interface: &'bound Interface<device::Core>, data: Pin<&'bound Self>);
 }
 
 /// A USB interface.
@@ -486,7 +502,10 @@ unsafe impl Sync for Device<device::Bound> {}
 /// ```
 #[macro_export]
 macro_rules! module_usb_driver {
-    ($($f:tt)*) => {
-        $crate::module_driver!(<T>, $crate::usb::Adapter<T>, { $($f)* });
+    (type: $type:ty, $($rest:tt)*) => {
+        $crate::module_driver!(<T>, $crate::usb::Adapter<T>, {
+            type: $crate::types::ForLt!($type),
+            $($rest)*
+        });
     }
 }
samples/rust/rust_driver_usb.rs +7 -7
index ab72e99e1274..271aaf415795 100644
@@ -20,26 +20,26 @@ struct SampleDriver {
 kernel::usb_device_table!(
     USB_TABLE,
     MODULE_USB_TABLE,
-    <SampleDriver as usb::Driver>::IdInfo,
+    <SampleDriver as usb::Driver<'_>>::IdInfo,
     [(usb::DeviceId::from_id(0x1234, 0x5678), ()),]
 );
 
-impl usb::Driver for SampleDriver {
+impl<'bound> usb::Driver<'bound> for SampleDriver {
     type IdInfo = ();
     const ID_TABLE: usb::IdTable<Self::IdInfo> = &USB_TABLE;
 
     fn probe(
-        intf: &usb::Interface<Core>,
-        _id: &usb::DeviceId,
-        _info: &Self::IdInfo,
-    ) -> impl PinInit<Self, Error> {
+        intf: &'bound usb::Interface<Core>,
+        _id: &'bound usb::DeviceId,
+        _info: &'bound Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'bound {
         let dev: &device::Device<Core> = intf.as_ref();
         dev_info!(dev, "Rust USB driver sample probed\n");
 
         Ok(Self { _intf: intf.into() })
     }
 
-    fn disconnect(intf: &usb::Interface<Core>, _data: Pin<&Self>) {
+    fn disconnect(intf: &'bound usb::Interface<Core>, _data: Pin<&'bound Self>) {
         let dev: &device::Device<Core> = intf.as_ref();
         dev_info!(dev, "Rust USB driver sample disconnected\n");
     }
Signature · 1 line
2.54.0
author maintainer
#21 lore raw

PATCH v2 16/25 rust: i2c: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

Make i2c::Driver take a lifetime parameter 'bound that ties device resources to the binding scope.

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a bound for<'bound> F::Of<'bound>: Driver<'bound>; module_i2c_driver! wraps the driver type in ForLt!() so drivers don't have to.

---
 rust/kernel/i2c.rs              | 119 +++++++++++++++++++-------------
 samples/rust/rust_driver_i2c.rs |  18 ++---
 2 files changed, 81 insertions(+), 56 deletions(-)
rust/kernel/i2c.rs +72 -47
index 208c73aa3ce3..2216b49604b2 100644
@@ -92,43 +92,58 @@ macro_rules! i2c_device_table {
 }
 
 /// An adapter for the registration of I2C drivers.
-pub struct Adapter<T: Driver>(T);
+///
+/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver's device
+/// private data type, i.e. `F::Of<'bound>` is the driver struct
+/// parameterized by `'bound`. The macro `module_i2c_driver!` generates
+/// this automatically via `ForLt!()`.
+pub struct Adapter<F>(PhantomData<F>);
 
 // SAFETY:
 // - `bindings::i2c_driver` is a C type declared as `repr(C)`.
-// - `T` is the type of the driver's device private data.
+// - `F::Of<'static>` is the stored type of the driver's device private data.
 // - `struct i2c_driver` embeds a `struct device_driver`.
 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
-unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
+unsafe impl<F> driver::DriverLayout for Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
+{
     type DriverType = bindings::i2c_driver;
-    type DriverData = ForLt!(T);
+    type DriverData = F;
     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
 }
 
 // SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
 // a preceding call to `register` has been successful.
-unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
+unsafe impl<F> driver::RegistrationOps for Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
+{
     unsafe fn register(
         idrv: &Opaque<Self::DriverType>,
         name: &'static CStr,
         module: &'static ThisModule,
     ) -> Result {
         build_assert!(
-            T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I2C_ID_TABLE.is_some(),
+            <F::Of<'static> as Driver<'static>>::ACPI_ID_TABLE.is_some()
+                || <F::Of<'static> as Driver<'static>>::OF_ID_TABLE.is_some()
+                || <F::Of<'static> as Driver<'static>>::I2C_ID_TABLE.is_some(),
             "At least one of ACPI/OF/Legacy tables must be present when registering an i2c driver"
         );
 
-        let i2c_table = match T::I2C_ID_TABLE {
+        let i2c_table = match <F::Of<'static> as Driver<'static>>::I2C_ID_TABLE {
             Some(table) => table.as_ptr(),
             None => core::ptr::null(),
         };
 
-        let of_table = match T::OF_ID_TABLE {
+        let of_table = match <F::Of<'static> as Driver<'static>>::OF_ID_TABLE {
             Some(table) => table.as_ptr(),
             None => core::ptr::null(),
         };
 
-        let acpi_table = match T::ACPI_ID_TABLE {
+        let acpi_table = match <F::Of<'static> as Driver<'static>>::ACPI_ID_TABLE {
             Some(table) => table.as_ptr(),
             None => core::ptr::null(),
         };
@@ -154,7 +169,11 @@ unsafe fn unregister(idrv: &Opaque<Self::DriverType>) {
     }
 }
 
-impl<T: Driver + 'static> Adapter<T> {
+impl<F> Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
+{
     extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_int {
         // SAFETY: The I2C bus only ever calls the probe callback with a valid pointer to a
         // `struct i2c_client`.
@@ -162,13 +181,12 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_
         // INVARIANT: `idev` is valid for the duration of `probe_callback()`.
         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };
 
-        let info = Self::i2c_id_info(idev)
-            .or_else(|| <Self as driver::Adapter<'_>>::id_info(idev.as_ref()));
-
         from_result(|| {
-            let data = T::probe(idev, info);
+            let info = Self::i2c_id_info(idev)
+                .or_else(|| <Self as driver::Adapter<'_>>::id_info(idev.as_ref()));
+            let data = <F::Of<'_> as Driver<'_>>::probe(idev, info);
 
-            idev.as_ref().set_drvdata::<ForLt!(T)>(data)?;
+            idev.as_ref().set_drvdata::<F>(data)?;
             Ok(0)
         })
     }
@@ -178,11 +196,10 @@ extern "C" fn remove_callback(idev: *mut bindings::i2c_client) {
         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };
 
         // SAFETY: `remove_callback` is only ever called after a successful call to
-        // `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called
-        // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { idev.as_ref().drvdata_borrow::<ForLt!(T)>() };
+        // `probe_callback`, hence it's guaranteed that drvdata has been set.
+        let data = unsafe { idev.as_ref().drvdata_borrow::<F>() };
 
-        T::unbind(idev, data);
+        <F::Of<'_> as Driver<'_>>::unbind(idev, data);
     }
 
     extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {
@@ -190,23 +207,24 @@ extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {
         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };
 
         // SAFETY: `shutdown_callback` is only ever called after a successful call to
-        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
-        // and stored a `Pin<KBox<T>>`.
-        let data = unsafe { idev.as_ref().drvdata_borrow::<ForLt!(T)>() };
+        // `probe_callback`, hence it's guaranteed that drvdata has been set.
+        let data = unsafe { idev.as_ref().drvdata_borrow::<F>() };
 
-        T::shutdown(idev, data);
+        <F::Of<'_> as Driver<'_>>::shutdown(idev, data);
     }
 
     /// The [`i2c::IdTable`] of the corresponding driver.
-    fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter<'static>>::IdInfo>> {
-        T::I2C_ID_TABLE
+    fn i2c_id_table<'bound>() -> Option<IdTable<<F::Of<'bound> as Driver<'bound>>::IdInfo>> {
+        <F::Of<'bound> as Driver<'bound>>::I2C_ID_TABLE
     }
 
     /// Returns the driver's private data from the matching entry in the [`i2c::IdTable`], if any.
     ///
     /// If this returns `None`, it means there is no match with an entry in the [`i2c::IdTable`].
-    fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter<'static>>::IdInfo> {
-        let table = Self::i2c_id_table()?;
+    fn i2c_id_info<'bound>(
+        dev: &I2cClient,
+    ) -> Option<&'bound <F::Of<'bound> as Driver<'bound>>::IdInfo> {
+        let table = Self::i2c_id_table::<'bound>()?;
 
         // SAFETY:
         // - `table` has static lifetime, hence it's valid for reads
@@ -225,15 +243,19 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter<'sta
     }
 }
 
-impl<'bound, T: Driver + 'static> driver::Adapter<'bound> for Adapter<T> {
-    type IdInfo = T::IdInfo;
+impl<'bound, F> driver::Adapter<'bound> for Adapter<F>
+where
+    F: ForLt + 'static,
+    F::Of<'bound>: Driver<'bound>,
+{
+    type IdInfo = <F::Of<'bound> as Driver<'bound>>::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
-        T::OF_ID_TABLE
+        <F::Of<'bound> as Driver<'bound>>::OF_ID_TABLE
     }
 
     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
-        T::ACPI_ID_TABLE
+        <F::Of<'bound> as Driver<'bound>>::ACPI_ID_TABLE
     }
 }
 
@@ -252,8 +274,11 @@ fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
 /// ```
 #[macro_export]
 macro_rules! module_i2c_driver {
-    ($($f:tt)*) => {
-        $crate::module_driver!(<T>, $crate::i2c::Adapter<T>, { $($f)* });
+    (type: $type:ty, $($rest:tt)*) => {
+        $crate::module_driver!(<T>, $crate::i2c::Adapter<T>, {
+            type: $crate::types::ForLt!($type),
+            $($rest)*
+        });
     };
 }
 
@@ -271,7 +296,7 @@ macro_rules! module_i2c_driver {
 /// kernel::acpi_device_table!(
 ///     ACPI_TABLE,
 ///     MODULE_ACPI_TABLE,
-///     <MyDriver as i2c::Driver>::IdInfo,
+///     <MyDriver as i2c::Driver<'_>>::IdInfo,
 ///     [
 ///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
 ///     ]
@@ -280,7 +305,7 @@ macro_rules! module_i2c_driver {
 /// kernel::i2c_device_table!(
 ///     I2C_TABLE,
 ///     MODULE_I2C_TABLE,
-///     <MyDriver as i2c::Driver>::IdInfo,
+///     <MyDriver as i2c::Driver<'_>>::IdInfo,
 ///     [
 ///          (i2c::DeviceId::new(c"rust_driver_i2c"), ())
 ///     ]
@@ -289,30 +314,30 @@ macro_rules! module_i2c_driver {
 /// kernel::of_device_table!(
 ///     OF_TABLE,
 ///     MODULE_OF_TABLE,
-///     <MyDriver as i2c::Driver>::IdInfo,
+///     <MyDriver as i2c::Driver<'_>>::IdInfo,
 ///     [
 ///         (of::DeviceId::new(c"test,device"), ())
 ///     ]
 /// );
 ///
-/// impl i2c::Driver for MyDriver {
+/// impl<'bound> i2c::Driver<'bound> for MyDriver {
 ///     type IdInfo = ();
 ///     const I2C_ID_TABLE: Option<i2c::IdTable<Self::IdInfo>> = Some(&I2C_TABLE);
 ///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
 ///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
 ///
 ///     fn probe(
-///         _idev: &i2c::I2cClient<Core>,
-///         _id_info: Option<&Self::IdInfo>,
-///     ) -> impl PinInit<Self, Error> {
+///         _idev: &'bound i2c::I2cClient<Core>,
+///         _id_info: Option<&'bound Self::IdInfo>,
+///     ) -> impl PinInit<Self, Error> + 'bound {
 ///         Err(ENODEV)
 ///     }
 ///
-///     fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self>) {
+///     fn shutdown(_idev: &'bound i2c::I2cClient<Core>, _this: Pin<&'bound Self>) {
 ///     }
 /// }
 ///```
-pub trait Driver: Send {
+pub trait Driver<'bound>: Send {
     /// The type holding information about each device id supported by the driver.
     // TODO: Use `associated_type_defaults` once stabilized:
     //
@@ -335,9 +360,9 @@ pub trait Driver: Send {
     /// Called when a new i2c client is added or discovered.
     /// Implementers should attempt to initialize the client here.
     fn probe(
-        dev: &I2cClient<device::Core>,
-        id_info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error>;
+        dev: &'bound I2cClient<device::Core>,
+        id_info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound;
 
     /// I2C driver shutdown.
     ///
@@ -350,7 +375,7 @@ fn probe(
     /// This callback is distinct from final resource cleanup, as the driver instance remains valid
     /// after it returns. Any deallocation or teardown of driver-owned resources should instead be
     /// handled in `Self::drop`.
-    fn shutdown(dev: &I2cClient<device::Core>, this: Pin<&Self>) {
+    fn shutdown(dev: &'bound I2cClient<device::Core>, this: Pin<&'bound Self>) {
         let _ = (dev, this);
     }
 
@@ -364,7 +389,7 @@ fn shutdown(dev: &I2cClient<device::Core>, this: Pin<&Self>) {
     /// operations to gracefully tear down the device.
     ///
     /// Otherwise, release operations for driver resources should be performed in `Self::drop`.
-    fn unbind(dev: &I2cClient<device::Core>, this: Pin<&Self>) {
+    fn unbind(dev: &'bound I2cClient<device::Core>, this: Pin<&'bound Self>) {
         let _ = (dev, this);
     }
 }
samples/rust/rust_driver_i2c.rs +9 -9
index 6be79f9e9fb5..042a18305817 100644
@@ -15,25 +15,25 @@
 kernel::acpi_device_table! {
     ACPI_TABLE,
     MODULE_ACPI_TABLE,
-    <SampleDriver as i2c::Driver>::IdInfo,
+    <SampleDriver as i2c::Driver<'_>>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), 0)]
 }
 
 kernel::i2c_device_table! {
     I2C_TABLE,
     MODULE_I2C_TABLE,
-    <SampleDriver as i2c::Driver>::IdInfo,
+    <SampleDriver as i2c::Driver<'_>>::IdInfo,
     [(i2c::DeviceId::new(c"rust_driver_i2c"), 0)]
 }
 
 kernel::of_device_table! {
     OF_TABLE,
     MODULE_OF_TABLE,
-    <SampleDriver as i2c::Driver>::IdInfo,
+    <SampleDriver as i2c::Driver<'_>>::IdInfo,
     [(of::DeviceId::new(c"test,rust_driver_i2c"), 0)]
 }
 
-impl i2c::Driver for SampleDriver {
+impl<'bound> i2c::Driver<'bound> for SampleDriver {
     type IdInfo = u32;
 
     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
@@ -41,9 +41,9 @@ impl i2c::Driver for SampleDriver {
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
 
     fn probe(
-        idev: &i2c::I2cClient<Core>,
-        info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+        idev: &'bound i2c::I2cClient<Core>,
+        info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
         let dev = idev.as_ref();
 
         dev_info!(dev, "Probe Rust I2C driver sample.\n");
@@ -55,11 +55,11 @@ fn probe(
         Ok(Self)
     }
 
-    fn shutdown(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn shutdown(idev: &'bound i2c::I2cClient<Core>, _this: Pin<&'bound Self>) {
         dev_info!(idev.as_ref(), "Shutdown Rust I2C driver sample.\n");
     }
 
-    fn unbind(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn unbind(idev: &'bound i2c::I2cClient<Core>, _this: Pin<&'bound Self>) {
         dev_info!(idev.as_ref(), "Unbind Rust I2C driver sample.\n");
     }
 }
Signature · 1 line
2.54.0
author maintainer
#22 lore raw

PATCH v2 17/25 rust: pci: make Bar lifetime-parameterized

In reply to Danilo Krummrich

Convert pci::Bar<SIZE> to pci::Bar<'bound, SIZE>, storing &'bound Device<Bound> to tie the BAR mapping lifetime to the device.

iomap_region_sized() now returns Result<Bar<'bound, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.

Add Bar::into_devres() to consume the bar and register it as a device-managed resource, returning Devres<Bar<'static, SIZE>>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind.

---
 drivers/gpu/nova-core/driver.rs |  7 ++--
 rust/kernel/devres.rs           |  2 +-
 rust/kernel/pci/io.rs           | 68 +++++++++++++++++----------------
 samples/rust/rust_driver_pci.rs |  5 ++-
 4 files changed, 44 insertions(+), 38 deletions(-)
drivers/gpu/nova-core/driver.rs +4 -3
index ed154cd93fa8..6ee2021ef56e 100644
@@ -47,7 +47,7 @@ pub(crate) struct NovaCore {
 // DMA addresses. These systems should be quite rare.
 const GPU_DMA_BITS: u32 = 47;
 
-pub(crate) type Bar0 = pci::Bar<BAR0_SIZE>;
+pub(crate) type Bar0 = pci::Bar<'static, BAR0_SIZE>;
 
 kernel::pci_device_table!(
     PCI_TABLE,
@@ -93,8 +93,9 @@ fn probe(
             // other threads of execution.
             unsafe { pdev.dma_set_mask_and_coherent(DmaMask::new::<GPU_DMA_BITS>())? };
 
-            let bar = Arc::pin_init(
-                pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0"),
+            let bar = Arc::new(
+                pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?
+                    .into_devres()?,
                 GFP_KERNEL,
             )?;
 
rust/kernel/devres.rs +1 -1
index 9e5f93aed20c..ec63317665f4 100644
@@ -304,7 +304,7 @@ pub fn device(&self) -> &Device {
     ///     pci, //
     /// };
     ///
-    /// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result {
+    /// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<'_, 0x4>>) -> Result {
     ///     let bar = devres.access(dev.as_ref())?;
     ///
     ///     let _ = bar.read32(0x0);
rust/kernel/pci/io.rs +36 -32

156 lines not on this page · raw message

samples/rust/rust_driver_pci.rs +3 -2
index 794311691d1e..bbcb816456e0 100644
@@ -45,7 +45,7 @@ mod regs {
     pub(super) const END: usize = 0x10;
 }
 
-type Bar0 = pci::Bar<{ regs::END }>;
+type Bar0 = pci::Bar<'static, { regs::END }>;
 
 #[derive(Copy, Clone, Debug)]
 struct TestIndex(u8);
@@ -160,7 +160,8 @@ fn probe(
             pdev.set_master();
 
             Ok(try_pin_init!(Self {
-                bar <- pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci"),
+                bar: pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci")?
+                    .into_devres()?,
                 index: *info,
                 _: {
                     let bar = bar.access(pdev.as_ref())?;
Signature · 1 line
2.54.0
author maintainer
#23 lore raw

PATCH v2 18/25 rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized

In reply to Danilo Krummrich

Add a lifetime parameter to IoMem<'bound, SIZE> and ExclusiveIoMem<'bound, SIZE>, storing a &'bound Device<Bound> reference to tie the mapping to the device's lifetime.

This mirrors the pci::Bar<'bound, SIZE> design and enables drivers to hold I/O memory mappings directly in their HRT private data, tied to the device lifetime.

IoRequest::iomap_* methods now return the mapping directly instead of wrapping it in Devres. Callers that need device-managed revocation can call the new into_devres() method.

---
 drivers/gpu/drm/tyr/driver.rs |   4 +-
 drivers/pwm/pwm_th1520.rs     |   4 +-
 rust/kernel/io/mem.rs         | 115 +++++++++++++++++-----------------
 3 files changed, 62 insertions(+), 61 deletions(-)
drivers/gpu/drm/tyr/driver.rs +2 -2
index 96d83605e4b9..295a627de2b2 100644
@@ -37,7 +37,7 @@
     regs, //
 };
 
-pub(crate) type IoMem = kernel::io::mem::IoMem<SZ_2M>;
+pub(crate) type IoMem = kernel::io::mem::IoMem<'static, SZ_2M>;
 
 pub(crate) struct TyrDrmDriver;
 
@@ -109,7 +109,7 @@ fn probe(
         let sram_regulator = Regulator::<regulator::Enabled>::get(pdev.as_ref(), c"sram")?;
 
         let request = pdev.io_request_by_index(0).ok_or(ENODEV)?;
-        let iomem = Arc::pin_init(request.iomap_sized::<SZ_2M>(), GFP_KERNEL)?;
+        let iomem = Arc::new(request.iomap_sized::<SZ_2M>()?.into_devres()?, GFP_KERNEL)?;
 
         issue_soft_reset(pdev.as_ref(), &iomem)?;
         gpu::l2_power_on(pdev.as_ref(), &iomem)?;
drivers/pwm/pwm_th1520.rs +2 -2
index a7831b4ebe00..3deb39d8e0fc 100644
@@ -92,7 +92,7 @@ struct Th1520WfHw {
 #[pin_data(PinnedDrop)]
 struct Th1520PwmDriverData {
     #[pin]
-    iomem: devres::Devres<IoMem<TH1520_PWM_REG_SIZE>>,
+    iomem: devres::Devres<IoMem<'static, TH1520_PWM_REG_SIZE>>,
     clk: Clk,
 }
 
@@ -351,7 +351,7 @@ fn probe(
             dev,
             TH1520_MAX_PWM_NUM,
             try_pin_init!(Th1520PwmDriverData {
-                iomem <- request.iomap_sized::<TH1520_PWM_REG_SIZE>(),
+                iomem <- request.iomap_sized::<TH1520_PWM_REG_SIZE>()?.into_devres(),
                 clk <- clk,
             }),
         )?;
rust/kernel/io/mem.rs +58 -57

220 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#24 lore raw

PATCH v2 19/25 samples: rust: rust_driver_pci: use HRT lifetime for Bar

In reply to Danilo Krummrich

Convert the sample driver to SampleDriver<'bound>, taking advantage of the lifetime-parameterized Driver trait.

The driver struct holds &'bound pci::Device directly instead of ARef<pci::Device>, and pci::Bar<'bound> directly instead of Devres<pci::Bar>. This removes PinnedDrop, pin_init_scope, and runtime revocation checks on BAR access.

---
 samples/rust/rust_driver_pci.rs | 89 +++++++++++++++------------------
 1 file changed, 39 insertions(+), 50 deletions(-)
samples/rust/rust_driver_pci.rs +39 -50
index bbcb816456e0..a7b7e580685c 100644
@@ -9,7 +9,6 @@
         Bound,
         Core, //
     },
-    devres::Devres,
     io::{
         register,
         register::Array,
@@ -17,8 +16,7 @@
     },
     num::Bounded,
     pci,
-    prelude::*,
-    sync::aref::ARef, //
+    prelude::*, //
 };
 
 mod regs {
@@ -45,7 +43,7 @@ mod regs {
     pub(super) const END: usize = 0x10;
 }
 
-type Bar0 = pci::Bar<'static, { regs::END }>;
+type Bar0<'bound> = pci::Bar<'bound, { regs::END }>;
 
 #[derive(Copy, Clone, Debug)]
 struct TestIndex(u8);
@@ -66,26 +64,24 @@ impl TestIndex {
     const NO_EVENTFD: Self = Self(0);
 }
 
-#[pin_data(PinnedDrop)]
-struct SampleDriver {
-    pdev: ARef<pci::Device>,
-    #[pin]
-    bar: Devres<Bar0>,
+struct SampleDriver<'bound> {
+    pdev: &'bound pci::Device,
+    bar: Bar0<'bound>,
     index: TestIndex,
 }
 
 kernel::pci_device_table!(
     PCI_TABLE,
     MODULE_PCI_TABLE,
-    <SampleDriver as pci::Driver<'_>>::IdInfo,
+    <SampleDriver<'_> as pci::Driver<'_>>::IdInfo,
     [(
         pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5),
         TestIndex::NO_EVENTFD
     )]
 );
 
-impl SampleDriver {
-    fn testdev(index: &TestIndex, bar: &Bar0) -> Result<u32> {
+impl SampleDriver<'_> {
+    fn testdev(index: &TestIndex, bar: &Bar0<'_>) -> Result<u32> {
         // Select the test.
         bar.write_reg(regs::TEST::zeroed().with_index(*index));
 
@@ -138,7 +134,7 @@ fn config_space(pdev: &pci::Device<Bound>) {
     }
 }
 
-impl<'bound> pci::Driver<'bound> for SampleDriver {
+impl<'bound> pci::Driver<'bound> for SampleDriver<'bound> {
     type IdInfo = TestIndex;
 
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
@@ -147,54 +143,47 @@ fn probe(
         pdev: &'bound pci::Device<Core>,
         info: &'bound Self::IdInfo,
     ) -> impl PinInit<Self, Error> + 'bound {
-        pin_init::pin_init_scope(move || {
-            let vendor = pdev.vendor_id();
-            dev_dbg!(
-                pdev,
-                "Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n",
-                vendor,
-                pdev.device_id()
-            );
-
-            pdev.enable_device_mem()?;
-            pdev.set_master();
-
-            Ok(try_pin_init!(Self {
-                bar: pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci")?
-                    .into_devres()?,
-                index: *info,
-                _: {
-                    let bar = bar.access(pdev.as_ref())?;
-
-                    dev_info!(
-                        pdev,
-                        "pci-testdev data-match count: {}\n",
-                        Self::testdev(info, bar)?
-                    );
-                    Self::config_space(pdev);
-                },
-                pdev: pdev.into(),
-            }))
+        let vendor = pdev.vendor_id();
+        dev_dbg!(
+            pdev,
+            "Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n",
+            vendor,
+            pdev.device_id()
+        );
+
+        pdev.enable_device_mem()?;
+        pdev.set_master();
+
+        let bar = pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci")?;
+
+        dev_info!(
+            pdev,
+            "pci-testdev data-match count: {}\n",
+            Self::testdev(info, &bar)?
+        );
+        Self::config_space(pdev);
+
+        Ok(Self {
+            pdev,
+            bar,
+            index: *info,
         })
     }
 
-    fn unbind(pdev: &'bound pci::Device<Core>, this: Pin<&'bound Self>) {
-        if let Ok(bar) = this.bar.access(pdev.as_ref()) {
-            // Reset pci-testdev by writing a new test index.
-            bar.write_reg(regs::TEST::zeroed().with_index(this.index));
-        }
+    fn unbind(_pdev: &'bound pci::Device<Core>, this: Pin<&'bound Self>) {
+        this.bar
+            .write_reg(regs::TEST::zeroed().with_index(this.index));
     }
 }
 
-#[pinned_drop]
-impl PinnedDrop for SampleDriver {
-    fn drop(self: Pin<&mut Self>) {
+impl Drop for SampleDriver<'_> {
+    fn drop(&mut self) {
         dev_dbg!(self.pdev, "Remove Rust PCI driver sample.\n");
     }
 }
 
 kernel::module_pci_driver! {
-    type: SampleDriver,
+    type: SampleDriver<'_>,
     name: "rust_driver_pci",
     authors: ["Danilo Krummrich"],
     description: "Rust PCI driver",
Signature · 1 line
2.54.0
author maintainer
#25 lore raw

PATCH v2 20/25 rust: driver-core: rename 'a lifetime to 'bound

In reply to Danilo Krummrich

Rename the generic lifetime parameter from 'a to 'bound in pci, platform, i2c and devres. This makes it explicit that the lifetime represents the device binding scope, consistent with the convention established by the HRT series.

---
 rust/kernel/devres.rs   | 14 +++++++++-----
 rust/kernel/i2c.rs      |  6 +++---
 rust/kernel/pci/irq.rs  | 38 +++++++++++++++++++-------------------
 rust/kernel/platform.rs | 18 +++++++++---------
 4 files changed, 40 insertions(+), 36 deletions(-)
rust/kernel/devres.rs +9 -5
index ec63317665f4..58efe80474bd 100644
@@ -280,10 +280,11 @@ pub fn device(&self) -> &Device {
         &self.dev
     }
 
-    /// Obtain `&'a T`, bypassing the [`Revocable`].
+    /// Obtain `&'bound T`, bypassing the [`Revocable`].
     ///
-    /// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting
-    /// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with.
+    /// This method allows to directly obtain a `&'bound T`, bypassing the
+    /// [`Revocable`], by presenting a `&'bound Device<Bound>` of the same
+    /// [`Device`] this [`Devres`] instance has been created with.
     ///
     /// # Errors
     ///
@@ -316,7 +317,7 @@ pub fn device(&self) -> &Device {
     ///     Ok(())
     /// }
     /// ```
-    pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {
+    pub fn access<'bound>(&'bound self, dev: &'bound Device<Bound>) -> Result<&'bound T> {
         if self.dev.as_raw() != dev.as_raw() {
             return Err(EINVAL);
         }
@@ -338,7 +339,10 @@ pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
     }
 
     /// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
-    pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
+    pub fn try_access_with_guard<'bound>(
+        &'bound self,
+        guard: &'bound rcu::Guard,
+    ) -> Option<&'bound T> {
         self.data().try_access_with_guard(guard)
     }
 }
rust/kernel/i2c.rs +3 -3
index 2216b49604b2..5a601cba7dc0 100644
@@ -584,11 +584,11 @@ unsafe impl Sync for I2cClient {}
 
 impl Registration {
     /// The C `i2c_new_client_device` function wrapper for manual I2C client creation.
-    pub fn new<'a>(
+    pub fn new<'bound>(
         i2c_adapter: &I2cAdapter,
         i2c_board_info: &I2cBoardInfo,
-        parent_dev: &'a device::Device<device::Bound>,
-    ) -> impl PinInit<Devres<Self>, Error> + 'a {
+        parent_dev: &'bound device::Device<device::Bound>,
+    ) -> impl PinInit<Devres<Self>, Error> + 'bound {
         Devres::new(parent_dev, Self::try_new(i2c_adapter, i2c_board_info))
     }
 
rust/kernel/pci/irq.rs +19 -19
index d9230e105541..92207fd46403 100644
@@ -76,19 +76,19 @@ const fn as_raw(self) -> u32 {
 /// This type ties an IRQ vector to the device it was allocated for,
 /// ensuring the vector is only used with the correct device.
 #[derive(Clone, Copy)]
-pub struct IrqVector<'a> {
-    dev: &'a Device<Bound>,
+pub struct IrqVector<'bound> {
+    dev: &'bound Device<Bound>,
     index: u32,
 }
 
-impl<'a> IrqVector<'a> {
+impl<'bound> IrqVector<'bound> {
     /// Creates a new [`IrqVector`] for the given device and index.
     ///
     /// # Safety
     ///
     /// - `index` must be a valid IRQ vector index for `dev`.
     /// - `dev` must point to a [`Device`] that has successfully allocated IRQ vectors.
-    unsafe fn new(dev: &'a Device<Bound>, index: u32) -> Self {
+    unsafe fn new(dev: &'bound Device<Bound>, index: u32) -> Self {
         Self { dev, index }
     }
 
@@ -98,10 +98,10 @@ fn index(&self) -> u32 {
     }
 }
 
-impl<'a> TryInto<IrqRequest<'a>> for IrqVector<'a> {
+impl<'bound> TryInto<IrqRequest<'bound>> for IrqVector<'bound> {
     type Error = Error;
 
-    fn try_into(self) -> Result<IrqRequest<'a>> {
+    fn try_into(self) -> Result<IrqRequest<'bound>> {
         // SAFETY: `self.as_raw` returns a valid pointer to a `struct pci_dev`.
         let irq = unsafe { bindings::pci_irq_vector(self.dev.as_raw(), self.index()) };
         if irq < 0 {
@@ -129,12 +129,12 @@ impl IrqVectorRegistration {
     ///
     /// Allocates IRQ vectors and registers them with devres for automatic cleanup.
     /// Returns a range of valid IRQ vectors.
-    fn register<'a>(
-        dev: &'a Device<Bound>,
+    fn register<'bound>(
+        dev: &'bound Device<Bound>,
         min_vecs: u32,
         max_vecs: u32,
         irq_types: IrqTypes,
-    ) -> Result<RangeInclusive<IrqVector<'a>>> {
+    ) -> Result<RangeInclusive<IrqVector<'bound>>> {
         // SAFETY:
         // - `dev.as_raw()` is guaranteed to be a valid pointer to a `struct pci_dev`
         //   by the type invariant of `Device`.
@@ -173,13 +173,13 @@ fn drop(&mut self) {
 
 impl Device<device::Bound> {
     /// Returns a [`kernel::irq::Registration`] for the given IRQ vector.
-    pub fn request_irq<'a, T: crate::irq::Handler + 'static>(
-        &'a self,
-        vector: IrqVector<'a>,
+    pub fn request_irq<'bound, T: crate::irq::Handler + 'static>(
+        &'bound self,
+        vector: IrqVector<'bound>,
         flags: irq::Flags,
         name: &'static CStr,
-        handler: impl PinInit<T, Error> + 'a,
-    ) -> impl PinInit<irq::Registration<T>, Error> + 'a {
+        handler: impl PinInit<T, Error> + 'bound,
+    ) -> impl PinInit<irq::Registration<T>, Error> + 'bound {
         pin_init::pin_init_scope(move || {
             let request = vector.try_into()?;
 
@@ -188,13 +188,13 @@ pub fn request_irq<'a, T: crate::irq::Handler + 'static>(
     }
 
     /// Returns a [`kernel::irq::ThreadedRegistration`] for the given IRQ vector.
-    pub fn request_threaded_irq<'a, T: crate::irq::ThreadedHandler + 'static>(
-        &'a self,
-        vector: IrqVector<'a>,
+    pub fn request_threaded_irq<'bound, T: crate::irq::ThreadedHandler + 'static>(
+        &'bound self,
+        vector: IrqVector<'bound>,
         flags: irq::Flags,
         name: &'static CStr,
-        handler: impl PinInit<T, Error> + 'a,
-    ) -> impl PinInit<irq::ThreadedRegistration<T>, Error> + 'a {
+        handler: impl PinInit<T, Error> + 'bound,
+    ) -> impl PinInit<irq::ThreadedRegistration<T>, Error> + 'bound {
         pin_init::pin_init_scope(move || {
             let request = vector.try_into()?;
 
rust/kernel/platform.rs +9 -9
index 9959364429b5..f59f22283c53 100644
@@ -365,13 +365,13 @@ macro_rules! define_irq_accessor_by_index {
         $handler_trait:ident
     ) => {
         $(#[$meta])*
-        pub fn $fn_name<'a, T: irq::$handler_trait + 'static>(
-            &'a self,
+        pub fn $fn_name<'bound, T: irq::$handler_trait + 'static>(
+            &'bound self,
             flags: irq::Flags,
             index: u32,
             name: &'static CStr,
-            handler: impl PinInit<T, Error> + 'a,
-        ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a {
+            handler: impl PinInit<T, Error> + 'bound,
+        ) -> impl PinInit<irq::$reg_type<T>, Error> + 'bound {
             pin_init::pin_init_scope(move || {
                 let request = self.$request_fn(index)?;
 
@@ -394,13 +394,13 @@ macro_rules! define_irq_accessor_by_name {
         $handler_trait:ident
     ) => {
         $(#[$meta])*
-        pub fn $fn_name<'a, T: irq::$handler_trait + 'static>(
-            &'a self,
+        pub fn $fn_name<'bound, T: irq::$handler_trait + 'static>(
+            &'bound self,
             flags: irq::Flags,
-            irq_name: &'a CStr,
+            irq_name: &'bound CStr,
             name: &'static CStr,
-            handler: impl PinInit<T, Error> + 'a,
-        ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a {
+            handler: impl PinInit<T, Error> + 'bound,
+        ) -> impl PinInit<irq::$reg_type<T>, Error> + 'bound {
             pin_init::pin_init_scope(move || {
                 let request = self.$request_fn(irq_name)?;
 
Signature · 1 line
2.54.0
author maintainer
#26 lore raw

PATCH v2 21/25 gpu: nova-core: rename 'a lifetime to 'bound

In reply to Danilo Krummrich

Rename the generic lifetime parameter from 'a to 'bound in nova-core. This makes it explicit that the lifetime represents the device binding scope, consistent with the convention established by the HRT series.

---
 drivers/gpu/nova-core/firmware/gsp.rs    |  8 ++++----
 drivers/gpu/nova-core/gpu.rs             |  8 ++++----
 drivers/gpu/nova-core/gsp/commands.rs    | 10 +++++-----
 drivers/gpu/nova-core/gsp/fw/commands.rs |  4 +++-
 4 files changed, 16 insertions(+), 14 deletions(-)
drivers/gpu/nova-core/firmware/gsp.rs +4 -4
index 2fcc255c3bc8..9dbd88c55f7e 100644
@@ -65,11 +65,11 @@ pub(crate) struct GspFirmware {
 impl GspFirmware {
     /// Loads the GSP firmware binaries, map them into `dev`'s address-space, and creates the page
     /// tables expected by the GSP bootloader to load it.
-    pub(crate) fn new<'a>(
-        dev: &'a device::Device<device::Bound>,
+    pub(crate) fn new<'bound>(
+        dev: &'bound device::Device<device::Bound>,
         chipset: Chipset,
-        ver: &'a str,
-    ) -> impl PinInit<Self, Error> + 'a {
+        ver: &'bound str,
+    ) -> impl PinInit<Self, Error> + 'bound {
         pin_init::pin_init_scope(move || {
             let firmware = super::request_firmware(dev, chipset, "gsp", ver)?;
 
drivers/gpu/nova-core/gpu.rs +4 -4
index 0f6fe9a1b955..9288b30fe4c3 100644
@@ -241,11 +241,11 @@ pub(crate) struct Gpu {
 }
 
 impl Gpu {
-    pub(crate) fn new<'a>(
-        pdev: &'a pci::Device<device::Bound>,
+    pub(crate) fn new<'bound>(
+        pdev: &'bound pci::Device<device::Bound>,
         devres_bar: Arc<Devres<Bar0>>,
-        bar: &'a Bar0,
-    ) -> impl PinInit<Self, Error> + 'a {
+        bar: &'bound Bar0,
+    ) -> impl PinInit<Self, Error> + 'bound {
         try_pin_init!(Self {
             spec: Spec::new(pdev.as_ref(), bar).inspect(|spec| {
                 dev_info!(pdev,"NVIDIA ({})\n", spec);
drivers/gpu/nova-core/gsp/commands.rs +5 -5
index c89c7b57a751..0da5b92f4b27 100644
@@ -35,18 +35,18 @@
 };
 
 /// The `GspSetSystemInfo` command.
-pub(crate) struct SetSystemInfo<'a> {
-    pdev: &'a pci::Device<device::Bound>,
+pub(crate) struct SetSystemInfo<'bound> {
+    pdev: &'bound pci::Device<device::Bound>,
 }
 
-impl<'a> SetSystemInfo<'a> {
+impl<'bound> SetSystemInfo<'bound> {
     /// Creates a new `GspSetSystemInfo` command using the parameters of `pdev`.
-    pub(crate) fn new(pdev: &'a pci::Device<device::Bound>) -> Self {
+    pub(crate) fn new(pdev: &'bound pci::Device<device::Bound>) -> Self {
         Self { pdev }
     }
 }
 
-impl<'a> CommandToGsp for SetSystemInfo<'a> {
+impl<'bound> CommandToGsp for SetSystemInfo<'bound> {
     const FUNCTION: MsgFunction = MsgFunction::GspSetSystemInfo;
     type Command = GspSetSystemInfo;
     type Reply = NoReply;
drivers/gpu/nova-core/gsp/fw/commands.rs +3 -1
index db46276430be..d3ef7ecdd73e 100644
@@ -24,7 +24,9 @@ pub(crate) struct GspSetSystemInfo {
 impl GspSetSystemInfo {
     /// Returns an in-place initializer for the `GspSetSystemInfo` command.
     #[allow(non_snake_case)]
-    pub(crate) fn init<'a>(dev: &'a pci::Device<device::Bound>) -> impl Init<Self, Error> + 'a {
+    pub(crate) fn init<'bound>(
+        dev: &'bound pci::Device<device::Bound>,
+    ) -> impl Init<Self, Error> + 'bound {
         type InnerGspSystemInfo = bindings::GspSystemInfo;
         let init_inner = try_init!(InnerGspSystemInfo {
             gpuPhysAddr: dev.resource_start(0)?,
Signature · 1 line
2.54.0
author maintainer
#27 lore raw

PATCH v2 22/25 gpu: nova-core: use HRT lifetime for Bar

In reply to Danilo Krummrich

Take advantage of the lifetime-parameterized pci::Bar<'bound> to hold the BAR mapping directly in NovaCore<'bound>, and pass a borrowed reference to Gpu<'bound>.

This eliminates the Arc<Devres<Bar0>> indirection, removes runtime revocation checks for BAR access, and simplifies Gpu::unbind().

---
 drivers/gpu/nova-core/driver.rs    | 40 ++++++++++++++----------------
 drivers/gpu/nova-core/gpu.rs       | 27 ++++++++------------
 drivers/gpu/nova-core/nova_core.rs |  2 +-
 3 files changed, 30 insertions(+), 39 deletions(-)
drivers/gpu/nova-core/driver.rs +19 -21
index 6ee2021ef56e..11b632ae3789 100644
@@ -14,12 +14,9 @@
     },
     prelude::*,
     sizes::SZ_16M,
-    sync::{
-        atomic::{
-            Atomic,
-            Relaxed, //
-        },
-        Arc,
+    sync::atomic::{
+        Atomic,
+        Relaxed, //
     },
     types::ForLt,
 };
@@ -30,9 +27,10 @@
 static AUXILIARY_ID_COUNTER: Atomic<u32> = Atomic::new(0);
 
 #[pin_data]
-pub(crate) struct NovaCore {
+pub(crate) struct NovaCore<'bound> {
     #[pin]
-    pub(crate) gpu: Gpu,
+    pub(crate) gpu: Gpu<'bound>,
+    bar: pci::Bar<'bound, BAR0_SIZE>,
     #[allow(clippy::type_complexity)]
     _reg: Devres<auxiliary::Registration<ForLt!(())>>,
 }
@@ -47,12 +45,12 @@ pub(crate) struct NovaCore {
 // DMA addresses. These systems should be quite rare.
 const GPU_DMA_BITS: u32 = 47;
 
-pub(crate) type Bar0 = pci::Bar<'static, BAR0_SIZE>;
+pub(crate) type Bar0 = kernel::io::Mmio<BAR0_SIZE>;
 
 kernel::pci_device_table!(
     PCI_TABLE,
     MODULE_PCI_TABLE,
-    <NovaCore as pci::Driver<'_>>::IdInfo,
+    <NovaCore<'_> as pci::Driver<'_>>::IdInfo,
     [
         // Modern NVIDIA GPUs will show up as either VGA or 3D controllers.
         (
@@ -74,7 +72,7 @@ pub(crate) struct NovaCore {
     ]
 );
 
-impl<'bound> pci::Driver<'bound> for NovaCore {
+impl<'bound> pci::Driver<'bound> for NovaCore<'bound> {
     type IdInfo = ();
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
@@ -93,14 +91,14 @@ fn probe(
             // other threads of execution.
             unsafe { pdev.dma_set_mask_and_coherent(DmaMask::new::<GPU_DMA_BITS>())? };
 
-            let bar = Arc::new(
-                pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?
-                    .into_devres()?,
-                GFP_KERNEL,
-            )?;
-
-            Ok(try_pin_init!(Self {
-                gpu <- Gpu::new(pdev, bar.clone(), bar.access(pdev.as_ref())?),
+            Ok(try_pin_init!(NovaCore {
+                bar: pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?,
+                // TODO: Use `&bar` self-referential pin-init syntax once available.
+                //
+                // SAFETY: `bar` is initialized before this expression is evaluated
+                // (`try_pin_init!()` initializes fields in declaration order), lives at a pinned
+                // stable address, and is dropped after `gpu` (struct field drop order).
+                gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }),
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c"nova-drm",
@@ -114,7 +112,7 @@ fn probe(
         })
     }
 
-    fn unbind(pdev: &pci::Device<Core>, this: Pin<&Self>) {
-        this.gpu.unbind(pdev.as_ref());
+    fn unbind(_pdev: &'bound pci::Device<Core>, this: Pin<&'bound Self>) {
+        this.gpu.unbind();
     }
 }
drivers/gpu/nova-core/gpu.rs +10 -17
index 9288b30fe4c3..03295fa6fb32 100644
@@ -2,13 +2,11 @@
 
 use kernel::{
     device,
-    devres::Devres,
     fmt,
     io::Io,
     num::Bounded,
     pci,
-    prelude::*,
-    sync::Arc, //
+    prelude::*, //
 };
 
 use crate::{
@@ -224,10 +222,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 
 /// Structure holding the resources required to operate the GPU.
 #[pin_data]
-pub(crate) struct Gpu {
+pub(crate) struct Gpu<'bound> {
     spec: Spec,
-    /// MMIO mapping of PCI BAR 0
-    bar: Arc<Devres<Bar0>>,
+    /// MMIO mapping of PCI BAR 0.
+    bar: &'bound Bar0,
     /// System memory page required for flushing all pending GPU-side memory writes done through
     /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation).
     sysmem_flush: SysmemFlush,
@@ -240,10 +238,9 @@ pub(crate) struct Gpu {
     gsp: Gsp,
 }
 
-impl Gpu {
-    pub(crate) fn new<'bound>(
+impl<'bound> Gpu<'bound> {
+    pub(crate) fn new(
         pdev: &'bound pci::Device<device::Bound>,
-        devres_bar: Arc<Devres<Bar0>>,
         bar: &'bound Bar0,
     ) -> impl PinInit<Self, Error> + 'bound {
         try_pin_init!(Self {
@@ -257,6 +254,8 @@ pub(crate) fn new<'bound>(
                     .inspect_err(|_| dev_err!(pdev, "GFW boot did not complete\n"))?;
             },
 
+            bar,
+
             sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,
 
             gsp_falcon: Falcon::new(
@@ -270,19 +269,13 @@ pub(crate) fn new<'bound>(
             gsp <- Gsp::new(pdev),
 
             _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)? },
-
-            bar: devres_bar,
         })
     }
 
     /// Called when the corresponding [`Device`](device::Device) is unbound.
     ///
     /// Note: This method must only be called from `Driver::unbind`.
-    pub(crate) fn unbind(&self, dev: &device::Device<device::Core>) {
-        kernel::warn_on!(self
-            .bar
-            .access(dev)
-            .inspect(|bar| self.sysmem_flush.unregister(bar))
-            .is_err());
+    pub(crate) fn unbind(&self) {
+        self.sysmem_flush.unregister(self.bar);
     }
 }
drivers/gpu/nova-core/nova_core.rs +1 -1
index 49c093a0cb42..ed5eb39c8201 100644
@@ -49,7 +49,7 @@ struct NovaCoreModule {
     // then `_debugfs_guard` clears `DEBUGFS_ROOT`.
     #[allow(clippy::type_complexity)]
     #[pin]
-    _driver: Registration<pci::Adapter<ForLt!(driver::NovaCore)>>,
+    _driver: Registration<pci::Adapter<ForLt!(driver::NovaCore<'_>)>>,
     _debugfs_guard: DebugfsRootGuard,
 }
 
Signature · 1 line
2.54.0
author maintainer
#28 lore raw

PATCH v2 23/25 gpu: nova-core: unregister sysmem flush page from Drop

In reply to Danilo Krummrich

Now that SysmemFlush can borrow the Bar via HRT lifetime, store a &'bound Bar0 reference and implement Drop to automatically unregister the sysmem flush page. This removes the need for manual unregister() calls and the Gpu::unbind() method.

Fixes 6554ad65b589 ("gpu: nova-core: register sysmem flush page")
---
 drivers/gpu/nova-core/driver.rs |  4 ----
 drivers/gpu/nova-core/fb.rs     | 22 ++++++++++------------
 drivers/gpu/nova-core/gpu.rs    |  9 +--------
 3 files changed, 11 insertions(+), 24 deletions(-)
drivers/gpu/nova-core/driver.rs +0 -4
index 11b632ae3789..31d2a8dadb7b 100644
@@ -111,8 +111,4 @@ fn probe(
             }))
         })
     }
-
-    fn unbind(_pdev: &'bound pci::Device<Core>, this: Pin<&'bound Self>) {
-        this.gpu.unbind();
-    }
 }
drivers/gpu/nova-core/fb.rs +10 -12
index bdd5eed760e1..a707fbfe3ced 100644
@@ -46,21 +46,20 @@
 /// Because of this, the sysmem flush memory page must be registered as early as possible during
 /// driver initialization, and before any falcon is reset.
 ///
-/// Users are responsible for manually calling [`Self::unregister`] before dropping this object,
-/// otherwise the GPU might still use it even after it has been freed.
-pub(crate) struct SysmemFlush {
+pub(crate) struct SysmemFlush<'bound> {
     /// Chipset we are operating on.
     chipset: Chipset,
     device: ARef<device::Device>,
+    bar: &'bound Bar0,
     /// Keep the page alive as long as we need it.
     page: CoherentHandle,
 }
 
-impl SysmemFlush {
+impl<'bound> SysmemFlush<'bound> {
     /// Allocate a memory page and register it as the sysmem flush page.
     pub(crate) fn register(
         dev: &device::Device<device::Bound>,
-        bar: &Bar0,
+        bar: &'bound Bar0,
         chipset: Chipset,
     ) -> Result<Self> {
         let page = CoherentHandle::alloc(dev, kernel::page::PAGE_SIZE, GFP_KERNEL)?;
@@ -70,19 +69,18 @@ pub(crate) fn register(
         Ok(Self {
             chipset,
             device: dev.into(),
+            bar,
             page,
         })
     }
+}
 
-    /// Unregister the managed sysmem flush page.
-    ///
-    /// In order to gracefully tear down the GPU, users must make sure to call this method before
-    /// dropping the object.
-    pub(crate) fn unregister(&self, bar: &Bar0) {
+impl Drop for SysmemFlush<'_> {
+    fn drop(&mut self) {
         let hal = hal::fb_hal(self.chipset);
 
-        if hal.read_sysmem_flush_page(bar) == self.page.dma_handle() {
-            let _ = hal.write_sysmem_flush_page(bar, 0).inspect_err(|e| {
+        if hal.read_sysmem_flush_page(self.bar) == self.page.dma_handle() {
+            let _ = hal.write_sysmem_flush_page(self.bar, 0).inspect_err(|e| {
                 dev_warn!(
                     &self.device,
                     "failed to unregister sysmem flush page: {:?}\n",
drivers/gpu/nova-core/gpu.rs +1 -8
index 03295fa6fb32..c17d068b35eb 100644
@@ -228,7 +228,7 @@ pub(crate) struct Gpu<'bound> {
     bar: &'bound Bar0,
     /// System memory page required for flushing all pending GPU-side memory writes done through
     /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation).
-    sysmem_flush: SysmemFlush,
+    sysmem_flush: SysmemFlush<'bound>,
     /// GSP falcon instance, used for GSP boot up and cleanup.
     gsp_falcon: Falcon<GspFalcon>,
     /// SEC2 falcon instance, used for GSP boot up and cleanup.
@@ -271,11 +271,4 @@ pub(crate) fn new(
             _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)? },
         })
     }
-
-    /// Called when the corresponding [`Device`](device::Device) is unbound.
-    ///
-    /// Note: This method must only be called from `Driver::unbind`.
-    pub(crate) fn unbind(&self) {
-        self.sysmem_flush.unregister(self.bar);
-    }
 }
Signature · 1 line
2.54.0
author maintainer
#29 lore raw

PATCH v2 24/25 gpu: nova-core: replace ARef<Device> with &'bound Device in SysmemFlush

In reply to Danilo Krummrich

Now that SysmemFlush is lifetime-parameterized, the ARef<Device> is unnecessary -- a plain &'bound Device reference suffices.

---
 drivers/gpu/nova-core/fb.rs | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/fb.rs +4 -5
index a707fbfe3ced..e22dec12ae7e 100644
@@ -15,8 +15,7 @@
         Alignable,
         Alignment, //
     },
-    sizes::*,
-    sync::aref::ARef, //
+    sizes::*, //
 };
 
 use crate::{
@@ -49,7 +48,7 @@
 pub(crate) struct SysmemFlush<'bound> {
     /// Chipset we are operating on.
     chipset: Chipset,
-    device: ARef<device::Device>,
+    device: &'bound device::Device,
     bar: &'bound Bar0,
     /// Keep the page alive as long as we need it.
     page: CoherentHandle,
@@ -58,7 +57,7 @@ pub(crate) struct SysmemFlush<'bound> {
 impl<'bound> SysmemFlush<'bound> {
     /// Allocate a memory page and register it as the sysmem flush page.
     pub(crate) fn register(
-        dev: &device::Device<device::Bound>,
+        dev: &'bound device::Device<device::Bound>,
         bar: &'bound Bar0,
         chipset: Chipset,
     ) -> Result<Self> {
@@ -68,7 +67,7 @@ pub(crate) fn register(
 
         Ok(Self {
             chipset,
-            device: dev.into(),
+            device: dev,
             bar,
             page,
         })
Signature · 1 line
2.54.0
author maintainer
#30 lore raw

PATCH v2 25/25 gpu: drm: tyr: use HRT lifetime for IoMem

In reply to Danilo Krummrich

Take advantage of the lifetime-parameterized IoMem<'bound> to use the memory mapping directly during probe, eliminating the Arc<Devres<IoMem>> indirection.

Since the IoMem is only used during probe, this also simplifies Register::read/write to be infallible -- the Devres access check is no longer needed, so reads return u32 directly and writes return ().

---
 drivers/gpu/drm/tyr/driver.rs | 14 ++++----
 drivers/gpu/drm/tyr/gpu.rs    | 62 +++++++++++++++++------------------
 drivers/gpu/drm/tyr/regs.rs   | 21 +++---------
 3 files changed, 41 insertions(+), 56 deletions(-)
drivers/gpu/drm/tyr/driver.rs +6 -8
index 295a627de2b2..e6c84a1433d2 100644
@@ -10,7 +10,6 @@
         Core,
         Device, //
     },
-    devres::Devres,
     drm,
     drm::ioctl,
     io::poll,
@@ -23,7 +22,6 @@
     sizes::SZ_2M,
     sync::{
         aref::ARef,
-        Arc,
         Mutex, //
     },
     time, //
@@ -37,7 +35,7 @@
     regs, //
 };
 
-pub(crate) type IoMem = kernel::io::mem::IoMem<'static, SZ_2M>;
+pub(crate) type IoMem = kernel::io::Mmio<SZ_2M>;
 
 pub(crate) struct TyrDrmDriver;
 
@@ -65,11 +63,11 @@ pub(crate) struct TyrDrmDeviceData {
     pub(crate) gpu_info: GpuInfo,
 }
 
-fn issue_soft_reset(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result {
-    regs::GPU_CMD.write(dev, iomem, regs::GPU_CMD_SOFT_RESET)?;
+fn issue_soft_reset(dev: &Device<Bound>, iomem: &IoMem) -> Result {
+    regs::GPU_CMD.write(iomem, regs::GPU_CMD_SOFT_RESET);
 
     poll::read_poll_timeout(
-        || regs::GPU_IRQ_RAWSTAT.read(dev, iomem),
+        || Ok(regs::GPU_IRQ_RAWSTAT.read(iomem)),
         |status| *status & regs::GPU_IRQ_RAWSTAT_RESET_COMPLETED != 0,
         time::Delta::from_millis(1),
         time::Delta::from_millis(100),
@@ -109,12 +107,12 @@ fn probe(
         let sram_regulator = Regulator::<regulator::Enabled>::get(pdev.as_ref(), c"sram")?;
 
         let request = pdev.io_request_by_index(0).ok_or(ENODEV)?;
-        let iomem = Arc::new(request.iomap_sized::<SZ_2M>()?.into_devres()?, GFP_KERNEL)?;
+        let iomem = request.iomap_sized::<SZ_2M>()?;
 
         issue_soft_reset(pdev.as_ref(), &iomem)?;
         gpu::l2_power_on(pdev.as_ref(), &iomem)?;
 
-        let gpu_info = GpuInfo::new(pdev.as_ref(), &iomem)?;
+        let gpu_info = GpuInfo::new(&iomem);
         gpu_info.log(pdev);
 
         let platform: ARef<platform::Device> = pdev.into();
drivers/gpu/drm/tyr/gpu.rs +30 -32

92 lines not on this page · raw message

drivers/gpu/drm/tyr/regs.rs +5 -16
index 611870c2e6af..0881b3812afd 100644
@@ -7,16 +7,7 @@
 // does.
 #![allow(dead_code)]
 
-use kernel::{
-    bits::bit_u32,
-    device::{
-        Bound,
-        Device, //
-    },
-    devres::Devres,
-    io::Io,
-    prelude::*, //
-};
+use kernel::{bits::bit_u32, io::Io};
 
 use crate::driver::IoMem;
 
@@ -29,15 +20,13 @@
 
 impl<const OFFSET: usize> Register<OFFSET> {
     #[inline]
-    pub(crate) fn read(&self, dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result<u32> {
-        let value = (*iomem).access(dev)?.read32(OFFSET);
-        Ok(value)
+    pub(crate) fn read(&self, iomem: &IoMem) -> u32 {
+        iomem.read32(OFFSET)
     }
 
     #[inline]
-    pub(crate) fn write(&self, dev: &Device<Bound>, iomem: &Devres<IoMem>, value: u32) -> Result {
-        (*iomem).access(dev)?.write32(value, OFFSET);
-        Ok(())
+    pub(crate) fn write(&self, iomem: &IoMem, value: u32) {
+        iomem.write32(value, OFFSET);
     }
 }
 
Signature · 1 line
2.54.0
author maintainer
#3 lore raw

Re: [PATCH v2 02/25] rust: types: add `ForLt` trait for higher-ranked lifetime support

In reply to Danilo Krummrich
Quoted 31 lines · Danilo Krummrich

From: Gary Guo <[email protected]>

There are a few cases, e.g. when dealing with data referencing each other, one might want to write code that are generic over lifetimes. For example, if you want take a function that takes &'a Foo and gives Bar<'a>, you can write:

    f: impl for<'a> FnOnce(&'a Foo) -> Bar<'a>,

However, it becomes tricky when you want that function to not have a fixed Bar, but have it be generic again. In this case, one needs something that is generic over types that are themselves generic over lifetimes.

ForLt provides such support. It provides a trait ForLt which describes a type generic over lifetime. One may use ForLt::Of<'a> to get an instance of a type for a specific lifetime.

For the case of cross referencing, one would almost always want the lifetime to be covariant. Therefore this is also made a requirement for the ForLt trait, so functions with ForLt trait bound can assume covariance.

A macro ForLt!() is provided to be able to obtain a type that implements ForLt. For example, ForLt!(for<'a> Bar<'a>) would yield a type that <TheType as ForLt>::Of<'a> is Bar<'a>. This also works with lifetime elision, e.g. ForLt!(Bar<'_>) or for types without lifetime at all, e.g. ForLt!(u32).

The API design draws inspiration from the higher-kinded-types [1] crate, however different design decision has been taken (e.g. covariance requirement) and the implementation is independent.

Quoted 6 lines

License headers use "Apache-2.0 OR MIT" because I anticipate this to be used in pin-init crate too which is licensed as such.

Tested-by on the v2 series
#31 lore raw
In reply to Danilo Krummrich
Quoted 91 lines · Danilo Krummrich

Currently, Rust device drivers access device resources such as PCI BAR mappings and I/O memory regions through Devres<T>.

Devres::access() provides zero-overhead access by taking a &Device<Bound> reference as proof that the device is still bound. Since a &Device<Bound> is available in almost all contexts by design, Devres is mostly a type-system level proof that the resource is valid, but it can also be used from scopes without this guarantee through its try_access() accessor.

This works well in general, but has a few limitations:

- Every access to a device resource goes through Devres::access(), which despite zero cost, adds boilerplate to every access site.

- Destructors do not receive a &Device<Bound>, so they must use try_access(), which can fail. In practice the access succeeds if teardown ordering is correct, but the type system can't express this, forcing drivers to handle a failure path that should never be taken.

- Sharing a resource across components (e.g. passing a BAR to a sub-component) requires Arc<Devres<T>>.

- Device references must be stored as ARef<Device> rather than plain &Device borrows.

These limitations stem from the driver's bus device private data being 'static -- the driver struct cannot borrow from the device reference it receives in probe(), even though it structurally cannot outlive the device binding.

This series introduces Higher-Ranked Lifetime Types (HRT) for Rust device drivers. An HRT is a type that is generic over a lifetime -- it does not have a fixed lifetime, but can be instantiated with any lifetime chosen by the caller.

Rust does not directly support types that are generic over a lifetime as type parameters; the ForLt trait (contributed by Gary Guo) encodes this internally.

The module_*_driver! macros handle the wrapping, so driver authors just write struct MyDriver<'a> and impl Driver<'a>.

With HRT, driver structs carry a lifetime parameter tied to the device binding scope -- the interval of a bus device being bound to a driver. Device resources like pci::Bar<'a> and IoMem<'a> are handed out with this lifetime, so the compiler enforces at build time that they do not escape the binding scope.

Before:

	struct MyDriver {
	    pdev: ARef<pci::Device>,
	    bar: Devres<pci::Bar<BAR_SIZE>>,
	}

	let io = self.bar.access(dev)?;
	io.read32(OFFSET);

After:

	struct MyDriver<'a> {
	    pdev: &'a pci::Device,
	    bar: pci::Bar<'a, BAR_SIZE>,
	}

	self.bar.read32(OFFSET);

Lifetime-parameterized device resources can be put into a Devres at any point via Bar::into_devres() / IoMem::into_devres(), providing the exact same semantics as before. This is useful for resources shared across subsystem boundaries where revocation is needed.

This also synergizes with the upcoming self-referential initialization support in pin-init, which allows one field of the driver struct to borrow another during initialization without unsafe code.

The same pattern is applied to auxiliary device registration data as a first example beyond bus device private data. Registration<F: ForLt> can hold lifetime-parameterized data tied to the parent driver's binding scope. Since the auxiliary bus guarantees that the parent remains bound while the auxiliary device is registered, the registration data can safely borrow the parent's device resources.

More generally, binding resource lifetimes to a registration scope applies to every registration that is scoped to a driver binding -- auxiliary devices, class devices, IRQ handlers, workqueues.

A follow-up series extends this to class device registrations, starting with DRM, so that class device callbacks (IOCTLs, etc.) can safely access device resources through the separate registration data bound to the registration's lifetime without Devres indirection.

The series contains a few driver patches for reference, indicated by the REF suffix.

Quoted 7 lines

Thanks to Gary for coming up with the ForLt implementation; thanks to Alice for the early discussions around lifetime-parameterized private data that helped shape the direction of this work.

This series depends on [1].

[1] https://lore.kernel.org/driver-core/[email protected]/

I have applied this series together with [1] on top of 7.1.0-rc1. I made some adaptions to local changes (e.g. my ARM64 TMU interrupt test) and boot tested it. Several parts this patch series touches (e.g. PCI, auxiliary, gpu) I might not use or even don't have it enabled. So I don't know if this is worth mentioning

Please feel free to ignore this, then.

Thanks

Dirk

Quoted 85 lines

Changes in v2:
- Add 'a bound to ForLt::Of<'a> and WithLt::Of, making the lifetime bound inherent to the trait; remove all F::Of<'static>: 'static where clauses
- Drop "rust: devres: add ForLt support to Devres"; Devres itself stays unchanged -- ForLt-aware access is introduced later through DevresLt in a separate series
- Use 'bound instead of 'a; add patches to consistently use 'bound for pre-existing 'a

Danilo Krummrich (24):
rust: driver core: drop drvdata before devres release
rust: device: generalize drvdata methods over ForLt
rust: driver: make Adapter trait lifetime-parameterized
rust: pci: implement Sync for Device<Bound>
rust: platform: implement Sync for Device<Bound>
rust: auxiliary: implement Sync for Device<Bound>
rust: usb: implement Sync for Device<Bound>
rust: device: implement Sync for Device<Bound>
rust: pci: make Driver trait lifetime-parameterized
rust: platform: make Driver trait lifetime-parameterized
rust: auxiliary: make Driver trait lifetime-parameterized
rust: auxiliary: generalize Registration over ForLt
samples: rust: rust_driver_auxiliary: showcase lifetime-bound
registration data
rust: usb: make Driver trait lifetime-parameterized
rust: i2c: make Driver trait lifetime-parameterized
rust: pci: make Bar lifetime-parameterized
rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
samples: rust: rust_driver_pci: use HRT lifetime for Bar
rust: driver-core: rename 'a lifetime to 'bound
gpu: nova-core: rename 'a lifetime to 'bound
gpu: nova-core: use HRT lifetime for Bar
gpu: nova-core: unregister sysmem flush page from Drop
gpu: nova-core: replace ARef<Device> with &'bound Device in
SysmemFlush
gpu: drm: tyr: use HRT lifetime for IoMem

Gary Guo (1):
rust: types: add ForLt trait for higher-ranked lifetime support

  drivers/base/dd.c                        |   2 +-
  drivers/cpufreq/rcpufreq_dt.rs           |  10 +-
  drivers/gpu/drm/nova/driver.rs           |   9 +-
  drivers/gpu/drm/tyr/driver.rs            |  24 ++-
  drivers/gpu/drm/tyr/gpu.rs               |  62 +++---
  drivers/gpu/drm/tyr/regs.rs              |  21 +-
  drivers/gpu/nova-core/driver.rs          |  48 ++---
  drivers/gpu/nova-core/fb.rs              |  31 ++-
  drivers/gpu/nova-core/firmware/gsp.rs    |   8 +-
  drivers/gpu/nova-core/gpu.rs             |  38 ++--
  drivers/gpu/nova-core/gsp/commands.rs    |  10 +-
  drivers/gpu/nova-core/gsp/fw/commands.rs |   4 +-
  drivers/gpu/nova-core/nova_core.rs       |   4 +-
  drivers/pwm/pwm_th1520.rs                |  14 +-
  include/linux/device/driver.h            |   4 +-
  rust/Makefile                            |   1 +
  rust/kernel/auxiliary.rs                 | 132 +++++++++----
  rust/kernel/cpufreq.rs                   |   8 +-
  rust/kernel/device.rs                    |  79 +++++---
  rust/kernel/devres.rs                    |  16 +-
  rust/kernel/driver.rs                    |  44 +++--
  rust/kernel/i2c.rs                       | 130 +++++++-----
  rust/kernel/io/mem.rs                    | 131 ++++++------
  rust/kernel/pci.rs                       |  89 ++++++---
  rust/kernel/pci/io.rs                    |  68 ++++---
  rust/kernel/pci/irq.rs                   |  38 ++--
  rust/kernel/platform.rs                  | 120 +++++++----
  rust/kernel/types.rs                     |   4 +
  rust/kernel/types/for_lt.rs              | 117 +++++++++++
  rust/kernel/usb.rs                       |  94 +++++----
  rust/macros/for_lt.rs                    | 242 +++++++++++++++++++++++
  rust/macros/lib.rs                       |  12 ++
  samples/rust/rust_debugfs.rs             |  10 +-
  samples/rust/rust_dma.rs                 |   9 +-
  samples/rust/rust_driver_auxiliary.rs    |  53 +++--
  samples/rust/rust_driver_i2c.rs          |  18 +-
  samples/rust/rust_driver_pci.rs          |  93 ++++-----
  samples/rust/rust_driver_platform.rs     |  12 +-
  samples/rust/rust_driver_usb.rs          |  14 +-
  samples/rust/rust_i2c_client.rs          |  12 +-
  samples/rust/rust_soc.rs                 |  12 +-
  41 files changed, 1220 insertions(+), 627 deletions(-)

create mode 100644 rust/kernel/types/for_lt.rs
create mode 100644 rust/macros/for_lt.rs

reviewer
#8 lore raw

Re: [PATCH v2 04/25] rust: driver: make Adapter trait lifetime-parameterized

In reply to Danilo Krummrich
Quoted 7 lines · Danilo Krummrich

Parameterize the Adapter trait with a lifetime, changing the id_info(), of_id_info() and acpi_id_info() methods to take &'bound Device<Bound> and return &'bound Self::IdInfo instead of &'static.

This is needed for the ForLt conversion of bus driver traits. Once Driver becomes lifetime-parameterized, its IdInfo associated type may depend on the lifetime parameter.

How? The IdInfo is part of the ID table which is static.

I feel that this is really just adding lifetime for the sake of adding it. Nothing in Adapter is really tied to device lifetime.

Quoted 2 lines

With Adapter<'bound>, the impl can set
IdInfo = <F::Of<'bound> as Driver<'bound>>::IdInfo and the lifetime flows

Well, I do get that you're trying to avoid writing Driver<'static>. This is needed because conceptually, a Driver trait have a lifetime-dependent part and a lifetime independent part.

IdInfo and ID_TABLE are the lifetime-independent part, and probe and unbind are lifetime dependent part. We really only have this issue because we use Self instead of an associated data for driver's data.

The Driver could be more cleanly designed if expressed like this:

    trait Driver {
        type IdInfo;
        const ID_TABLE: IdTable<Self::IdInfo>;

        type Data<'bound>;

        fn probe<'bound>(
            dev: &'bound Device<device::Core>,
            id_info: &'bound Self::IdInfo,
        ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;

        ...
    }

Then there's no Driver<'static> at all.

But even if we don't go with that design, I'd prefer using Driver<'static> to giving lifetime parameters to types that shouldn't have one.

Quoted 1 line

through naturally, avoiding the need for transmute.

I applied the following diff and it doesn't require additional transmute?

rust/kernel/driver.rs +4 -4
index 7c5148772697..4c5bc31fd71d 100644
@@ -316,7 +316,7 @@ unsafe fn acpi_of_match_device(
 /// of a device and a driver.
 ///
 /// It provides bus independent functions for device / driver interactions.
-pub trait Adapter<'bound> {
+pub trait Adapter {
     /// The type holding driver private data about each device id supported by the driver.
     type IdInfo: 'static;
 
@@ -326,7 +326,7 @@ pub trait Adapter<'bound> {
     /// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.
     ///
     /// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].
-    fn acpi_id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
+    fn acpi_id_info(dev: &Device<Bound>) -> Option<&'static Self::IdInfo> {
         #[cfg(not(CONFIG_ACPI))]
         {
             let _ = dev;
@@ -360,7 +360,7 @@ fn acpi_id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
     /// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.
     ///
     /// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].
-    fn of_id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
+    fn of_id_info(dev: &Device<Bound>) -> Option<&'static Self::IdInfo> {
         let table = Self::of_id_table()?;
 
         #[cfg(not(any(CONFIG_OF, CONFIG_ACPI)))]
@@ -424,7 +424,7 @@ fn of_id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
     ///
     /// If this returns `None`, it means that there is no match in any of the ID tables directly
     /// associated with a [`device::Device`].
-    fn id_info(dev: &'bound Device<Bound>) -> Option<&'bound Self::IdInfo> {
+    fn id_info(dev: &Device<Bound>) -> Option<&'static Self::IdInfo> {
         let id = Self::acpi_id_info(dev);
         if id.is_some() {
             return id;
rust/kernel/i2c.rs +6 -6
index 5a601cba7dc0..739b97c9917d 100644
@@ -183,7 +183,7 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_
 
         from_result(|| {
             let info = Self::i2c_id_info(idev)
-                .or_else(|| <Self as driver::Adapter<'_>>::id_info(idev.as_ref()));
+                .or_else(|| <Self as driver::Adapter>::id_info(idev.as_ref()));
             let data = <F::Of<'_> as Driver<'_>>::probe(idev, info);
 
             idev.as_ref().set_drvdata::<F>(data)?;
@@ -243,19 +243,19 @@ fn i2c_id_info<'bound>(
     }
 }
 
-impl<'bound, F> driver::Adapter<'bound> for Adapter<F>
+impl<F> driver::Adapter for Adapter<F>
 where
     F: ForLt + 'static,
-    F::Of<'bound>: Driver<'bound>,
+    for<'bound> F::Of<'bound>: Driver<'bound>,
 {
-    type IdInfo = <F::Of<'bound> as Driver<'bound>>::IdInfo;
+    type IdInfo = <F::Of<'static> as Driver<'static>>::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
-        <F::Of<'bound> as Driver<'bound>>::OF_ID_TABLE
+        <F::Of<'static> as Driver<'static>>::OF_ID_TABLE
     }
 
     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
-        <F::Of<'bound> as Driver<'bound>>::ACPI_ID_TABLE
+        <F::Of<'static> as Driver<'static>>::ACPI_ID_TABLE
     }
 }
 
rust/kernel/platform.rs +5 -5
index f59f22283c53..f4df2e474ca0 100644
@@ -120,7 +120,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff
         let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
 
         from_result(|| {
-            let info = <Self as driver::Adapter<'_>>::id_info(pdev.as_ref());
+            let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
             let data = <F::Of<'_> as Driver<'_>>::probe(pdev, info);
 
             pdev.as_ref().set_drvdata::<F>(data)?;
@@ -143,19 +143,19 @@ extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
     }
 }
 
-impl<'bound, F> driver::Adapter<'bound> for Adapter<F>
+impl<F> driver::Adapter for Adapter<F>
 where
     F: ForLt + 'static,
     for<'b> F::Of<'b>: Driver<'b>,
 {
-    type IdInfo = <F::Of<'bound> as Driver<'bound>>::IdInfo;
+    type IdInfo = <F::Of<'static> as Driver<'static>>::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
-        <F::Of<'bound> as Driver<'bound>>::OF_ID_TABLE
+        <F::Of<'static> as Driver<'static>>::OF_ID_TABLE
     }
 
     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
-        <F::Of<'bound> as Driver<'bound>>::ACPI_ID_TABLE
+        <F::Of<'static> as Driver<'static>>::ACPI_ID_TABLE
     }
 }
 
maintainer
#5 lore raw

Re: [PATCH v2 03/25] rust: device: generalize drvdata methods over ForLt

In reply to Danilo Krummrich

rust/kernel/driver.rs line 127

Quoted 4 lines · Danilo Krummrich
rust/kernel/driver.rs +2 -2
-    /// The type of the driver's device private data.
-    type DriverData;
+    /// The [`ForLt`](trait@ForLt) encoding of the driver's device private data type.
+    type DriverData: ForLt;

Associated types support ForLt natively.

    type DriverData<'bound>;

Alice

author maintainer
#9 lore raw

Re: [PATCH v2 04/25] rust: driver: make Adapter trait lifetime-parameterized

In reply to Gary Guo
Quoted 2 lines · Gary Guo

I applied the following diff and it doesn't require additional transmute?

You are correct, this patch isn't needed -- at least it is not needed anymore, it was at some point during the implementation of this series. I will drop it.

author maintainer
#6 lore raw

Re: [PATCH v2 03/25] rust: device: generalize drvdata methods over ForLt

In reply to Alice Ryhl
Quoted 7 lines · Alice Ryhl

rust/kernel/driver.rs line 127

Quoted 4 lines · Danilo Krummrich
rust/kernel/driver.rs +2 -2
-    /// The type of the driver's device private data.
-    type DriverData;
+    /// The [`ForLt`](trait@ForLt) encoding of the driver's device private data type.
+    type DriverData: ForLt;

Associated types support ForLt natively.

Correct, and as it stands DriverData is only directly used for Device::drvdata_obtain(), which doesn't necessarily need the covariance guarantee the ForLt bound provides.

However, I chose to use ForLt regardless as it prevents future users of DriverData from running into the covariance trap, plus it keeps the code more streamlined in the driver-core and in buses.

author maintainer
#32 lore raw
In reply to Dirk Behme
Quoted 9 lines · Dirk Behme

I have applied this series together with [1] on top of 7.1.0-rc1. I made some adaptions to local changes (e.g. my ARM64 TMU interrupt test) and boot tested it. Several parts this patch series touches (e.g. PCI, auxiliary, gpu) I might not use or even don't have it enabled. So I don't know if this is worth mentioning

Please feel free to ignore this, then.

Thanks Dirk! Any test coverage is valuable and much appreciated.