rust: device: Higher-Ranked Lifetime Types for device drivers
Subsystems (19)
Danilo Krummrich
maintainerv3 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.
Bus driver traits use a Generic Associated Type (GAT) type Data<'bound> to introduce the lifetime on the private data, rather than parameterizing the Driver trait itself. This avoids a driver trait global lifetime and avoids the need for ForLt for bus device private data, making the bus implementations much simpler. ForLt is only needed for auxiliary registration data, where the lifetime is not introduced by a trait callback but must be threaded through Registration.
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<'bound> and IoMem<'bound> 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<'bound> {
pdev: &'bound pci::Device,
bar: pci::Bar<'bound, 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.
Changes in v3:
- Rework all bus "make Driver trait lifetime-parameterized" patches to use a GAT (type Data<'bound>); in the context of adding a 'bound lifetime, this avoids a driver trait global lifetime and avoids ForLt for bus device private data making the bus implementations much simpler
Changes in v2:
- Add 'a bound to ForLt::Of<'a> and WithLt::Of, making the lifetime bound inherent to the trait; remove all F::Of<'static>: 'static where clauses
- Drop "rust: devres: add ForLt support to Devres"; Devres itself stays unchanged -- ForLt-aware access is introduced later through DevresLt in a separate series
- Use 'bound instead of 'a; add patches to consistently use 'bound for pre-existing 'a
Danilo Krummrich (24):
rust: driver: decouple driver private data from driver type
rust: driver core: drop drvdata before devres release
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: usb: make Driver trait lifetime-parameterized
rust: i2c: make Driver trait lifetime-parameterized
rust: driver: update module documentation for GAT-based Data type
rust: auxiliary: generalize Registration over ForLt
samples: rust: rust_driver_auxiliary: showcase lifetime-bound
registration data
rust: pci: make Bar lifetime-parameterized
rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
samples: rust: rust_driver_pci: use HRT lifetime for Bar
rust: driver-core: rename 'a lifetime to 'bound
gpu: nova-core: rename 'a lifetime to 'bound
gpu: nova-core: use lifetime for Bar
gpu: nova-core: unregister sysmem flush page from Drop
gpu: nova-core: replace ARef<Device> with &'bound Device in
SysmemFlush
gpu: drm: tyr: use lifetime for IoMem
Gary Guo (3):
rust: alloc: remove 'static bound on ForeignOwnable
rust: driver: move 'static bounds to constructor
rust: types: add ForLt trait for higher-ranked lifetime support
drivers/base/dd.c | 2 +- drivers/cpufreq/rcpufreq_dt.rs | 9 +- drivers/gpu/drm/nova/driver.rs | 6 +- drivers/gpu/drm/tyr/driver.rs | 23 ++- drivers/gpu/drm/tyr/gpu.rs | 62 +++--- drivers/gpu/drm/tyr/regs.rs | 21 +- drivers/gpu/nova-core/driver.rs | 51 ++--- drivers/gpu/nova-core/fb.rs | 31 ++- drivers/gpu/nova-core/firmware/gsp.rs | 8 +- drivers/gpu/nova-core/gpu.rs | 38 ++-- drivers/gpu/nova-core/gsp/commands.rs | 10 +- drivers/gpu/nova-core/gsp/fw/commands.rs | 4 +- drivers/gpu/nova-core/nova_core.rs | 2 +- drivers/pwm/pwm_th1520.rs | 13 +- include/linux/device/driver.h | 4 +- rust/Makefile | 1 + rust/kernel/alloc/kbox.rs | 24 ++- rust/kernel/auxiliary.rs | 98 +++++---- rust/kernel/cpufreq.rs | 9 +- rust/kernel/device.rs | 12 +- rust/kernel/devres.rs | 16 +- rust/kernel/driver.rs | 37 ++-- rust/kernel/i2c.rs | 62 +++--- rust/kernel/io/mem.rs | 133 +++++++------ rust/kernel/pci.rs | 39 ++-- rust/kernel/pci/io.rs | 68 ++++--- rust/kernel/pci/irq.rs | 38 ++-- rust/kernel/platform.rs | 62 +++--- rust/kernel/types.rs | 12 +- rust/kernel/types/for_lt.rs | 117 +++++++++++ rust/kernel/usb.rs | 53 +++-- rust/macros/for_lt.rs | 242 +++++++++++++++++++++++ rust/macros/lib.rs | 12 ++ samples/rust/rust_debugfs.rs | 9 +- samples/rust/rust_dma.rs | 6 +- samples/rust/rust_driver_auxiliary.rs | 41 ++-- samples/rust/rust_driver_i2c.rs | 13 +- samples/rust/rust_driver_pci.rs | 90 ++++----- samples/rust/rust_driver_platform.rs | 9 +- samples/rust/rust_driver_usb.rs | 13 +- samples/rust/rust_i2c_client.rs | 14 +- samples/rust/rust_soc.rs | 9 +- 42 files changed, 1011 insertions(+), 512 deletions(-) create mode 100644 rust/kernel/types/for_lt.rs create mode 100644 rust/macros/for_lt.rs
base-commit: 8d3bea93f483cb8f92b9f85d1528268a6469af28
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 1/27 rust: alloc: remove `'static` bound on `ForeignOwnable`
From: Gary Guo <[email protected]>
The 'static bound is currently necessary because there's no restriction on the lifetime of the GAT. Add a Self: 'a bound to restrict possible lifetimes on Borrowed and BorrowedMut, and lift the 'static requirement.
--- rust/kernel/alloc/kbox.rs | 24 ++++++++++++++++++------ rust/kernel/types.rs | 8 ++++++-- 2 files changed, 24 insertions(+), 8 deletions(-)
rust/kernel/alloc/kbox.rs +18 -6
@@ -477,7 +477,7 @@ fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>// SAFETY: The pointer returned by `into_foreign` comes from a well aligned // pointer to `T` allocated by `A`. -unsafe impl <T : 'static,A >ForeignOwnable for Box <T ,A > +unsafe impl <T ,A >ForeignOwnable for Box <T ,A >where A :Allocator , {
@@ -487,8 +487,14 @@ unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A> core::mem::align_of ::<T >() }; -type Borrowed <'a> = &'aT ; -type BorrowedMut <'a> = &'amut T ; +type Borrowed <'a> + = &'aT +where +Self : 'a; +type BorrowedMut <'a> + = &'amut T +where +Self : 'a;fn into_foreign (self) -> *mut c_void {Box ::into_raw (self).cast ()
@@ -516,13 +522,19 @@ unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> &'a mut T {// SAFETY: The pointer returned by `into_foreign` comes from a well aligned // pointer to `T` allocated by `A`. -unsafe impl <T : 'static,A >ForeignOwnable for Pin <Box <T ,A >> +unsafe impl <T ,A >ForeignOwnable for Pin <Box <T ,A >>where A :Allocator , {const FOREIGN_ALIGN :usize = <Box <T ,A >as ForeignOwnable >::FOREIGN_ALIGN ; -type Borrowed <'a> =Pin <&'aT >; -type BorrowedMut <'a> =Pin <&'amut T >; +type Borrowed <'a> + =Pin <&'aT > +where +Self : 'a; +type BorrowedMut <'a> + =Pin <&'amut T > +where +Self : 'a;fn into_foreign (self) -> *mut c_void {// SAFETY: We are still treating the box as pinned.
rust/kernel/types.rs +6 -2
@@ -27,10 +27,14 @@ pub unsafe trait ForeignOwnable: Sized {const FOREIGN_ALIGN :usize ;/// Type used to immutably borrow a value that is currently foreign-owned. -type Borrowed <'a>; +type Borrowed <'a> +where +Self : 'a;/// Type used to mutably borrow a value that is currently foreign-owned. -type BorrowedMut <'a>; +type BorrowedMut <'a> +where +Self : 'a;/// Converts a Rust-owned object to a foreign-owned one. ///
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 2/27 rust: driver: move 'static bounds to constructor
In reply to Danilo KrummrichFrom: Gary Guo <[email protected]>
With the ForeignOwnable lifetime change, the 'static bound is no longer necessary on the drvdata methods or bus adapter impls. Move it to the Registration constructor instead.
--- rust/kernel/auxiliary.rs | 6 +++--- rust/kernel/device.rs | 8 ++++---- rust/kernel/driver.rs | 7 +++++-- rust/kernel/i2c.rs | 8 ++++---- rust/kernel/pci.rs | 6 +++--- rust/kernel/platform.rs | 8 ++++---- rust/kernel/usb.rs | 6 +++--- 7 files changed, 26 insertions(+), 23 deletions(-)
rust/kernel/auxiliary.rs +3 -3
@@ -44,7 +44,7 @@// - `T` is the type of the driver's device private data. // - `struct auxiliary_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 <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::auxiliary_driver ;type DriverData =T ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver);
@@ -52,7 +52,7 @@ unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {// 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 <T :Driver > driver::RegistrationOps for Adapter <T > {unsafe fn register ( adrv: &Opaque <Self ::DriverType >, name: &'static CStr,
@@ -78,7 +78,7 @@ unsafe fn unregister(adrv: &Opaque<Self::DriverType>) { } } -impl <T :Driver + 'static>Adapter <T > { +impl <T :Driver >Adapter <T > {extern "C" fn probe_callback ( adev: *mut bindings::auxiliary_device , id: *const bindings::auxiliary_device_id,
rust/kernel/device.rs +4 -4
@@ -203,7 +203,7 @@ pub unsafe fn as_bound(&self) -> &Device<Bound> {impl Device <CoreInternal > {/// Store a pointer to the bound driver's private data. -pub fn set_drvdata <T : 'static>(&self, data:impl PinInit <T ,Error >) ->Result { +pub fn set_drvdata <T >(&self, data:impl PinInit <T ,Error >) ->Result {let data =KBox ::pin_init (data,GFP_KERNEL )?;// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
@@ -218,7 +218,7 @@ pub fn set_drvdata<T: 'static>(&self, data: impl PinInit<T, Error>) -> Result {/// /// - The type `T` must match the type of the `ForeignOwnable` previously stored by /// [`Device::set_drvdata`]. -pub (crate )unsafe fn drvdata_obtain <T : 'static>(&self) ->Option <Pin <KBox <T >>> { +pub (crate )unsafe fn drvdata_obtain <T >(&self) ->Option <Pin <KBox <T >>> {// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`. let ptr =unsafe { bindings::dev_get_drvdata (self.as_raw ()) };
@@ -244,7 +244,7 @@ pub(crate) unsafe fn drvdata_obtain<T: 'static>(&self) -> Option<Pin<KBox<T>>> {/// device is fully unbound. /// - The type `T` must match the type of the `ForeignOwnable` previously stored by /// [`Device::set_drvdata`]. -pub unsafe fn drvdata_borrow <T : 'static>(&self) ->Pin <&T > { +pub unsafe fn drvdata_borrow <T >(&self) ->Pin <&T > {// SAFETY: `drvdata_unchecked()` has the exact same safety requirements as the ones // required by this method. unsafe { self.drvdata_unchecked () }
@@ -260,7 +260,7 @@ impl Device<Bound> {/// the device is fully unbound. /// - The type `T` must match the type of the `ForeignOwnable` previously stored by /// [`Device::set_drvdata`]. -unsafe fn drvdata_unchecked <T : 'static>(&self) ->Pin <&T > { +unsafe fn drvdata_unchecked <T >(&self) ->Pin <&T > {// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`. let ptr =unsafe { bindings::dev_get_drvdata (self.as_raw ()) };
rust/kernel/driver.rs +5 -2
@@ -181,7 +181,7 @@ unsafe impl<T: RegistrationOps> Sync for Registration<T> {}// any thread, so `Registration` is `Send`. unsafe impl <T :RegistrationOps >Send for Registration <T > {} -impl <T :RegistrationOps + 'static>Registration <T > { +impl <T :RegistrationOps >Registration <T > {extern "C" fn post_unbind_callback (dev: *mut bindings::device ) {// SAFETY: The driver core only ever calls the post unbind callback with a valid pointer to // a `struct device`.
@@ -215,7 +215,10 @@ fn callbacks_attach(drv: &Opaque<T::DriverType>) { } /// Creates a new instance of the registration object. - pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> { + pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> + where + T: 'static, + { try_pin_init!(Self { reg <- Opaque::try_ffi_init(|ptr: *mut T::DriverType| { // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.
rust/kernel/i2c.rs +4 -4
@@ -96,7 +96,7 @@ macro_rules! i2c_device_table {// - `T` is the 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 <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::i2c_driver ;type DriverData =T ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver);
@@ -104,7 +104,7 @@ unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {// 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 <T :Driver > driver::RegistrationOps for Adapter <T > {unsafe fn register ( idrv: &Opaque <Self ::DriverType >, name: &'static CStr,
@@ -151,7 +151,7 @@ unsafe fn unregister(idrv: &Opaque<Self::DriverType>) { } } -impl <T :Driver + 'static>Adapter <T > { +impl <T :Driver >Adapter <T > {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`.
@@ -222,7 +222,7 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::Id } } -impl <T :Driver + 'static> driver::Adapter for Adapter <T > { +impl <T :Driver > driver::Adapter for Adapter <T > {type IdInfo =T ::IdInfo ;fn of_id_table () ->Option <of::IdTable <Self ::IdInfo >> {
rust/kernel/pci.rs +3 -3
@@ -62,7 +62,7 @@// - `T` is the type of the driver's device private data. // - `struct pci_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 <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::pci_driver ;type DriverData =T ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver);
@@ -70,7 +70,7 @@ unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {// 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 <T :Driver > driver::RegistrationOps for Adapter <T > {unsafe fn register ( pdrv: &Opaque <Self ::DriverType >, name: &'static CStr,
@@ -96,7 +96,7 @@ unsafe fn unregister(pdrv: &Opaque<Self::DriverType>) { } } -impl <T :Driver + 'static>Adapter <T > { +impl <T :Driver >Adapter <T > {extern "C" fn probe_callback ( pdev: *mut bindings::pci_dev , id: *const bindings::pci_device_id,
rust/kernel/platform.rs +4 -4
@@ -48,7 +48,7 @@// - `T` is the type of the driver's device private data. // - `struct platform_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 <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::platform_driver ;type DriverData =T ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver);
@@ -56,7 +56,7 @@ unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {// 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 <T :Driver > driver::RegistrationOps for Adapter <T > {unsafe fn register ( pdrv: &Opaque <Self ::DriverType >, name: &'static CStr,
@@ -91,7 +91,7 @@ unsafe fn unregister(pdrv: &Opaque<Self::DriverType>) { } } -impl <T :Driver + 'static>Adapter <T > { +impl <T :Driver >Adapter <T > {extern "C" fn probe_callback (pdev: *mut bindings::platform_device ) -> kernel::ffi::c_int {// SAFETY: The platform bus only ever calls the probe callback with a valid pointer to a // `struct platform_device`.
@@ -124,7 +124,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::platform_device) { } } -impl <T :Driver + 'static> driver::Adapter for Adapter <T > { +impl <T :Driver > driver::Adapter for Adapter <T > {type IdInfo =T ::IdInfo ;fn of_id_table () ->Option <of::IdTable <Self ::IdInfo >> {
rust/kernel/usb.rs +3 -3
@@ -39,7 +39,7 @@// - `T` is the 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 <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::usb_driver ;type DriverData =T ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver);
@@ -47,7 +47,7 @@ unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {// 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 <T :Driver > driver::RegistrationOps for Adapter <T > {unsafe fn register ( udrv: &Opaque <Self ::DriverType >, name: &'static CStr,
@@ -73,7 +73,7 @@ unsafe fn unregister(udrv: &Opaque<Self::DriverType>) { } } -impl <T :Driver + 'static>Adapter <T > { +impl <T :Driver >Adapter <T > {extern "C" fn probe_callback ( intf: *mut bindings::usb_interface , id: *const bindings::usb_device_id,
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 3/27 rust: driver: decouple driver private data from driver type
In reply to Danilo KrummrichAdd a type Data<'bound> associated type to all bus driver traits, decoupling the driver's bus device private data type from the driver struct itself.
In the context of adding a 'bound lifetime, making this an associated type has the advantage that it allows us to avoid a driver trait global lifetime and it avoids the need for ForLt for bus device private data; both of which make the subsequent implementation by buses much simpler.
All existing drivers and doc examples set type Data = Self to preserve the current behavior.
--- drivers/cpufreq/rcpufreq_dt.rs | 1 + drivers/gpu/drm/nova/driver.rs | 1 + drivers/gpu/drm/tyr/driver.rs | 1 + drivers/gpu/nova-core/driver.rs | 1 + drivers/pwm/pwm_th1520.rs | 1 + rust/kernel/auxiliary.rs | 18 +++++++++------- rust/kernel/cpufreq.rs | 1 + rust/kernel/driver.rs | 22 ++++++++++++-------- rust/kernel/i2c.rs | 30 +++++++++++++++------------ rust/kernel/io/mem.rs | 2 ++ rust/kernel/pci.rs | 19 ++++++++++------- rust/kernel/platform.rs | 18 +++++++++------- rust/kernel/usb.rs | 20 +++++++++++------- samples/rust/rust_debugfs.rs | 1 + samples/rust/rust_dma.rs | 1 + samples/rust/rust_driver_auxiliary.rs | 2 ++ samples/rust/rust_driver_i2c.rs | 1 + samples/rust/rust_driver_pci.rs | 1 + samples/rust/rust_driver_platform.rs | 1 + samples/rust/rust_driver_usb.rs | 1 + samples/rust/rust_i2c_client.rs | 1 + samples/rust/rust_soc.rs | 1 + 22 files changed, 94 insertions(+), 51 deletions(-)
drivers/cpufreq/rcpufreq_dt.rs +1 -0
@@ -201,6 +201,7 @@ fn register_em(policy: &mut cpufreq::Policy) {impl platform::Driver for CPUFreqDTDriver {type IdInfo = (); +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE ); fn probe(
drivers/gpu/drm/nova/driver.rs +1 -0
@@ -51,6 +51,7 @@ pub(crate) struct NovaData {impl auxiliary::Driver for NovaDriver {type IdInfo = (); +type Data =Self ;const ID_TABLE : auxiliary::IdTable <Self ::IdInfo > = &AUX_TABLE ;fn probe (adev: &auxiliary::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > {
drivers/gpu/drm/tyr/driver.rs +1 -0
@@ -91,6 +91,7 @@ fn issue_soft_reset(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result {impl platform::Driver for TyrPlatformDriverData {type IdInfo = (); +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE ); fn probe(
drivers/gpu/nova-core/driver.rs +1 -0
@@ -74,6 +74,7 @@ pub(crate) struct NovaCore {impl pci::Driver for NovaCore {type IdInfo = (); +type Data =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ;fn probe (pdev: &pci::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > {
drivers/pwm/pwm_th1520.rs +1 -0
@@ -316,6 +316,7 @@ fn drop(self: Pin<&mut Self>) {impl platform::Driver for Th1520PwmPlatformDriver {type IdInfo = (); +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE ); fn probe(
rust/kernel/auxiliary.rs +11 -7
@@ -41,12 +41,12 @@// SAFETY: // - `bindings::auxiliary_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `T::Data` is the type of the driver's device private data. // - `struct auxiliary_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::auxiliary_driver ; -type DriverData =T ; +type DriverData <'bound> =T ::Data ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -111,8 +111,8 @@ 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 >() }; +// and stored a `Pin<KBox<T::Data>>`. +let data =unsafe { adev.as_ref ().drvdata_borrow ::<T ::Data >() };T ::unbind (adev, data); }
@@ -202,13 +202,17 @@ pub trait Driver {/// type IdInfo: 'static = (); type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data ; +/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;/// Auxiliary driver probe. /// /// Called when an auxiliary device is matches a corresponding driver. -fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) ->impl PinInit <Self ,Error >; +fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) + ->impl PinInit <Self ::Data ,Error >;/// Auxiliary driver unbind. ///
@@ -219,8 +223,8 @@ pub trait Driver {/// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O /// operations to gracefully tear down the device. /// -/// Otherwise, release operations for driver resources should be performed in `Self::drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self >) { +/// Otherwise, release operations for driver resources should be performed in `Drop`. +fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
rust/kernel/cpufreq.rs +1 -0
@@ -888,6 +888,7 @@ fn register_em(_policy: &mut Policy) {/// /// impl platform::Driver for SampleDriver { /// type IdInfo = (); +/// type Data = Self; /// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; /// /// fn probe(
rust/kernel/driver.rs +13 -9
@@ -17,6 +17,9 @@//! /// The type holding information about each device ID supported by the driver. //! type IdInfo: 'static; //! +//! /// The type of the driver's bus device private data. +//! type Data; +//! //! /// The table of OF device ids supported by the driver. //! const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; //!
@@ -24,10 +27,11 @@//! 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: &Device<device::Core>, id_info: &Self::IdInfo) +//! -> impl PinInit<Self::Data, Error>; //! //! /// Driver unbind (optional). -//! fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) { +//! fn unbind(dev: &Device<device::Core>, this: Pin<&Self::Data>) { //! let _ = (dev, this); //! } //! }
@@ -42,9 +46,9 @@ )]#" )] //! -//! The `probe()` callback should return a `impl PinInit<Self, Error>`, i.e. the driver's private -//! data. The bus abstraction should store the pointer in the corresponding bus device. The generic -//! [`Device`] infrastructure provides common helpers for this purpose on its +//! The `probe()` callback should return a `impl PinInit<Self::Data, Error>`, i.e. the driver's +//! private data. The bus abstraction should store the pointer in the corresponding bus device. The +//! generic [`Device`] infrastructure provides common helpers for this purpose on its //! [`Device<CoreInternal>`] implementation. //! //! All driver callbacks should provide a reference to the driver's private data. Once the driver
@@ -118,8 +122,8 @@ 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 type of the driver's bus device private data. +type DriverData <'bound>;/// Byte offset of the embedded `struct device_driver` within `DriverType`. ///
@@ -193,8 +197,8 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::device) {// driver's device private data. // // SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the -// driver's device private data type. -drop (unsafe { dev.drvdata_obtain ::<T ::DriverData >() }); +// driver's bus device private data type. +drop (unsafe { dev.drvdata_obtain ::<T ::DriverData <'_>>() }); }/// Attach generic `struct device_driver` callbacks.
rust/kernel/i2c.rs +17 -13
@@ -93,12 +93,12 @@ macro_rules! i2c_device_table {// SAFETY: // - `bindings::i2c_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `T::Data` is the 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 > driver::DriverLayout for Adapter <T > {type DriverType = bindings::i2c_driver ; -type DriverData =T ; +type DriverData <'bound> =T ::Data ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -176,8 +176,8 @@ 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 >() }; +// and stored a `Pin<KBox<T::Data>>`. +let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data >() };T ::unbind (idev, data); }
@@ -188,8 +188,8 @@ 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 >() }; +// and stored a `Pin<KBox<T::Data>>`. +let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data >() };T ::shutdown (idev, data); }
@@ -294,6 +294,7 @@ macro_rules! module_i2c_driver {/// /// impl i2c::Driver for MyDriver { /// type IdInfo = (); +/// type Data = Self; /// 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);
@@ -301,11 +302,11 @@ macro_rules! module_i2c_driver {/// fn probe( /// _idev: &i2c::I2cClient<Core>, /// _id_info: Option<&Self::IdInfo>, -/// ) -> impl PinInit<Self, Error> { +/// ) -> impl PinInit<Self::Data, Error> { /// Err(ENODEV) /// } /// -/// fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self>) { +/// fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self::Data>) { /// } /// } ///```
@@ -318,6 +319,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data ; +/// The table of device ids supported by the driver. const I2C_ID_TABLE :Option <IdTable <Self ::IdInfo >> =None ;
@@ -334,7 +338,7 @@ pub trait Driver: Send {fn probe ( dev: &I2cClient <device::Core >, id_info:Option <&Self ::IdInfo >, - ) ->impl PinInit <Self ,Error >; + ) ->impl PinInit <Self ::Data ,Error >;/// I2C driver shutdown. ///
@@ -346,8 +350,8 @@ 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 >) { +/// handled in `Drop`. +fn shutdown (dev: &I2cClient <device::Core >, this:Pin <&Self ::Data >) {let _ = (dev, this); }
@@ -360,8 +364,8 @@ fn shutdown(dev: &I2cClient<device::Core>, this: Pin<&Self>) {/// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O /// 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 >) { +/// Otherwise, release operations for driver resources should be performed in `Drop`. +fn unbind (dev: &I2cClient <device::Core >, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
rust/kernel/io/mem.rs +2 -0
@@ -62,6 +62,7 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S/// /// impl platform::Driver for SampleDriver { /// # type IdInfo = (); +/// # type Data = Self; /// /// fn probe( /// pdev: &platform::Device<Core>,
@@ -126,6 +127,7 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(/// /// impl platform::Driver for SampleDriver { /// # type IdInfo = (); +/// # type Data = Self; /// /// fn probe( /// pdev: &platform::Device<Core>,
rust/kernel/pci.rs +12 -7
@@ -59,12 +59,12 @@// SAFETY: // - `bindings::pci_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `T::Data` is the type of the driver's device private data. // - `struct pci_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::pci_driver ; -type DriverData =T ; +type DriverData <'bound> =T ::Data ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -129,8 +129,8 @@ 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 >() }; +// and stored a `Pin<KBox<T::Data>>`. +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() };T ::unbind (pdev, data); }
@@ -279,6 +279,7 @@ macro_rules! pci_device_table {/// /// impl pci::Driver for MyDriver { /// type IdInfo = (); +/// type Data = Self; /// const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; /// /// fn probe(
@@ -300,6 +301,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data ; +/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -307,7 +311,8 @@ pub trait Driver: Send {/// /// Called when a new pci device is added or discovered. Implementers should /// attempt to initialize the device here. -fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) ->impl PinInit <Self ,Error >; +fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) + ->impl PinInit <Self ::Data ,Error >;/// PCI driver unbind. ///
@@ -318,8 +323,8 @@ pub trait Driver: Send {/// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O /// operations to gracefully tear down the device. /// -/// Otherwise, release operations for driver resources should be performed in `Self::drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self >) { +/// Otherwise, release operations for driver resources should be performed in `Drop`. +fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
rust/kernel/platform.rs +11 -7
@@ -45,12 +45,12 @@// SAFETY: // - `bindings::platform_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `T::Data` is the type of the driver's device private data. // - `struct platform_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::platform_driver ; -type DriverData =T ; +type DriverData <'bound> =T ::Data ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -117,8 +117,8 @@ 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 >() }; +// and stored a `Pin<KBox<T::Data>>`. +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() };T ::unbind (pdev, data); }
@@ -192,6 +192,7 @@ macro_rules! module_platform_driver {/// /// impl platform::Driver for MyDriver { /// type IdInfo = (); +/// type Data = Self; /// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); /// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE); ///
@@ -212,6 +213,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data ; +/// The table of OF device ids supported by the driver. const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =None ;
@@ -225,7 +229,7 @@ pub trait Driver: Send {fn probe ( dev: &Device <device::Core >, id_info:Option <&Self ::IdInfo >, - ) ->impl PinInit <Self ,Error >; + ) ->impl PinInit <Self ::Data ,Error >;/// Platform driver unbind. ///
@@ -236,8 +240,8 @@ fn probe(/// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O /// operations to gracefully tear down the device. /// -/// Otherwise, release operations for driver resources should be performed in `Self::drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self >) { +/// Otherwise, release operations for driver resources should be performed in `Drop`. +fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
rust/kernel/usb.rs +12 -8
@@ -36,12 +36,12 @@// SAFETY: // - `bindings::usb_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `T::Data` is the 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 > driver::DriverLayout for Adapter <T > {type DriverType = bindings::usb_driver ; -type DriverData =T ; +type DriverData <'bound> =T ::Data ;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -109,8 +109,8 @@ 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 >() }; +// and stored a `Pin<KBox<T::Data>>`. +let data =unsafe { dev.drvdata_borrow ::<T ::Data >() };T ::disconnect (intf, data); }
@@ -287,23 +287,27 @@ macro_rules! usb_device_table {/// /// impl usb::Driver for MyDriver { /// type IdInfo = (); +/// type Data = Self; /// 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> { +/// ) -> impl PinInit<Self::Data, Error> { /// Err(ENODEV) /// } /// -/// fn disconnect(_interface: &usb::Interface<Core>, _data: Pin<&Self>) {} +/// fn disconnect(_interface: &usb::Interface<Core>, _data: Pin<&Self::Data>) {} /// } ///``` pub trait Driver {/// The type holding information about each one of the device ids supported by the driver. type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data ; +/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -315,12 +319,12 @@ fn probe( interface: &Interface<device::Core>, id: &DeviceId, id_info: &Self::IdInfo, - ) -> impl PinInit<Self, Error>; + ) -> impl PinInit<Self::Data, Error>;/// 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: &Interface <device::Core >, data:Pin <&Self ::Data >); }/// A USB interface.
samples/rust/rust_debugfs.rs +1 -0
@@ -117,6 +117,7 @@ fn from_str(s: &str) -> Result<Self> {impl platform::Driver for RustDebugFs {type IdInfo = (); +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =None ;const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );
samples/rust/rust_dma.rs +1 -0
@@ -58,6 +58,7 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}impl pci::Driver for DmaSampleDriver {type IdInfo = (); +type Data =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ;fn probe (pdev: &pci::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > {
samples/rust/rust_driver_auxiliary.rs +2 -0
@@ -31,6 +31,7 @@impl auxiliary::Driver for AuxiliaryDriver {type IdInfo = (); +type Data =Self ;const ID_TABLE : auxiliary::IdTable <Self ::IdInfo > = &AUX_TABLE ;
@@ -65,6 +66,7 @@ struct ParentDriver {impl pci::Driver for ParentDriver {type IdInfo = (); +type Data =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ;
samples/rust/rust_driver_i2c.rs +1 -0
@@ -35,6 +35,7 @@impl i2c::Driver for SampleDriver {type IdInfo =u32 ; +type Data =Self ;const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );const I2C_ID_TABLE :Option <i2c::IdTable <Self ::IdInfo >> =Some (&I2C_TABLE );
samples/rust/rust_driver_pci.rs +1 -0
@@ -140,6 +140,7 @@ fn config_space(pdev: &pci::Device<Bound>) {impl pci::Driver for SampleDriver {type IdInfo =TestIndex ; +type Data =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ;
samples/rust/rust_driver_platform.rs +1 -0
@@ -101,6 +101,7 @@ struct SampleDriver {impl platform::Driver for SampleDriver {type IdInfo =Info ; +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );
samples/rust/rust_driver_usb.rs +1 -0
@@ -26,6 +26,7 @@ struct SampleDriver {impl usb::Driver for SampleDriver {type IdInfo = (); +type Data =Self ;const ID_TABLE : usb::IdTable <Self ::IdInfo > = &USB_TABLE ; fn probe(
samples/rust/rust_i2c_client.rs +1 -0
@@ -106,6 +106,7 @@ struct SampleDriver {impl platform::Driver for SampleDriver {type IdInfo = (); +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );
samples/rust/rust_soc.rs +1 -0
@@ -37,6 +37,7 @@ struct SampleSocDriver {impl platform::Driver for SampleSocDriver {type IdInfo = (); +type Data =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 4/27 rust: driver core: drop drvdata before devres release
In reply to Danilo KrummrichMove 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
@@ -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
@@ -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
@@ -193,8 +193,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 bus device private data type.
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 5/27 rust: pci: implement Sync for Device<Bound>
In reply to Danilo KrummrichImplement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct pci_dev as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for drivers to store &'bound pci::Device<Bound> in their private data while remaining Send.
--- rust/kernel/pci.rs | 4 ++++ 1 file changed, 4 insertions(+)
rust/kernel/pci.rs +4 -0
@@ -528,3 +528,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
Danilo Krummrich
maintainerPATCH v3 6/27 rust: platform: implement Sync for Device<Bound>
In reply to Danilo KrummrichImplement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct platform_device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for drivers to store &'bound platform::Device<Bound> in their private data while remaining Send.
--- rust/kernel/platform.rs | 4 ++++ 1 file changed, 4 insertions(+)
rust/kernel/platform.rs +4 -0
@@ -565,3 +565,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
Danilo Krummrich
maintainerPATCH v3 7/27 rust: auxiliary: implement Sync for Device<Bound>
In reply to Danilo KrummrichImplement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct auxiliary_device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for drivers to store &'bound auxiliary::Device<Bound> in their private data while remaining Send.
--- rust/kernel/auxiliary.rs | 4 ++++ 1 file changed, 4 insertions(+)
rust/kernel/auxiliary.rs +4 -0
@@ -369,6 +369,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
Danilo Krummrich
maintainerPATCH v3 8/27 rust: usb: implement Sync for Device<Bound>
In reply to Danilo KrummrichImplement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct usb_device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for drivers to store &'bound usb::Device<Bound> in their private data while remaining Send.
--- rust/kernel/usb.rs | 4 ++++ 1 file changed, 4 insertions(+)
rust/kernel/usb.rs +4 -0
@@ -468,6 +468,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
Danilo Krummrich
maintainerPATCH v3 9/27 rust: device: implement Sync for Device<Bound>
In reply to Danilo KrummrichImplement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for types that hold &'bound Device<Bound>, such as io::mem::IoMem, to be Send.
--- rust/kernel/device.rs | 4 ++++ 1 file changed, 4 insertions(+)
rust/kernel/device.rs +4 -0
@@ -467,6 +467,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
Danilo Krummrich
maintainerPATCH v3 10/27 rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichAdd a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
The probe() and unbind() callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.
Existing drivers set type Data<'bound> = Self, preserving the current behavior.
--- drivers/gpu/nova-core/driver.rs | 9 ++++++--- rust/kernel/pci.rs | 24 +++++++++++++----------- samples/rust/rust_dma.rs | 7 +++++-- samples/rust/rust_driver_auxiliary.rs | 7 +++++-- samples/rust/rust_driver_pci.rs | 7 +++++-- 5 files changed, 34 insertions(+), 20 deletions(-)
drivers/gpu/nova-core/driver.rs +6 -3
@@ -74,10 +74,13 @@ pub(crate) struct NovaCore {impl pci::Driver for NovaCore {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ; -fn probe (pdev: &pci::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound pci::Device <Core >, + _info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ,Error > + 'bound { pin_init::pin_init_scope (move || {dev_dbg! (pdev,"Probe Nova Core GPU driver.\n" );
@@ -109,7 +112,7 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, E }) } -fn unbind (pdev: &pci::Device <Core >, this:Pin <&Self >) { +fn unbind <'bound>(pdev: &'bound pci::Device <Core >, this:Pin <&'boundSelf >) { this.gpu.unbind (pdev.as_ref ()); } }
rust/kernel/pci.rs +13 -11
@@ -64,7 +64,7 @@// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::pci_driver ; -type DriverData <'bound> =T ::Data ; +type DriverData <'bound> =T ::Data <'bound>;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -130,7 +130,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::Data>>`. -let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::unbind (pdev, data); }
@@ -279,13 +279,13 @@ macro_rules! pci_device_table {/// /// impl pci::Driver for MyDriver { /// type IdInfo = (); -/// type Data = Self; +/// type Data<'bound> = Self; /// const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; /// -/// fn probe( -/// _pdev: &pci::Device<Core>, -/// _id_info: &Self::IdInfo, -/// ) -> impl PinInit<Self, Error> { +/// fn probe<'bound>( +/// _pdev: &'bound pci::Device<Core>, +/// _id_info: &'bound Self::IdInfo, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { /// Err(ENODEV) /// } /// }
@@ -302,7 +302,7 @@ pub trait Driver: Send {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -311,8 +311,10 @@ pub trait Driver: Send {/// /// Called when a new pci device is added or discovered. Implementers should /// attempt to initialize the device here. -fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) - ->impl PinInit <Self ::Data ,Error >; +fn probe <'bound>( + dev: &'boundDevice <device::Core >, + id_info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;/// PCI driver unbind. ///
@@ -324,7 +326,7 @@ fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo)/// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be performed in `Drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) { +fn unbind <'bound>(dev: &'boundDevice <device::Core >, this:Pin <&'boundSelf ::Data <'bound>>) {let _ = (dev, this); } }
samples/rust/rust_dma.rs +5 -2
@@ -58,10 +58,13 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}impl pci::Driver for DmaSampleDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ; -fn probe (pdev: &pci::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound pci::Device <Core >, + _info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ,Error > + 'bound { pin_init::pin_init_scope (move || {dev_info! (pdev,"Probe DMA test driver.\n" );
samples/rust/rust_driver_auxiliary.rs +5 -2
@@ -66,11 +66,14 @@ struct ParentDriver { impl pci::Driver for ParentDriver { type IdInfo = (); - type Data = Self; + type Data<'bound> = Self; const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe<'bound>( + pdev: &'bound pci::Device<Core>, + _info: &'bound Self::IdInfo, + ) -> impl PinInit<Self, Error> + 'bound { Ok(Self { _reg0: auxiliary::Registration::new( pdev.as_ref(),
samples/rust/rust_driver_pci.rs +5 -2
@@ -140,11 +140,14 @@ fn config_space(pdev: &pci::Device<Bound>) { impl pci::Driver for SampleDriver { type IdInfo = TestIndex; - type Data = Self; + type Data<'bound> = Self; const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe<'bound>( + pdev: &'bound pci::Device<Core>, + info: &'bound Self::IdInfo, + ) -> impl PinInit<Self, Error> + 'bound { pin_init::pin_init_scope(move || { let vendor = pdev.vendor_id(); dev_dbg!(
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 11/27 rust: platform: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichAdd a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
The probe() and unbind() callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.
Existing drivers set type Data<'bound> = Self, preserving the current behavior.
--- drivers/cpufreq/rcpufreq_dt.rs | 10 +++++----- drivers/gpu/drm/tyr/driver.rs | 10 +++++----- drivers/pwm/pwm_th1520.rs | 10 +++++----- rust/kernel/cpufreq.rs | 10 +++++----- rust/kernel/io/mem.rs | 20 ++++++++++---------- rust/kernel/platform.rs | 26 +++++++++++++------------- samples/rust/rust_debugfs.rs | 10 +++++----- samples/rust/rust_driver_platform.rs | 10 +++++----- samples/rust/rust_i2c_client.rs | 15 +++++++++------ samples/rust/rust_soc.rs | 10 +++++----- 10 files changed, 67 insertions(+), 64 deletions(-)
drivers/cpufreq/rcpufreq_dt.rs +5 -5
@@ -201,13 +201,13 @@ fn register_em(policy: &mut cpufreq::Policy) {impl platform::Driver for CPUFreqDTDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;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 > { +fn probe <'bound>( + pdev: &'bound platform::Device <Core >, + _id_info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound { cpufreq::Registration ::<CPUFreqDTDriver >::new_foreign_owned (pdev.as_ref ())?;Ok (Self {}) }
drivers/gpu/drm/tyr/driver.rs +5 -5
@@ -91,13 +91,13 @@ fn issue_soft_reset(dev: &Device<Bound>, iomem: &Devres<IoMem>) -> Result {impl platform::Driver for TyrPlatformDriverData {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;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 > { +fn probe <'bound>( + pdev: &'bound platform::Device <Core >, + _info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {let core_clk =Clk ::get (pdev.as_ref (),Some (c"core" ))?;let stacks_clk =OptionalClk ::get (pdev.as_ref (),Some (c"stacks" ))?;let coregroup_clk =OptionalClk ::get (pdev.as_ref (),Some (c"coregroup" ))?;
drivers/pwm/pwm_th1520.rs +5 -5
@@ -316,13 +316,13 @@ fn drop(self: Pin<&mut Self>) {impl platform::Driver for Th1520PwmPlatformDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;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 > { +fn probe <'bound>( + pdev: &'bound platform::Device <Core >, + _id_info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {let dev = pdev.as_ref ();let request = pdev.io_request_by_index (0 ).ok_or (ENODEV )?;
rust/kernel/cpufreq.rs +5 -5
@@ -888,13 +888,13 @@ fn register_em(_policy: &mut Policy) {/// /// impl platform::Driver for SampleDriver { /// type IdInfo = (); -/// type Data = Self; +/// type Data<'bound> = Self; /// 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> { +/// fn probe<'bound>( +/// pdev: &'bound platform::Device<Core>, +/// _id_info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self, Error> + 'bound { /// cpufreq::Registration::<SampleDriver>::new_foreign_owned(pdev.as_ref())?; /// Ok(Self {}) /// }
rust/kernel/io/mem.rs +10 -10
@@ -62,12 +62,12 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S/// /// impl platform::Driver for SampleDriver { /// # type IdInfo = (); -/// # type Data = Self; +/// # type Data<'bound> = Self; /// -/// fn probe( -/// pdev: &platform::Device<Core>, -/// info: Option<&Self::IdInfo>, -/// ) -> impl PinInit<Self, Error> { +/// fn probe<'bound>( +/// pdev: &'bound platform::Device<Core>, +/// info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self, Error> + 'bound { /// let offset = 0; // Some offset. /// /// // If the size is known at compile time, use [`Self::iomap_sized`].
@@ -127,12 +127,12 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(/// /// impl platform::Driver for SampleDriver { /// # type IdInfo = (); -/// # type Data = Self; +/// # type Data<'bound> = Self; /// -/// fn probe( -/// pdev: &platform::Device<Core>, -/// info: Option<&Self::IdInfo>, -/// ) -> impl PinInit<Self, Error> { +/// fn probe<'bound>( +/// pdev: &'bound platform::Device<Core>, +/// info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self, Error> + 'bound { /// let offset = 0; // Some offset. /// /// // Unlike [`Self::iomap_sized`], here the size of the memory region
rust/kernel/platform.rs +13 -13
@@ -50,7 +50,7 @@// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::platform_driver ; -type DriverData <'bound> =T ::Data ; +type DriverData <'bound> =T ::Data <'bound>;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -118,7 +118,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::Data>>`. -let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::unbind (pdev, data); }
@@ -192,14 +192,14 @@ macro_rules! module_platform_driver {/// /// impl platform::Driver for MyDriver { /// type IdInfo = (); -/// type Data = Self; +/// type Data<'bound> = Self; /// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); /// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE); /// -/// fn probe( -/// _pdev: &platform::Device<Core>, -/// _id_info: Option<&Self::IdInfo>, -/// ) -> impl PinInit<Self, Error> { +/// fn probe<'bound>( +/// _pdev: &'bound platform::Device<Core>, +/// _id_info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { /// Err(ENODEV) /// } /// }
@@ -214,7 +214,7 @@ pub trait Driver: Send {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;/// The table of OF device ids supported by the driver. const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =None ;
@@ -226,10 +226,10 @@ pub trait Driver: Send {/// /// Called when a new platform device is added or discovered. /// Implementers should attempt to initialize the device here. -fn probe ( - dev: &Device <device::Core >, - id_info:Option <&Self ::IdInfo >, - ) ->impl PinInit <Self ::Data ,Error >; +fn probe <'bound>( + dev: &'boundDevice <device::Core >, + id_info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;/// Platform driver unbind. ///
@@ -241,7 +241,7 @@ fn probe(/// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be performed in `Drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) { +fn unbind <'bound>(dev: &'boundDevice <device::Core >, this:Pin <&'boundSelf ::Data <'bound>>) {let _ = (dev, this); } }
samples/rust/rust_debugfs.rs +5 -5
@@ -117,14 +117,14 @@ fn from_str(s: &str) -> Result<Self> {impl platform::Driver for RustDebugFs {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;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 > { +fn probe <'bound>( + pdev: &'bound platform::Device <Core >, + _info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {RustDebugFs ::new (pdev).pin_chain (|this| { this.counter.store (91 ,Relaxed ); {
samples/rust/rust_driver_platform.rs +5 -5
@@ -101,14 +101,14 @@ struct SampleDriver {impl platform::Driver for SampleDriver {type IdInfo =Info ; -type Data =Self ; +type Data <'bound> =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE ); -fn probe ( - pdev: &platform::Device <Core >, - info:Option <&Self ::IdInfo >, - ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound platform::Device <Core >, + info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {let dev = pdev.as_ref ();dev_dbg! (dev,"Probe Rust Platform driver sample.\n" );
samples/rust/rust_i2c_client.rs +9 -6
@@ -106,14 +106,14 @@ struct SampleDriver {impl platform::Driver for SampleDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE ); -fn probe ( - pdev: &platform::Device <device::Core >, - _info:Option <&Self ::IdInfo >, - ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound platform::Device <device::Core >, + _info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {dev_info! ( pdev.as_ref (),"Probe Rust I2C Client registration sample.\n"
@@ -130,7 +130,10 @@ fn probe( }) } -fn unbind (pdev: &platform::Device <device::Core >, _this:Pin <&Self >) { +fn unbind <'bound>( + pdev: &'bound platform::Device <device::Core >, + _this:Pin <&'boundSelf ::Data <'bound>>, + ) {dev_info! ( pdev.as_ref (),"Unbind Rust I2C Client registration sample.\n"
samples/rust/rust_soc.rs +5 -5
@@ -37,14 +37,14 @@ struct SampleSocDriver {impl platform::Driver for SampleSocDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE ); -fn probe ( - pdev: &platform::Device <Core >, - _info:Option <&Self ::IdInfo >, - ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound platform::Device <Core >, + _info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {dev_dbg! (pdev,"Probe Rust SoC driver sample.\n" );let pdev = pdev.into ();
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 12/27 rust: auxiliary: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichAdd a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
The probe() and unbind() callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.
Existing drivers set type Data<'bound> = Self, preserving the current behavior.
--- drivers/gpu/drm/nova/driver.rs | 7 +++++-- rust/kernel/auxiliary.rs | 14 ++++++++------ samples/rust/rust_driver_auxiliary.rs | 7 +++++-- 3 files changed, 18 insertions(+), 10 deletions(-)
drivers/gpu/drm/nova/driver.rs +5 -2
@@ -51,10 +51,13 @@ pub(crate) struct NovaData {impl auxiliary::Driver for NovaDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const ID_TABLE : auxiliary::IdTable <Self ::IdInfo > = &AUX_TABLE ; -fn probe (adev: &auxiliary::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + adev: &'bound auxiliary::Device <Core >, + _info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ,Error > + 'bound {let data =try_pin_init! (NovaData { adev: adev.into () });let drm = drm::Device ::<Self >::new (adev.as_ref (), data)?;
rust/kernel/auxiliary.rs +8 -6
@@ -46,7 +46,7 @@// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::auxiliary_driver ; -type DriverData <'bound> =T ::Data ; +type DriverData <'bound> =T ::Data <'bound>;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -112,7 +112,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::Data>>`. -let data =unsafe { adev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { adev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::unbind (adev, data); }
@@ -203,7 +203,7 @@ pub trait Driver {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -211,8 +211,10 @@ pub trait Driver {/// Auxiliary driver probe. /// /// Called when an auxiliary device is matches a corresponding driver. -fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) - ->impl PinInit <Self ::Data ,Error >; +fn probe <'bound>( + dev: &'boundDevice <device::Core >, + id_info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;/// Auxiliary driver unbind. ///
@@ -224,7 +226,7 @@ fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo)/// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be performed in `Drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) { +fn unbind <'bound>(dev: &'boundDevice <device::Core >, this:Pin <&'boundSelf ::Data <'bound>>) {let _ = (dev, this); } }
samples/rust/rust_driver_auxiliary.rs +5 -2
@@ -31,11 +31,14 @@impl auxiliary::Driver for AuxiliaryDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const ID_TABLE : auxiliary::IdTable <Self ::IdInfo > = &AUX_TABLE ; -fn probe (adev: &auxiliary::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + adev: &'bound auxiliary::Device <Core >, + _info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ,Error > + 'bound {dev_info! ( adev,"Probing auxiliary driver for auxiliary device with id={}\n" ,
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 13/27 rust: usb: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichAdd a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
The probe() and unbind() callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.
Existing drivers set type Data<'bound> = Self, preserving the current behavior.
--- rust/kernel/usb.rs | 39 +++++++++++++++++++-------------- samples/rust/rust_driver_usb.rs | 14 ++++++------ 2 files changed, 30 insertions(+), 23 deletions(-)
rust/kernel/usb.rs +23 -16
@@ -41,7 +41,7 @@// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::usb_driver ; -type DriverData <'bound> =T ::Data ; +type DriverData <'bound> =T ::Data <'bound>;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -110,7 +110,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::Data>>`. -let data =unsafe { dev.drvdata_borrow ::<T ::Data >() }; +let data =unsafe { dev.drvdata_borrow ::<T ::Data <'_>>() };T ::disconnect (intf, data); }
@@ -287,18 +287,22 @@ macro_rules! usb_device_table {/// /// impl usb::Driver for MyDriver { /// type IdInfo = (); -/// type Data = Self; +/// type Data<'bound> = Self; /// const ID_TABLE: usb::IdTable<Self::IdInfo> = &USB_TABLE; /// -/// fn probe( -/// _interface: &usb::Interface<Core>, -/// _id: &usb::DeviceId, -/// _info: &Self::IdInfo, -/// ) -> impl PinInit<Self::Data, Error> { +/// fn probe<'bound>( +/// _interface: &'bound usb::Interface<Core>, +/// _id: &'bound usb::DeviceId, +/// _info: &'bound Self::IdInfo, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { /// Err(ENODEV) /// } /// -/// fn disconnect(_interface: &usb::Interface<Core>, _data: Pin<&Self::Data>) {} +/// fn disconnect<'bound>( +/// _interface: &'bound usb::Interface<Core>, +/// _data: Pin<&'bound Self::Data<'bound>>, +/// ) { +/// } /// } ///``` pub trait Driver {
@@ -306,7 +310,7 @@ pub trait Driver {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -315,16 +319,19 @@ 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 ::Data ,Error >; +fn probe <'bound>( + interface: &'boundInterface <device::Core >, + id: &'boundDeviceId , + id_info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;/// USB driver disconnect. /// /// Called when the USB interface is about to be unbound from this driver. -fn disconnect (interface: &Interface <device::Core >, data:Pin <&Self ::Data >); +fn disconnect <'bound>( + interface: &'boundInterface <device::Core >, + data:Pin <&'boundSelf ::Data <'bound>>, + ); }/// A USB interface.
samples/rust/rust_driver_usb.rs +7 -7
@@ -26,21 +26,21 @@ struct SampleDriver {impl usb::Driver for SampleDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;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 > { +fn probe <'bound>( + intf: &'bound usb::Interface <Core >, + _id: &'bound usb::DeviceId , + _info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ,Error > + 'bound {let dev: &device::Device <Core > = intf.as_ref ();dev_info! (dev,"Rust USB driver sample probed\n" );Ok (Self { _intf: intf.into () }) } -fn disconnect (intf: &usb::Interface <Core >, _data:Pin <&Self >) { +fn disconnect <'bound>(intf: &'bound usb::Interface <Core >, _data:Pin <&'boundSelf >) {let dev: &device::Device <Core > = intf.as_ref ();dev_info! (dev,"Rust USB driver sample disconnected\n" ); }
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 14/27 rust: i2c: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichAdd a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
The probe() and unbind() callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.
Existing drivers set type Data<'bound> = Self, preserving the current behavior.
--- rust/kernel/i2c.rs | 38 +++++++++++++++++++-------------- samples/rust/rust_driver_i2c.rs | 14 ++++++------ 2 files changed, 29 insertions(+), 23 deletions(-)
rust/kernel/i2c.rs +22 -16
@@ -98,7 +98,7 @@ macro_rules! i2c_device_table {// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::i2c_driver ; -type DriverData <'bound> =T ::Data ; +type DriverData <'bound> =T ::Data <'bound>;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }
@@ -177,7 +177,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::Data>>`. -let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::unbind (idev, data); }
@@ -189,7 +189,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::Data>>`. -let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::shutdown (idev, data); }
@@ -294,19 +294,22 @@ macro_rules! module_i2c_driver {/// /// impl i2c::Driver for MyDriver { /// type IdInfo = (); -/// type Data = Self; +/// type Data<'bound> = Self; /// 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::Data, Error> { +/// fn probe<'bound>( +/// _idev: &'bound i2c::I2cClient<Core>, +/// _id_info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { /// Err(ENODEV) /// } /// -/// fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self::Data>) { +/// fn shutdown<'bound>( +/// _idev: &'bound i2c::I2cClient<Core>, +/// this: Pin<&'bound Self::Data<'bound>>, +/// ) { /// } /// } ///```
@@ -320,7 +323,7 @@ pub trait Driver: Send {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;/// The table of device ids supported by the driver. const I2C_ID_TABLE :Option <IdTable <Self ::IdInfo >> =None ;
@@ -335,10 +338,10 @@ 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 ::Data ,Error >; +fn probe <'bound>( + dev: &'boundI2cClient <device::Core >, + id_info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;/// I2C driver shutdown. ///
@@ -351,7 +354,10 @@ 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 `Drop`. -fn shutdown (dev: &I2cClient <device::Core >, this:Pin <&Self ::Data >) { +fn shutdown <'bound>( + dev: &'boundI2cClient <device::Core >, + this:Pin <&'boundSelf ::Data <'bound>>, + ) {let _ = (dev, this); }
@@ -365,7 +371,7 @@ fn shutdown(dev: &I2cClient<device::Core>, this: Pin<&Self::Data>) {/// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be performed in `Drop`. -fn unbind (dev: &I2cClient <device::Core >, this:Pin <&Self ::Data >) { +fn unbind <'bound>(dev: &'boundI2cClient <device::Core >, this:Pin <&'boundSelf ::Data <'bound>>) {let _ = (dev, this); } }
samples/rust/rust_driver_i2c.rs +7 -7
@@ -35,16 +35,16 @@impl i2c::Driver for SampleDriver {type IdInfo =u32 ; -type Data =Self ; +type Data <'bound> =Self ;const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );const I2C_ID_TABLE :Option <i2c::IdTable <Self ::IdInfo >> =Some (&I2C_TABLE );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 > { +fn probe <'bound>( + idev: &'bound i2c::I2cClient <Core >, + info:Option <&'boundSelf ::IdInfo >, + ) ->impl PinInit <Self ,Error > + 'bound {let dev = idev.as_ref ();dev_info! (dev,"Probe Rust I2C driver sample.\n" );
@@ -56,11 +56,11 @@ fn probe(Ok (Self ) } -fn shutdown (idev: &i2c::I2cClient <Core >, _this:Pin <&Self >) { +fn shutdown <'bound>(idev: &'bound i2c::I2cClient <Core >, _this:Pin <&'boundSelf >) {dev_info! (idev.as_ref (),"Shutdown Rust I2C driver sample.\n" ); } -fn unbind (idev: &i2c::I2cClient <Core >, _this:Pin <&Self >) { +fn unbind <'bound>(idev: &'bound i2c::I2cClient <Core >, _this:Pin <&'boundSelf >) {dev_info! (idev.as_ref (),"Unbind Rust I2C driver sample.\n" ); } }
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 15/27 rust: driver: update module documentation for GAT-based Data type
In reply to Danilo KrummrichNow that all bus driver traits use type Data<'bound>: 'bound, update the illustrative driver trait in the module documentation to reflect the GAT pattern and lifetime-parameterized callbacks.
--- rust/kernel/driver.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-)
rust/kernel/driver.rs +13 -7
@@ -18,7 +18,7 @@//! type IdInfo: 'static; //! //! /// The type of the driver's bus device private data. -//! type Data; +//! type Data<'bound>: 'bound; //! //! /// The table of OF device ids supported by the driver. //! const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
@@ -27,11 +27,16 @@//! 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::Data, Error>; +//! fn probe<'bound>( +//! dev: &'bound Device<device::Core>, +//! id_info: &'bound Self::IdInfo, +//! ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound; //! //! /// Driver unbind (optional). -//! fn unbind(dev: &Device<device::Core>, this: Pin<&Self::Data>) { +//! fn unbind<'bound>( +//! dev: &'bound Device<device::Core>, +//! this: Pin<&'bound Self::Data<'bound>>, +//! ) { //! let _ = (dev, this); //! } //! }
@@ -46,9 +51,10 @@ )]#" )] //! -//! The `probe()` callback should return a `impl PinInit<Self::Data, Error>`, i.e. the driver's -//! private data. The bus abstraction should store the pointer in the corresponding bus device. The -//! generic [`Device`] infrastructure provides common helpers for this purpose on its +//! The `probe()` callback should return a +//! `impl PinInit<Self::Data<'bound>, Error>`, i.e. the driver's private data. The bus +//! abstraction should store the pointer in the corresponding bus device. The generic +//! [`Device`] infrastructure provides common helpers for this purpose on its //! [`Device<CoreInternal>`] implementation. //! //! All driver callbacks should provide a reference to the driver's private data. Once the driver
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 16/27 rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Danilo KrummrichFrom: 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
@@ -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
@@ -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
@@ -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
Danilo Krummrich
maintainerPATCH v3 17/27 rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichGeneralize 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 | 68 +++++++++++++++++---------- samples/rust/rust_driver_auxiliary.rs | 8 ++-- 3 files changed, 52 insertions(+), 28 deletions(-)
drivers/gpu/nova-core/driver.rs +3 -1
@@ -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 +44 -24
151 lines not on this page · raw message
samples/rust/rust_driver_auxiliary.rs +5 -3
@@ -14,6 +14,7 @@ driver, pci, prelude::*, + types::ForLt, InPlaceModule, // };
@@ -55,9 +56,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!(
@@ -101,7 +103,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
Danilo Krummrich
maintainerPATCH v3 18/27 samples: rust: rust_driver_auxiliary: showcase lifetime-bound registration data
In reply to Danilo KrummrichMake 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
@@ -52,14 +52,15 @@ fn probe<'bound>( } } -struct Data { +struct Data <'bound> { index:u32 , + parent: &'bound pci::Device <Bound >, }#[allow(clippy::type_complexity)] struct ParentDriver { - _reg0:Devres <auxiliary::Registration <ForLt! (Data )>>, - _reg1:Devres <auxiliary::Registration <ForLt! (Data )>>, + _reg0:Devres <auxiliary::Registration <ForLt! (Data <'_>)>>, + _reg1:Devres <auxiliary::Registration <ForLt! (Data <'_>)>>, } kernel::pci_device_table!(
@@ -85,14 +86,20 @@ fn probe<'bound>( 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, + }, )?, }) }
@@ -100,13 +107,11 @@ fn probe<'bound>(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 (),
@@ -114,7 +119,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
Danilo Krummrich
maintainerPATCH v3 19/27 rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichConvert pci::Bar<SIZE> to pci::Bar<'bound, SIZE>, storing &'bound Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized() now returns Result<Bar<'bound, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.
Add Bar::into_devres() to consume the bar and register it as a device-managed resource, returning Devres<Bar<'static, SIZE>>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind.
--- drivers/gpu/nova-core/driver.rs | 7 ++-- rust/kernel/devres.rs | 2 +- rust/kernel/pci/io.rs | 68 +++++++++++++++++---------------- samples/rust/rust_driver_pci.rs | 5 ++- 4 files changed, 44 insertions(+), 38 deletions(-)
drivers/gpu/nova-core/driver.rs +4 -3
@@ -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 ,
@@ -94,8 +94,9 @@ fn probe<'bound>(// 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
@@ -304,7 +304,7 @@ pub fn device(&self) -> &Device {/// pci, // /// }; /// -/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result { +/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<'_, 0x4>>) -> Result { /// let bar = devres.access(dev.as_ref())?; /// /// let _ = bar.read32(0x0);
rust/kernel/pci/io.rs +36 -32
156 lines not on this page · raw message
samples/rust/rust_driver_pci.rs +3 -2
@@ -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 );
@@ -161,7 +161,8 @@ fn probe<'bound>( 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
Danilo Krummrich
maintainerPATCH v3 20/27 rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
In reply to Danilo KrummrichAdd a lifetime parameter to IoMem<'bound, SIZE> and ExclusiveIoMem<'bound, SIZE>, storing a &'bound Device<Bound> reference to tie the mapping to the device's lifetime.
This mirrors the pci::Bar<'bound, SIZE> design and enables drivers to hold I/O memory mappings directly in their HRT private data, tied to the device lifetime.
IoRequest::iomap_* methods now return the mapping directly instead of wrapping it in Devres. Callers that need device-managed revocation can call the new into_devres() method.
--- drivers/gpu/drm/tyr/driver.rs | 4 +- drivers/pwm/pwm_th1520.rs | 4 +- rust/kernel/io/mem.rs | 115 +++++++++++++++++----------------- 3 files changed, 62 insertions(+), 61 deletions(-)
drivers/gpu/drm/tyr/driver.rs +2 -2
@@ -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 ;
@@ -110,7 +110,7 @@ fn probe<'bound>(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
@@ -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 , }
@@ -352,7 +352,7 @@ fn probe<'bound>( dev, TH1520_MAX_PWM_NUM,try_pin_init! (Th1520PwmDriverData { - iomem <- request.iomap_sized ::<TH1520_PWM_REG_SIZE >(), + iomem <- request.iomap_sized ::<TH1520_PWM_REG_SIZE >()?.into_devres (), clk <- clk, }), )?;
rust/kernel/io/mem.rs +58 -57
220 lines not on this page · raw message
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 21/27 samples: rust: rust_driver_pci: use HRT lifetime for Bar
In reply to Danilo KrummrichConvert the sample driver to SampleDriver<'bound>, taking advantage of the lifetime-parameterized Driver trait.
The driver struct holds &'bound pci::Device directly instead of ARef<pci::Device>, and pci::Bar<'bound> directly instead of Devres<pci::Bar>. This removes PinnedDrop, pin_init_scope, and runtime revocation checks on BAR access.
--- samples/rust/rust_driver_pci.rs | 89 +++++++++++++++------------------ 1 file changed, 40 insertions(+), 49 deletions(-)
samples/rust/rust_driver_pci.rs +40 -49
@@ -9,7 +9,6 @@ Bound, Core, // }, - devres::Devres, io::{ register, register::Array,
@@ -17,8 +16,7 @@ }, num::Bounded, pci, - prelude::*, - sync::aref::ARef, // + prelude::*, // };mod regs {
@@ -45,7 +43,7 @@ mod regs {pub (super )const END :usize =0x10 ; } -type Bar0 = pci::Bar <'static, { regs::END }>; +type Bar0 <'bound> = pci::Bar <'bound, { regs::END }>;#[derive( Copy , Clone , Debug )] struct TestIndex (u8 );
@@ -66,14 +64,14 @@ impl TestIndex {const NO_EVENTFD :Self =Self (0 ); } -#[pin_data( PinnedDrop )] -struct SampleDriver { - pdev:ARef <pci::Device >, -#[pin] - bar:Devres <Bar0 >, +struct SampleDriverData <'bound> { + pdev: &'bound pci::Device , + bar:Bar0 <'bound>, index:TestIndex , } +struct SampleDriver ; + kernel::pci_device_table!(PCI_TABLE ,MODULE_PCI_TABLE ,
@@ -84,8 +82,8 @@ struct SampleDriver { )] ); -impl SampleDriver { -fn testdev (index: &TestIndex , bar: &Bar0 ) ->Result <u32 > { +impl SampleDriverData <'_> { +fn testdev (index: &TestIndex , bar: &Bar0 <'_>) ->Result <u32 > {// Select the test. bar.write_reg (regs::TEST ::zeroed ().with_index (*index));
@@ -140,56 +138,49 @@ fn config_space(pdev: &pci::Device<Bound>) {impl pci::Driver for SampleDriver {type IdInfo =TestIndex ; -type Data <'bound> =Self ; +type Data <'bound> =SampleDriverData <'bound>;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ;fn probe <'bound>( pdev: &'bound pci::Device <Core >, info: &'boundSelf ::IdInfo , - ) ->impl PinInit <Self ,Error > + 'bound { - pin_init::pin_init_scope (move || { -let vendor = pdev.vendor_id (); -dev_dbg! ( - pdev, -"Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n" , - vendor, - pdev.device_id () - ); - - pdev.enable_device_mem ()?; - pdev.set_master (); - -Ok (try_pin_init! (Self { - bar: pdev.iomap_region_sized ::<{ regs::END }>(0 ,c"rust_driver_pci" )? - .into_devres ()?, - index: *info, - _: { -let bar = bar.access (pdev.as_ref ())?; - -dev_info! ( - pdev, -"pci-testdev data-match count: {}\n" , -Self ::testdev (info, bar)? - ); -Self ::config_space (pdev); - }, - pdev: pdev.into (), - })) + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound { +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" , +SampleDriverData ::testdev (info, &bar)? + ); +SampleDriverData ::config_space (pdev); + +Ok (SampleDriverData { + pdev, + bar, + index: *info, }) } -fn unbind (pdev: &pci::Device <Core >, this:Pin <&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 <'bound>(_pdev: &'bound pci::Device <Core >, this:Pin <&'boundSelf ::Data <'bound>>) { + 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 SampleDriverData <'_> { +fn drop (&mut self) {dev_dbg! (self.pdev,"Remove Rust PCI driver sample.\n" ); } }
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 22/27 rust: driver-core: rename 'a lifetime to 'bound
In reply to Danilo KrummrichRename the generic lifetime parameter from 'a to 'bound in pci, platform, i2c and devres. This makes it explicit that the lifetime represents the device binding scope, consistent with the convention established by the HRT series.
--- rust/kernel/devres.rs | 14 +++++++++----- rust/kernel/i2c.rs | 6 +++--- rust/kernel/pci/irq.rs | 38 +++++++++++++++++++------------------- rust/kernel/platform.rs | 18 +++++++++--------- 4 files changed, 40 insertions(+), 36 deletions(-)
rust/kernel/devres.rs +9 -5
@@ -280,10 +280,11 @@ pub fn device(&self) -> &Device { &self.dev } -/// Obtain `&'a T`, bypassing the [`Revocable`]. +/// Obtain `&'bound T`, bypassing the [`Revocable`]. /// -/// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting -/// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with. +/// This method allows to directly obtain a `&'bound T`, bypassing the +/// [`Revocable`], by presenting a `&'bound Device<Bound>` of the same +/// [`Device`] this [`Devres`] instance has been created with. /// /// # Errors ///
@@ -316,7 +317,7 @@ pub fn device(&self) -> &Device {/// Ok(()) /// } /// ``` -pub fn access <'a>(&'a self, dev: &'aDevice <Bound >) ->Result <&'aT > { +pub fn access <'bound>(&'bound self, dev: &'boundDevice <Bound >) ->Result <&'boundT > {if self.dev.as_raw () != dev.as_raw () {return Err (EINVAL ); }
@@ -338,7 +339,10 @@ pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> { }/// [`Devres`] accessor for [`Revocable::try_access_with_guard`]. -pub fn try_access_with_guard <'a>(&'a self, guard: &'a rcu::Guard ) ->Option <&'aT > { +pub fn try_access_with_guard <'bound>( + &'bound self, + guard: &'bound rcu::Guard , + ) ->Option <&'boundT > { self.data ().try_access_with_guard (guard) } }
rust/kernel/i2c.rs +3 -3
@@ -566,11 +566,11 @@ unsafe impl Sync for I2cClient {}impl Registration {/// The C `i2c_new_client_device` function wrapper for manual I2C client creation. -pub fn new <'a>( +pub fn new <'bound>( i2c_adapter: &I2cAdapter , i2c_board_info: &I2cBoardInfo , - parent_dev: &'a device::Device <device::Bound >, - ) ->impl PinInit <Devres <Self >,Error > + 'a { + parent_dev: &'bound device::Device <device::Bound >, + ) ->impl PinInit <Devres <Self >,Error > + 'bound {Devres ::new (parent_dev,Self ::try_new (i2c_adapter, i2c_board_info)) }
rust/kernel/pci/irq.rs +19 -19
@@ -76,19 +76,19 @@ const fn as_raw(self) -> u32 {/// This type ties an IRQ vector to the device it was allocated for, /// ensuring the vector is only used with the correct device. #[derive( Clone , Copy )] -pub struct IrqVector <'a> { - dev: &'aDevice <Bound >, +pub struct IrqVector <'bound> { + dev: &'boundDevice <Bound >, index:u32 , } -impl <'a>IrqVector <'a> { +impl <'bound>IrqVector <'bound> {/// Creates a new [`IrqVector`] for the given device and index. /// /// # Safety /// /// - `index` must be a valid IRQ vector index for `dev`. /// - `dev` must point to a [`Device`] that has successfully allocated IRQ vectors. -unsafe fn new (dev: &'aDevice <Bound >, index:u32 ) ->Self { +unsafe fn new (dev: &'boundDevice <Bound >, index:u32 ) ->Self {Self { dev, index } }
@@ -98,10 +98,10 @@ fn index(&self) -> u32 { } } -impl <'a>TryInto <IrqRequest <'a>>for IrqVector <'a> { +impl <'bound>TryInto <IrqRequest <'bound>>for IrqVector <'bound> {type Error =Error ; -fn try_into (self) ->Result <IrqRequest <'a>> { +fn try_into (self) ->Result <IrqRequest <'bound>> {// SAFETY: `self.as_raw` returns a valid pointer to a `struct pci_dev`. let irq =unsafe { bindings::pci_irq_vector (self.dev.as_raw (), self.index ()) };if irq <0 {
@@ -129,12 +129,12 @@ impl IrqVectorRegistration {/// /// Allocates IRQ vectors and registers them with devres for automatic cleanup. /// Returns a range of valid IRQ vectors. -fn register <'a>( - dev: &'aDevice <Bound >, +fn register <'bound>( + dev: &'boundDevice <Bound >, min_vecs:u32 , max_vecs:u32 , irq_types:IrqTypes , - ) ->Result <RangeInclusive <IrqVector <'a>>> { + ) ->Result <RangeInclusive <IrqVector <'bound>>> {// SAFETY: // - `dev.as_raw()` is guaranteed to be a valid pointer to a `struct pci_dev` // by the type invariant of `Device`.
@@ -173,13 +173,13 @@ fn drop(&mut self) {impl Device <device::Bound > {/// Returns a [`kernel::irq::Registration`] for the given IRQ vector. -pub fn request_irq <'a,T :crate ::irq::Handler + 'static>( - &'a self, - vector:IrqVector <'a>, +pub fn request_irq <'bound,T :crate ::irq::Handler + 'static>( + &'bound self, + vector:IrqVector <'bound>, flags: irq::Flags , name: &'staticCStr , - handler:impl PinInit <T ,Error > + 'a, - ) ->impl PinInit <irq::Registration <T >,Error > + 'a { + handler:impl PinInit <T ,Error > + 'bound, + ) ->impl PinInit <irq::Registration <T >,Error > + 'bound { pin_init::pin_init_scope (move || {let request = vector.try_into ()?;
@@ -188,13 +188,13 @@ pub fn request_irq<'a, T: crate::irq::Handler + 'static>( }/// Returns a [`kernel::irq::ThreadedRegistration`] for the given IRQ vector. -pub fn request_threaded_irq <'a,T :crate ::irq::ThreadedHandler + 'static>( - &'a self, - vector:IrqVector <'a>, +pub fn request_threaded_irq <'bound,T :crate ::irq::ThreadedHandler + 'static>( + &'bound self, + vector:IrqVector <'bound>, flags: irq::Flags , name: &'staticCStr , - handler:impl PinInit <T ,Error > + 'a, - ) ->impl PinInit <irq::ThreadedRegistration <T >,Error > + 'a { + handler:impl PinInit <T ,Error > + 'bound, + ) ->impl PinInit <irq::ThreadedRegistration <T >,Error > + 'bound { pin_init::pin_init_scope (move || {let request = vector.try_into ()?;
rust/kernel/platform.rs +9 -9
@@ -337,13 +337,13 @@ macro_rules! define_irq_accessor_by_index { $handler_trait:ident ) => { $(#[$meta])* - pub fn $fn_name<'a, T: irq::$handler_trait + 'static>( - &'a self, + pub fn $fn_name<'bound, T: irq::$handler_trait + 'static>( + &'bound self, flags: irq::Flags, index: u32, name: &'static CStr, - handler: impl PinInit<T, Error> + 'a, - ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a { + handler: impl PinInit<T, Error> + 'bound, + ) -> impl PinInit<irq::$reg_type<T>, Error> + 'bound { pin_init::pin_init_scope(move || { let request = self.$request_fn(index)?;
@@ -366,13 +366,13 @@ macro_rules! define_irq_accessor_by_name { $handler_trait:ident ) => { $(#[$meta])* - pub fn $fn_name<'a, T: irq::$handler_trait + 'static>( - &'a self, + pub fn $fn_name<'bound, T: irq::$handler_trait + 'static>( + &'bound self, flags: irq::Flags, - irq_name: &'a CStr, + irq_name: &'bound CStr, name: &'static CStr, - handler: impl PinInit<T, Error> + 'a, - ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a { + handler: impl PinInit<T, Error> + 'bound, + ) -> impl PinInit<irq::$reg_type<T>, Error> + 'bound { pin_init::pin_init_scope(move || { let request = self.$request_fn(irq_name)?;
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 23/27 gpu: nova-core: rename 'a lifetime to 'bound
In reply to Danilo KrummrichRename the generic lifetime parameter from 'a to 'bound in nova-core. This makes it explicit that the lifetime represents the device binding scope, consistent with the convention established by the HRT series.
--- drivers/gpu/nova-core/firmware/gsp.rs | 8 ++++---- drivers/gpu/nova-core/gpu.rs | 8 ++++---- drivers/gpu/nova-core/gsp/commands.rs | 10 +++++----- drivers/gpu/nova-core/gsp/fw/commands.rs | 4 +++- 4 files changed, 16 insertions(+), 14 deletions(-)
drivers/gpu/nova-core/firmware/gsp.rs +4 -4
@@ -65,11 +65,11 @@ pub(crate) struct GspFirmware {impl GspFirmware {/// Loads the GSP firmware binaries, map them into `dev`'s address-space, and creates the page /// tables expected by the GSP bootloader to load it. -pub (crate )fn new <'a>( - dev: &'a device::Device <device::Bound >, +pub (crate )fn new <'bound>( + dev: &'bound device::Device <device::Bound >, chipset:Chipset , - ver: &'astr , - ) ->impl PinInit <Self ,Error > + 'a { + ver: &'boundstr , + ) ->impl PinInit <Self ,Error > + 'bound { pin_init::pin_init_scope (move || {let firmware =super ::request_firmware (dev, chipset,"gsp" , ver)?;
drivers/gpu/nova-core/gpu.rs +4 -4
@@ -241,11 +241,11 @@ pub(crate) struct Gpu { } impl Gpu { - pub(crate) fn new<'a>( - pdev: &'a pci::Device<device::Bound>, + pub(crate) fn new<'bound>( + pdev: &'bound pci::Device<device::Bound>, devres_bar: Arc<Devres<Bar0>>, - bar: &'a Bar0, - ) -> impl PinInit<Self, Error> + 'a { + bar: &'bound Bar0, + ) -> impl PinInit<Self, Error> + 'bound { try_pin_init!(Self { spec: Spec::new(pdev.as_ref(), bar).inspect(|spec| { dev_info!(pdev,"NVIDIA ({})\n", spec);
drivers/gpu/nova-core/gsp/commands.rs +5 -5
@@ -35,18 +35,18 @@ };/// The `GspSetSystemInfo` command. -pub (crate )struct SetSystemInfo <'a> { - pdev: &'a pci::Device <device::Bound >, +pub (crate )struct SetSystemInfo <'bound> { + pdev: &'bound pci::Device <device::Bound >, } -impl <'a>SetSystemInfo <'a> { +impl <'bound>SetSystemInfo <'bound> {/// Creates a new `GspSetSystemInfo` command using the parameters of `pdev`. -pub (crate )fn new (pdev: &'a pci::Device <device::Bound >) ->Self { +pub (crate )fn new (pdev: &'bound pci::Device <device::Bound >) ->Self {Self { pdev } } } -impl <'a>CommandToGsp for SetSystemInfo <'a> { +impl <'bound>CommandToGsp for SetSystemInfo <'bound> {const FUNCTION :MsgFunction =MsgFunction ::GspSetSystemInfo ;type Command =GspSetSystemInfo ;type Reply =NoReply ;
drivers/gpu/nova-core/gsp/fw/commands.rs +3 -1
@@ -24,7 +24,9 @@ pub(crate) struct GspSetSystemInfo { impl GspSetSystemInfo { /// Returns an in-place initializer for the `GspSetSystemInfo` command. #[allow(non_snake_case)] - pub(crate) fn init<'a>(dev: &'a pci::Device<device::Bound>) -> impl Init<Self, Error> + 'a { + pub(crate) fn init<'bound>( + dev: &'bound pci::Device<device::Bound>, + ) -> impl Init<Self, Error> + 'bound { type InnerGspSystemInfo = bindings::GspSystemInfo; let init_inner = try_init!(InnerGspSystemInfo { gpuPhysAddr: dev.resource_start(0)?,
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 24/27 gpu: nova-core: use lifetime for Bar
In reply to Danilo KrummrichTake advantage of the lifetime-parameterized pci::Bar<'bound> to hold the BAR mapping directly in NovaCore<'bound>, and pass a borrowed reference to Gpu<'bound>.
This eliminates the Arc<Devres<Bar0>> indirection, removes runtime revocation checks for BAR access, and simplifies Gpu::unbind().
--- drivers/gpu/nova-core/driver.rs | 46 +++++++++++++++--------------- drivers/gpu/nova-core/gpu.rs | 27 +++++++----------- drivers/gpu/nova-core/nova_core.rs | 2 +- 3 files changed, 34 insertions(+), 41 deletions(-)
drivers/gpu/nova-core/driver.rs +23 -23
@@ -14,12 +14,9 @@ }, prelude::*, sizes::SZ_16M, - sync::{ - atomic::{ - Atomic, - Relaxed, // - }, - Arc, + sync::atomic::{ + Atomic, + Relaxed, // }, types::ForLt, };
@@ -30,9 +27,10 @@static AUXILIARY_ID_COUNTER :Atomic <u32 > =Atomic ::new (0 );#[pin_data] -pub (crate )struct NovaCore { +pub (crate )struct NovaCore <'bound> {#[pin] -pub (crate ) gpu:Gpu , +pub (crate ) gpu:Gpu <'bound>, + bar: pci::Bar <'bound,BAR0_SIZE >,#[allow(clippy::type_complexity)] _reg:Devres <auxiliary::Registration <ForLt! (())>>, }
@@ -47,12 +45,14 @@ 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 >; + +pub (crate )struct NovaCoreDriver ; kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - <NovaCore as pci::Driver>::IdInfo, + <NovaCoreDriver as pci::Driver>::IdInfo, [ // Modern NVIDIA GPUs will show up as either VGA or 3D controllers. (
@@ -74,15 +74,15 @@ pub(crate) struct NovaCore { ] ); -impl pci::Driver for NovaCore { +impl pci::Driver for NovaCoreDriver {type IdInfo = (); -type Data <'bound> =Self ; +type Data <'bound> =NovaCore <'bound>;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ;fn probe <'bound>( pdev: &'bound pci::Device <Core >, _info: &'boundSelf ::IdInfo , - ) ->impl PinInit <Self ,Error > + 'bound { + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound { pin_init::pin_init_scope (move || {dev_dbg! (pdev,"Probe Nova Core GPU driver.\n" );
@@ -94,14 +94,14 @@ fn probe<'bound>(// 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",
@@ -115,7 +115,7 @@ fn probe<'bound>( }) } -fn unbind <'bound>(pdev: &'bound pci::Device <Core >, this:Pin <&'boundSelf >) { - this.gpu.unbind (pdev.as_ref ()); +fn unbind <'bound>(_pdev: &'bound pci::Device <Core >, this:Pin <&'boundSelf ::Data <'bound>>) { + this.gpu.unbind (); } }
drivers/gpu/nova-core/gpu.rs +10 -17
@@ -2,13 +2,11 @@use kernel::{ device, - devres::Devres , fmt, io::Io , num::Bounded , pci, - prelude::*, - sync::Arc ,// + prelude::*,// };use crate ::{
@@ -224,10 +222,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {/// Structure holding the resources required to operate the GPU. #[pin_data] -pub (crate )struct Gpu { +pub (crate )struct Gpu <'bound> { spec:Spec , -/// MMIO mapping of PCI BAR 0 - bar:Arc <Devres <Bar0 >>, +/// MMIO mapping of PCI BAR 0. + bar: &'boundBar0 ,/// System memory page required for flushing all pending GPU-side memory writes done through /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation). sysmem_flush:SysmemFlush ,
@@ -240,10 +238,9 @@ pub(crate) struct Gpu { gsp: Gsp, } -impl Gpu { -pub (crate )fn new <'bound>( +impl <'bound>Gpu <'bound> { +pub (crate )fn new ( pdev: &'bound pci::Device <device::Bound >, - devres_bar:Arc <Devres <Bar0 >>, bar: &'boundBar0 , ) ->impl PinInit <Self ,Error > + 'bound {try_pin_init! (Self {
@@ -257,6 +254,8 @@ pub(crate) fn new<'bound>( .inspect_err(|_| dev_err!(pdev, "GFW boot did not complete\n"))?; }, + bar, + sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?, gsp_falcon: Falcon::new(
@@ -270,19 +269,13 @@ pub(crate) fn new<'bound>( gsp <- Gsp::new(pdev), _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)? }, - - bar: devres_bar, }) }/// Called when the corresponding [`Device`](device::Device) is unbound. /// /// Note: This method must only be called from `Driver::unbind`. -pub (crate )fn unbind (&self, dev: &device::Device <device::Core >) { - kernel::warn_on!(self - .bar - .access (dev) - .inspect (|bar| self.sysmem_flush.unregister (bar)) - .is_err ()); +pub (crate )fn unbind (&self) { + self.sysmem_flush.unregister (self.bar); } }
drivers/gpu/nova-core/nova_core.rs +1 -1
@@ -47,7 +47,7 @@ struct NovaCoreModule {// Fields are dropped in declaration order, so `_driver` is dropped first, // then `_debugfs_guard` clears `DEBUGFS_ROOT`. #[pin] - _driver: Registration<pci::Adapter<driver::NovaCore>>, + _driver: Registration<pci::Adapter<driver::NovaCoreDriver>>, _debugfs_guard: DebugfsRootGuard, }
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 25/27 gpu: nova-core: unregister sysmem flush page from Drop
In reply to Danilo KrummrichNow that SysmemFlush can borrow the Bar via HRT lifetime, store a &'bound Bar0 reference and implement Drop to automatically unregister the sysmem flush page. This removes the need for manual unregister() calls and the Gpu::unbind() method.
--- 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
@@ -114,8 +114,4 @@ fn probe<'bound>( })) }) } - -fn unbind <'bound>(_pdev: &'bound pci::Device <Core >, this:Pin <&'boundSelf ::Data <'bound>>) { - this.gpu.unbind (); - } }
drivers/gpu/nova-core/fb.rs +10 -12
@@ -46,21 +46,20 @@/// Because of this, the sysmem flush memory page must be registered as early as possible during /// driver initialization, and before any falcon is reset. /// -/// Users are responsible for manually calling [`Self::unregister`] before dropping this object, -/// otherwise the GPU might still use it even after it has been freed. -pub (crate )struct SysmemFlush { +pub (crate )struct SysmemFlush <'bound> {/// Chipset we are operating on. chipset:Chipset , device:ARef <device::Device >, + bar: &'boundBar0 ,/// Keep the page alive as long as we need it. page:CoherentHandle , } -impl SysmemFlush { +impl <'bound>SysmemFlush <'bound> {/// Allocate a memory page and register it as the sysmem flush page. pub (crate )fn register ( dev: &device::Device <device::Bound >, - bar: &Bar0 , + bar: &'boundBar0 , 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
@@ -228,7 +228,7 @@ pub(crate) struct Gpu<'bound> { bar: &'bound Bar0, /// System memory page required for flushing all pending GPU-side memory writes done through /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation). - sysmem_flush: SysmemFlush, + sysmem_flush: SysmemFlush<'bound>, /// GSP falcon instance, used for GSP boot up and cleanup. gsp_falcon: Falcon<GspFalcon>,/// SEC2 falcon instance, used for GSP boot up and cleanup.
@@ -271,11 +271,4 @@ pub(crate) fn new( _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)? }, }) } - -/// Called when the corresponding [`Device`](device::Device) is unbound. -/// -/// Note: This method must only be called from `Driver::unbind`. -pub (crate )fn unbind (&self) { - self.sysmem_flush.unregister (self.bar); - } }
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v3 26/27 gpu: nova-core: replace ARef<Device> with &'bound Device in SysmemFlush
In reply to Danilo KrummrichNow that SysmemFlush is lifetime-parameterized, the ARef<Device> is unnecessary -- a plain &'bound Device reference suffices.
--- drivers/gpu/nova-core/fb.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/fb.rs +4 -5
@@ -15,8 +15,7 @@ Alignable, Alignment, // }, - sizes::*, - sync::aref::ARef, // + sizes::*, // };use crate ::{
@@ -49,7 +48,7 @@pub (crate )struct SysmemFlush <'bound> {/// Chipset we are operating on. chipset:Chipset , - device:ARef <device::Device >, + device: &'bound device::Device , bar: &'boundBar0 ,/// Keep the page alive as long as we need it. page:CoherentHandle ,
@@ -58,7 +57,7 @@ pub(crate) struct SysmemFlush<'bound> {impl <'bound>SysmemFlush <'bound> {/// Allocate a memory page and register it as the sysmem flush page. pub (crate )fn register ( - dev: &device::Device <device::Bound >, + dev: &'bound device::Device <device::Bound >, bar: &'boundBar0 , 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
Danilo Krummrich
maintainerPATCH v3 27/27 gpu: drm: tyr: use lifetime for IoMem
In reply to Danilo KrummrichTake advantage of the lifetime-parameterized IoMem<'bound> to use the memory mapping directly during probe, eliminating the Arc<Devres<IoMem>> indirection.
Since the IoMem is only used during probe, this also simplifies Register::read/write to be infallible -- the Devres access check is no longer needed, so reads return u32 directly and writes return ().
---
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
@@ -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),
@@ -110,12 +108,12 @@ fn probe<'bound>(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
@@ -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
[email protected]
AI reviewRe: [PATCH v3 03/27] rust: driver: decouple driver private data from driver type
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] The new `Data` associated type on bus driver traits lacks a `Send` bound, allowing safe Rust code…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The new Data associated type on bus driver traits lacks a Send bound, allowing safe Rust code to store thread-unsafe types in device drvdata. --
commit e138a8068792e58e92b3ef6ae49ec5c3c073f8c9
Author: Danilo Krummrich <[email protected]>
rust: driver: decouple driver private data from driver type
This commit adds a Data associated type to all bus driver traits, separating the driver's device private data type from the driver struct. This avoids a global lifetime on the driver trait and simplifies bus implementations.
Quoted 4 lines
rust/kernel/pci.rs +0
-0
[ ... ]
rust/kernel/pci.rs pub trait Driver: Send { · line 306
Quoted 7 lines
rust/kernel/pci.rs +3
-0@@ -300,6 +301,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data ; +
Does this associated type need a Send bound?
Prior to this change, the driver data was restricted to Self, which requires Send (as seen in the trait definition above). By extracting it to an unconstrained associated type, safe Rust code could potentially use a thread-unsafe type like Rc for the driver data.
Since the device core can trigger unbind operations from arbitrary threads (for example, via sysfs), post_unbind_callback might drop the driver data on a different thread than the one that created it. Could this lead to data races or memory corruption if a !Send type is used?
Quoted 2 lines
rust/kernel/pci.rs +0
-0/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
[email protected]
AI reviewRe: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Safe Rust code can directly name and use `UnsafeForLtImpl` to bypass covariance proofs, leading to…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Safe Rust code can directly name and use UnsafeForLtImpl to bypass covariance proofs, leading to use-after-free.
- [High] The ForLt! macro fails to check covariance for types wrapped in macro invocations.
- [Low] The cast_ref function is incorrectly annotated with #[inline(always)].
--
commit 2088fc9ea2c7348deada4ab3dfcc55a6783dcf27
Author: Gary Guo <[email protected]>
rust: types: add ForLt trait for higher-ranked lifetime support
This commit adds a ForLt trait and macro to support types that are generic over a lifetime, ensuring covariance for safe lifetime shortening. It provides a way to represent types that are themselves generic over lifetimes, which is useful for cross-referencing data.
Quoted 5 lines
rust/kernel/types/for_lt.rs new file +0
-0
[ ... ]
rust/kernel/types/for_lt.rs line 91
Quoted 7 lines
rust/kernel/types/for_lt.rs new file +7
-0+/// Cast a reference to a shorter lifetime. +#[inline(always)] +fn cast_ref <'r, 'short: 'r, 'long: 'short>(long: &'rSelf ::Of <'long>) -> &'rSelf ::Of <'short> { +// SAFETY: This is sound as this trait guarantees covariance. +unsafe { core::mem::transmute (long) } + } +}
Should this function use #[inline] instead of #[inline(always)]?
According to the Rust coding guidelines, #[inline(always)] is reserved for functions using build_assert!() that depend on function parameters. For small forwarding abstractions like this, #[inline] should be used.
[ ... ]
Quoted 4 lines
rust/kernel/types/for_lt.rs new file +4
-0+/// `N` is to provide the macro a place to emit arbitrary items, in case it needs to prove +/// additional properties. +#[doc(hidden)] +pub struct UnsafeForLtImpl <T : ?Sized ,WF ,const N :usize >(PhantomData <(WF ,T )>);
rust/kernel/types/for_lt.rs line 115
Quoted 10 lines
rust/kernel/types/for_lt.rs new file +10
-0+ +// This is a helper trait for implementation `ForLt` to be able to use HRTB. +#[doc(hidden)] +pub trait WithLt <'a> { +type Of : 'a; +} + +// SAFETY: In `ForLt!` macro, a covariance proof is generated when naming `UnsafeForLtImpl` +// and it will fail to evaluate if the type is not covariant. +unsafe impl <T : ?Sized +for <'a>WithLt <'a>,WF >ForLt for UnsafeForLtImpl <T ,WF ,0 > {
Does this allow safe Rust code to bypass covariance proofs?
Because UnsafeForLtImpl is a public type, it appears safe code can name it directly to safely obtain a ForLt implementation for a contravariant or invariant type. For example:
UnsafeForLtImpl<dyn for<'a> WithLt<'a, Of = fn(&'a ())>, fn(&'static ()), 0>
This would bypass the compiler variance checks generated by the macro's anonymous const block, potentially enabling use-after-free vulnerabilities from safe code via cast_ref.
Quoted 5 lines
rust/macros/for_lt.rs new file +0
-0
[ ... ]
rust/macros/for_lt.rs line 164
Quoted 6 lines
rust/macros/for_lt.rs new file +6
-0+// `&[mut] T` is covariant over lifetime. +// In case we have `&[mut] NoLifetime`, we don't need to do additional checks. + Type::Reference(ty) if !ty.elem.has_lifetime(self.0) => (), + + // No mention of lifetime at all, no need to perform compiler check. + ty if !ty.has_lifetime(self.0) => (),
Can this logic fail to check covariance for types wrapped in macro invocations?
The syntactic prover uses has_lifetime to determine if a type depends on the generic lifetime binder. However, the underlying syn visitor does not traverse into the unparsed TokenStream of a macro invocation.
If a user provides a type wrapped in a macro, such as ForLt!(for<'a> SomeMacro!(fn(&'a u32))), has_lifetime will return false.
This would cause the macro to silently skip generating the prove_covariant safety checks, which might allow unsound lifetime downcasting on contravariant types.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
[email protected]
AI reviewRe: [PATCH v3 09/27] rust: device: implement Sync for Device<Bound>
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Device<Bound> implements Sync but omits Send, leading to inconsistent thread-safety traits. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Device<Bound> implements Sync but omits Send, leading to inconsistent thread-safety traits. --
commit e675b37d10f2f352ac9ef52da2da8c8f4d217a5b
Author: Danilo Krummrich <[email protected]>
rust: device: implement Sync for Device<Bound>
This commit implements the Sync trait for Device<Bound> so that types holding a reference to it can be Send.
rust/kernel/device.rs unsafe impl Send for Device {} · line 472
Quoted 11 lines
rust/kernel/device.rs +3
-0@@ -467,6 +467,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 > {}
Should Device<Bound> also implement Send?
Since Device<Normal> explicitly implements both Send and Sync, and the safety comment notes that the Bound marker does not affect thread safety, omitting Send leaves Device<Bound> as !Send.
While &Device<Bound> is Send because the type is Sync, any user structure tracking device state at compile time with PhantomData<Device<Bound>> would unexpectedly become !Send.
Would it be appropriate to add an unsafe impl Send for Device<Bound> {} here to maintain consistency with Device<Normal>?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
[email protected]
AI reviewRe: [PATCH v3 13/27] rust: usb: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Critical] Use-After-Free vulnerability due to incorrect `'bound` lifetime on dynamic `DeviceId`.…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Critical] Use-After-Free vulnerability due to incorrect 'bound lifetime on dynamic DeviceId.
- [High] Soundness violation and FFI lifetime bypass in driver data retrieval.
- [Low] Commit message incorrectly references unbind() instead of disconnect(). --
commit 92ace0018c4af4c9a4ccdae5f9dd912c5a7f6ab0
Author: Danilo Krummrich <[email protected]>
rust: usb: make Driver trait lifetime-parameterized
This commit introduces a 'bound lifetime parameter to the usb::Driver::Data associated type. This allows driver private data to store references directly instead of relying on Devres. The probe and disconnect callbacks are updated to use this lifetime.
Quoted 2 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.
This isn't a bug, but the commit message references unbind() instead of disconnect(). The USB subsystem specifically uses disconnect(), whereas unbind() is typically used by other bus types like platform drivers.
Quoted 4 lines
rust/kernel/usb.rs +0
-0
[ ... ]
rust/kernel/usb.rs extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) { · line 116
Quoted 9 lines
rust/kernel/usb.rs +1
-1@@ -110,7 +110,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::Data>>`. -let data =unsafe { dev.drvdata_borrow ::<T ::Data >() }; +let data =unsafe { dev.drvdata_borrow ::<T ::Data <'_>>() };T ::disconnect (intf, data); }
Does this violate the type matching contract of ForeignOwnable?
The data is originally stored in probe_callback() with a local 'probe lifetime but is retrieved here with a newly instantiated local '_ lifetime.
If a driver implements Data<'bound> such that it is invariant over 'bound (for example, by using interior mutability like Cell<&'bound Interface>), then T::Data<'probe> and T::Data<'_> are formally different types in Rust.
Transmuting between invariant types with different lifetimes could violate the safety preconditions of ForeignOwnable and bypass the borrow checker's ability to verify constraints across the FFI boundary.
[ ... ]
Quoted 4 lines
rust/kernel/usb.rs +0
-0@@ -315,16 +319,19 @@ pub trait Driver {/// /// Called when a new USB interface is bound to this driver. /// Implementers should attempt to initialize the interface here.
rust/kernel/usb.rs pub trait Driver { · line 326
Quoted 10 lines
rust/kernel/usb.rs +5
-5-fn probe ( - interface: &Interface <device::Core >, - id: &DeviceId , - id_info: &Self ::IdInfo , - ) ->impl PinInit <Self ::Data ,Error >; +fn probe <'bound>( + interface: &'boundInterface <device::Core >, + id: &'boundDeviceId , + id_info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;
Can tying the id parameter to the 'bound lifetime result in a use-after-free?
When a device is bound using a dynamic ID (added via the new_id sysfs attribute), the USB core passes a pointer to a dynamically allocated struct usb_dynid to the probe function via usb_match_dynamic_id().
Userspace can remove dynamic IDs at any time using the remove_id sysfs attribute, which unlinks and frees the usb_dynid without checking if any currently bound devices matched against it.
If a Rust driver safely stores the id reference in its private Data<'bound> based on this lifetime guarantee, it could hold a dangling pointer once the dynamic ID is removed, potentially causing a use-after-free later during the device's lifecycle.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
[email protected]
AI reviewRe: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The introduction of the `'bound` lifetime parameter allows drivers to capture short-lived…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The introduction of the 'bound lifetime parameter allows drivers to capture short-lived references into driver private data, leading to a formal use-after-free (provenance violation) and Undefined Behavior when accessed later.
- [Low] The signature of unbind in samples/rust/rust_driver_pci.rs does not match the newly parameterized pci::Driver trait, causing a compilation error.
--
commit e20151fd03221a2c3958612a0dabaa50cdd67768
Author: Danilo Krummrich <[email protected]>
rust: pci: make Driver trait lifetime-parameterized
This changes the pci::Driver trait to add a 'bound lifetime to the associated Data type, allowing bus device private data to capture the device and driver bound lifetime.
Quoted 4 lines
rust/kernel/pci.rs +0
-0
[ ... ]
rust/kernel/pci.rs extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) { · line 133
Quoted 6 lines
rust/kernel/pci.rs +1
-1@@ -130,7 +130,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::Data>>`. -let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };
Does this lead to a formal use-after-free and provenance violation under Rust's aliasing rules?
In probe_callback, a reference to pdev is created with a lifetime restricted to the callback's scope, which is stored in Data<'probe>.
Since set_drvdata stores this data by converting it to a raw pointer, the 'probe lifetime formally ends when probe_callback returns.
Between probe and remove, the C subsystem can mutate the pci_dev struct using its parent raw pointer, which invalidates the child reference created during probe.
When remove_callback calls drvdata_borrow, does this execute an unchecked transmute from the expired 'probe lifetime to a fresh 'remove lifetime?
When the driver accesses these references, will it use a reference with an invalidated provenance tag and trigger undefined behavior?
Would it be safer to use ARef<Device>, which stores a raw pointer and creates fresh references on demand, rather than circumventing the borrow checker with synthetic lifetimes?
[ ... ]
Quoted 11 lines
samples/rust/rust_driver_pci.rs +1
-1@@ -140,11 +140,14 @@ fn config_space(pdev: &pci::Device<Bound>) {impl pci::Driver for SampleDriver {type IdInfo =TestIndex ; -type Data =Self ; +type Data <'bound> =Self ;
samples/rust/rust_driver_pci.rs fn config_space(pdev: &pci::Device<Bound>) { · line 153
Quoted 10 lines
samples/rust/rust_driver_pci.rs +4
-1const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe<'bound>( + pdev: &'bound pci::Device<Core>, + info: &'bound Self::IdInfo, + ) -> impl PinInit<Self, Error> + 'bound { pin_init::pin_init_scope(move || { let vendor = pdev.vendor_id(); dev_dbg!(
Does the unbind method in this file also need to be updated to match the new pci::Driver trait signature?
Since the trait adds a 'bound lifetime parameter to unbind, failing to update the implementation here leaves elided lifetimes that resolve to two separate anonymous lifetimes.
Will the compiler reject this with a lifetime parameter mismatch error, breaking the build?
I note this regression is fixed later in the patch series by the commit "samples: rust: rust_driver_pci: use HRT lifetime for Bar", but does it break git bisectability here?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
[email protected]
AI reviewRe: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] Unsound lifetime erasure in `Registration::new` allows safe code to trigger Use-After-Free.…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] Unsound lifetime erasure in Registration::new allows safe code to trigger Use-After-Free.
- [Critical] Lockless read and premature teardown of registration_data_rust causes Use-After-Free. --
commit c525b4daa575d3a91524d98a70e2c2b7a56eca5b
Author: Danilo Krummrich <[email protected]>
rust: auxiliary: generalize Registration over ForLt
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.
Quoted 12 lines
rust/kernel/auxiliary.rs +3
-1@@ -271,12 +272,16 @@ pub fn parent(&self) -> &device::Device<device::Bound> {/// Returns a pinned reference to the registration data set by the registering (parent) driver. /// -/// Returns [`EINVAL`] if `T` does not match the type used by the parent driver when calling +/// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The returned +/// reference has its lifetime shortened from `'static` to `&self`'s borrow lifetime via +/// [`ForLt::cast_ref`].
rust/kernel/auxiliary.rs pub fn parent(&self) -> &device::Device<device::Bound> { · line 286
Quoted 10 lines
rust/kernel/auxiliary.rs +3
-1+/// +/// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling /// [`Registration::new()`]. /// /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was /// registered by a C driver. -pub fn registration_data <T : 'static>(&self) ->Result <Pin <&T >> { +pub fn registration_data <F :ForLt >(&self) ->Result <Pin <&F ::Of <'_>>> {// SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`. let ptr =unsafe { (*self.as_raw ()).registration_data_rust };
Does this lockless read of registration_data_rust allow a use-after-free?
While this wasn't introduced by this patch, it appears to remain a vulnerability in the code modified here. In Registration::drop(), the memory backing this pointer is freed via Pin::from_foreign(...), but dropping the Registration (when the parent device unbinds) does not guarantee the struct auxiliary_device is destroyed.
Other kernel threads might still hold a reference to the auxiliary device (e.g., via ARef<Device>). When Registration::drop() frees the data, it doesn't set registration_data_rust to NULL.
Without synchronization, could another thread with an ARef<Device> call the safe registration_data() method after the devres has unwound and access freed memory?
Should the registration data be freed in the auxiliary device's release callback instead, or should proper synchronization be introduced?
[ ... ]
Quoted 26 lines
rust/kernel/auxiliary.rs +7
-5@@ -389,43 +399,51 @@ struct RegistrationData<T> { -impl<T: Send + Sync + 'static> Registration<T> { +impl<F: ForLt> Registration<F> +where + for<'a> F::Of<'a>: Send + Sync, +{ /// Create and register a new auxiliary device with the given registration data. /// /// The `data` is owned by the registration and can be accessed through the auxiliary device /// via [`Device::registration_data()`]. - pub fn new<E>( - parent: &device::Device<device::Bound>, + pub fn new<'bound, E>( + parent: &'bound device::Device<device::Bound>, name: &CStr, id: u32, modname: &CStr, - data: impl PinInit<T, E>, + data: impl PinInit<F::Of<'bound>, E>, ) -> Result<Devres<Self>> where Error: From<E>, { let data = KBox::pin_init::<Error>( try_pin_init!(RegistrationData { - type_id: TypeId::of::<T>(),
rust/kernel/auxiliary.rs struct RegistrationData<T> { · line 428
Quoted 10 lines
rust/kernel/auxiliary.rs +5
-0+ type_id: TypeId::of::<F::Of<'static>>(), data <- data, }), GFP_KERNEL, )?; +// SAFETY: Lifetimes are erased and do not affect layout, so RegistrationData<F::Of<'bound>> +// and RegistrationData<F::Of<'static>> have identical representation. +let data:Pin <KBox <RegistrationData <F ::Of <'static>>>> = +unsafe { core::mem::transmute (data) };
Can this transmute allow safe code to trigger a use-after-free?
Since Registration::new accepts parent: &'bound device::Device and
data: impl PinInit<F::Of<'bound>, E>, Rust's lifetime covariance allows callers to borrow parent for an arbitrarily short lifetime (e.g., the scope of a stack variable inside the probe function) and pass data containing references bounded by that short lifetime.
This function unsafely uses core::mem::transmute to erase this lifetime to 'static. Since it returns a Devres<Registration<F>> which has no lifetime parameters, it is treated as 'static, allowing safe Rust code to place the Devres into the parent device's devres list.
When the local stack variables go out of scope, won't the Devres still hold the data, causing an exploitable use-after-free when Device::registration_data() is called or when Registration::drop() cleans up?
Should Registration::new be marked unsafe so the caller guarantees the references outlive the device's bound state, or should the API be redesigned to structurally capture the lifetime?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
[email protected]
AI reviewRe: [PATCH v3 22/27] rust: driver-core: rename 'a lifetime to 'bound
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The lifetime parameter in `Devres::try_access_with_guard` was incorrectly renamed from `'a` to…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The lifetime parameter in Devres::try_access_with_guard was incorrectly renamed from 'a to 'bound, which contradicts its actual semantic meaning. --
commit 8a559ac68ebb5e20ec1214cce81f98b5f5db59d8
Author: Danilo Krummrich <[email protected]>
rust: driver-core: rename 'a lifetime to 'bound
This commit renames the generic lifetime parameter from 'a to 'bound across several driver core modules. The rename is intended to make it explicit that the lifetime represents the device binding scope.
Quoted 4 lines
rust/kernel/devres.rs +0
-0
[ ... ]
rust/kernel/devres.rs pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> { · line 345
Quoted 9 lines
rust/kernel/devres.rs +4
-1@@ -338,7 +339,10 @@ pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> { }/// [`Devres`] accessor for [`Revocable::try_access_with_guard`]. -pub fn try_access_with_guard <'a>(&'a self, guard: &'a rcu::Guard ) ->Option <&'aT > { +pub fn try_access_with_guard <'bound>( + &'bound self, + guard: &'bound rcu::Guard , + ) ->Option <&'boundT > {
Is the 'bound name appropriate for this specific lifetime?
The commit message notes that 'bound represents the device binding scope, but here the lifetime is explicitly tied to the rcu::Guard. An RCU guard's lifetime represents the duration of the RCU read-side critical section, which is typically much shorter than the device binding scope.
This isn't a bug since the compiler will still enforce the correct lifetime constraints, but using 'bound here might be misleading when comparing it to the stated intent in the commit message.
Quoted 3 lines
rust/kernel/devres.rs +0
-0self.data ().try_access_with_guard (guard) } }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
[email protected]
AI reviewRe: [PATCH v3 08/27] rust: usb: implement Sync for Device<Bound>
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] The patch is unusable for its stated purpose because `usb::Device` is private and cannot be…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] The patch is unusable for its stated purpose because usb::Device is private and cannot be obtained as a <Bound> instance.
- [High] Missing Sync implementation for usb::Interface<device::Bound>, which is the type USB drivers actually bind to.
- [Medium] The patch omits the Send trait for Device<device::Bound> and fails to use generic bounds for context markers. --
commit 58da801d401502ae94fc21b502a93555301c6b9c
Author: Danilo Krummrich <[email protected]>
rust: usb: implement Sync for Device<Bound>
This commit implements the Sync trait for Device<Bound> to allow drivers to store bound device references in their private data while maintaining thread safety.
Quoted 10 lines
rust: usb: implement Sync for Device<Bound>
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
usb_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound usb::Device<Bound> in their private data while remaining Send.
Since drivers bind to a usb::Interface rather than a usb::Device, do they actually need to store usb::Interface<device::Bound> instead? If so, it appears Sync is not implemented for usb::Interface<device::Bound>, which might leave driver data structures unable to be sent across threads.
Additionally, it looks like struct Device in rust/kernel/usb.rs is private since it lacks the pub modifier. Because drivers reside outside the kernel::usb module, are they able to name usb::Device as a field type?
Even if it were public, is there a way for drivers to obtain a Bound instance? usb::Interface implements AsRef<Device>, but this returns a reference to Device<Normal>, and there does not seem to be an as_bound() method available.
rust/kernel/usb.rs unsafe impl Send for Device {} · line 473
Quoted 11 lines
rust/kernel/usb.rs +3
-0@@ -468,6 +468,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 > {}
Should Send also be implemented for Device<device::Bound>? Bound is a zero-sized marker, and Device<Normal> implements both Send and Sync.
Would it be better to implement these thread-safety traits generically over all context markers to avoid omissions? For example, implementing them for Device<Ctx> where Ctx: device::DeviceContext.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
[email protected]
AI reviewRe: [PATCH v3 07/27] rust: auxiliary: implement Sync for Device<Bound>
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The commit implements `Sync` for `Device<device::Bound>` but omits the corresponding `Send`…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The commit implements Sync for Device<device::Bound> but omits the corresponding Send implementation. --
commit 2db1931adb556a37661b5663fe290ef2d37425ff
Author: Danilo Krummrich <[email protected]>
rust: auxiliary: implement Sync for Device<Bound>
This commit implements the Sync trait for Device<Bound> in the auxiliary bus abstraction. This allows drivers to safely store shared references to the bound device in their private data.
Quoted 3 lines
rust/kernel/auxiliary.rs +0
-0
[ ... ]
rust/kernel/auxiliary.rs unsafe impl Send for Device {} · line 374
Quoted 7 lines
rust/kernel/auxiliary.rs +3
-0@@ -369,6 +369,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 > {}
Should we also implement Send for Device<device::Bound>?
The commit message correctly notes that the Bound type-state marker is zero-sized and does not alter the thread safety properties of the underlying auxiliary_device struct. However, omitting the Send implementation creates an API asymmetry compared to Device<Normal>.
Because ARef<T> requires T: Send + Sync for the reference-counted pointer itself to be Send, the missing Send implementation prevents drivers from safely sending an ARef<Device<Bound>> across threads.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
[email protected]
AI reviewRe: [PATCH v3 04/27] rust: driver core: drop drvdata before devres release
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] Moving `post_unbind_rust()` before `devres_release_all()` subverts the LIFO devres teardown…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Moving post_unbind_rust() before devres_release_all() subverts the LIFO devres teardown order, leading to a Use-After-Free (UAF) when devm-managed resources are accessed after driver data is dropped. --
commit b146fb08eba0390797844ff1665d36d951226d10
Author: Danilo Krummrich <[email protected]>
rust: driver core: drop drvdata before devres release
This commit moves the execution of the Rust-specific post_unbind_rust callback to occur before devres_release_all() in device_unbind_cleanup(). It aims to allow Rust driver structs to hold direct references to devres-managed resources by ensuring the private data is dropped before devres actions are released.
drivers/base/dd.c static DEVICE_ATTR_RW(state_synced); · line 598
Quoted 12 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);
Does this regression subvert the devres teardown order, potentially leading to a use-after-free?
The devres framework enforces a last-in, first-out teardown order. Device drivers typically allocate their private driver data first, then register active endpoints like devm_request_irq, multifunction child devices, or sysfs attributes.
By moving the destruction of the driver's private data before devres_release_all(), any devm-managed resource will remain active and exposed to hardware interrupts or userspace after the driver's data has already been freed.
Additionally, dev_set_drvdata(dev, NULL) is only called later in this function. If an external event occurs between post_unbind_rust() and devres_release_all(), or if a devm action callback internally retrieves the context using dev_get_drvdata(), could this dereference a dangling pointer to the already-freed driver data?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
[email protected]
AI reviewRe: [PATCH v3 14/27] rust: i2c: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Critical] Use-After-Free due to I2C devres and subsystem teardown running before driver Data Drop.…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Critical] Use-After-Free due to I2C devres and subsystem teardown running before driver Data Drop.
- [High] Soundness hole allowing safe code to trigger UB via unchecked lifetime variance in GAT.
- [Low] Documentation mismatch in SAFETY comment for drvdata_borrow.
--
commit acb687d5f7c058a48caf341d55413d5a1b7e20ee
Author: Danilo Krummrich <[email protected]>
rust: i2c: make Driver trait lifetime-parameterized
This commit adds a 'bound lifetime parameter to the associated Data type in the Driver trait. This allows driver implementations to capture the device bound lifetime, enabling the storage of device resources by reference rather than requiring Devres.
Quoted 4 lines
rust/kernel/i2c.rs +0
-0
[ ... ]
rust/kernel/i2c.rs extern "C" fn remove_callback(idev: *mut bindings::i2c_client) { · line 179
Quoted 4 lines
rust/kernel/i2c.rs +0
-0@@ -177,7 +177,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::Data>>`.
This isn't a bug, but the SAFETY comment still says Pin<KBox<T::Data>> instead of T::Data<'_>.
rust/kernel/i2c.rs extern "C" fn remove_callback(idev: *mut bindings::i2c_client) { · line 180
Quoted 2 lines
rust/kernel/i2c.rs +1
-1-let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };
Does retrieving the data via drvdata_borrow::<T::Data<'_>>() bypass lifetime checking and introduce a soundness regression?
Because the Driver::Data associated type is not constrained to be covariant, a driver could define an invariant Data type (for example, containing a Cell<Option<&'bound I2cClient>>).
During unbind(), the driver could write a short-lived reference into the Data struct. When remove_callback returns, this reference expires, leaving a dangling pointer.
If that pointer is accessed in Drop, could it violate Rust's aliasing rules and trigger undefined behavior?
[ ... ]
rust/kernel/i2c.rs extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) { · line 191
Quoted 4 lines
rust/kernel/i2c.rs +0
-0@@ -189,7 +189,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::Data>>`.
This isn't a bug, but the SAFETY comment here also refers to Pin<KBox<T::Data>> instead of reflecting the new 'bound lifetime.
Quoted 2 lines
rust/kernel/i2c.rs +1
-1-let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { idev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };
[ ... ]
rust/kernel/i2c.rs pub trait Driver: Send { · line 326
Quoted 6 lines
rust/kernel/i2c.rs +1
-1@@ -320,7 +323,7 @@ pub trait Driver: Send {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;
If a driver uses the 'bound lifetime to hold references to devres-managed resources or I2C subsystem resources (like debugfs entries), will this lead to a use-after-free regression?
In the I2C subsystem, i2c_device_remove() explicitly calls devres_release_group() and cleans up subsystem state after the driver's remove callback completes. The driver's Data is dropped later when the driver core calls post_unbind_rust via device_unbind_cleanup().
By the time Drop is called on Data, wouldn't all devres resources already be freed, causing a use-after-free if they are accessed during Drop?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
[email protected]
AI reviewRe: [PATCH v3 05/27] rust: pci: implement Sync for Device<Bound>
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Implementing `Sync` for `Device<device::Bound>` introduces a soundness hole because it exposes…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Implementing Sync for Device<device::Bound> introduces a soundness hole because it exposes unsynchronized C state mutations via shared references. --
commit 4843eee61665efed707d8df24917bb38f72f7f5b
Author: Danilo Krummrich <[email protected]>
rust: pci: implement Sync for Device<Bound>
This commit implements Sync for Device<Bound> in addition to Device<Normal>, allowing drivers to store shared references to bound devices in their private data while remaining Send.
Quoted 4 lines
rust/kernel/pci.rs +0
-0
[ ... ]
rust/kernel/pci.rs unsafe impl Send for Device {} · line 534
Quoted 7 lines
// SAFETY:
Devicecan be shared among threads because all methods ofDevice// (i.e. `Device<Normal>) are thread safe.
unsafe impl Sync for Device {}rust/kernel/pci.rs +4
-0+ +// 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 > {}
Does implementing Sync for Device<device::Bound> introduce a data race if initialization methods are called concurrently?
Device<device::Bound> provides initialization methods like alloc_irq_vectors() that take a shared reference (&self). If a safe Rust driver spawns multiple threads and shares this reference, they could concurrently call alloc_irq_vectors().
This calls the C function pci_alloc_irq_vectors(), which performs lockless state mutations on the struct pci_dev, such as setting dev->msix_enabled = 1 in msix_capability_init().
Since these lockless mutations are exposed through a shared reference in Rust, could this lead to state corruption when the device is accessed from multiple threads at the same time?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
[email protected]
AI reviewRe: [PATCH REF v3 27/27] gpu: drm: tyr: use lifetime for IoMem
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Meaningful mismatch between the commit message and the code regarding the I/O memory type.…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Meaningful mismatch between the commit message and the code regarding the I/O memory type.
- [Low] The dev parameter is now unused in issue_soft_reset and l2_power_on.
--
commit 763cc0c53067cdbb12995b72ad25897a1324b9d9
Author: Danilo Krummrich <[email protected]>
gpu: drm: tyr: use lifetime for IoMem
This commit simplifies the memory mapping during probe by using the mapped memory directly and eliminating the Arc<Devres<IoMem>> indirection, which also makes Register::read/write infallible.
Quoted 3 lines
Take advantage of the lifetime-parameterized IoMem<'bound> to use the memory mapping directly during probe, eliminating the Arc<Devres<IoMem>> indirection.
The commit message mentions using the lifetime-parameterized IoMem<'bound>, but the code changes the type alias to kernel::io::Mmio<SZ_2M> which lacks a lifetime parameter. Is this difference intentional?
Quoted 4 lines
drivers/gpu/drm/tyr/driver.rs +0
-0
[ ... ]
drivers/gpu/drm/tyr/driver.rs pub(crate) struct TyrDrmDeviceData { · line 67
Quoted 8 lines
drivers/gpu/drm/tyr/driver.rs +2
-2@@ -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 );
Does the dev parameter still need to be in the function signature here? It appears to be unused now that it is no longer passed to regs::GPU_CMD.write().
[ ... ]
Quoted 4 lines
drivers/gpu/drm/tyr/gpu.rs +0
-0
[ ... ]
drivers/gpu/drm/tyr/gpu.rs fn from(value: u32) -> Self { · line 210
Quoted 8 lines
drivers/gpu/drm/tyr/gpu.rs +2
-2@@ -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 );
Are there any remaining uses for the dev parameter in this function, or could it be removed from the signature?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=27
[email protected]
AI reviewRe: [PATCH REF v3 25/27] gpu: nova-core: unregister sysmem flush page from Drop
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Hardware Teardown Order Inversion due to Rust struct drop order - [High] PCIe Posted Write Race…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Hardware Teardown Order Inversion due to Rust struct drop order
- [High] PCIe Posted Write Race leading to potential DMA Use-After-Free
--
commit 1e4442de0219b840e2a05e974e6828767c51d68c
Author: Danilo Krummrich <[email protected]>
gpu: nova-core: unregister sysmem flush page from Drop
This commit automatically unregisters the sysmem flush page by implementing the Drop trait for SysmemFlush and storing a bound reference. This removes the need for manual unregister calls and the Gpu unbind method.
Quoted 4 lines
drivers/gpu/nova-core/fb.rs +0
-0
[ ... ]
Quoted 13 lines
drivers/gpu/nova-core/fb.rs +2
-3@@ -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
drivers/gpu/nova-core/fb.rs pub(crate) fn register( · line 83
Quoted 10 lines
drivers/gpu/nova-core/fb.rs +4
-4-/// 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| {
Could this lead to a race condition with the PCIe bus?
PCIe MMIO writes are posted, so the write to 0 might be buffered in the PCIe root complex and not immediately reach the GPU. Because the Drop implementation finishes right after the write, the page field will drop and free the underlying DMA memory.
Is it possible the GPU could attempt to write to the freed sysmem flush page before the MMIO write actually reaches the hardware? Would adding a register read-back here help flush the posted write before the memory gets freed?
Quoted 3 lines
drivers/gpu/nova-core/fb.rs +0
-0dev_warn! ( &self.device,"failed to unregister sysmem flush page: {:?}\n" ,
[ ... ]
drivers/gpu/nova-core/gpu.rs pub(crate) struct Gpu<'bound> { · line 234
Quoted 13 lines
drivers/gpu/nova-core/gpu.rs +1
-1@@ -228,7 +228,7 @@ pub(crate) struct Gpu<'bound> { bar: &'bound Bar0, /// System memory page required for flushing all pending GPU-side memory writes done through /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation). - sysmem_flush: SysmemFlush, + sysmem_flush: SysmemFlush<'bound>, /// GSP falcon instance, used for GSP boot up and cleanup. gsp_falcon: Falcon<GspFalcon>,/// SEC2 falcon instance, used for GSP boot up and cleanup.
With the explicit unbind call removed, the code now relies entirely on Rust's drop semantics for cleanup.
Since Rust drops struct fields in declaration order (top-to-bottom), sysmem_flush will be dropped before gsp_falcon, sec2_falcon, and gsp.
If any of these subsequent components perform hardware teardown or memory flushes in their Drop implementations, could they attempt to use the sysmem flush page after it has been unregistered and freed?
Does sysmem_flush need to be placed at the end of the Gpu struct to ensure correct first-in-last-out teardown ordering?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
[email protected]
AI reviewRe: [PATCH v3 19/27] rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] The `name` pointer passed to `pci_request_region` is stored directly in the kernel's resource…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The name pointer passed to pci_request_region is stored directly in the kernel's resource tree, causing a Use-After-Free if a dynamically allocated string is passed. --
commit 288028203fe9a624774ed430783fe427c724785b
Author: Danilo Krummrich <[email protected]>
rust: pci: make Bar lifetime-parameterized
Convert pci::Bar to be lifetime-parameterized over the device bound. iomap_region_sized now returns Result<Bar<'bound, SIZE>> directly. Add Bar::into_devres() to register the bar as a device-managed resource.
Quoted 4 lines
rust/kernel/pci/io.rs +0
-0
[ ... ]
Quoted 6 lines
rust/kernel/pci/io.rs +0
-2@@ -146,14 +145,14 @@ impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {/// /// `Bar` always holds an `IoRaw` instance that holds a valid pointer to the start of the I/O /// memory mapped PCI BAR and its size. -pub struct Bar <const SIZE :usize =0 > { - pdev:ARef <Device >,
rust/kernel/pci/io.rs impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> { · line 155
Quoted 10 lines
rust/kernel/pci/io.rs +4
-2+pub struct Bar <'bound,const SIZE :usize =0 > { + pdev: &'boundDevice <device::Bound >, io:MmioRaw <SIZE >, num:i32 , } -impl <const SIZE :usize >Bar <SIZE > { -pub (super )fn new (pdev: &Device , num:u32 , name: &CStr ) ->Result <Self > { +impl <'bound,const SIZE :usize >Bar <'bound,SIZE > { +pub (super )fn new (pdev: &'boundDevice <device::Bound >, num:u32 , name: &CStr ) ->Result <Self > {
Does this name parameter need a 'static bound?
The kernel's pci_request_region() function (via __request_region_locked()) stores the raw string pointer directly into the struct resource tree (res->name = name) without copying it.
Because the API does not enforce a 'static lifetime on name, a caller could pass a dynamically allocated CString that is dropped immediately. If this happens, the kernel resource tree will hold a dangling pointer, resulting in a use-after-free when /proc/iomem or /proc/ioports are read.
While the previous signature (name: &'a CStr) also failed to guarantee the string outlived the resource, should we enforce name: &'static CStr here to prevent memory corruption?
[ ... ]
Quoted 26 lines
rust/kernel/pci/io.rs +6
-10@@ -249,20 +257,16 @@ fn deref(&self) -> &Self::Target {impl Device <device::Bound > {/// Maps an entire PCI BAR after performing a region-request on it. I/O operation bound checks /// can be performed on compile time for offsets (plus the requested type size) < SIZE. -pub fn iomap_region_sized <'a,const SIZE :usize >( - &'a self, +pub fn iomap_region_sized <'bound,const SIZE :usize >( + &'bound self, bar:u32 , - name: &'aCStr , - ) ->impl PinInit <Devres <Bar <SIZE >>,Error > + 'a { -Devres ::new (self.as_ref (),Bar ::<SIZE >::new (self, bar, name)) + name: &CStr , + ) ->Result <Bar <'bound,SIZE >> { +Bar ::new (self, bar, name) }/// Maps an entire PCI BAR after performing a region-request on it. -pub fn iomap_region <'a>( - &'a self, - bar:u32 , - name: &'aCStr , - ) ->impl PinInit <Devres <Bar >,Error > + 'a { +pub fn iomap_region <'bound>(&'bound self, bar:u32 , name: &CStr ) ->Result <Bar <'bound>> { self.iomap_region_sized ::<0 >(bar, name) }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
[email protected]
AI reviewRe: [PATCH v3 21/27] samples: rust: rust_driver_pci: use HRT lifetime for Bar
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Architectural lifecycle violation: executing hardware side-effects eagerly in `probe` leads to…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Architectural lifecycle violation: executing hardware side-effects eagerly in probe leads to unprotected state modifications on driver context memory allocation failure.
- [Low] Struct initialization fails to compile due to a type mismatch (&Device<Core> vs &Device<Normal>).
--
commit f81a99d5cad1217b9f1436bd6e9df66b0e436f05
Author: Danilo Krummrich <[email protected]> Date: Sun May 17 00:01:09 2026 +0000
samples: rust: rust_driver_pci: use HRT lifetime for Bar
This commit updates the sample driver to use a lifetime-parameterized Driver trait, keeping references to the PCI device and Bar directly. It removes PinnedDrop and the deferred pin_init_scope closure. This avoids runtime revocation checks on BAR access.
Quoted 4 lines
samples/rust/rust_driver_pci.rs +0
-0
[ ... ]
Quoted 10 lines
samples/rust/rust_driver_pci.rs +3
-5-#[pin_data( PinnedDrop )] -struct SampleDriver { - pdev:ARef <pci::Device >, -#[pin] - bar:Devres <Bar0 >, +struct SampleDriverData <'bound> { + pdev: &'bound pci::Device , + bar:Bar0 <'bound>, index:TestIndex , }
[ ... ]
Quoted 5 lines
fn probe<'bound>(
pdev: &'bound pci::Device<Core>,
info: &'boundSelf::IdInfo,samples/rust/rust_driver_pci.rs +0
-2- ) -> impl PinInit<Self, Error> + 'bound { - pin_init::pin_init_scope(move || {
[ ... ]
Quoted 2 lines
samples/rust/rust_driver_pci.rs +0
-2- pdev.enable_device_mem ()?; - pdev.set_master ();
[ ... ]
samples/rust/rust_driver_pci.rs fn config_space(pdev: &pci::Device<Bound>) { · line 158
Quoted 11 lines
samples/rust/rust_driver_pci.rs +11
-0+ ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { +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();
Does this early hardware initialization introduce a state leak if the driver context memory allocation fails?
By removing the deferred pin_init_scope closure, these hardware side-effects now execute eagerly inside probe() before the initialization recipe is returned.
If the subsequent driver context memory allocation fails, the Bar0 field will unmap the I/O region when SampleDriverData is dropped, but would the PCI device remain incorrectly enabled and in bus-mastering mode?
samples/rust/rust_driver_pci.rs fn config_space(pdev: &pci::Device<Bound>) { · line 170
Quoted 12 lines
samples/rust/rust_driver_pci.rs +12
-0+ +let bar = pdev.iomap_region_sized ::<{ regs::END }>(0 ,c"rust_driver_pci" )?; + +dev_info! ( + pdev, +"pci-testdev data-match count: {}\n" , +SampleDriverData ::testdev (info, &bar)? + ); +SampleDriverData ::config_space (pdev); + +Ok (SampleDriverData { + pdev,
Will this struct initialization result in a mismatched types compilation error?
The probe method receives pdev as &'bound pci::Device<Core>, but the SampleDriverData struct declares its pdev field as &'bound pci::Device, which defaults to the implicit context &'bound pci::Device<device::Normal>.
Because Rust does not perform implicit Deref coercions during struct field initialization, does passing a &Device<Core> directly to a field expecting a &Device<Normal> fail to build?
Quoted 4 lines
samples/rust/rust_driver_pci.rs +2
-0+ bar, + index: *info, }) }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
[email protected]
AI reviewRe: [PATCH REF v3 24/27] gpu: nova-core: use lifetime for Bar
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Teardown order inversion causes Use-After-Free of PCI BAR during auxiliary device unbind - [Low]…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Teardown order inversion causes Use-After-Free of PCI BAR during auxiliary device unbind
- [Low] Incorrect safety comment regarding try_pin_init! evaluation order contradicts the struct definition --
commit a3050bb7eec253af2f0de783f6b97a3dcbc7b499
Author: Danilo Krummrich <[email protected]>
gpu: nova-core: use lifetime for Bar
Take advantage of the lifetime-parameterized pci::Bar<'bound> to hold the BAR mapping directly in NovaCore<'bound>, and pass a borrowed reference to Gpu<'bound>. This eliminates the Arc<Devres<Bar0>> indirection and simplifies Gpu::unbind().
Quoted 17 lines
drivers/gpu/nova-core/driver.rs +3
-2@@ -30,9 +27,10 @@static AUXILIARY_ID_COUNTER :Atomic <u32 > =Atomic ::new (0 );#[pin_data] -pub (crate )struct NovaCore { +pub (crate )struct NovaCore <'bound> {#[pin] -pub (crate ) gpu:Gpu , +pub (crate ) gpu:Gpu <'bound>, + bar: pci::Bar <'bound,BAR0_SIZE >,#[allow(clippy::type_complexity)] _reg:Devres <auxiliary::Registration <ForLt! (())>>, }
[ ... ]
Quoted 4 lines
drivers/gpu/nova-core/driver.rs +0
-0@@ -94,14 +94,14 @@ fn probe<'bound>(// other threads of execution. unsafe { pdev.dma_set_mask_and_coherent (DmaMask ::new ::<GPU_DMA_BITS >())? };
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 98
Quoted 10 lines
drivers/gpu/nova-core/driver.rs +2
-8-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")?,
Can this teardown order inversion cause a use-after-free of the PCI BAR during the auxiliary device unbind process?
Since bar is now placed directly in NovaCore while _reg is still managed by devres via .into_devres()?, driver data (NovaCore) drops before devres_release_all() is executed.
This means bar will be dropped and the MMIO region unmapped when NovaCore drops, but the auxiliary device (nova-drm) remains registered until the devres subsystem cleans it up later.
When the auxiliary device eventually unregisters and unbinds, won't it attempt to access the already unmapped GPU hardware BAR?
Should _reg also be removed from devres and placed as a direct field in NovaCore? If so, since Rust drops struct fields in declaration order, _reg would need to be declared before bar to ensure it is dropped first.
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 103
Quoted 5 lines
drivers/gpu/nova-core/driver.rs +5
-0+// 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).
This isn't a bug, but is the safety comment regarding the try_pin_init! evaluation order accurate?
The comment states that try_pin_init! initializes fields in declaration order. However, in the NovaCore struct definition above, gpu is actually declared before bar.
If the macro evaluated fields in declaration order, gpu would be initialized first, and the unsafe block below would read uninitialized memory. Doesn't try_pin_init! evaluate initializers in the lexical order they are written within the macro invocation, which is why bar is safely initialized first here?
Quoted 8 lines
drivers/gpu/nova-core/driver.rs +1
-0+ gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }), _reg: auxiliary::Registration::new( pdev.as_ref (), c"nova-drm",AUXILIARY_ID_COUNTER.fetch_add(1, Relaxed), ) .into_devres()?, }))
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
[email protected]
AI reviewRe: [PATCH v3 20/27] rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
In reply to Danilo KrummrichThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Missing `?` operator after `into_devres()` causes a compilation error in…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Missing ? operator after into_devres() causes a compilation error in drivers/pwm/pwm_th1520.rs. --
commit a23bc481c58c23ac450d2b4d6632694158a96cc9
Author: Danilo Krummrich <[email protected]>
rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
This commit adds a lifetime parameter to IoMem and ExclusiveIoMem to tie the mapping to the device's lifetime. It updates the io requests to return the mapping directly, while providing an into_devres() method for callers that need device-managed revocation.
Quoted 4 lines
drivers/pwm/pwm_th1520.rs +0
-0
[ ... ]
drivers/pwm/pwm_th1520.rs fn probe<'bound>( · line 355
Quoted 6 lines
drivers/pwm/pwm_th1520.rs +1
-1@@ -352,7 +352,7 @@ fn probe<'bound>( 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 (),
Since into_devres() returns a Result type, does this need a trailing ? operator to unwrap the value? It looks like omitting it will cause a type mismatch and build failure because try_pin_init! expects the unwrapped Devres value here.
Quoted 3 lines
drivers/pwm/pwm_th1520.rs +0
-0clk <- clk, }), )?;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
Danilo Krummrich
maintainerRe: [PATCH v3 03/27] rust: driver: decouple driver private data from driver type
In reply to Danilo Krummrichrust/kernel/driver.rs line 21
Quoted 10 lines · Danilo Krummrich
rust/kernel/driver.rs +2
-0@@ -17,6 +17,9 @@//! /// The type holding information about each device ID supported by the driver. //! type IdInfo: 'static; //! +//! /// The type of the driver's bus device private data. +//! type Data;
Should be:
@@ -13,10 +13,13 @@
//! The main driver interface is defined by a bus specific driver trait. For instance:
//!
//! ```ignore
-//! pub trait Driver: Send {
+//! pub trait Driver {
//! /// The type holding information about each device ID supported by the driver.
//! type IdInfo: 'static;
//!
+//! /// The type of the driver's bus device private data.
+//! type Data: Send;
Re: [PATCH v3 01/27] rust: alloc: remove `'static` bound on `ForeignOwnable`
In reply to Danilo KrummrichQuoted 9 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
The
'staticbound is currently necessary because there's no restriction on the lifetime of the GAT. Add aSelf: 'abound to restrict possible lifetimes onBorrowedandBorrowedMut, and lift the'staticrequirement.Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 02/27] rust: driver: move 'static bounds to constructor
In reply to Danilo KrummrichQuoted 9 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
With the ForeignOwnable lifetime change, the 'static bound is no longer necessary on the drvdata methods or bus adapter impls. Move it to the Registration constructor instead.
Signed-off-by Gary Guo <[email protected]>Co-developed-by Danilo Krummrich <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 03/27] rust: driver: decouple driver private data from driver type
In reply to Danilo KrummrichQuoted 9 lines · Danilo Krummrich
Add a type Data<'bound> associated type to all bus driver traits, decoupling the driver's bus device private data type from the driver struct itself.
In the context of adding a 'bound lifetime, making this an associated type has the advantage that it allows us to avoid a driver trait global lifetime and it avoids the need for ForLt for bus device private data; both of which make the subsequent implementation by buses much simpler.
Quoted 4 lines
All existing drivers and doc examples set type Data = Self to preserve the current behavior.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 04/27] rust: driver core: drop drvdata before devres release
In reply to Danilo KrummrichQuoted 13 lines · Danilo Krummrich
Move the
post_unbind_rustcallback beforedevres_release_all()indevice_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.
Quoted 5 lines
Without this change, devres resources would be freed first, leaving the driver's bus device private data with dangling references during its destructor.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 05/27] rust: pci: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
pci_devas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound pci::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 06/27] rust: platform: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
platform_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound platform::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 07/27] rust: auxiliary: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
auxiliary_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound auxiliary::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 08/27] rust: usb: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
usb_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound usb::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 09/27] rust: device: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for types that hold &'bound Device<Bound>, such as
io::mem::IoMem, to be Send.Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
Quoted 7 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 11/27] rust: platform: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
Quoted 8 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Acked-by Uwe Kleine-König <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Gary Guo
reviewerRe: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 27 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/driver.rs | 9 ++++++--- rust/kernel/pci.rs | 24 +++++++++++++----------- samples/rust/rust_dma.rs | 7 +++++-- samples/rust/rust_driver_auxiliary.rs | 7 +++++-- samples/rust/rust_driver_pci.rs | 7 +++++-- 5 files changed, 34 insertions(+), 20 deletions(-)drivers/gpu/nova-core/driver.rs +0
-0
drivers/gpu/nova-core/driver.rs pub(crate) struct NovaCore { · line 81
Quoted 10 lines
drivers/gpu/nova-core/driver.rs +3
-2@@ -74,10 +74,13 @@ pub(crate) struct NovaCore {impl pci::Driver for NovaCore {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ; -fn probe (pdev: &pci::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound pci::Device<Core>,
This is technically incorrect, as the Device<Core> only lives as long as the callback. Having 'bound would be incorrect.
This can either be addressed via
pdev: &pci::Device<Core>, pdev_bound: &'bound pci::Device<Bound>, ...
or perhaps by adding a lifetime to Core<'_>
pdev: &'bound pci::Device<Core<'_>>,
Best,
Gary
Quoted 148 lines
drivers/gpu/nova-core/driver.rs +3
-1+ _info: &'bound Self::IdInfo, + ) -> impl PinInit<Self, Error> + 'bound { pin_init::pin_init_scope(move || { dev_dbg!(pdev, "Probe Nova Core GPU driver.\n");@@ -109,7 +112,7 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, E }) } -fn unbind (pdev: &pci::Device <Core >, this:Pin <&Self >) { +fn unbind <'bound>(pdev: &'bound pci::Device <Core >, this:Pin <&'boundSelf >) { this.gpu.unbind (pdev.as_ref ()); } }rust/kernel/pci.rs +13
-11@@ -64,7 +64,7 @@// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. unsafe impl <T :Driver > driver::DriverLayout for Adapter <T > {type DriverType = bindings::pci_driver ; -type DriverData <'bound> =T ::Data ; +type DriverData <'bound> =T ::Data <'bound>;const DEVICE_DRIVER_OFFSET :usize = core::mem::offset_of!(Self ::DriverType , driver); }@@ -130,7 +130,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::Data>>`. -let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::unbind (pdev, data); }@@ -279,13 +279,13 @@ macro_rules! pci_device_table {/// /// impl pci::Driver for MyDriver { /// type IdInfo = (); -/// type Data = Self; +/// type Data<'bound> = Self; /// const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; /// -/// fn probe( -/// _pdev: &pci::Device<Core>, -/// _id_info: &Self::IdInfo, -/// ) -> impl PinInit<Self, Error> { +/// fn probe<'bound>( +/// _pdev: &'bound pci::Device<Core>, +/// _id_info: &'bound Self::IdInfo, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { /// Err(ENODEV) /// } /// } @@ -302,7 +302,7 @@ pub trait Driver: Send {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data ; +type Data <'bound>: 'bound;/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;@@ -311,8 +311,10 @@ pub trait Driver: Send {/// /// Called when a new pci device is added or discovered. Implementers should /// attempt to initialize the device here. -fn probe (dev: &Device <device::Core >, id_info: &Self ::IdInfo ) - ->impl PinInit <Self ::Data ,Error >; +fn probe <'bound>( + dev: &'boundDevice <device::Core >, + id_info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound;/// PCI driver unbind. /// @@ -324,7 +326,7 @@ fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo)/// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be performed in `Drop`. -fn unbind (dev: &Device <device::Core >, this:Pin <&Self ::Data >) { +fn unbind <'bound>(dev: &'boundDevice <device::Core >, this:Pin <&'boundSelf ::Data <'bound>>) {let _ = (dev, this); } }samples/rust/rust_dma.rs +5
-2@@ -58,10 +58,13 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}impl pci::Driver for DmaSampleDriver {type IdInfo = (); -type Data =Self ; +type Data <'bound> =Self ;const ID_TABLE : pci::IdTable <Self ::IdInfo > = &PCI_TABLE ; -fn probe (pdev: &pci::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe <'bound>( + pdev: &'bound pci::Device <Core >, + _info: &'boundSelf ::IdInfo , + ) ->impl PinInit <Self ,Error > + 'bound { pin_init::pin_init_scope (move || {dev_info! (pdev,"Probe DMA test driver.\n" );samples/rust/rust_driver_auxiliary.rs +5
-2@@ -66,11 +66,14 @@ struct ParentDriver { impl pci::Driver for ParentDriver { type IdInfo = (); - type Data = Self; + type Data<'bound> = Self; const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe<'bound>( + pdev: &'bound pci::Device<Core>, + _info: &'bound Self::IdInfo, + ) -> impl PinInit<Self, Error> + 'bound { Ok(Self { _reg0: auxiliary::Registration::new( pdev.as_ref(),samples/rust/rust_driver_pci.rs +5
-2@@ -140,11 +140,14 @@ fn config_space(pdev: &pci::Device<Bound>) { impl pci::Driver for SampleDriver { type IdInfo = TestIndex; - type Data = Self; + type Data<'bound> = Self; const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe<'bound>( + pdev: &'bound pci::Device<Core>, + info: &'bound Self::IdInfo, + ) -> impl PinInit<Self, Error> + 'bound { pin_init::pin_init_scope(move || { let vendor = pdev.vendor_id(); dev_dbg!(
Re: [PATCH v3 12/27] rust: auxiliary: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
Quoted 7 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 13/27] rust: usb: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
Quoted 7 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 14/27] rust: i2c: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
Quoted 8 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Acked-by Igor Korotin <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH v3 15/27] rust: driver: update module documentation for GAT-based Data type
In reply to Danilo KrummrichQuoted 5 lines · Danilo Krummrich
Now that all bus driver traits use type Data<'bound>: 'bound, update the illustrative driver trait in the module documentation to reflect the GAT pattern and lifetime-parameterized callbacks.
Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerRe: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Gary GuoQuoted 5 lines · Gary Guo
Review
Quoted 2 lines
(quoted diff) +2
-0+ fn probe<'bound>( + pdev: &'bound pci::Device<Core>,This is technically incorrect, as the
Device<Core>only lives as long as the callback. Having'boundwould be incorrect.
I think that's more on the theoretical side, as Core is not Sync, but I agree it makes sense to address.
Quoted 3 lines
or perhaps by adding a lifetime to
Core<'_>pdev: &'bound pci::Device<Core<'_>>,
This seems reasonable.
Re: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Add a 'bound lifetime to the associated Data, changing type Data to type Data<'bound>.
This allows the driver's bus device private data to capture the device / driver bound lifetime; device resources can be stored directly by reference rather than requiring Devres.
Quoted 8 lines
The
probe()andunbind()callbacks thus gain a 'bound lifetime parameter on the methods themselves; avoiding a global lifetime on the trait impl.Existing drivers set type Data<'bound> = Self, preserving the current behavior.
Signed-off-by Danilo Krummrich <[email protected]>---
Is this really sound without a covariance proof? For example, with this version you could stash a Cell<Option<&'bound pci::Device<Bound>> (even with Gary's suggested Core<'_> change) and then observe that reference on Drop of Data, which seems unsound to me.
Re: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Danilo KrummrichQuoted 142 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 Fooand givesBar<'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.
ForLtprovides such support. It provides a traitForLtwhich describes a type generic over lifetime. One may useForLt::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
ForLttrait, so functions withForLttrait bound can assume covariance.A macro
ForLt!()is provided to be able to obtain a type that implementsForLt. For example,ForLt!(for<'a> Bar<'a>)would yield a type that<TheType as ForLt>::Of<'a>isBar<'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.
Link https://docs.rs/higher-kinded-types/ [1]Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>---
rust/macros/for_lt.rs new file +102
-0+trait TypeExt { +fn expand_elided_lifetime (&self, explicit_lt: &Lifetime ) ->Type ; +fn replace_lifetime (&self, src: &Lifetime , dst: &Lifetime ) ->Type ; +fn has_lifetime (&self, lt: &Lifetime ) ->bool ; +} + +impl TypeExt for Type { +fn expand_elided_lifetime (&self, explicit_lt: &Lifetime ) ->Type { +struct ElidedLifetimeExpander <'a>(&'aLifetime ); + +impl VisitMut for ElidedLifetimeExpander <'_> { +fn visit_lifetime_mut (&mut self, lifetime: &mut Lifetime ) { +// Expand explicit `'_` +if lifetime.ident =="_" { + *lifetime = self.0 .clone (); + } + } + +fn visit_type_reference_mut (&mut self, reference: &mut syn::TypeReference ) { + syn::visit_mut::visit_type_reference_mut (self, reference); + +if reference.lifetime.is_none () { + reference.lifetime =Some (self.0 .clone ()); + } + } + } + +let mut ret = self.clone (); +ElidedLifetimeExpander (explicit_lt).visit_type_mut (&mut ret); + ret + } + +fn replace_lifetime (&self, src: &Lifetime , dst: &Lifetime ) ->Type { +struct LifetimeReplacer <'a>(&'aLifetime , &'aLifetime ); + +impl VisitMut for LifetimeReplacer <'_> { +fn visit_lifetime_mut (&mut self, lifetime: &mut Lifetime ) { +if lifetime.ident == self.0 .ident { + *lifetime = self.1 .clone (); + } + } + } + +let mut ret = self.clone (); +LifetimeReplacer (src, dst).visit_type_mut (&mut ret); + ret + } + +fn has_lifetime (&self, lt: &Lifetime ) ->bool { +struct HasLifetime <'a>(&'aLifetime ,bool ); + +impl Visit <'_>for HasLifetime <'_> { +fn visit_lifetime (&mut self, lifetime: &Lifetime ) { +if lifetime.ident == self.0 .ident { + self.1 =true ; + } + } + } + +let mut visitor =HasLifetime (lt,false ); + visitor.visit_type (self); + visitor.1 + } +} + +struct Prover <'a>(&'aLifetime ,Vec <&'aType >); + +impl <'a>Prover <'a> { +/// Prove that `ty` is covariant over `'lt`. +/// +/// This also needs to prove that it'll be wellformed for any instance of `'lt`. +/// It can be assumed that `ty` will be wellformed if `'lt` is substituted to `'static`. +fn prove (&mut self, ty: &'aType ) { +match ty { + Type::Paren(ty) => self.prove(&ty.elem), + Type::Group(ty) => self.prove(&ty.elem), + + // No lifetime involved + Type::Never(_) => {} + + // `[T; N]` and `[T]` is covariant over `T`. + Type::Array(ty) => self.prove(&ty.elem), + Type::Slice(ty) => self.prove(&ty.elem), + + Type::Tuple(ty) => { + for elem in &ty.elems { + self.prove(elem); + } + } + + // `*const T` is covariant over `T` + Type::Ptr(ty) if ty.const_token.is_some() => self.prove(&ty.elem), + + // `&T` is covariant over `T` and lifetime. + // + // Note that if we encounter `&'other_lt T`, then we still need to make sure the type + // is wellformed if `T` involves `&'lt`, so we defer to the compiler. + // + // This is to block cases like `ForLt!(for<'a> &'static &'a u32)`, as the presence of + // the type implies `'a: 'static` but this is unsound. + Type::Reference(ty) + if ty.mutability.is_none() && ty.lifetime.as_ref() == Some(self.0) =>
rust/macros/for_lt.rs line 164
Quoted 10 lines
rust/macros/for_lt.rs new file +10
-0+ { + self.prove (&ty.elem) + } + +// `&[mut] T` is covariant over lifetime. +// In case we have `&[mut] NoLifetime`, we don't need to do additional checks. + Type::Reference(ty) if !ty.elem.has_lifetime(self.0) => (), + + // No mention of lifetime at all, no need to perform compiler check. + ty if !ty.has_lifetime(self.0) => (),
This treats macros as not having a lifetime, but it allows this which is not covariant for 'a IIUC:
```
trait Trait {}
macro_rules! asdf {
() => { dyn Trait };
}
type NotCovariant = ForLt!(for<'a> &'a mut asdf!());
```And you can get rid of the macro too:
``` type NotCovariant = ForLt!(for<'a> &'a mut dyn Trait); ```
These are not covariant because dyn Trait has an elided +'a lifetime.
I feel that the syntactic checking is kinda difficult to get right since it would need to handle all ways lifetimes can be elided now and in the future.
Would it be that bad to always emit the proofs?
Re: [PATCH v3 19/27] rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichQuoted 6 lines · Danilo Krummrich
Convert pci::Bar<SIZE> to pci::Bar<'bound, SIZE>, storing &'bound Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized()now returns Result<Bar<'bound, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.
Quoted 7 lines
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.Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v3 20/27] rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
In reply to Danilo KrummrichQuoted 8 lines · Danilo Krummrich
Add a lifetime parameter to IoMem<'bound, SIZE> and ExclusiveIoMem<'bound, SIZE>, storing a &'bound Device<Bound> reference to tie the mapping to the device's lifetime.
This mirrors the pci::Bar<'bound, SIZE> design and enables drivers to hold I/O memory mappings directly in their HRT private data, tied to the device lifetime.
Quoted 7 lines
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.Acked-by Uwe Kleine-König <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v3 21/27] samples: rust: rust_driver_pci: use HRT lifetime for Bar
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Convert the sample driver to SampleDriver<'bound>, taking advantage of the lifetime-parameterized Driver trait.
The driver struct holds &'bound
pci::Devicedirectly instead of ARef<pci::Device>, and pci::Bar<'bound> directly instead of Devres<pci::Bar>. This removes PinnedDrop,pin_init_scope, and runtime revocation checks on BAR access.Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v3 22/27] rust: driver-core: rename 'a lifetime to 'bound
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
Rename the generic lifetime parameter from 'a to 'bound in pci, platform, i2c and devres. This makes it explicit that the lifetime represents the device binding scope, consistent with the convention established by the HRT series.
Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v3 18/27] samples: rust: rust_driver_auxiliary: showcase lifetime-bound registration data
In reply to Danilo KrummrichQuoted 9 lines · 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 throughadev.parent().Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichQuoted 67 lines · 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.Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/driver.rs | 4 +- rust/kernel/auxiliary.rs | 68 +++++++++++++++++---------- samples/rust/rust_driver_auxiliary.rs | 8 ++-- 3 files changed, 52 insertions(+), 28 deletions(-)drivers/gpu/nova-core/driver.rs +3
-1@@ -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 +7
-2@@ -20,6 +20,7 @@ }, prelude::*, types::{ +ForLt ,ForeignOwnable ,Opaque ,// },@@ -271,12 +272,16 @@ pub fn parent(&self) -> &device::Device<device::Bound> {/// Returns a pinned reference to the registration data set by the registering (parent) driver. /// -/// Returns [`EINVAL`] if `T` does not match the type used by the parent driver when calling +/// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The returned +/// reference has its lifetime shortened from `'static` to `&self`'s borrow lifetime via +/// [`ForLt::cast_ref`]. +/// +/// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling /// [`Registration::new()`]. /// /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was /// registered by a C driver. -pub fn registration_data <T : 'static>(&self) ->Result <Pin <&T >> { +pub fn registration_data <F :ForLt >(&self) ->Result <Pin <&F ::Of <'_>>> {// SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`. let ptr =unsafe { (*self.as_raw ()).registration_data_rust };if ptr.is_null () {
rust/kernel/auxiliary.rs pub fn registration_data<T: 'static>(&self) -> Result<Pin<&T>> { · line 301
Quoted 10 lines
rust/kernel/auxiliary.rs +2
-2@@ -289,18 +294,23 @@ pub fn registration_data<T: 'static>(&self) -> Result<Pin<&T>> {// SAFETY: `ptr` is non-null and was set via `into_foreign()` in `Registration::new()`; // `RegistrationData` is `#[repr(C)]` with `type_id` at offset 0, so reading a `TypeId` -// at the start of the allocation is valid regardless of `T`. +// at the start of the allocation is valid regardless of `F`. let type_id =unsafe { ptr.cast ::<TypeId >().read () }; -if type_id !=TypeId ::of ::<T >() { +if type_id !=TypeId ::of ::<F ::Of <'static>>() {return Err (EINVAL ); }
This seems a little dangerous to me, since the caller can specify the ForLt type which means it can rewrite the lifetime of the ForLt encoded type to be whatever it wants. The runtime check here only looks at the typeid of the encoded type but can't check the mapping from forlt::of given lifetime to actual underlying type lifetime instantiation. For example, in the next patch on the sample aux driver you can do:
``` let data = adev.registration_data::<ForLt!(for<'a> Data<'static>)>()?; let pdev: &'static pci::Device<Bound> = data.parent; ```
and mint a 'static reference to a bound device, which seems unsound to me. So maybe this needs to store the typeid of F instead? so that it can store the actual mapping from forlt lifetime to underlying type lifetimes.
Overall I feel it's unfortunate to have this be a runtime check though. What about requiring all device ids declared to be supported by an aux bus driver to have the same rust registration data type? Not sure how common it is to want to have the same aux bus driver support a very hetereogenous set of aux bus devices though. I think getting rid of the runtime check was discussed on the other patch series adding the rust sideband registration data on the C side, but if there's not much real use case for hetereogenous registration data types in a single aux bus driver then it might be worth the added safety. WDYT?
Danilo Krummrich
maintainerRe: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
Quoted 9 lines · Eliot Courtney
For example, in the next patch on the sample aux driver you can do:
``` let data = adev.registration_data::<ForLt!(for<'a> Data<'static>)>()?; let pdev: &'static pci::Device<Bound> = data.parent; ```and mint a 'static reference to a bound device, which seems unsound to me.
Good catch, I applied the fix.
Additionally, we could probably reject unused lifetime binders in the ForLt!() macro, which doesn't help when used with a type alias, but may be a good defensive measure anyway.
Quoted 2 lines
What about requiring all device ids declared to be supported by an aux bus driver to have the same rust registration data type?
Please see [1] and [2].
Thanks,
Danilo
[1] https://lore.kernel.org/driver-core/[email protected]/
[2] https://lore.kernel.org/driver-core/[email protected]/
Danilo Krummrich
maintainerRe: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Eliot CourtneyQuoted 4 lines · Eliot Courtney
Is this really sound without a covariance proof? For example, with this version you could stash a Cell<Option<&'bound pci::Device<Bound>> (even with Gary's suggested Core<'_> change) and then observe that reference on Drop of Data, which seems unsound to me.
The Core<'_> change seems unrelated, Core is not Sync, so you can't store it in the first place.
Otherwise, I don't see how one can exploit this. The formal invariance of Cell<Option<&'bound pci::Device<Bound>> is not practically exploitable because the framework controls what lifetimes are available and everything reachable through 'bound outlives the data; something that is shorter lived than 'bound can't be stored either.
Bringing back ForLt for this reason seems undesirable, as it has a real design cost.
Alexandre Courbot
maintainerRe: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Danilo KrummrichOn Sun May 17, 2026 at 9:01 AM JST, Danilo Krummrich wrote:
<snip>
rust/kernel/types/for_lt.rs line 105
Quoted 12 lines
rust/kernel/types/for_lt.rs new file +12
-0+/// This is intended to be an "unsafe-to-refer-to" type. +/// +/// Must only be used by the `ForLt!` macro. +/// +/// `T` is the magic `dyn for<'a> WithLt<'a, TypeThatUse<'a>>` generated by macro. +/// +/// `WF` is a type that the macro can use to assert some specific type is well-formed. +/// +/// `N` is to provide the macro a place to emit arbitrary items, in case it needs to prove +/// additional properties. +#[doc(hidden)] +pub struct UnsafeForLtImpl <T : ?Sized ,WF ,const N :usize >(PhantomData <(WF ,T )>);
Although the documentation makes it clear this should never be referenced directly, doing so is still possible, which creates a loophole for breaking covariance using only safe code.
For instance (untested, and based on my limited understanding of the patch):
type Bad = UnsafeForLtImpl<
dyn for<'a> WithLt<'a, Of = Cell<&'a u8>>,
(),
0,Quoted 1 line
;
The blanket ForLt implementation applies, and now we can store a shorter-lived reference into the Cell and potentially observe it after its lifetime.
This could be worked around by defining the type implementing ForLt locally, at the cost of ergonomics since the ForLt type would be declared separately:
// Defines DataLt and implements ForLt on it after emitting // covariance proof.
define_for_lt!(DataLt = for<'a> Data<'a>);
...
something: Devres<auxiliary::Registration<DataLt>>
I'm not claiming this is better; but imho the tradeoff is worth considering.
Gary Guo
reviewerRe: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichQuoted 8 lines · Danilo Krummrich
Quoted 7 lines · Eliot Courtney
For example, in the next patch on the sample aux driver you can do:
``` let data = adev.registration_data::<ForLt!(for<'a> Data<'static>)>()?; let pdev: &'static pci::Device<Bound> = data.parent; ```
Quoted 8 lines
Quoted 2 lines
and mint a 'static reference to a bound device, which seems unsound to me.
Good catch, I applied the fix.
Additionally, we could probably reject unused lifetime binders in the ForLt!() macro, which doesn't help when used with a type alias, but may be a good defensive measure anyway.
That won't work, ForLt!(T) is basically not using the lifetime binder, and you do need that to work.
Best,
Gary
Quoted 11 lines
Quoted 3 lines
What about requiring all device ids declared to be supported by an aux bus driver to have the same rust registration data type?
Please see [1] and [2].
Thanks,
Danilo[1] https://lore.kernel.org/driver-core/[email protected]/
[2] https://lore.kernel.org/driver-core/[email protected]/
Gary Guo
reviewerRe: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Eliot CourtneyQuoted 148 lines · Eliot Courtney
Quoted 147 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 Fooand givesBar<'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.
ForLtprovides such support. It provides a traitForLtwhich describes a type generic over lifetime. One may useForLt::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
ForLttrait, so functions withForLttrait bound can assume covariance.A macro
ForLt!()is provided to be able to obtain a type that implementsForLt. For example,ForLt!(for<'a> Bar<'a>)would yield a type that<TheType as ForLt>::Of<'a>isBar<'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.
Link https://docs.rs/higher-kinded-types/ [1]Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>---
rust/macros/for_lt.rs new file +107
-0+trait TypeExt { +fn expand_elided_lifetime (&self, explicit_lt: &Lifetime ) ->Type ; +fn replace_lifetime (&self, src: &Lifetime , dst: &Lifetime ) ->Type ; +fn has_lifetime (&self, lt: &Lifetime ) ->bool ; +} + +impl TypeExt for Type { +fn expand_elided_lifetime (&self, explicit_lt: &Lifetime ) ->Type { +struct ElidedLifetimeExpander <'a>(&'aLifetime ); + +impl VisitMut for ElidedLifetimeExpander <'_> { +fn visit_lifetime_mut (&mut self, lifetime: &mut Lifetime ) { +// Expand explicit `'_` +if lifetime.ident =="_" { + *lifetime = self.0 .clone (); + } + } + +fn visit_type_reference_mut (&mut self, reference: &mut syn::TypeReference ) { + syn::visit_mut::visit_type_reference_mut (self, reference); + +if reference.lifetime.is_none () { + reference.lifetime =Some (self.0 .clone ()); + } + } + } + +let mut ret = self.clone (); +ElidedLifetimeExpander (explicit_lt).visit_type_mut (&mut ret); + ret + } + +fn replace_lifetime (&self, src: &Lifetime , dst: &Lifetime ) ->Type { +struct LifetimeReplacer <'a>(&'aLifetime , &'aLifetime ); + +impl VisitMut for LifetimeReplacer <'_> { +fn visit_lifetime_mut (&mut self, lifetime: &mut Lifetime ) { +if lifetime.ident == self.0 .ident { + *lifetime = self.1 .clone (); + } + } + } + +let mut ret = self.clone (); +LifetimeReplacer (src, dst).visit_type_mut (&mut ret); + ret + } + +fn has_lifetime (&self, lt: &Lifetime ) ->bool { +struct HasLifetime <'a>(&'aLifetime ,bool ); + +impl Visit <'_>for HasLifetime <'_> { +fn visit_lifetime (&mut self, lifetime: &Lifetime ) { +if lifetime.ident == self.0 .ident { + self.1 =true ; + } + } + } + +let mut visitor =HasLifetime (lt,false ); + visitor.visit_type (self); + visitor.1 + } +} + +struct Prover <'a>(&'aLifetime ,Vec <&'aType >); + +impl <'a>Prover <'a> { +/// Prove that `ty` is covariant over `'lt`. +/// +/// This also needs to prove that it'll be wellformed for any instance of `'lt`. +/// It can be assumed that `ty` will be wellformed if `'lt` is substituted to `'static`. +fn prove (&mut self, ty: &'aType ) { +match ty { +Type ::Paren (ty) => self.prove (&ty.elem), +Type ::Group (ty) => self.prove (&ty.elem), + +// No lifetime involved +Type ::Never (_) => {} + +// `[T; N]` and `[T]` is covariant over `T`. +Type ::Array (ty) => self.prove (&ty.elem), +Type ::Slice (ty) => self.prove (&ty.elem), + +Type ::Tuple (ty) => { +for elemin &ty.elems { + self.prove (elem); + } + } + +// `*const T` is covariant over `T` +Type ::Ptr (ty)if ty.const_token.is_some () => self.prove (&ty.elem), + +// `&T` is covariant over `T` and lifetime. +// +// Note that if we encounter `&'other_lt T`, then we still need to make sure the type +// is wellformed if `T` involves `&'lt`, so we defer to the compiler. +// +// This is to block cases like `ForLt!(for<'a> &'static &'a u32)`, as the presence of +// the type implies `'a: 'static` but this is unsound. +Type ::Reference (ty) +if ty.mutability.is_none () && ty.lifetime.as_ref () ==Some (self.0 ) => + { + self.prove (&ty.elem) + } + +// `&[mut] T` is covariant over lifetime.
Quoted 8 lines
rust/macros/for_lt.rs line 164
Quoted 5 lines
rust/macros/for_lt.rs new file +5
-0+// In case we have `&[mut] NoLifetime`, we don't need to do additional checks. + Type::Reference(ty) if !ty.elem.has_lifetime(self.0) => (), + + // No mention of lifetime at all, no need to perform compiler check. + ty if !ty.has_lifetime(self.0) => (),This treats macros as not having a lifetime, but it allows this which is not covariant for 'a IIUC:
Good catch. I shall require treat macro as having lifetimes. I thought about this case when implementing self-referential lifetime in pin-init but didn't remember to retrospectively apply it here.
Quoted 17 lines
``` trait Trait {} macro_rules! asdf { () => { dyn Trait }; } type NotCovariant = ForLt!(for<'a> &'a mut asdf!()); ```And you can get rid of the macro too:
``` type NotCovariant = ForLt!(for<'a> &'a mut dyn Trait); ```
Quoted 7 lines
These are not covariant because dyn Trait has an elided +'a lifetime.
I feel that the syntactic checking is kinda difficult to get right since it would need to handle all ways lifetimes can be elided now and in the future.
Would it be that bad to always emit the proofs?
The proofs are items inside a constant block, and thus they cannot refer to generic parameters at all. Therefore, omitting proofs are important to make the macro work for obvious cases inside generic context. One use case is
impl<T> Foo<T> {
/* use ForLt!(T) here */
}Best,
Gary
Gary Guo
reviewerRe: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Alexandre CourbotQuoted 18 lines · Alexandre Courbot
On Sun May 17, 2026 at 9:01 AM JST, Danilo Krummrich wrote:
<snip>rust/kernel/types/for_lt.rs line 105
Quoted 12 lines
rust/kernel/types/for_lt.rs new file +12
-0+/// This is intended to be an "unsafe-to-refer-to" type. +/// +/// Must only be used by the `ForLt!` macro. +/// +/// `T` is the magic `dyn for<'a> WithLt<'a, TypeThatUse<'a>>` generated by macro. +/// +/// `WF` is a type that the macro can use to assert some specific type is well-formed. +/// +/// `N` is to provide the macro a place to emit arbitrary items, in case it needs to prove +/// additional properties. +#[doc(hidden)] +pub struct UnsafeForLtImpl <T : ?Sized ,WF ,const N :usize >(PhantomData <(WF ,T )>);Although the documentation makes it clear this should never be referenced directly, doing so is still possible, which creates a loophole for breaking covariance using only safe code.
I'm aware. That's why it has Unsafe in the name. But there's no way to create unsafe-to-name types, and without adt_const_params only integers can be used as const generic parameters and thus I cannot use a unsafe-to-create const parameter for this.
Quoted 14 lines
For instance (untested, and based on my limited understanding of the patch):
type Bad = UnsafeForLtImpl<
dyn for<'a> WithLt<'a, Of = Cell<&'a u8>>, (), 0,Quoted 1 line
;
The blanket
ForLtimplementation applies, and now we can store a shorter-lived reference into theCelland potentially observe it after its lifetime.
Quoted 7 lines
This could be worked around by defining the type implementing
ForLtlocally, at the cost of ergonomics since theForLttype would be declared separately:// Defines
DataLtand implementsForLton it after emitting // covariance proof.
define_for_lt!(DataLt = for<'a> Data<'a>);
An earlier version of this series have ForLt!() being quite ubiquitous, so I want to avoid this approach as this'll be need everywhere. But now we switch to use GAT for driver data, so perhaps this isn't too terrible anymore (only driver-core and aux device registration would need this).
This could even be extended to support generic types, such as
define_for_lt!(DataLt<T> = for<'a> Data<'a, T>);
This does also have th benefit of not having the type_complexity issue.
Danilo, what do you think?
---
I suppose If we're going down the new type approach, I also have some idea about generalizing this further to a generic utility that annotate GAT about variance.
#[variance_check]
trait MyTrait {
type MyGat<#[covariant] 'a>;
}
#[variance_check]
impl MyTrait for MyFoo {
type MyGat<#[covariant] 'a> = Bar;
}Then the expansion of define_for_lt! would just be
struct DataLt<T>(PhantomData<T>);
#[variance_check]
impl<T> ForLt for DataLt<T> {
type Of<#[covariant] 'a> = Data<'a, T>;
}Best,
Gary
Gary Guo
reviewerRe: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 6 lines · Danilo Krummrich
Quoted 4 lines · Eliot Courtney
Is this really sound without a covariance proof? For example, with this version you could stash a Cell<Option<&'bound pci::Device<Bound>> (even with Gary's suggested Core<'_> change) and then observe that reference on Drop of Data, which seems unsound to me.
Quoted 8 lines
The Core<'_> change seems unrelated, Core is not Sync, so you can't store it in the first place.
Otherwise, I don't see how one can exploit this. The formal invariance of Cell<Option<&'bound pci::Device<Bound>> is not practically exploitable because the framework controls what lifetimes are available and everything reachable through 'bound outlives the data; something that is shorter lived than 'bound can't be stored either.
The current code is problematic as the unbind callback have Pin<&'bound Self::Data<'bound>>. I think we've discussed this last week and the conclusion is that this isn't sound, and the callback should have Pin<&Self::Data<'bound>> instead (the outer lifetime should be callback-scoped)`. Did you forget to make the change?
Quoted 3 lines
Bringing back ForLt for this reason seems undesirable, as it has a real design cost.
If we have the #[variance_check] macro (like I mentioned in another thread), we could use that to check instead, but it'll still be unsound if lifetime of driver data escapes to devres due to destruction order.
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
Quoted 2 lines · Gary Guo
the callback should have
Pin<&Self::Data<'bound>>instead (the outer lifetime should be callback-scoped)`. Did you forget to make the change?
Yes, I thought I had that staged already, but forgot about it; good catch, thanks!
Re: [PATCH v3 03/27] rust: driver: decouple driver private data from driver type
In reply to Danilo KrummrichQuoted 16 lines · Danilo Krummrich
rust/kernel/driver.rs line 21
Quoted 10 lines · Danilo Krummrich
rust/kernel/driver.rs +2
-0@@ -17,6 +17,9 @@//! /// The type holding information about each device ID supported by the driver. //! type IdInfo: 'static; //! +//! /// The type of the driver's bus device private data. +//! type Data; Should be:
(quoted diff) +0
-0@@ -13,10 +13,13 @@ //! The main driver interface is defined by a bus specific driver trait. For instance:
Review line 22
Quoted 10 lines
(quoted diff) +3
-1//! //! ```ignore -//! pub trait Driver: Send { +//! pub trait Driver { //! /// The type holding information about each device ID supported by the driver. //! type IdInfo: 'static; //! +//! /// The type of the driver's bus device private data. +//! type Data: Send;
With this fix applied.
Best,
Gary
Re: [PATCH v3 04/27] rust: driver core: drop drvdata before devres release
In reply to Danilo KrummrichQuoted 13 lines · Danilo Krummrich
Move the
post_unbind_rustcallback beforedevres_release_all()indevice_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.
Quoted 5 lines
Without this change, devres resources would be freed first, leaving the driver's bus device private data with dangling references during its destructor.
Signed-off-by Danilo Krummrich <[email protected]>
Quoted 5 lines
--- drivers/base/dd.c | 2 +- include/linux/device/driver.h | 4 ++-- rust/kernel/driver.rs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-)
Re: [PATCH v3 05/27] rust: pci: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
pci_devas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound pci::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Quoted 3 lines
--- rust/kernel/pci.rs | 4 ++++ 1 file changed, 4 insertions(+)
Re: [PATCH v3 06/27] rust: platform: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
platform_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound platform::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Quoted 3 lines
--- rust/kernel/platform.rs | 4 ++++ 1 file changed, 4 insertions(+)
Re: [PATCH v3 07/27] rust: auxiliary: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
auxiliary_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound auxiliary::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Quoted 3 lines
--- rust/kernel/auxiliary.rs | 4 ++++ 1 file changed, 4 insertions(+)
Re: [PATCH v3 08/27] rust: usb: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct
usb_deviceas Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.This is needed for drivers to store &'bound usb::Device<Bound> in their private data while remaining Send.
Signed-off-by Danilo Krummrich <[email protected]>
Quoted 3 lines
--- rust/kernel/usb.rs | 4 ++++ 1 file changed, 4 insertions(+)
Re: [PATCH v3 09/27] rust: device: implement Sync for Device<Bound>
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Implement Sync for Device<Bound> in addition to Device<Normal>.
Device<Bound> uses the same underlying struct device as Device<Normal>; Bound is a zero-sized type-state marker that does not affect thread safety.
This is needed for types that hold &'bound Device<Bound>, such as
io::mem::IoMem, to be Send.Signed-off-by Danilo Krummrich <[email protected]>
Quoted 3 lines
--- rust/kernel/device.rs | 4 ++++ 1 file changed, 4 insertions(+)
Danilo Krummrich
maintainerRe: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Gary GuoQuoted 1 line · Gary Guo
Danilo, what do you think?
Two thoughts about this:
(1) The blast radius is bigger than just auxiliary device registrations; this pattern is applicable to all kinds of registrations that provide the guarantee to be scoped to the bus device being bound. I.e. it is true for any class device registration, IRQ registration, etc. They should all support HRT eventually; there is a subsequent series where I started to implement this for DRM.
(2) I'm not concerned about the UnsafeForLtImpl approach, as I think for a human one would really need to be willing to abuse it by intention. I.e. it is not really different to just using unsafe {} while knowing not to be able to satisfy the safety requirement.
That said, I expect LLMs to be (heavily) used to write drivers, and LLMs are typically trained to be compliant. So, I could imagine that a prompt along the lines of "Can't we make this work without unsafe somehow?" leads to an LLM abusing this, while going unnoticed for the user.
That said, I think that requiring define_for_lt!() wouldn't be that big of an issue; the number of registrations per driver is rather limited.
Besides that, considering (2) it may actually address a practical concern.
If you want to make the change I'm happy to integrate it in a v4, otherwise a follow-up seems reasonable as well.
Re: [PATCH v3 16/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
Quoted 5 lines · Danilo Krummrich
That said, I expect LLMs to be (heavily) used to write drivers, and LLMs are typically trained to be compliant. So, I could imagine that a prompt along the lines of "Can't we make this work without unsafe somehow?" leads to an LLM abusing this, while going unnoticed for the user.
Could we steer LLMs to avoid that? e.g. adding a line about Unsafe* items to Sashiko's prompts.
Also, a checkpatch.pl (or similar) warning may be doable too, since false positives are OK there.
It could go to the ASH (Acknowledged Soundness Holes) list we discussed some times if we end up adding it.
Cheers,
Miguel
Re: [PATCH v3 18/27] samples: rust: rust_driver_auxiliary: showcase lifetime-bound registration data
In reply to Danilo KrummrichQuoted 8 lines · 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 throughadev.parent().Signed-off-by Danilo Krummrich <[email protected]>
Quoted 3 lines
--- samples/rust/rust_driver_auxiliary.rs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-)
Gary Guo
reviewerRe: [PATCH v3 19/27] rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichQuoted 109 lines · Danilo Krummrich
Convert pci::Bar<SIZE> to pci::Bar<'bound, SIZE>, storing &'bound Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized()now returns Result<Bar<'bound, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.Add
Bar::into_devres()to consume the bar and register it as a device-managed resource, returning Devres<Bar<'static, SIZE>>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind.Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/driver.rs | 7 ++-- rust/kernel/devres.rs | 2 +- rust/kernel/pci/io.rs | 68 +++++++++++++++++---------------- samples/rust/rust_driver_pci.rs | 5 ++- 4 files changed, 44 insertions(+), 38 deletions(-)drivers/gpu/nova-core/driver.rs +4
-3@@ -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 ,@@ -94,8 +94,9 @@ fn probe<'bound>(// 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@@ -304,7 +304,7 @@ pub fn device(&self) -> &Device {/// pci, // /// }; /// -/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result { +/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<'_, 0x4>>) -> Result { /// let bar = devres.access(dev.as_ref())?; /// /// let _ = bar.read32(0x0); rust/kernel/pci/io.rs +6
-7@@ -14,8 +14,7 @@ Mmio, MmioRaw, // }, - prelude::*, - sync::aref::ARef, // + prelude::*, // };use core::{ marker::PhantomData ,@@ -78,15 +77,15 @@ impl ConfigSpaceKind for Extended {/// The generic parameter `S` indicates the maximum size of the configuration space. /// Use [`Normal`] for 256-byte legacy configuration space or [`Extended`] for /// 4096-byte PCIe extended configuration space (default). -pub struct ConfigSpace <'a,S :ConfigSpaceKind =Extended > { -pub (crate ) pdev: &'aDevice <device::Bound >, +pub struct ConfigSpace <'bound,S :ConfigSpaceKind =Extended > { +pub (crate ) pdev: &'boundDevice <device::Bound >, _marker:PhantomData <S >, }/// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn` and `$write_fn`. macro_rules! impl_config_space_io_capable { ($ty:ty, $read_fn:ident, $write_fn:ident) => { -impl <'a,S :ConfigSpaceKind >IoCapable <$ty>for ConfigSpace <'a,S > { +impl <'bound,S :ConfigSpaceKind >IoCapable <$ty>for ConfigSpace <'bound,S > {unsafe fn io_read (&self, address:usize ) -> $ty {let mut val: $ty =0 ;@@ -119,7 +118,7 @@ unsafe fn io_write(&self, value: $ty, address: usize) {impl_config_space_io_capable! (u16 , pci_read_config_word, pci_write_config_word);impl_config_space_io_capable! (u32 , pci_read_config_dword, pci_write_config_dword); -impl <'a,S :ConfigSpaceKind >Io for ConfigSpace <'a,S > { +impl <'bound,S :ConfigSpaceKind >Io for ConfigSpace <'bound,S > {/// Returns the base address of the I/O region. It is always 0 for configuration space. #[inline] fn addr (&self) ->usize {@@ -133,7 +132,7 @@ fn maxsize(&self) -> usize { } } -impl <'a,S :ConfigSpaceKind >IoKnownSize for ConfigSpace <'a,S > { +impl <'bound,S :ConfigSpaceKind >IoKnownSize for ConfigSpace <'bound,S > {const MIN_SIZE :usize =S ::SIZE ; }
rust/kernel/pci/io.rs impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> { · line 149
Quoted 7 lines
rust/kernel/pci/io.rs +2
-2@@ -146,14 +145,14 @@ impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {/// /// `Bar` always holds an `IoRaw` instance that holds a valid pointer to the start of the I/O /// memory mapped PCI BAR and its size. -pub struct Bar <const SIZE :usize =0 > { - pdev:ARef <Device >, +pub struct Bar <'bound,const SIZE :usize =0 > { + pdev: &'boundDevice <device::Bound >,
I think there's probably no need to name this 'bound. From an individual resource's perspective, there is no need to ensure that the lifetime is living as long as a bound device.
It is perfectly fine to temporarily obtain a Bar and just destroy it before device is unbound. So in some sense, this is
struct Bar<'a, const SIZE: usize> where 'bound: 'a
and this bound is implied by the &'a Device<device::Bound> type.
For interfaces which currently require invariance (e.g. Driver::Data<'bound>), the name change is more important because the API does require a matching lifetime (and also DevResLt).
Quoted 33 lines
rust/kernel/pci/io.rs +7
-8io: MmioRaw<SIZE>, num: i32, } -impl <const SIZE :usize >Bar <SIZE > { -pub (super )fn new (pdev: &Device , num:u32 , name: &CStr ) ->Result <Self > { +impl <'bound,const SIZE :usize >Bar <'bound,SIZE > { +pub (super )fn new (pdev: &'boundDevice <device::Bound >, num:u32 , name: &CStr ) ->Result <Self > {let len = pdev.resource_len (num)?;if len ==0 {return Err (ENOMEM );@@ -196,11 +195,7 @@ pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> { } }; -Ok (Bar { - pdev: pdev.into (), - io, - num, - }) +Ok (Bar { pdev, io, num }) }/// # Safety @@ -219,11 +214,24 @@ unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {fn release (&self) {// SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`. -unsafe {Self ::do_release (&self.pdev, self.io.addr (), self.num) }; +unsafe {Self ::do_release (self.pdev, self.io.addr (), self.num) }; + } + +/// Consume the `Bar` and register it as a device-managed resource.
rust/kernel/pci/io.rs unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) { · line 230
Quoted 10 lines
rust/kernel/pci/io.rs +10
-0+/// +/// The returned `Devres<Bar<'static, SIZE>>` can outlive the original lifetime `'bound`. Access +/// to the BAR is revoked when the device is unbound. +pub fn into_devres (self) ->Result <Devres <Bar <'static,SIZE >>> { +// SAFETY: Casting to `'static` is sound because `Devres` guarantees the `Bar` does not +// actually outlive the device -- access is revoked and the resource is released when the +// device is unbound. +let bar:Bar <'static,SIZE > =unsafe { core::mem::transmute (self) }; +let pdev = bar.pdev; +Devres ::new (pdev.as_ref (), bar)
One thing to note (which kinda motivates to suggest 'bound might not be a good name) is that while this is sound for Bar, this logic isn't true in general for things that with the same shape as Bar.
For example, say if we have
struct MyResource<'bound> {
dev: &'bound Device<Bound>,
data: &'bound [u8],
}then it's not okay to turn this into DevRes<MyResource<'static>> (or DevResLt<ForLt!(MyResource<'_>)>, because the user can shorten the lifetime on &Device<Bound>:
fn bad_fn<'bound>(dev: &'bound Device<Bound>) -> DevRes<MyResource<'static>> {
let local = [0; 64];
// Basically `MyResource<'local>`.
let my_resource = MyResource {
dev,
data: &local,
};
my_resource.into_devres()
}Now this is obviously bad because the resource now outlives local despite that it shouldn't. The 'bound lifetime becomes the the confusion factor here.
If this is just &'a, then you need to actually justify why the into_devres() is fine, which you still can for Bar not for MyResource.
(This also means that sound and generic API of DevResLt would need either an API with invariant lifetime, or with callback API. So something like
struct BoundDevice<'bound>(&'bound Device<Bound>, PhantomData<fn(&'bound ())-> &'bound ()>);
impl BoundDevice<'bound> {
fn into_devres<F: ForLt>(&self, value: F::Of<'bound>) -> DevResLt<F>;
}Or
impl Device<Bound> {
fn new_devres<F: ForLt>(&self, f: impl for<'bound> FnOnce(&'bound Device<Bound>) -> F::Of<'bound>) -> DevResLt<F>;
}Either way, I think we probably want to limit 'bound to cases where it's actually 'bound and not some possibly shortened lifetime.
Best,
Gary
Quoted 92 lines
rust/kernel/pci/io.rs +11
-15} } -impl Bar { +impl Bar <'_> {#[inline] pub (super )fn index_is_valid (index:u32 ) ->bool {// A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries. @@ -231,13 +239,13 @@ pub(super) fn index_is_valid(index: u32) -> bool { } } -impl <const SIZE :usize >Drop for Bar <SIZE > { +impl <const SIZE :usize >Drop for Bar <'_,SIZE > {fn drop (&mut self) { self.release (); } } -impl <const SIZE :usize >Deref for Bar <SIZE > { +impl <const SIZE :usize >Deref for Bar <'_,SIZE > {type Target =Mmio <SIZE >;fn deref (&self) -> &Self ::Target {@@ -249,20 +257,16 @@ fn deref(&self) -> &Self::Target {impl Device <device::Bound > {/// Maps an entire PCI BAR after performing a region-request on it. I/O operation bound checks /// can be performed on compile time for offsets (plus the requested type size) < SIZE. -pub fn iomap_region_sized <'a,const SIZE :usize >( - &'a self, +pub fn iomap_region_sized <'bound,const SIZE :usize >( + &'bound self, bar:u32 , - name: &'aCStr , - ) ->impl PinInit <Devres <Bar <SIZE >>,Error > + 'a { -Devres ::new (self.as_ref (),Bar ::<SIZE >::new (self, bar, name)) + name: &CStr , + ) ->Result <Bar <'bound,SIZE >> { +Bar ::new (self, bar, name) }/// Maps an entire PCI BAR after performing a region-request on it. -pub fn iomap_region <'a>( - &'a self, - bar:u32 , - name: &'aCStr , - ) ->impl PinInit <Devres <Bar >,Error > + 'a { +pub fn iomap_region <'bound>(&'bound self, bar:u32 , name: &CStr ) ->Result <Bar <'bound>> { self.iomap_region_sized ::<0 >(bar, name) }@@ -282,7 +286,7 @@ pub fn cfg_size(&self) -> ConfigSpaceSize { }/// Return an initialized normal (256-byte) config space object. -pub fn config_space <'a>(&'a self) ->ConfigSpace <'a,Normal > { +pub fn config_space <'bound>(&'bound self) ->ConfigSpace <'bound,Normal > {ConfigSpace { pdev: self, _marker:PhantomData ,@@ -290,7 +294,7 @@ pub fn config_space<'a>(&'a self) -> ConfigSpace<'a, Normal> { }/// Return an initialized extended (4096-byte) config space object. -pub fn config_space_extended <'a>(&'a self) ->Result <ConfigSpace <'a,Extended >> { +pub fn config_space_extended <'bound>(&'bound self) ->Result <ConfigSpace <'bound,Extended >> {if self.cfg_size () !=ConfigSpaceSize ::Extended {return Err (EINVAL ); }samples/rust/rust_driver_pci.rs +3
-2@@ -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 );@@ -161,7 +161,8 @@ fn probe<'bound>( 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())?;
Gary Guo
reviewerRe: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichQuoted 48 lines · 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.Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/driver.rs | 4 +- rust/kernel/auxiliary.rs | 68 +++++++++++++++++---------- samples/rust/rust_driver_auxiliary.rs | 8 ++-- 3 files changed, 52 insertions(+), 28 deletions(-)[snip]
rust/kernel/auxiliary.rs +10
-7@@ -389,43 +399,51 @@ struct RegistrationData<T> {/// This type represents the registration of a [`struct auxiliary_device`]. When its parent device /// is unbound, the corresponding auxiliary device will be unregistered from the system. /// -/// The type parameter `T` is the type of the registration data owned by the registering (parent) -/// driver. It can be accessed by the auxiliary driver through -/// [`Device::registration_data()`]. +/// The type parameter `F` is a [`ForLt`](trait@ForLt) encoding of the registration +/// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](macro@ForLt). +/// The data can be accessed by the auxiliary driver through [`Device::registration_data()`]. /// /// # Invariants /// /// `self.adev` always holds a valid pointer to an initialized and registered /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a -/// valid `Pin<KBox<RegistrationData<T>>>`. -pub struct Registration <T : 'static> { +/// valid `Pin<KBox<RegistrationData<F::Of<'static>>>>`. +pub struct Registration <F :ForLt > { adev:NonNull <bindings::auxiliary_device >, - _data:PhantomData <T >, + _data:PhantomData <F >, } -impl <T :Send +Sync + 'static>Registration <T > { +impl <F :ForLt >Registration <F > +where +for <'a>F ::Of <'a>:Send +Sync , +{/// Create and register a new auxiliary device with the given registration data. /// /// The `data` is owned by the registration and can be accessed through the auxiliary device /// via [`Device::registration_data()`].
rust/kernel/auxiliary.rs struct RegistrationData<T> { · line 430
Quoted 10 lines
rust/kernel/auxiliary.rs +3
-3-pub fn new <E >( - parent: &device::Device <device::Bound >, +pub fn new <'bound,E >( + parent: &'bound device::Device <device::Bound >, name: &CStr , id:u32 , modname: &CStr , - data:impl PinInit <T ,E >, + data:impl PinInit <F ::Of <'bound>,E >, ) ->Result <Devres <Self >>
I think this is unsound for the reason that I gave in another email
https://lore.kernel.org/rust-for-linux/[email protected]/.
Best,
Gary
Quoted 34 lines
rust/kernel/auxiliary.rs +9
-2where Error: From<E>, {let data =KBox ::pin_init ::<Error >(try_pin_init! (RegistrationData { - type_id:TypeId ::of ::<T >(), + type_id:TypeId ::of ::<F ::Of <'static >>(), data <- data, }),GFP_KERNEL , )?; +// SAFETY: Lifetimes are erased and do not affect layout, so RegistrationData<F::Of<'bound>> +// and RegistrationData<F::Of<'static>> have identical representation. +let data:Pin <KBox <RegistrationData <F ::Of <'static>>>> = +unsafe { core::mem::transmute (data) }; +let boxed:KBox <Opaque <bindings::auxiliary_device >> =KBox ::zeroed (GFP_KERNEL )?;let adev = boxed.get ();@@ -455,7 +473,9 @@ pub fn new<E>(if ret !=0 {// SAFETY: `registration_data` was set above via `into_foreign()`. drop (unsafe { -Pin ::<KBox <RegistrationData <T >>>::from_foreign ((*adev).registration_data_rust) +Pin ::<KBox <RegistrationData <F ::Of <'static>>>>::from_foreign ( + (*adev).registration_data_rust, + ) });// SAFETY: `adev` is guaranteed to be a valid pointer to a @@ -478,7 +498,7 @@ pub fn new<E>( } }
Gary Guo
reviewerRe: [PATCH v3 22/27] rust: driver-core: rename 'a lifetime to 'bound
In reply to Danilo KrummrichQuoted 33 lines · Danilo Krummrich
Rename the generic lifetime parameter from 'a to 'bound in pci, platform, i2c and devres. This makes it explicit that the lifetime represents the device binding scope, consistent with the convention established by the HRT series.
Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/devres.rs | 14 +++++++++----- rust/kernel/i2c.rs | 6 +++--- rust/kernel/pci/irq.rs | 38 +++++++++++++++++++------------------- rust/kernel/platform.rs | 18 +++++++++--------- 4 files changed, 40 insertions(+), 36 deletions(-)rust/kernel/devres.rs +4
-3@@ -280,10 +280,11 @@ pub fn device(&self) -> &Device { &self.dev } -/// Obtain `&'a T`, bypassing the [`Revocable`]. +/// Obtain `&'bound T`, bypassing the [`Revocable`]. /// -/// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting -/// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with. +/// This method allows to directly obtain a `&'bound T`, bypassing the +/// [`Revocable`], by presenting a `&'bound Device<Bound>` of the same +/// [`Device`] this [`Devres`] instance has been created with. /// /// # Errors ///
rust/kernel/devres.rs pub fn device(&self) -> &Device { · line 323
Quoted 8 lines
rust/kernel/devres.rs +1
-1@@ -316,7 +317,7 @@ pub fn device(&self) -> &Device {/// Ok(()) /// } /// ``` -pub fn access <'a>(&'a self, dev: &'aDevice <Bound >) ->Result <&'aT > { +pub fn access <'bound>(&'bound self, dev: &'boundDevice <Bound >) ->Result <&'boundT > {if self.dev.as_raw () != dev.as_raw () {return Err (EINVAL ); }
For the same reason that I outlined in the other email, I think this should keep the generic 'a name as this is not the actual lifetime of 'bound, just a shortened one.
Quoted 18 lines
rust/kernel/devres.rs +4
-1@@ -338,7 +339,10 @@ pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> { }/// [`Devres`] accessor for [`Revocable::try_access_with_guard`]. -pub fn try_access_with_guard <'a>(&'a self, guard: &'a rcu::Guard ) ->Option <&'aT > { +pub fn try_access_with_guard <'bound>( + &'bound self, + guard: &'bound rcu::Guard , + ) ->Option <&'boundT > { self.data ().try_access_with_guard (guard) } }rust/kernel/i2c.rs +0
-0@@ -566,11 +566,11 @@ unsafe impl Sync for I2cClient {}
rust/kernel/i2c.rs unsafe impl Sync for I2cClient {} · line 573
Quoted 10 lines
rust/kernel/i2c.rs +3
-3impl Registration {/// The C `i2c_new_client_device` function wrapper for manual I2C client creation. -pub fn new <'a>( +pub fn new <'bound>( i2c_adapter: &I2cAdapter , i2c_board_info: &I2cBoardInfo , - parent_dev: &'a device::Device <device::Bound >, - ) ->impl PinInit <Devres <Self >,Error > + 'a { + parent_dev: &'bound device::Device <device::Bound >, + ) ->impl PinInit <Devres <Self >,Error > + 'bound {
This really shouldn't be 'bound. The lifetime here is just a technical one, due to the reason impl Trait is used.
This whole function is conceptually
pub init fn new(i2c_adapter: &I2cAdapter, i2c_board: &I2cboardInfo, parent_dev: &Device<Bound>) -> Result<DevRes<Self>, Error>;
and note that the lifetime does not appear anywhere.
If we follow the desugaring used by async, the desugared version is
pub fn new<'init>(
i2c_adapter: &'init I2cAdapter,
i2c_board_info: &'init I2cBoardInfo,
parent_dev: &'init device::Device<device::Bound>,
) -> impl PinInit<Devres<Self>, Error> + 'init {
Notably, the returned PinInit can (and should) capture all lifetime parameters to the function so they can be used in the init process.
BTW, if you do need explicit bound lifetime, then it looks like
pub fn new<'init, 'bound>(
i2c_adapter: &'init I2cAdapter,
i2c_board_info: &'init I2cBoardInfo,
parent_dev: &'bound device::Device<device::Bound>,
) -> impl PinInit<Devres<Self>, Error> + 'init where
'bound: 'init
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH v3 22/27] rust: driver-core: rename 'a lifetime to 'bound
Quoted 10 lines · Gary Guo
rust/kernel/devres.rs pub fn device(&self) -> &Device { · line 323
Quoted 5 lines · Danilo Krummrich
rust/kernel/devres.rs +1
-1-pub fn access <'a>(&'a self, dev: &'aDevice <Bound >) ->Result <&'aT > { +pub fn access <'bound>(&'bound self, dev: &'boundDevice <Bound >) ->Result <&'boundT > {if self.dev.as_raw () != dev.as_raw () {return Err (EINVAL ); }For the same reason that I outlined in the other email, I think this should keep the generic
'aname as this is not the actual lifetime of'bound, just a shortened one.
I think it depends on how you want to read it, i.e. do we consider 'bound to be:
- the lifetime for the full duration of a device bound to a driver, or
- some lifetime that guarantees that the device remains bound for (which can also be shorter).
For this and the other cases you commented on I obviously applied the second interpretation.
That said, I think for consistency and ambiguity reasons it does make sense to reserve the term 'bound for the first one exclusively, and also clearly document that.
Danilo Krummrich
maintainerRe: [PATCH v3 19/27] rust: pci: make Bar lifetime-parameterized
In reply to Gary GuoQuoted 2 lines · Gary Guo
Either way, I think we probably want to limit
'boundto cases where it's actually'boundand not some possibly shortened lifetime.
Agreed; [1] for reference.
Danilo Krummrich
maintainerRe: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
In reply to Gary GuoQuoted 10 lines · Gary Guo
Review
Quoted 8 lines · Danilo Krummrich
(quoted diff) +3
-1+ pub fn new<'bound, E>( + parent: &'bound device::Device<device::Bound>, name: &CStr, id: u32, modname: &CStr, - data: impl PinInit<T, E>, + data: impl PinInit<F::Of<'bound>, E>, ) -> Result<Devres<Self>>
Quoted 2 lines
I think this is unsound for the reason that I gave in another email
https://lore.kernel.org/rust-for-linux/[email protected]/.
Indeed, this has to be fixed. I looked into the options brought up in the linked reply, i.e. the "new type" approach and the "closure" approach. And after playing around with both of them, I'm not really satisfied with either of those.
The "new type" one is simple and works, but has the disadvantage that, well, we need a new type and update all callsites where we would ever want to create registrations (mainly probe though).
The "closure" one on the other hand creates a little bit of an odd API and by its nature does not allow to move pre-existing resources into the closure, which is a major limitation (maybe there is some way, but if so I didn't find it).
I instead went with something else: Currently we return a Devres<auxiliary::Registration<_>>. However, since we're moving to lifetimes anyway, we can just return an auxiliary::Registration<'bound, _> instead, which makes the return type invariant over 'bound, which makes the problem go away naturally.
Please find the diff below for reference.
rust/kernel/auxiliary.rs +16 -16
@@ -12,7 +12,7 @@ RawDeviceId, RawDeviceIdIndex, // }, - devres::Devres, + driver, error::{ from_result,
@@ -408,12 +408,12 @@ struct RegistrationData<T> {/// `self.adev` always holds a valid pointer to an initialized and registered /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a /// valid `Pin<KBox<RegistrationData<F::Of<'static>>>>`. -pub struct Registration <F :ForLt + 'static> { +pub struct Registration <'bound,F :ForLt + 'static> { adev:NonNull <bindings::auxiliary_device >, - _data:PhantomData <F >, + _phantom:PhantomData <(fn (&'bound ()) -> &'bound (),F )>, } -impl <F :ForLt >Registration <F > +impl <'bound,F :ForLt >Registration <'bound,F >where for <'a>F ::Of <'a>:Send +Sync , {
@@ -421,13 +421,13 @@ impl<F: ForLt> Registration<F>/// /// The `data` is owned by the registration and can be accessed through the auxiliary device /// via [`Device::registration_data()`]. -pub fn new <'bound,E >( +pub fn new <E >( parent: &'bound device::Device <device::Bound >, name: &CStr , id:u32 , modname: &CStr , data:impl PinInit <F ::Of <'bound>,E >, - ) ->Result <Devres <Self >> + ) ->Result <Self >where Error :From <E >, {
@@ -439,8 +439,10 @@ pub fn new<'bound, E>( GFP_KERNEL, )?; -// SAFETY: Lifetimes are erased and do not affect layout, so RegistrationData<F::Of<'bound>> -// and RegistrationData<F::Of<'static>> have identical representation. +// SAFETY: `'bound` is invariant (via `Registration`'s `PhantomData`), guaranteeing it +// represents the full binding scope. Lifetimes do not affect layout, so +// RegistrationData<F::Of<'bound>> and RegistrationData<F::Of<'static>> have identical +// representation. let data:Pin <KBox <RegistrationData <F ::Of <'static>>>> =unsafe { core::mem::transmute (data) };
@@ -487,18 +489,16 @@ pub fn new<'bound, E>(// INVARIANT: The device will remain registered until `auxiliary_device_delete()` is // called, which happens in `Self::drop()`. -let reg =Self { +Ok (Self {// SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated // successfully. adev:unsafe {NonNull ::new_unchecked (adev) }, - _data:PhantomData , - }; - -Devres ::new ::<core::convert::Infallible >(parent, reg) + _phantom:PhantomData , + }) } } -impl <F :ForLt >Drop for Registration <F > { +impl <F :ForLt >Drop for Registration <'_,F > {fn drop (&mut self) {// SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered // `struct auxiliary_device`.
@@ -520,7 +520,7 @@ fn drop(&mut self) { }// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread. -unsafe impl <F :ForLt >Send for Registration <F >where for <'a>F ::Of <'a>:Send {} +unsafe impl <F :ForLt >Send for Registration <'_,F >where for <'a>F ::Of <'a>:Send {}// SAFETY: `Registration` does not expose any methods or fields that need synchronization. -unsafe impl <F :ForLt >Sync for Registration <F >where for <'a>F ::Of <'a>:Send {} +unsafe impl <F :ForLt >Sync for Registration <'_,F >where for <'a>F ::Of <'a>:Send {}
samples/rust/rust_driver_auxiliary.rs +10 -11
@@ -10,7 +10,6 @@ Bound, Core, // }, - devres::Devres, driver, pci, prelude::*,
@@ -58,29 +57,29 @@ struct Data<'bound> { } #[allow(clippy::type_complexity)] -struct ParentDriver { - _reg0: Devres<auxiliary::Registration<ForLt!(Data<'_>)>>, - _reg1: Devres<auxiliary::Registration<ForLt!(Data<'_>)>>, +struct ParentDriver<'bound> { + _reg0: auxiliary::Registration<'bound, ForLt!(Data<'_>)>, + _reg1: auxiliary::Registration<'bound, ForLt!(Data<'_>)>, } 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 pci::Driver for ParentDriver<'_> { type IdInfo = (); - type Data<'bound> = Self; + type Data<'bound> = ParentDriver<'bound>; const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; fn probe<'bound>( pdev: &'bound pci::Device<Core>, _info: &'bound Self::IdInfo, - ) -> impl PinInit<Self, Error> + 'bound { - Ok(Self { + ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { + Ok(ParentDriver { _reg0: auxiliary::Registration::new( pdev.as_ref(), AUXILIARY_NAME,
@@ -105,7 +104,7 @@ fn probe<'bound>( } } -impl ParentDriver { +impl ParentDriver <'_> {fn connect (adev: &auxiliary::Device <Bound >) ->Result {let data = adev.registration_data ::<ForLt! (Data <'_>)>()?;let pdev = data.parent;
@@ -131,7 +130,7 @@ fn connect(adev: &auxiliary::Device<Bound>) -> Result {#[pin_data] struct SampleModule {#[pin] - _pci_driver: driver::Registration <pci::Adapter <ParentDriver >>, + _pci_driver: driver::Registration <pci::Adapter <ParentDriver <'static>>>,#[pin] _aux_driver: driver::Registration <auxiliary::Adapter <AuxiliaryDriver >>, }
Re: [PATCH v3 10/27] rust: pci: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 6 lines · Danilo Krummrich
Quoted 2 lines · Gary Guo
the callback should have
Pin<&Self::Data<'bound>>instead (the outer lifetime should be callback-scoped)`. Did you forget to make the change?Yes, I thought I had that staged already, but forgot about it; good catch, thanks!
I think this resolves my concern and it's nicer for drivers to use than requiring covariance on their Data types. Thanks!
Gary Guo
reviewerRe: [PATCH v3 17/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichQuoted 48 lines · Danilo Krummrich
Quoted 10 lines · Gary Guo
Review
Quoted 8 lines · Danilo Krummrich
(quoted diff) +3
-1+ pub fn new<'bound, E>( + parent: &'bound device::Device<device::Bound>, name: &CStr, id: u32, modname: &CStr, - data: impl PinInit<T, E>, + data: impl PinInit<F::Of<'bound>, E>, ) -> Result<Devres<Self>>Quoted 2 lines
I think this is unsound for the reason that I gave in another email
https://lore.kernel.org/rust-for-linux/[email protected]/.Indeed, this has to be fixed. I looked into the options brought up in the linked reply, i.e. the "new type" approach and the "closure" approach. And after playing around with both of them, I'm not really satisfied with either of those.
The "new type" one is simple and works, but has the disadvantage that, well, we need a new type and update all callsites where we would ever want to create registrations (mainly probe though).
The "closure" one on the other hand creates a little bit of an odd API and by its nature does not allow to move pre-existing resources into the closure, which is a major limitation (maybe there is some way, but if so I didn't find it).
I instead went with something else: Currently we return a Devres<auxiliary::Registration<_>>. However, since we're moving to lifetimes anyway, we can just return an auxiliary::Registration<'bound, _> instead, which makes the return type invariant over 'bound, which makes the problem go away naturally.
Please find the diff below for reference.
rust/kernel/auxiliary.rs +1
-1@@ -12,7 +12,7 @@ RawDeviceId, RawDeviceIdIndex, // }, - devres::Devres, + driver, error::{ from_result,
rust/kernel/auxiliary.rs struct RegistrationData<T> { · line 413
Quoted 8 lines
rust/kernel/auxiliary.rs +2
-2@@ -408,12 +408,12 @@ struct RegistrationData<T> {/// `self.adev` always holds a valid pointer to an initialized and registered /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a /// valid `Pin<KBox<RegistrationData<F::Of<'static>>>>`. -pub struct Registration <F :ForLt + 'static> { +pub struct Registration <'bound,F :ForLt + 'static> { adev:NonNull <bindings::auxiliary_device >, - _data:PhantomData <F >, + _phantom:PhantomData <(fn (&'bound ()) -> &'bound (),F )>,
The type itself may be invariant over the lifetime, but it would still accept a shorter lifetime (which again, is a case where I think having 'bound becomes a factor for confusion).
You can still pass in a shortened lifetime to Registration::new and then leak a registration (yes, Leakpocalypse strikes again), so the invariance here isn't actually serving purpose.
fn bad_fn(dev: &device::Device<device::Bound>, buf: &[u8]) {
forget(Box::pin_init(Registration::new(dev, c"foo", 0, c"bar", buf)))
}Best,
Gary
Quoted 137 lines
rust/kernel/auxiliary.rs +13
-13} -impl <F :ForLt >Registration <F > +impl <'bound,F :ForLt >Registration <'bound,F >where for <'a>F ::Of <'a>:Send +Sync , {@@ -421,13 +421,13 @@ impl<F: ForLt> Registration<F>/// /// The `data` is owned by the registration and can be accessed through the auxiliary device /// via [`Device::registration_data()`]. -pub fn new <'bound,E >( +pub fn new <E >( parent: &'bound device::Device <device::Bound >, name: &CStr , id:u32 , modname: &CStr , data:impl PinInit <F ::Of <'bound>,E >, - ) ->Result <Devres <Self >> + ) ->Result <Self >where Error :From <E >, {@@ -439,8 +439,10 @@ pub fn new<'bound, E>( GFP_KERNEL, )?; -// SAFETY: Lifetimes are erased and do not affect layout, so RegistrationData<F::Of<'bound>> -// and RegistrationData<F::Of<'static>> have identical representation. +// SAFETY: `'bound` is invariant (via `Registration`'s `PhantomData`), guaranteeing it +// represents the full binding scope. Lifetimes do not affect layout, so +// RegistrationData<F::Of<'bound>> and RegistrationData<F::Of<'static>> have identical +// representation. let data:Pin <KBox <RegistrationData <F ::Of <'static>>>> =unsafe { core::mem::transmute (data) };@@ -487,18 +489,16 @@ pub fn new<'bound, E>(// INVARIANT: The device will remain registered until `auxiliary_device_delete()` is // called, which happens in `Self::drop()`. -let reg =Self { +Ok (Self {// SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated // successfully. adev:unsafe {NonNull ::new_unchecked (adev) }, - _data:PhantomData , - }; - -Devres ::new ::<core::convert::Infallible >(parent, reg) + _phantom:PhantomData , + }) } } -impl <F :ForLt >Drop for Registration <F > { +impl <F :ForLt >Drop for Registration <'_,F > {fn drop (&mut self) {// SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered // `struct auxiliary_device`. @@ -520,7 +520,7 @@ fn drop(&mut self) { }// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread. -unsafe impl <F :ForLt >Send for Registration <F >where for <'a>F ::Of <'a>:Send {} +unsafe impl <F :ForLt >Send for Registration <'_,F >where for <'a>F ::Of <'a>:Send {}// SAFETY: `Registration` does not expose any methods or fields that need synchronization. -unsafe impl <F :ForLt >Sync for Registration <F >where for <'a>F ::Of <'a>:Send {} +unsafe impl <F :ForLt >Sync for Registration <'_,F >where for <'a>F ::Of <'a>:Send {}samples/rust/rust_driver_auxiliary.rs +10
-11@@ -10,7 +10,6 @@ Bound, Core, // }, - devres::Devres, driver, pci, prelude::*,@@ -58,29 +57,29 @@ struct Data<'bound> { } #[allow(clippy::type_complexity)] -struct ParentDriver { - _reg0: Devres<auxiliary::Registration<ForLt!(Data<'_>)>>, - _reg1: Devres<auxiliary::Registration<ForLt!(Data<'_>)>>, +struct ParentDriver<'bound> { + _reg0: auxiliary::Registration<'bound, ForLt!(Data<'_>)>, + _reg1: auxiliary::Registration<'bound, ForLt!(Data<'_>)>, } 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 pci::Driver for ParentDriver<'_> { type IdInfo = (); - type Data<'bound> = Self; + type Data<'bound> = ParentDriver<'bound>; const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; fn probe<'bound>( pdev: &'bound pci::Device<Core>, _info: &'bound Self::IdInfo, - ) -> impl PinInit<Self, Error> + 'bound { - Ok(Self { + ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { + Ok(ParentDriver { _reg0: auxiliary::Registration::new( pdev.as_ref(), AUXILIARY_NAME,@@ -105,7 +104,7 @@ fn probe<'bound>( } } -impl ParentDriver { +impl ParentDriver <'_> {fn connect (adev: &auxiliary::Device <Bound >) ->Result {let data = adev.registration_data ::<ForLt! (Data <'_>)>()?;let pdev = data.parent;@@ -131,7 +130,7 @@ fn connect(adev: &auxiliary::Device<Bound>) -> Result {#[pin_data] struct SampleModule {#[pin] - _pci_driver: driver::Registration <pci::Adapter <ParentDriver >>, + _pci_driver: driver::Registration <pci::Adapter <ParentDriver <'static>>>,#[pin] _aux_driver: driver::Registration <auxiliary::Adapter <AuxiliaryDriver >>, }