Skip to contentSkip to conversation

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

PATCH Superseded Danilo Krummrich 7 participants 39 messages Apr 27 – May 5

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

v1 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

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]/

Danilo Krummrich (23):
rust: driver core: drop drvdata before devres release
rust: devres: add ForLt support to Devres
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
gpu: nova-core: use HRT lifetime for Bar
gpu: nova-core: unregister sysmem flush page from Drop
gpu: nova-core: replace ARef<Device> with &'a 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/gpu.rs          |  32 +---
 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              | 144 ++++++++++-----
 rust/kernel/cpufreq.rs                |   8 +-
 rust/kernel/device.rs                 |  84 ++++++---
 rust/kernel/devres.rs                 |  31 +++-
 rust/kernel/driver.rs                 |  44 +++--
 rust/kernel/i2c.rs                    | 121 ++++++++-----
 rust/kernel/io/mem.rs                 | 118 ++++++-------
 rust/kernel/pci.rs                    |  88 +++++++---
 rust/kernel/pci/io.rs                 |  50 +++---
 rust/kernel/platform.rs               | 101 +++++++----
 rust/kernel/types.rs                  |   4 +
 rust/kernel/types/for_lt.rs           | 117 +++++++++++++
 rust/kernel/usb.rs                    |  93 ++++++----
 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 +-
 37 files changed, 1182 insertions(+), 570 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 1/24 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 36de8098754d..8f0e50729215 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
#4 lore raw

PATCH 2/24 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
#6 lore raw

PATCH 3/24 rust: devres: add ForLt support to Devres

In reply to Danilo Krummrich

Use ForLt::cast_ref() in Devres access methods, enabling lifetime shortening for types that are covariant over their lifetime parameter.

This is a no-op for 'static types, but prepares Devres for use with lifetime-parameterized types such as pci::Bar<'_, SIZE>.

Add DevresGuard as a wrapper around RevocableGuard that applies ForLt::cast_ref() on deref().

---
 rust/kernel/devres.rs | 29 ++++++++++++++++++++++++-----
 1 file changed, 24 insertions(+), 5 deletions(-)
rust/kernel/devres.rs +24 -5
index 9e5f93aed20c..7baabcdb1ad3 100644
@@ -24,6 +24,7 @@
         Arc, //
     },
     types::{
+        ForLt,
         ForeignOwnable,
         Opaque, //
     },
@@ -324,22 +325,26 @@ pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {
         // SAFETY: `dev` being the same device as the device this `Devres` has been created for
         // proves that `self.data` hasn't been revoked and is guaranteed to not be revoked as long
         // as `dev` lives; `dev` lives at least as long as `self`.
-        Ok(unsafe { self.data().access() })
+        Ok(<ForLt!(T)>::cast_ref(unsafe { self.data().access() }))
     }
 
     /// [`Devres`] accessor for [`Revocable::try_access`].
-    pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
-        self.data().try_access()
+    #[allow(clippy::type_complexity)]
+    pub fn try_access(&self) -> Option<DevresGuard<'_, ForLt!(T)>> {
+        self.data().try_access().map(DevresGuard)
     }
 
     /// [`Devres`] accessor for [`Revocable::try_access_with`].
     pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
-        self.data().try_access_with(f)
+        self.data()
+            .try_access_with(|data| f(<ForLt!(T)>::cast_ref(data)))
     }
 
     /// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
     pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
-        self.data().try_access_with_guard(guard)
+        self.data()
+            .try_access_with_guard(guard)
+            .map(<ForLt!(T)>::cast_ref)
     }
 }
 
@@ -365,6 +370,20 @@ fn drop(&mut self) {
     }
 }
 
+/// Guard returned by [`Devres::try_access`].
+///
+/// Dereferences to `F::Of<'a>`, applying [`ForLt::cast_ref`] to shorten the lifetime of the
+/// stored data to the guard's borrow lifetime.
+pub struct DevresGuard<'a, F: ForLt>(RevocableGuard<'a, F::Of<'static>>);
+
+impl<'a, F: ForLt> core::ops::Deref for DevresGuard<'a, F> {
+    type Target = F::Of<'a>;
+
+    fn deref(&self) -> &Self::Target {
+        F::cast_ref(&*self.0)
+    }
+}
+
 /// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.
 fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
 where
Signature · 1 line
2.54.0
author maintainer
#8 lore raw

PATCH 4/24 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<'a> 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    | 80 +++++++++++++++++++++++++++++-----------
 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, 101 insertions(+), 47 deletions(-)
rust/kernel/auxiliary.rs +4 -3
index 467befea8e44..5cd10b254baf 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 +58 -22

129 lines not on this page · raw message

rust/kernel/driver.rs +10 -5
index 8f0e50729215..29a67b12c872 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
#9 lore raw

PATCH 5/24 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 &'a Device<Bound> and return &'a 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<'a>, the impl can set IdInfo = <F::Of<'a> as Driver<'a>>::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 &'a.

---
 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 29a67b12c872..91490040d77e 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.
@@ -289,7 +293,7 @@ fn init(
 /// of a device and a driver.
 ///
 /// It provides bus independent functions for device / driver interactions.
-pub trait Adapter {
+pub trait Adapter<'a> {
     /// The type holding driver private data about each device id supported by the driver.
     type IdInfo: 'static;
 
@@ -299,7 +303,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: &'a Device<Bound>) -> Option<&'a Self::IdInfo> {
         #[cfg(not(CONFIG_ACPI))]
         {
             let _ = dev;
@@ -333,7 +337,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: &'a Device<Bound>) -> Option<&'a Self::IdInfo> {
         #[cfg(not(CONFIG_OF))]
         {
             let _ = dev;
@@ -369,7 +373,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: &'a Device<Bound>) -> Option<&'a Self::IdInfo> {
         let id = Self::acpi_id_info(dev);
         if id.is_some() {
             return id;
rust/kernel/i2c.rs +5 -5
index cde3dd7a6cc7..08d310aa9d6b 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<'a, T: Driver + 'static> driver::Adapter<'a> for Adapter<T> {
     type IdInfo = T::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
rust/kernel/platform.rs +2 -2
index 7ff69e3eea90..1585b6a1ac45 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<'a, T: Driver + 'static> driver::Adapter<'a> 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 6/24 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 &'a 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
#13 lore raw

PATCH 7/24 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 &'a 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 1585b6a1ac45..ae648304eb5b 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
#14 lore raw

PATCH 8/24 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 &'a 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 5cd10b254baf..8a278ddb5b95 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
#15 lore raw

PATCH 9/24 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 &'a 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
#16 lore raw

PATCH 10/24 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 &'a 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 09cbe8a438a9..b330b87178d3 100644
@@ -503,6 +503,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
#17 lore raw

PATCH 11/24 rust: pci: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

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

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a HRTB bound for<'a> F::Of<'a>: Driver<'a>; 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                    | 79 +++++++++++++++++++--------
 samples/rust/rust_dma.rs              |  9 ++-
 samples/rust/rust_driver_auxiliary.rs | 13 +++--
 samples/rust/rust_driver_pci.rs       | 11 ++--
 6 files changed, 86 insertions(+), 39 deletions(-)
drivers/gpu/nova-core/driver.rs +6 -3
index 8fe484d357f6..815489dd92d0 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<'a> pci::Driver<'a> 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: &'a pci::Device<Core>,
+        _info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         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 +55 -24

177 lines not on this page · raw message

samples/rust/rust_dma.rs +6 -3
index 129bb4b39c04..8b6f8c923049 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<'a> pci::Driver<'a> 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: &'a pci::Device<Core>,
+        _info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         pin_init::pin_init_scope(move || {
             dev_info!(pdev, "Probe DMA test driver.\n");
 
samples/rust/rust_driver_auxiliary.rs +9 -4
index 319ef734c02b..f57b2b03adb6 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<'a> pci::Driver<'a> 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: &'a pci::Device<Core>,
+        _info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         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..2747beecb5fd 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<'a> pci::Driver<'a> 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: &'a pci::Device<Core>,
+        info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         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: &'a pci::Device<Core>, this: Pin<&'a 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
#18 lore raw

PATCH 12/24 rust: platform: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

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

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a bound for<'a> F::Of<'a>: Driver<'a>; 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              | 92 ++++++++++++++++++----------
 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, 116 insertions(+), 85 deletions(-)
drivers/cpufreq/rcpufreq_dt.rs +5 -5
index f17bf64c22e2..06c05f946829 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<'a> platform::Driver<'a> 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: &'a platform::Device<Core>,
+        _id_info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         cpufreq::Registration::<CPUFreqDTDriver>::new_foreign_owned(pdev.as_ref())?;
         Ok(Self {})
     }
drivers/gpu/drm/tyr/driver.rs +5 -5
index 279710b36a10..7cc47ec76863 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<'a> platform::Driver<'a> 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: &'a platform::Device<Core>,
+        _info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         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..7139f3f4373d 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<'a> platform::Driver<'a> 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: &'a platform::Device<Core>,
+        _id_info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         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 91490040d77e..03974690406b 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<'a>: 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: &'a Device<device::Core>,
+//!         id_info: &'a Self::IdInfo,
+//!     ) -> impl PinInit<Self, Error> + 'a;
 //!
 //!     /// Driver unbind (optional).
-//!     fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
+//!     fn unbind(dev: &'a Device<device::Core>, this: Pin<&'a Self>) {
 //!         let _ = (dev, this);
 //!     }
 //! }
rust/kernel/io/mem.rs +8 -8
index 7dc78d547f7a..a483e59054e8 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<'a> platform::Driver<'a> for SampleDriver {
     ///    # type IdInfo = ();
     ///
     ///    fn probe(
-    ///       pdev: &platform::Device<Core>,
-    ///       info: Option<&Self::IdInfo>,
-    ///    ) -> impl PinInit<Self, Error> {
+    ///       pdev: &'a platform::Device<Core>,
+    ///       info: Option<&'a Self::IdInfo>,
+    ///    ) -> impl PinInit<Self, Error> + 'a {
     ///       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<'a> platform::Driver<'a> for SampleDriver {
     ///    # type IdInfo = ();
     ///
     ///    fn probe(
-    ///       pdev: &platform::Device<Core>,
-    ///       info: Option<&Self::IdInfo>,
-    ///    ) -> impl PinInit<Self, Error> {
+    ///       pdev: &'a platform::Device<Core>,
+    ///       info: Option<&'a Self::IdInfo>,
+    ///    ) -> impl PinInit<Self, Error> + 'a {
     ///       let offset = 0; // Some offset.
     ///
     ///       // Unlike [`Self::iomap_sized`], here the size of the memory region
rust/kernel/platform.rs +60 -32

199 lines not on this page · raw message

samples/rust/rust_debugfs.rs +5 -5
index 0963efe19f93..0d88a9aaa957 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<'a> platform::Driver<'a> 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: &'a platform::Device<Core>,
+        _info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         RustDebugFs::new(pdev).pin_chain(|this| {
             this.counter.store(91, Relaxed);
             {
samples/rust/rust_driver_platform.rs +6 -6
index f2229d176fb9..cf9177bf3202 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<'a> platform::Driver<'a> 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: &'a platform::Device<Core>,
+        info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         let dev = pdev.as_ref();
 
         dev_dbg!(dev, "Probe Rust Platform driver sample.\n");
samples/rust/rust_i2c_client.rs +6 -6
index 8d2c12e535b0..342755df8b95 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<'a> platform::Driver<'a> 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: &'a platform::Device<device::Core>,
+        _info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         dev_info!(
             pdev.as_ref(),
             "Probe Rust I2C Client registration sample.\n"
samples/rust/rust_soc.rs +6 -6
index 8079c1c48416..16f1e4bcfa36 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<'a> platform::Driver<'a> 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: &'a platform::Device<Core>,
+        _info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         dev_dbg!(pdev, "Probe Rust SoC driver sample.\n");
 
         let pdev = pdev.into();
Signature · 1 line
2.54.0
author maintainer
#19 lore raw

PATCH 13/24 rust: auxiliary: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

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

Internally, Adapter<T: Driver> becomes Adapter<F: ForLt> with a bound for<'a> F::Of<'a>: Driver<'a>; 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              | 59 ++++++++++++++++++---------
 samples/rust/rust_driver_auxiliary.rs | 12 ++++--
 3 files changed, 54 insertions(+), 26 deletions(-)
drivers/gpu/drm/nova/driver.rs +6 -3
index b1af0a099551..183d0e679a0b 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<'a> auxiliary::Driver<'a> 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: &'a auxiliary::Device<Core>,
+        _info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         let data = try_pin_init!(NovaData { adev: adev.into() });
 
         let drm = drm::Device::<Self>::new(adev.as_ref(), data)?;
rust/kernel/auxiliary.rs +40 -19

128 lines not on this page · raw message

samples/rust/rust_driver_auxiliary.rs +8 -4
index f57b2b03adb6..d35963ac7fa4 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<'a> auxiliary::Driver<'a> 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: &'a auxiliary::Device<Core>,
+        _info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         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
#20 lore raw

PATCH 14/24 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              | 80 ++++++++++++++++++---------
 samples/rust/rust_driver_auxiliary.rs |  7 ++-
 3 files changed, 61 insertions(+), 30 deletions(-)
drivers/gpu/nova-core/driver.rs +3 -1
index 815489dd92d0..2a17fc99d9b6 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 +54 -26

157 lines not on this page · raw message

samples/rust/rust_driver_auxiliary.rs +4 -3
index d35963ac7fa4..4ad619c5731e 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
#21 lore raw

PATCH 15/24 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 4ad619c5731e..010ec2201a69 100644
@@ -51,14 +51,15 @@ fn probe(
     }
 }
 
-struct Data {
+struct Data<'a> {
     index: u32,
+    parent: &'a 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
#22 lore raw

PATCH 16/24 rust: usb: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

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

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

---
 rust/kernel/usb.rs              | 84 ++++++++++++++++++++-------------
 samples/rust/rust_driver_usb.rs | 14 +++---
 2 files changed, 58 insertions(+), 40 deletions(-)
rust/kernel/usb.rs +51 -33
index 442e456fd2d3..f519444cf8d0 100644
@@ -35,22 +35,34 @@
 };
 
 /// 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<'a>` is the driver struct parameterized by `'a`. 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<'a> F::Of<'a>: Driver<'a>,
+{
     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<'a> F::Of<'a>: Driver<'a>,
+{
     unsafe fn register(
         udrv: &Opaque<Self::DriverType>,
         name: &'static CStr,
@@ -61,7 +73,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 +88,11 @@ unsafe fn unregister(udrv: &Opaque<Self::DriverType>) {
     }
 }
 
-impl<T: Driver + 'static> Adapter<T> {
+impl<F> Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'a> F::Of<'a>: Driver<'a>,
+{
     extern "C" fn probe_callback(
         intf: *mut bindings::usb_interface,
         id: *const bindings::usb_device_id,
@@ -87,16 +103,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 +127,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 +296,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<'a> usb::Driver<'a> 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: &'a usb::Interface<Core>,
+///         _id: &'a usb::DeviceId,
+///         _info: &'a Self::IdInfo,
+///     ) -> impl PinInit<Self, Error> + 'a {
 ///         Err(ENODEV)
 ///     }
 ///
-///     fn disconnect(_interface: &usb::Interface<Core>, _data: Pin<&Self>) {}
+///     fn disconnect(_interface: &'a usb::Interface<Core>, _data: Pin<&'a Self>) {}
 /// }
 ///```
-pub trait Driver {
+pub trait Driver<'a> {
     /// The type holding information about each one of the device ids supported by the driver.
     type IdInfo: 'static;
 
@@ -315,15 +330,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: &'a Interface<device::Core>,
+        id: &'a DeviceId,
+        id_info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a;
 
     /// 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: &'a Interface<device::Core>, data: Pin<&'a Self>);
 }
 
 /// A USB interface.
@@ -486,7 +501,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..6f3e5db9f35d 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<'a> usb::Driver<'a> 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: &'a usb::Interface<Core>,
+        _id: &'a usb::DeviceId,
+        _info: &'a Self::IdInfo,
+    ) -> impl PinInit<Self, Error> + 'a {
         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: &'a usb::Interface<Core>, _data: Pin<&'a 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
#23 lore raw

PATCH 17/24 rust: i2c: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich

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

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

---
 rust/kernel/i2c.rs              | 116 +++++++++++++++++++-------------
 samples/rust/rust_driver_i2c.rs |  18 ++---
 2 files changed, 78 insertions(+), 56 deletions(-)
rust/kernel/i2c.rs +69 -47
index 08d310aa9d6b..4464146d6c4d 100644
@@ -92,43 +92,57 @@ 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<'a>` is the driver struct parameterized by `'a`. 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<'a> F::Of<'a>: Driver<'a>,
+{
     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<'a> F::Of<'a>: Driver<'a>,
+{
     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 +168,11 @@ unsafe fn unregister(idrv: &Opaque<Self::DriverType>) {
     }
 }
 
-impl<T: Driver + 'static> Adapter<T> {
+impl<F> Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'a> F::Of<'a>: Driver<'a>,
+{
     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 +180,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 +195,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 +206,22 @@ 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<'a>() -> Option<IdTable<<F::Of<'a> as Driver<'a>>::IdInfo>> {
+        <F::Of<'a> as Driver<'a>>::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<'a>(dev: &I2cClient) -> Option<&'a <F::Of<'a> as Driver<'a>>::IdInfo> {
+        let table = Self::i2c_id_table::<'a>()?;
 
         // SAFETY:
         // - `table` has static lifetime, hence it's valid for reads
@@ -225,15 +240,19 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter<'sta
     }
 }
 
-impl<'a, T: Driver + 'static> driver::Adapter<'a> for Adapter<T> {
-    type IdInfo = T::IdInfo;
+impl<'a, F> driver::Adapter<'a> for Adapter<F>
+where
+    F: ForLt + 'static,
+    F::Of<'a>: Driver<'a>,
+{
+    type IdInfo = <F::Of<'a> as Driver<'a>>::IdInfo;
 
     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
-        T::OF_ID_TABLE
+        <F::Of<'a> as Driver<'a>>::OF_ID_TABLE
     }
 
     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
-        T::ACPI_ID_TABLE
+        <F::Of<'a> as Driver<'a>>::ACPI_ID_TABLE
     }
 }
 
@@ -252,8 +271,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 +293,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 +302,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 +311,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<'a> i2c::Driver<'a> 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: &'a i2c::I2cClient<Core>,
+///         _id_info: Option<&'a Self::IdInfo>,
+///     ) -> impl PinInit<Self, Error> + 'a {
 ///         Err(ENODEV)
 ///     }
 ///
-///     fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self>) {
+///     fn shutdown(_idev: &'a i2c::I2cClient<Core>, _this: Pin<&'a Self>) {
 ///     }
 /// }
 ///```
-pub trait Driver: Send {
+pub trait Driver<'a>: Send {
     /// The type holding information about each device id supported by the driver.
     // TODO: Use `associated_type_defaults` once stabilized:
     //
@@ -335,9 +357,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: &'a I2cClient<device::Core>,
+        id_info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a;
 
     /// I2C driver shutdown.
     ///
@@ -350,7 +372,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: &'a I2cClient<device::Core>, this: Pin<&'a Self>) {
         let _ = (dev, this);
     }
 
@@ -364,7 +386,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: &'a I2cClient<device::Core>, this: Pin<&'a Self>) {
         let _ = (dev, this);
     }
 }
samples/rust/rust_driver_i2c.rs +9 -9
index 6be79f9e9fb5..f86c1cf7c786 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<'a> i2c::Driver<'a> 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: &'a i2c::I2cClient<Core>,
+        info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
         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: &'a i2c::I2cClient<Core>, _this: Pin<&'a Self>) {
         dev_info!(idev.as_ref(), "Shutdown Rust I2C driver sample.\n");
     }
 
-    fn unbind(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn unbind(idev: &'a i2c::I2cClient<Core>, _this: Pin<&'a Self>) {
         dev_info!(idev.as_ref(), "Unbind Rust I2C driver sample.\n");
     }
 }
Signature · 1 line
2.54.0
author maintainer
#25 lore raw

PATCH 18/24 rust: pci: make Bar lifetime-parameterized

In reply to Danilo Krummrich

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

iomap_region_sized() now returns Result<Bar<'a, 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           | 50 ++++++++++++++++++---------------
 samples/rust/rust_driver_pci.rs |  5 ++--
 4 files changed, 35 insertions(+), 29 deletions(-)
drivers/gpu/nova-core/driver.rs +4 -3
index 2a17fc99d9b6..149a20748e86 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 7baabcdb1ad3..6f3c58355d10 100644
@@ -305,7 +305,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 +27 -23

101 lines not on this page · raw message

samples/rust/rust_driver_pci.rs +3 -2
index 2747beecb5fd..38d639731229 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
#26 lore raw

PATCH 19/24 rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized

In reply to Danilo Krummrich

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

This mirrors the pci::Bar<'a, 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         | 102 +++++++++++++++++-----------------
 3 files changed, 55 insertions(+), 55 deletions(-)
drivers/gpu/drm/tyr/driver.rs +2 -2
index 7cc47ec76863..eaa84efdfdf7 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 7139f3f4373d..a45fe359c371 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 +51 -51

194 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#27 lore raw

PATCH 20/24 samples: rust: rust_driver_pci: use HRT lifetime for Bar

In reply to Danilo Krummrich

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

The driver struct holds &'a pci::Device directly instead of ARef<pci::Device>, and pci::Bar<'a> 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 38d639731229..7f763f43a38d 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<'a> = pci::Bar<'a, { 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<'a> {
+    pdev: &'a pci::Device,
+    bar: Bar0<'a>,
     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<'a> pci::Driver<'a> for SampleDriver {
+impl<'a> pci::Driver<'a> for SampleDriver<'a> {
     type IdInfo = TestIndex;
 
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
@@ -147,54 +143,47 @@ fn probe(
         pdev: &'a pci::Device<Core>,
         info: &'a Self::IdInfo,
     ) -> impl PinInit<Self, Error> + 'a {
-        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: &'a pci::Device<Core>, this: Pin<&'a 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: &'a pci::Device<Core>, this: Pin<&'a 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
#28 lore raw

PATCH 21/24 gpu: nova-core: use HRT lifetime for Bar

In reply to Danilo Krummrich

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

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 149a20748e86..ec9cecb30f63 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<'a> {
     #[pin]
-    pub(crate) gpu: Gpu,
+    pub(crate) gpu: Gpu<'a>,
+    bar: pci::Bar<'a, 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<'a> pci::Driver<'a> for NovaCore {
+impl<'a> pci::Driver<'a> for NovaCore<'a> {
     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: &'a pci::Device<Core>, this: Pin<&'a Self>) {
+        this.gpu.unbind();
     }
 }
drivers/gpu/nova-core/gpu.rs +10 -17
index 0f6fe9a1b955..922197f2aeef 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<'a> {
     spec: Spec,
-    /// MMIO mapping of PCI BAR 0
-    bar: Arc<Devres<Bar0>>,
+    /// MMIO mapping of PCI BAR 0.
+    bar: &'a 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<'a>(
+impl<'a> Gpu<'a> {
+    pub(crate) fn new(
         pdev: &'a pci::Device<device::Bound>,
-        devres_bar: Arc<Devres<Bar0>>,
         bar: &'a Bar0,
     ) -> impl PinInit<Self, Error> + 'a {
         try_pin_init!(Self {
@@ -257,6 +254,8 @@ pub(crate) fn new<'a>(
                     .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<'a>(
             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
#29 lore raw

PATCH 22/24 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 &'a 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 ec9cecb30f63..401ae213991f 100644
@@ -111,8 +111,4 @@ fn probe(
             }))
         })
     }
-
-    fn unbind(_pdev: &'a pci::Device<Core>, this: Pin<&'a Self>) {
-        this.gpu.unbind();
-    }
 }
drivers/gpu/nova-core/fb.rs +10 -12
index bdd5eed760e1..cbc42e98afca 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<'a> {
     /// Chipset we are operating on.
     chipset: Chipset,
     device: ARef<device::Device>,
+    bar: &'a Bar0,
     /// Keep the page alive as long as we need it.
     page: CoherentHandle,
 }
 
-impl SysmemFlush {
+impl<'a> SysmemFlush<'a> {
     /// Allocate a memory page and register it as the sysmem flush page.
     pub(crate) fn register(
         dev: &device::Device<device::Bound>,
-        bar: &Bar0,
+        bar: &'a 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 922197f2aeef..ff9a90a46609 100644
@@ -228,7 +228,7 @@ pub(crate) struct Gpu<'a> {
     bar: &'a 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<'a>,
     /// 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
#30 lore raw

PATCH 23/24 gpu: nova-core: replace ARef<Device> with &'a Device in SysmemFlush

In reply to Danilo Krummrich

Now that SysmemFlush is lifetime-parameterized, the ARef<Device> is unnecessary -- a plain &'a 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 cbc42e98afca..e5a2c9d42f27 100644
@@ -15,8 +15,7 @@
         Alignable,
         Alignment, //
     },
-    sizes::*,
-    sync::aref::ARef, //
+    sizes::*, //
 };
 
 use crate::{
@@ -49,7 +48,7 @@
 pub(crate) struct SysmemFlush<'a> {
     /// Chipset we are operating on.
     chipset: Chipset,
-    device: ARef<device::Device>,
+    device: &'a device::Device,
     bar: &'a Bar0,
     /// Keep the page alive as long as we need it.
     page: CoherentHandle,
@@ -58,7 +57,7 @@ pub(crate) struct SysmemFlush<'a> {
 impl<'a> SysmemFlush<'a> {
     /// Allocate a memory page and register it as the sysmem flush page.
     pub(crate) fn register(
-        dev: &device::Device<device::Bound>,
+        dev: &'a device::Device<device::Bound>,
         bar: &'a 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
#31 lore raw

PATCH 24/24 gpu: drm: tyr: use HRT lifetime for IoMem

In reply to Danilo Krummrich

Take advantage of the lifetime-parameterized IoMem<'a> 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 ().

---
Not yet updated to Tyr using the register!() macro, but probably good enough for reference.

---
 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 eaa84efdfdf7..d305ad433e03 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
#5 lore raw

Re: [PATCH 02/24] 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.

reviewer
#11 lore raw

Re: [PATCH 06/24] rust: pci: implement Sync for Device<Bound>

In reply to Danilo Krummrich
Quoted 17 lines · 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 &'a Device<Bound> (required for Bar::into_devres()) while remaining Send.

---
 rust/kernel/pci.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/pci.rs +0 -0
index fe5148f41d8b..6f82f2e6c74f 100644

rust/kernel/pci.rs unsafe impl Send for Device {} · line 532

Quoted 7 lines
rust/kernel/pci.rs +4 -0
@@ -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> {}

Given that you're now implementing for two ctx marker types, it might worth changing the existing one to spell out the Normal explicitly (also saves you from having to spell it out in the comment).

It might also make sense to write a comment to say that why it's not the case for Device<Core>.

Best,
Gary

maintainer Acked-by on the v1 series
#34 lore raw
In reply to Danilo Krummrich

Hello,

Quoted 1 line · Danilo Krummrich
 drivers/pwm/pwm_th1520.rs             |  14 +-

I didn't try to understand what you do here, but there is nothing scheduled so far for the pwm_th1520 driver in my tree, so

for patches #12 and #19 touching this driver for merging through (I guess) the rust tree. Maybe Michal wants to say something about the actual change.

Best regards
Uwe

author maintainer
#35 lore raw
Quoted 2 lines · Uwe Kleine-König

I didn't try to understand what you do here, but there is nothing scheduled so far for the pwm_th1520 driver in my tree, so

Compressed to one sentence, it is driver core plumbing to allow bus device private data (and registration data) to represent their lifetime being tied to the device / driver lifecycle with native Rust lifetimes.

Drivers can take advantage of this subsequently; for reference see the nova-core changes at the end of this series.

Quoted 4 lines

for patches #12 and #19 touching this driver for merging through (I guess) the rust tree.

Thanks -- as mentioned, it is driver core plumbing, so eventually I'll take it through the driver core tree.

- Danilo

author maintainer
#12 lore raw

Re: [PATCH 06/24] rust: pci: implement Sync for Device<Bound>

In reply to Gary Guo
Quoted 3 lines · Gary Guo

Given that you're now implementing for two ctx marker types, it might worth changing the existing one to spell out the Normal explicitly (also saves you from having to spell it out in the comment).

I don't think this belongs in this commit and I'm not sure it is worth creating new ones for only this purpose.

Quoted 2 lines

It might also make sense to write a comment to say that why it's not the case for Device<Core>.

I think the documentation in [1] explains (or at least implies) it. Where do you suggest to put such a comment? It seems a bit repretitive to have it for all bus devices.

[1] https://rust.docs.kernel.org/kernel/device/struct.Core.html

author maintainer
#7 lore raw

Re: [PATCH 03/24] rust: devres: add ForLt support to Devres

In reply to Danilo Krummrich
Quoted 10 lines · Danilo Krummrich

Use ForLt::cast_ref() in Devres access methods, enabling lifetime shortening for types that are covariant over their lifetime parameter.

This is a no-op for 'static types, but prepares Devres for use with lifetime-parameterized types such as pci::Bar<'_, SIZE>.

Add DevresGuard as a wrapper around RevocableGuard that applies ForLt::cast_ref() on deref().

Please disregard this patch, it does nothing for this patch series.

It sneaked in from a subsequent series I work on which makes device resource types, such as pci::Bar, ForLt!() types themselves.

One difficulty is that ForLt!(Bar<'_, SIZE>) fails when SIZE is a generic const parameter, as it would require generic_const_exprs.

maintainer
#2 lore raw

Re: [PATCH 01/24] rust: driver core: drop drvdata before devres release

In reply to Danilo Krummrich
Quoted 29 lines · Danilo Krummrich

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 +0 -0
index 5799a60fd058..be59d2e13a15 100644

drivers/base/dd.c static DEVICE_ATTR_RW(state_synced); · line 601

Quoted 10 lines
drivers/base/dd.c +1 -1
@@ -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;

I seem to recall that we discussed a plan to have two classes of devres callbacks where device unbind proceeds as follows:

1. Run first class of devres callbacks.
2. Device is now considered unbound.
3. Run second class of devres callbacks.

Is that still the plan?

Alice

maintainer
#36 lore raw
In reply to Danilo Krummrich

Super cool to see this!

Quoted 10 lines · Danilo Krummrich

Before:

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

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

After:

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

	self.bar.read32(OFFSET);

I think we should establish a convention for how to name the lifetime early. Using just the generic name 'a is probably not ideal.

How about using 'dev for lifetimes that correspond to the lifetime of the device being bound?

Alice

#37 lore raw
Quoted 20 lines · Alice Ryhl

Super cool to see this!

Quoted 17 lines · Danilo Krummrich

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>,
	}
Quoted 7 lines
Quoted 1 line
	self.bar.read32(OFFSET);

I think we should establish a convention for how to name the lifetime early. Using just the generic name 'a is probably not ideal.

How about using 'dev for lifetimes that correspond to the lifetime of the device being bound?

Good idea, it's not obvious what this lifetime covers at first sight. I'd even hammer it a bit more in the documentation as it is quite an essential point.

author maintainer
#3 lore raw

Re: [PATCH 01/24] rust: driver core: drop drvdata before devres release

In reply to Alice Ryhl
Quoted 44 lines · Alice Ryhl
Quoted 29 lines · Danilo Krummrich

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 +0 -0
index 5799a60fd058..be59d2e13a15 100644

drivers/base/dd.c static DEVICE_ATTR_RW(state_synced); · line 601

Quoted 10 lines
drivers/base/dd.c +1 -1
@@ -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;

I seem to recall that we discussed a plan to have two classes of devres callbacks where device unbind proceeds as follows:

Quoted 5 lines

1. Run first class of devres callbacks.
2. Device is now considered unbound.
3. Run second class of devres callbacks.

Is that still the plan?

Yes, it is -- I have most patches for this around and landed some devres prerequisites last cycle.

Also note that this series already makes the situation better in this regard, since when drivers use HRT types rather than Devres, only Registration types remain to be guarded by devres.

author maintainer
#38 lore raw
In reply to Alice Ryhl
Quoted 20 lines · Alice Ryhl

Super cool to see this!

Quoted 17 lines · Danilo Krummrich

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>,
	}
Quoted 7 lines
Quoted 1 line
	self.bar.read32(OFFSET);

I think we should establish a convention for how to name the lifetime early. Using just the generic name 'a is probably not ideal.

How about using 'dev for lifetimes that correspond to the lifetime of the device being bound?

I'd rather not go for 'dev, as it could be confused with the lifetime of the struct device itself, which is reference counted and independent from the device / driver binding lifecycle.

People already confuse this all the time, so I'd rather go for 'bound, which is more precise, but could be a bit long on the other hand.

maintainer Acked-by on v1 17/24
#24 lore raw

Re: [PATCH 17/24] rust: i2c: make Driver trait lifetime-parameterized

In reply to Danilo Krummrich
Quoted 337 lines · Danilo Krummrich

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

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

---
  rust/kernel/i2c.rs              | 116 +++++++++++++++++++-------------
  samples/rust/rust_driver_i2c.rs |  18 ++---
  2 files changed, 78 insertions(+), 56 deletions(-)
rust/kernel/i2c.rs +69 -47
index 08d310aa9d6b..4464146d6c4d 100644
@@ -92,43 +92,57 @@ 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<'a>` is the driver struct parameterized by `'a`. 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<'a> F::Of<'a>: Driver<'a>,
+{
      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<'a> F::Of<'a>: Driver<'a>,
+{
      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 +168,11 @@ unsafe fn unregister(idrv: &Opaque<Self::DriverType>) {
      }
  }
 
-impl<T: Driver + 'static> Adapter<T> {
+impl<F> Adapter<F>
+where
+    F: ForLt + 'static,
+    for<'a> F::Of<'a>: Driver<'a>,
+{
      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 +180,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 +195,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 +206,22 @@ 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<'a>() -> Option<IdTable<<F::Of<'a> as Driver<'a>>::IdInfo>> {
+        <F::Of<'a> as Driver<'a>>::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<'a>(dev: &I2cClient) -> Option<&'a <F::Of<'a> as Driver<'a>>::IdInfo> {
+        let table = Self::i2c_id_table::<'a>()?;
 
          // SAFETY:
          // - `table` has static lifetime, hence it's valid for reads
@@ -225,15 +240,19 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter<'sta
      }
  }
 
-impl<'a, T: Driver + 'static> driver::Adapter<'a> for Adapter<T> {
-    type IdInfo = T::IdInfo;
+impl<'a, F> driver::Adapter<'a> for Adapter<F>
+where
+    F: ForLt + 'static,
+    F::Of<'a>: Driver<'a>,
+{
+    type IdInfo = <F::Of<'a> as Driver<'a>>::IdInfo;
 
      fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
-        T::OF_ID_TABLE
+        <F::Of<'a> as Driver<'a>>::OF_ID_TABLE
      }
 
      fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
-        T::ACPI_ID_TABLE
+        <F::Of<'a> as Driver<'a>>::ACPI_ID_TABLE
      }
  }
 
@@ -252,8 +271,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 +293,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 +302,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 +311,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<'a> i2c::Driver<'a> 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: &'a i2c::I2cClient<Core>,
+///         _id_info: Option<&'a Self::IdInfo>,
+///     ) -> impl PinInit<Self, Error> + 'a {
  ///         Err(ENODEV)
  ///     }
  ///
-///     fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self>) {
+///     fn shutdown(_idev: &'a i2c::I2cClient<Core>, _this: Pin<&'a Self>) {
  ///     }
  /// }
  ///```
-pub trait Driver: Send {
+pub trait Driver<'a>: Send {
      /// The type holding information about each device id supported by the driver.
      // TODO: Use `associated_type_defaults` once stabilized:
      //
@@ -335,9 +357,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: &'a I2cClient<device::Core>,
+        id_info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a;
 
      /// I2C driver shutdown.
      ///
@@ -350,7 +372,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: &'a I2cClient<device::Core>, this: Pin<&'a Self>) {
          let _ = (dev, this);
      }
 
@@ -364,7 +386,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: &'a I2cClient<device::Core>, this: Pin<&'a Self>) {
          let _ = (dev, this);
      }
  }
samples/rust/rust_driver_i2c.rs +7 -7
index 6be79f9e9fb5..f86c1cf7c786 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<'a> i2c::Driver<'a> 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: &'a i2c::I2cClient<Core>,
+        info: Option<&'a Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'a {
          let dev = idev.as_ref();
 
          dev_info!(dev, "Probe Rust I2C driver sample.\n");
@@ -55,11 +55,11 @@ fn probe(
          Ok(Self)
      }
 

samples/rust/rust_driver_i2c.rs fn probe( · line 65

Quoted 10 lines
samples/rust/rust_driver_i2c.rs +2 -2
-    fn shutdown(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn shutdown(idev: &'a i2c::I2cClient<Core>, _this: Pin<&'a Self>) {
          dev_info!(idev.as_ref(), "Shutdown Rust I2C driver sample.\n");
      }
 
-    fn unbind(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn unbind(idev: &'a i2c::I2cClient<Core>, _this: Pin<&'a Self>) {
          dev_info!(idev.as_ref(), "Unbind Rust I2C driver sample.\n");
      }
  }

Cheers
Igor

#32 lore raw

Re: [PATCH REF 24/24] gpu: drm: tyr: use HRT lifetime for IoMem

In reply to Danilo Krummrich
Quoted 7 lines · Danilo Krummrich

Take advantage of the lifetime-parameterized IoMem<'a> 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 ().

Hi Danilo,
Is the intended model that DRM drivers keep lifetime-bound resources such as IoMem<'bound> only in platform drvdata and access them via Device::drvdata_borrow()?

Or is the expectation that drm::Driver should also have a lifetime-parameterized Data associated type?

The reason I ask is that Tyr currently stores an MMIO handle in several areas, (firmware, MMU/address-space management, and IRQ handling) and it does register accesses directly. See what we're trying to do:
https://lore.kernel.org/rust-for-linux/[email protected]/

Moving IoMem<'bound> only into platform drvdata would require a big refactor to thread &IoMem<'_> through those paths or fetch it from drvdata at each hardware access site. So, I wanted to clarify the plan first before I start this work.

Thanks,
Deborah

Quoted 215 lines

---
Not yet updated to Tyr using the register!() macro, but probably good enough for reference.

---
 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 eaa84efdfdf7..d305ad433e03 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
index a88775160f98..bb0473c85bf7 100644
@@ -10,7 +10,6 @@
         Bound,
         Device, //
     },
-    devres::Devres,
     io::poll,
     platform,
     prelude::*,
@@ -35,37 +34,36 @@
 pub(crate) struct GpuInfo(pub(crate) uapi::drm_panthor_gpu_info);
 
 impl GpuInfo {
-    pub(crate) fn new(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result<Self> {
-        let gpu_id = regs::GPU_ID.read(dev, iomem)?;
-        let csf_id = regs::GPU_CSF_ID.read(dev, iomem)?;
-        let gpu_rev = regs::GPU_REVID.read(dev, iomem)?;
-        let core_features = regs::GPU_CORE_FEATURES.read(dev, iomem)?;
-        let l2_features = regs::GPU_L2_FEATURES.read(dev, iomem)?;
-        let tiler_features = regs::GPU_TILER_FEATURES.read(dev, iomem)?;
-        let mem_features = regs::GPU_MEM_FEATURES.read(dev, iomem)?;
-        let mmu_features = regs::GPU_MMU_FEATURES.read(dev, iomem)?;
-        let thread_features = regs::GPU_THREAD_FEATURES.read(dev, iomem)?;
-        let max_threads = regs::GPU_THREAD_MAX_THREADS.read(dev, iomem)?;
-        let thread_max_workgroup_size = regs::GPU_THREAD_MAX_WORKGROUP_SIZE.read(dev, iomem)?;
-        let thread_max_barrier_size = regs::GPU_THREAD_MAX_BARRIER_SIZE.read(dev, iomem)?;
-        let coherency_features = regs::GPU_COHERENCY_FEATURES.read(dev, iomem)?;
-
-        let texture_features = regs::GPU_TEXTURE_FEATURES0.read(dev, iomem)?;
-
-        let as_present = regs::GPU_AS_PRESENT.read(dev, iomem)?;
-
-        let shader_present = u64::from(regs::GPU_SHADER_PRESENT_LO.read(dev, iomem)?);
+    pub(crate) fn new(iomem: &IoMem) -> Self {
+        let gpu_id = regs::GPU_ID.read(iomem);
+        let csf_id = regs::GPU_CSF_ID.read(iomem);
+        let gpu_rev = regs::GPU_REVID.read(iomem);
+        let core_features = regs::GPU_CORE_FEATURES.read(iomem);
+        let l2_features = regs::GPU_L2_FEATURES.read(iomem);
+        let tiler_features = regs::GPU_TILER_FEATURES.read(iomem);
+        let mem_features = regs::GPU_MEM_FEATURES.read(iomem);
+        let mmu_features = regs::GPU_MMU_FEATURES.read(iomem);
+        let thread_features = regs::GPU_THREAD_FEATURES.read(iomem);
+        let max_threads = regs::GPU_THREAD_MAX_THREADS.read(iomem);
+        let thread_max_workgroup_size = regs::GPU_THREAD_MAX_WORKGROUP_SIZE.read(iomem);
+        let thread_max_barrier_size = regs::GPU_THREAD_MAX_BARRIER_SIZE.read(iomem);
+        let coherency_features = regs::GPU_COHERENCY_FEATURES.read(iomem);
+
+        let texture_features = regs::GPU_TEXTURE_FEATURES0.read(iomem);
+
+        let as_present = regs::GPU_AS_PRESENT.read(iomem);
+
+        let shader_present = u64::from(regs::GPU_SHADER_PRESENT_LO.read(iomem));
         let shader_present =
-            shader_present | u64::from(regs::GPU_SHADER_PRESENT_HI.read(dev, iomem)?) << 32;
+            shader_present | u64::from(regs::GPU_SHADER_PRESENT_HI.read(iomem)) << 32;
 
-        let tiler_present = u64::from(regs::GPU_TILER_PRESENT_LO.read(dev, iomem)?);
-        let tiler_present =
-            tiler_present | u64::from(regs::GPU_TILER_PRESENT_HI.read(dev, iomem)?) << 32;
+        let tiler_present = u64::from(regs::GPU_TILER_PRESENT_LO.read(iomem));
+        let tiler_present = tiler_present | u64::from(regs::GPU_TILER_PRESENT_HI.read(iomem)) << 32;
 
-        let l2_present = u64::from(regs::GPU_L2_PRESENT_LO.read(dev, iomem)?);
-        let l2_present = l2_present | u64::from(regs::GPU_L2_PRESENT_HI.read(dev, iomem)?) << 32;
+        let l2_present = u64::from(regs::GPU_L2_PRESENT_LO.read(iomem));
+        let l2_present = l2_present | u64::from(regs::GPU_L2_PRESENT_HI.read(iomem)) << 32;
 
-        Ok(Self(uapi::drm_panthor_gpu_info {
+        Self(uapi::drm_panthor_gpu_info {
             gpu_id,
             gpu_rev,
             csf_id,
@@ -88,7 +86,7 @@ pub(crate) fn new(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result<Self> {
             core_features,
             pad: 0,
             gpu_features: 0,
-        }))
+        })
     }
 
     pub(crate) fn log(&self, pdev: &platform::Device) {
@@ -208,11 +206,11 @@ fn from(value: u32) -> Self {
 }
 
 /// Powers on the l2 block.
-pub(crate) fn l2_power_on(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result {
-    regs::L2_PWRON_LO.write(dev, iomem, 1)?;
+pub(crate) fn l2_power_on(dev: &Device<Bound>, iomem: &IoMem) -> Result {
+    regs::L2_PWRON_LO.write(iomem, 1);
 
     poll::read_poll_timeout(
-        || regs::L2_READY_LO.read(dev, iomem),
+        || Ok(regs::L2_READY_LO.read(iomem)),
         |status| *status == 1,
         Delta::from_millis(1),
         Delta::from_millis(100),
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
#33 lore raw

Re: [PATCH REF 24/24] gpu: drm: tyr: use HRT lifetime for IoMem

Quoted 2 lines · Deborah Brouwer

Is the intended model that DRM drivers keep lifetime-bound resources such as IoMem<'bound> only in platform drvdata and access them via Device::drvdata_borrow()?

No, this method is unsafe and intended for busses only, drivers should never use it directly.

Quoted 2 lines

Or is the expectation that drm::Driver should also have a lifetime-parameterized Data associated type?

Exactly, the plan is to have lifetime-parameterized private data on the drm::Registration, which is available in IOCTLs. The cover letter mentions that briefly:

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.

This becomes possible as I also have patches that protect DRM IOCTLs through the drm::UnbindGuard (which is just drm_dev_enter() and drm_dev_exit()). Together with drm_dev_unplug() being called when the drm::Registration is dropped all IOCTLs are guaranteed to provide a bound scope of the underlying bus device and hence the device resources in the DRM registration data availble through the IOCTLs.

I have all those patches ready and I plan to send them this week.

Quoted 4 lines

The reason I ask is that Tyr currently stores an MMIO handle in several areas, (firmware, MMU/address-space management, and IRQ handling) and it does register accesses directly. See what we're trying to do:
https://lore.kernel.org/rust-for-linux/[email protected]/

Note that you are not blocked by this, you can always move IoMem<'_> into a Devres through IoMem::into_devres() and use it without lifetime bounds. But of course the goal is to make this unnecessary.

Quoted 3 lines

Moving IoMem<'bound> only into platform drvdata would require a big refactor to thread &IoMem<'_> through those paths or fetch it from drvdata at each hardware access site. So, I wanted to clarify the plan first before I start this work.

No worries, that'd be the exact opposite of what we want to achieve. :)