rust: device: Higher-Ranked Lifetime Types for device drivers
Subsystems (19)
Danilo Krummrich
maintainerv4 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 v4:
- Use 'bound only for lifetimes that represent the full duration of a device being bound to a driver
- Make Core and CoreInternal lifetime-parameterized
- Split auxiliary::Registration constructor into unsafe fn new_with_lt (borrowed data) and safe fn new ('static data) to close mem::forget() soundness hole
- Use TypeId::of::<F>() instead of TypeId::of::<F::Of<'static>>() in auxiliary registration_data()
- Handle Type::Macro in ForLt! covariance and WF checks; proc macros cannot expand macro_rules invocations, so use WithLt trait projection for lifetime substitution
- Fix missing Send bound in type Data: Send
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: device: make Core and CoreInternal lifetime-parameterized
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: pci: make Bar lifetime-parameterized
rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
samples: rust: rust_driver_pci: use HRT lifetime for Bar
gpu: nova-core: separate driver type from driver data
rust: auxiliary: generalize Registration over ForLt
samples: rust: rust_driver_auxiliary: showcase lifetime-bound
registration data
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 | 52 ++--- drivers/gpu/nova-core/fb.rs | 31 ++- drivers/gpu/nova-core/gpu.rs | 38 ++-- 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 | 142 +++++++++---- rust/kernel/cpufreq.rs | 9 +- rust/kernel/device.rs | 61 ++++-- rust/kernel/devres.rs | 2 +- rust/kernel/dma.rs | 2 +- rust/kernel/driver.rs | 41 ++-- rust/kernel/i2c.rs | 61 +++--- rust/kernel/io/mem.rs | 121 ++++++------ rust/kernel/pci.rs | 51 +++-- rust/kernel/pci/id.rs | 2 +- rust/kernel/pci/io.rs | 50 ++--- rust/kernel/platform.rs | 52 ++--- rust/kernel/types.rs | 12 +- rust/kernel/types/for_lt.rs | 117 +++++++++++ rust/kernel/usb.rs | 61 +++--- rust/macros/for_lt.rs | 274 ++++++++++++++++++++++++++ rust/macros/lib.rs | 12 ++ samples/rust/rust_debugfs.rs | 11 +- samples/rust/rust_dma.rs | 6 +- samples/rust/rust_driver_auxiliary.rs | 79 +++++--- 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 | 17 +- samples/rust/rust_i2c_client.rs | 14 +- samples/rust/rust_soc.rs | 9 +- 40 files changed, 1095 insertions(+), 511 deletions(-) create mode 100644 rust/kernel/types/for_lt.rs create mode 100644 rust/macros/for_lt.rs
base-commit: 454257f6d124a92342dcbb7710c03dd6ef96c731
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v4 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
[email protected]
AI reviewRe: [PATCH v4 01/27] rust: alloc: remove `'static` bound on `ForeignOwnable`
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] Removing the `'static` bound on `Box` and `Pin<Box>` implementations of `ForeignOwnable`…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] Removing the 'static bound on Box and Pin<Box> implementations of ForeignOwnable allows safe Rust code to cause use-after-free vulnerabilities by passing short-lived references to long-lived C subsystems.
- [Low] The commit lifts the 'static requirement from the ForeignOwnable trait for Box implementations but fails to apply it uniformly, leaving Arc<T> inconsistently restricted.
--
commit 3010ad31fe43876a42708e20baf90c11f6c4ba78
Author: Gary Guo <[email protected]>
rust: alloc: remove 'static bound on ForeignOwnable
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.
Quoted 4 lines
rust/kernel/alloc/kbox.rs +0
-0
[ ... ]
rust/kernel/alloc/kbox.rs fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> · line 480
Quoted 6 lines
rust/kernel/alloc/kbox.rs +1
-1@@ -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 >
[Severity: Critical]
Does removing the 'static bound here allow safe Rust code to cause use-after-free vulnerabilities by passing short-lived references to long-lived C subsystems?
For example, GenDiskBuilder::build accepts a generic Operations type T, takes its QueueData, and stores it in the C subsystem via ForeignOwnable::into_foreign. Previously, the 'static bound implicitly ensured QueueData did not contain local references.
If safe code constructs a GenDisk using a Box holding stack references, and then that GenDisk is leaked via core::mem::forget(disk), the block device would remain registered in C while the stack frame ends.
When the C callback queue_rq executes asynchronously, could it dereference a dangling pointer resulting in a use-after-free?
[Severity: Low]
This isn't a bug, but should the 'static bound on Arc<T> in rust/kernel/sync/arc.rs also be removed for consistency?
The commit message implies lifting the 'static requirement generally, but it appears Arc<T> still retains its explicit unsafe impl<T: 'static> ForeignOwnable for Arc<T> implementation.
Quoted 3 lines
rust/kernel/alloc/kbox.rs +0
-0where A: Allocator, {
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Danilo Krummrich
maintainerPATCH v4 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 v4 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 | 24 +++++++++++--------- rust/kernel/i2c.rs | 32 +++++++++++++++------------ rust/kernel/io/mem.rs | 2 ++ rust/kernel/pci.rs | 21 +++++++++++------- rust/kernel/platform.rs | 20 ++++++++++------- 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, 98 insertions(+), 55 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 :Send ; +/// 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 +14 -10
@@ -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; +//! //! /// 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 +18 -14
@@ -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,15 +302,15 @@ 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>) { /// } /// } ///``` -pub trait Driver :Send { +pub trait Driver {/// The type holding information about each device id supported by the driver. // TODO: Use `associated_type_defaults` once stabilized: //
@@ -318,6 +319,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data :Send ; +/// 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 +13 -8
@@ -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(
@@ -291,7 +292,7 @@ macro_rules! pci_device_table {///``` /// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the /// `Adapter` documentation for an example. -pub trait Driver :Send { +pub trait Driver {/// The type holding information about each device id supported by the driver. // TODO: Use `associated_type_defaults` once stabilized: //
@@ -300,6 +301,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data :Send ; +/// 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 +12 -8
@@ -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); ///
@@ -203,7 +204,7 @@ macro_rules! module_platform_driver {/// } /// } ///``` -pub trait Driver :Send { +pub trait Driver {/// The type holding driver private data about each device id supported by the driver. // TODO: Use associated_type_defaults once stabilized: //
@@ -212,6 +213,9 @@ pub trait Driver: Send {// ``` type IdInfo : 'static; +/// The type of the driver's bus device private data. +type Data :Send ; +/// 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 :Send ; +/// 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
[email protected]
AI reviewRe: [PATCH v4 03/27] rust: driver: decouple driver private data from driver type
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The commit message explicitly states that the patch adds a `Data<'bound>` associated type, but…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The commit message explicitly states that the patch adds a Data<'bound> associated type, but the implementation only adds a standard associated type type Data: Send;. --
commit 36c9216be2c21a3bf349085eb24629f94228e6bd
Author: Danilo Krummrich <[email protected]>
rust: driver: decouple driver private data from driver type
This commit adds a Data associated type to bus driver traits, decoupling the driver's device private data type from the driver struct itself. It updates existing drivers to use type Data = Self to preserve current behavior.
Quoted 10 lines
rust: driver: decouple driver private data from driver type
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.
[Severity: Medium]
Is the commit message accurate for this patch?
The commit message explicitly states that the patch adds a Data<'bound> associated type and details the advantages of the 'bound lifetime parameter. However, the implementation in this patch only adds a standard associated type (type Data: Send;) without the 'bound lifetime parameter.
Could this part of the commit message have been intended for a later patch in the series where the lifetime parameter is actually introduced?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Danilo Krummrich
maintainerPATCH v4 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
[email protected]
AI reviewRe: [PATCH v4 04/27] rust: driver core: drop drvdata before devres release
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] Reordering `post_unbind_rust` before `devres_release_all` violates LIFO resource management…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Reordering post_unbind_rust before devres_release_all violates LIFO resource management and introduces a critical Use-After-Free (UAF) vulnerability for drivers. --
commit 13c328caac1fcbff52dab3f760a99e254b3f15b9
Author: Danilo Krummrich <[email protected]>
rust: driver core: drop drvdata before devres release
This commit moves the post_unbind_rust callback before devres_release_all() in device_unbind_cleanup(). This allows Rust driver structs to hold direct references to devres-managed resources by ensuring the driver's device private data is dropped before devres actions are released.
drivers/base/dd.c static DEVICE_ATTR_RW(state_synced); · line 598
Quoted 11 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);
[Severity: Critical]
Does this reordering introduce a use-after-free for devres cleanup actions or active interrupts?
By executing post_unbind_rust() and freeing the driver data before devres_release_all() is called, devm-managed resources are still active while the driver data is gone. If a hardware interrupt or timer fires in this window, or if a custom devm_add_action cleanup callback relies on a context pointer to the driver data, won't it attempt to access freed memory?
To safely accommodate the lifetime requirements, should the driver data instead be modeled as a devres resource itself so it is dropped at the correct point in the unbind sequence?
Quoted 1 line
drivers/base/dd.c +0
-0arch_teardown_dma_ops (dev);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Danilo Krummrich
maintainerPATCH v4 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 v4 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 v4 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 v4 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
[email protected]
AI reviewRe: [PATCH v4 08/27] rust: usb: implement Sync for Device<Bound>
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The patch completely fails to achieve its stated goal for USB drivers due to subsystem…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The patch completely fails to achieve its stated goal for USB drivers due to subsystem architectural mismatches (private types and missing trait implementations).
- [Medium] Piecemeal typestate trait implementations for thread-safety instead of generic blanket implementations.
--
commit f4c2e06f2819d0d1a95f07b0e3275550140ba681
Author: Danilo Krummrich <[email protected]>
rust: usb: implement Sync for Device<Bound>
This commit implements the Sync trait for Device<Bound> in the USB subsystem. The goal is to allow drivers to safely store bound USB device references inside their private data structures.
Quoted 2 lines
This is needed for drivers to store &'bound usb::Device<Bound> in their private data while remaining Send.
[Severity: High]
Does this change actually allow drivers to store the device in their private data?
Currently, usb::Device is strictly private to the kernel::usb module, so external drivers cannot declare fields of this type. Even if it were public, AsRef<Device> for Interface<Ctx> returns &usb::Device<Normal>, which discards the typestate context and prevents drivers from obtaining a Bound reference.
Additionally, drivers in the USB subsystem typically bind to and receive &usb::Interface rather than usb::Device. Would we also need to add Sync to usb::Interface<Bound> so that drivers can store the interface they receive?
Quoted 4 lines
rust/kernel/usb.rs +0
-0
[ ... ]
rust/kernel/usb.rs unsafe impl Send for Device {} · line 473
Quoted 7 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 > {}
[Severity: Medium]
Would it be more robust to use a generic blanket implementation for thread safety instead of piecemeal implementations for specific contexts?
The thread safety of usb::Device depends on the underlying C pointer rather than the zero-sized PhantomData marker. By implementing Sync manually for each context, this omits Send for Device<Bound> and leaves other valid contexts like Core and CoreInternal without Sync implementations.
Could we use something like this instead?
unsafe impl<Ctx: device::DeviceContext> Sync for Device<Ctx> {}
This would ensure correct system-wide thread safety for all typestates.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Danilo Krummrich
maintainerPATCH v4 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 v4 10/27 rust: device: make Core and CoreInternal lifetime-parameterized
In reply to Danilo KrummrichDevice<Core> references in probe callbacks are scoped to the callback, not the full binding duration. Add a lifetime parameter to Core and CoreInternal to accurately represent this in the type system.
--- drivers/cpufreq/rcpufreq_dt.rs | 2 +- drivers/gpu/drm/nova/driver.rs | 5 ++- drivers/gpu/drm/tyr/driver.rs | 2 +- drivers/gpu/nova-core/driver.rs | 4 +-- drivers/gpu/nova-core/gpu.rs | 2 +- drivers/pwm/pwm_th1520.rs | 2 +- rust/kernel/auxiliary.rs | 12 ++++--- rust/kernel/cpufreq.rs | 2 +- rust/kernel/device.rs | 49 +++++++++++++++++++++------ rust/kernel/devres.rs | 2 +- rust/kernel/dma.rs | 2 +- rust/kernel/driver.rs | 6 ++-- rust/kernel/i2c.rs | 16 ++++----- rust/kernel/io/mem.rs | 4 +-- rust/kernel/pci.rs | 20 ++++++----- rust/kernel/pci/id.rs | 2 +- rust/kernel/platform.rs | 12 +++---- rust/kernel/usb.rs | 16 ++++----- samples/rust/rust_debugfs.rs | 4 +-- samples/rust/rust_dma.rs | 2 +- samples/rust/rust_driver_auxiliary.rs | 7 ++-- samples/rust/rust_driver_i2c.rs | 6 ++-- samples/rust/rust_driver_pci.rs | 4 +-- samples/rust/rust_driver_platform.rs | 2 +- samples/rust/rust_driver_usb.rs | 8 ++--- samples/rust/rust_i2c_client.rs | 4 +-- samples/rust/rust_soc.rs | 2 +- 27 files changed, 118 insertions(+), 81 deletions(-)
drivers/cpufreq/rcpufreq_dt.rs +1 -1
@@ -205,7 +205,7 @@ impl platform::Driver for CPUFreqDTDriver {const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );fn probe ( - pdev: &platform::Device <Core >, + pdev: &platform::Device <Core <'_>>, _id_info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > { cpufreq::Registration ::<CPUFreqDTDriver >::new_foreign_owned (pdev.as_ref ())?;
drivers/gpu/drm/nova/driver.rs +4 -1
@@ -54,7 +54,10 @@ impl auxiliary::Driver for NovaDriver {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 > { +fn probe ( + adev: &auxiliary::Device <Core <'_>>, + _info: &Self ::IdInfo , + ) ->impl PinInit <Self ,Error > {let data =try_pin_init! (NovaData { adev: adev.into () });let drm = drm::Device ::<Self >::new (adev.as_ref (), data)?;
drivers/gpu/drm/tyr/driver.rs +1 -1
@@ -95,7 +95,7 @@ impl platform::Driver for TyrPlatformDriverData {const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );fn probe ( - pdev: &platform::Device <Core >, + pdev: &platform::Device <Core <'_>>, _info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {let core_clk =Clk ::get (pdev.as_ref (),Some (c"core" ))?;
drivers/gpu/nova-core/driver.rs +2 -2
@@ -77,7 +77,7 @@ impl pci::Driver for NovaCore {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 > { +fn probe (pdev: &pci::Device <Core <'_>>, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { pin_init::pin_init_scope (move || {dev_dbg! (pdev,"Probe Nova Core GPU driver.\n" );
@@ -109,7 +109,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 (pdev: &pci::Device <Core <'_>>, this:Pin <&Self >) { this.gpu.unbind (pdev.as_ref ()); } }
drivers/gpu/nova-core/gpu.rs +1 -1
@@ -278,7 +278,7 @@ pub(crate) fn new<'a>(/// 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 >) { +pub (crate )fn unbind (&self, dev: &device::Device <device::Core <'_>>) { kernel::warn_on!(self .bar .access (dev)
drivers/pwm/pwm_th1520.rs +1 -1
@@ -320,7 +320,7 @@ impl platform::Driver for Th1520PwmPlatformDriver {const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );fn probe ( - pdev: &platform::Device <Core >, + pdev: &platform::Device <Core <'_>>, _id_info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {let dev = pdev.as_ref ();
rust/kernel/auxiliary.rs +7 -5
@@ -87,7 +87,7 @@ extern "C" fn probe_callback(// `struct auxiliary_device`. // // INVARIANT: `adev` is valid for the duration of `probe_callback()`. -let adev =unsafe { &*adev.cast ::<Device <device::CoreInternal >>() }; +let adev =unsafe { &*adev.cast ::<Device <device::CoreInternal <'_>>>() };// SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id` // and does not add additional invariants, so it's safe to transmute.
@@ -107,7 +107,7 @@ extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {// `struct auxiliary_device`. // // INVARIANT: `adev` is valid for the duration of `remove_callback()`. -let adev =unsafe { &*adev.cast ::<Device <device::CoreInternal >>() }; +let adev =unsafe { &*adev.cast ::<Device <device::CoreInternal <'_>>>() };// 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
@@ -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 ( + dev: &Device <device::Core <'_>>, + id_info: &Self ::IdInfo , + ) ->impl PinInit <Self ::Data ,Error >;/// 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 (dev: &Device <device::Core <'_>>, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
rust/kernel/cpufreq.rs +1 -1
@@ -892,7 +892,7 @@ fn register_em(_policy: &mut Policy) {/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; /// /// fn probe( -/// pdev: &platform::Device<Core>, +/// pdev: &platform::Device<Core<'_>>, /// _id_info: Option<&Self::IdInfo>, /// ) -> impl PinInit<Self, Error> { /// cpufreq::Registration::<SampleDriver>::new_foreign_owned(pdev.as_ref())?;
rust/kernel/device.rs +38 -11
107 lines not on this page · raw message
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/dma.rs +1 -1
@@ -47,7 +47,7 @@/// where the underlying bus is DMA capable, such as: #[cfg_attr( CONFIG_PCI , doc = "* [`pci::Device`](kernel::pci::Device)" )] /// * [`platform::Device`](::kernel::platform::Device) -pub trait Device :AsRef <device::Device <Core >> { +pub trait Device <'a>:AsRef <device::Device <Core <'a>>> {/// Set up the device's DMA streaming addressing capabilities. /// /// This method is usually called once from `probe()` as soon as the device capabilities are
rust/kernel/driver.rs +3 -3
@@ -27,11 +27,11 @@//! const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None; //! //! /// Driver probe. -//! fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) +//! 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::Data>) { +//! fn unbind(dev: &Device<device::Core<'_>>, this: Pin<&Self::Data>) { //! let _ = (dev, this); //! } //! }
@@ -191,7 +191,7 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::device) {// a `struct device`. // // INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`. -let dev =unsafe { &*dev.cast ::<device::Device <device::CoreInternal >>() }; +let dev =unsafe { &*dev.cast ::<device::Device <device::CoreInternal <'_>>>() };// `remove()` has been completed at this point; devres resources are still valid and will // be released after the driver's bus device private data is dropped.
rust/kernel/i2c.rs +8 -8
@@ -157,7 +157,7 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_// `struct i2c_client`. // // INVARIANT: `idev` is valid for the duration of `probe_callback()`. -let idev =unsafe { &*idev.cast ::<I2cClient <device::CoreInternal >>() }; +let idev =unsafe { &*idev.cast ::<I2cClient <device::CoreInternal <'_>>>() };let info =Self ::i2c_id_info (idev).or_else (|| <Self as driver::Adapter >::id_info (idev.as_ref ()));
@@ -172,7 +172,7 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_extern "C" fn remove_callback (idev: *mut bindings::i2c_client ) {// SAFETY: `idev` is a valid pointer to a `struct i2c_client`. -let idev =unsafe { &*idev.cast ::<I2cClient <device::CoreInternal >>() }; +let idev =unsafe { &*idev.cast ::<I2cClient <device::CoreInternal <'_>>>() };// SAFETY: `remove_callback` is only ever called after a successful call to // `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called
@@ -184,7 +184,7 @@ extern "C" fn remove_callback(idev: *mut bindings::i2c_client) {extern "C" fn shutdown_callback (idev: *mut bindings::i2c_client ) {// SAFETY: `shutdown_callback` is only ever called for a valid `idev` -let idev =unsafe { &*idev.cast ::<I2cClient <device::CoreInternal >>() }; +let idev =unsafe { &*idev.cast ::<I2cClient <device::CoreInternal <'_>>>() };// SAFETY: `shutdown_callback` is only ever called after a successful call to // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
@@ -300,13 +300,13 @@ macro_rules! module_i2c_driver {/// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE); /// /// fn probe( -/// _idev: &i2c::I2cClient<Core>, +/// _idev: &i2c::I2cClient<Core<'_>>, /// _id_info: Option<&Self::IdInfo>, /// ) -> impl PinInit<Self::Data, Error> { /// Err(ENODEV) /// } /// -/// fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self::Data>) { +/// fn shutdown(_idev: &i2c::I2cClient<Core<'_>>, this: Pin<&Self::Data>) { /// } /// } ///```
@@ -336,7 +336,7 @@ pub trait Driver {/// Called when a new i2c client is added or discovered. /// Implementers should attempt to initialize the client here. fn probe ( - dev: &I2cClient <device::Core >, + dev: &I2cClient <device::Core <'_>>, id_info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ::Data ,Error >;
@@ -351,7 +351,7 @@ fn probe(/// This callback is distinct from final resource cleanup, as the driver instance remains valid /// after it returns. Any deallocation or teardown of driver-owned resources should instead be /// handled in `Drop`. -fn shutdown (dev: &I2cClient <device::Core >, this:Pin <&Self ::Data >) { +fn shutdown (dev: &I2cClient <device::Core <'_>>, this:Pin <&Self ::Data >) {let _ = (dev, this); }
@@ -365,7 +365,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 (dev: &I2cClient <device::Core <'_>>, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
rust/kernel/io/mem.rs +2 -2
@@ -65,7 +65,7 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S/// # type Data = Self; /// /// fn probe( -/// pdev: &platform::Device<Core>, +/// pdev: &platform::Device<Core<'_>>, /// info: Option<&Self::IdInfo>, /// ) -> impl PinInit<Self, Error> { /// let offset = 0; // Some offset.
@@ -130,7 +130,7 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(/// # type Data = Self; /// /// fn probe( -/// pdev: &platform::Device<Core>, +/// pdev: &platform::Device<Core<'_>>, /// info: Option<&Self::IdInfo>, /// ) -> impl PinInit<Self, Error> { /// let offset = 0; // Some offset.
rust/kernel/pci.rs +11 -9
@@ -105,7 +105,7 @@ extern "C" fn probe_callback(// `struct pci_dev`. // // INVARIANT: `pdev` is valid for the duration of `probe_callback()`. -let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal >>() }; +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() };// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct pci_device_id` and // does not add additional invariants, so it's safe to transmute.
@@ -125,7 +125,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {// `struct pci_dev`. // // INVARIANT: `pdev` is valid for the duration of `remove_callback()`. -let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal >>() }; +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() };// 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
@@ -283,7 +283,7 @@ macro_rules! pci_device_table {/// const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; /// /// fn probe( -/// _pdev: &pci::Device<Core>, +/// _pdev: &pci::Device<Core<'_>>, /// _id_info: &Self::IdInfo, /// ) -> impl PinInit<Self, Error> { /// Err(ENODEV)
@@ -311,8 +311,10 @@ pub trait Driver {/// /// 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 ( + dev: &Device <device::Core <'_>>, + id_info: &Self ::IdInfo , + ) ->impl PinInit <Self ::Data ,Error >;/// 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 (dev: &Device <device::Core <'_>>, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
@@ -359,7 +361,7 @@ impl Device {/// /// ``` /// # use kernel::{device::Core, pci::{self, Vendor}, prelude::*}; -/// fn log_device_info(pdev: &pci::Device<Core>) -> Result { +/// fn log_device_info(pdev: &pci::Device<Core<'_>>) -> Result { /// // Get an instance of `Vendor`. /// let vendor = pdev.vendor_id(); /// dev_info!(
@@ -450,7 +452,7 @@ pub fn pci_class(&self) -> Class { } } -impl Device <device::Core > { +impl <'a>Device <device::Core <'a>> {/// Enable memory resources for this device. pub fn enable_device_mem (&self) ->Result {// SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
@@ -476,7 +478,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> kernel::impl_device_context_deref!(unsafe {Device }); kernel::impl_device_context_into_aref!(Device ); -impl crate ::dma::Device for Device <device::Core > {} +impl <'a>crate ::dma::Device <'a>for Device <device::Core <'a>> {}// SAFETY: Instances of `Device` are always reference-counted. unsafe impl crate ::sync::aref::AlwaysRefCounted for Device {
rust/kernel/pci/id.rs +1 -1
@@ -19,7 +19,7 @@/// /// ``` /// # use kernel::{device::Core, pci::{self, Class}, prelude::*}; -/// fn probe_device(pdev: &pci::Device<Core>) -> Result { +/// fn probe_device(pdev: &pci::Device<Core<'_>>) -> Result { /// let pci_class = pdev.pci_class(); /// dev_info!( /// pdev,
rust/kernel/platform.rs +6 -6
@@ -97,7 +97,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff// `struct platform_device`. // // INVARIANT: `pdev` is valid for the duration of `probe_callback()`. -let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal >>() }; +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() };let info = <Self as driver::Adapter >::id_info (pdev.as_ref ());from_result (|| {
@@ -113,7 +113,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {// `struct platform_device`. // // INVARIANT: `pdev` is valid for the duration of `remove_callback()`. -let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal >>() }; +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() };// 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
@@ -197,7 +197,7 @@ macro_rules! module_platform_driver {/// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE); /// /// fn probe( -/// _pdev: &platform::Device<Core>, +/// _pdev: &platform::Device<Core<'_>>, /// _id_info: Option<&Self::IdInfo>, /// ) -> impl PinInit<Self, Error> { /// Err(ENODEV)
@@ -227,7 +227,7 @@ pub trait Driver {/// Called when a new platform device is added or discovered. /// Implementers should attempt to initialize the device here. fn probe ( - dev: &Device <device::Core >, + dev: &Device <device::Core <'_>>, id_info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ::Data ,Error >;
@@ -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 (dev: &Device <device::Core <'_>>, this:Pin <&Self ::Data >) {let _ = (dev, this); } }
@@ -513,7 +513,7 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> { kernel::impl_device_context_deref!(unsafe {Device }); kernel::impl_device_context_into_aref!(Device ); -impl crate ::dma::Device for Device <device::Core > {} +impl <'a>crate ::dma::Device <'a>for Device <device::Core <'a>> {}// SAFETY: Instances of `Device` are always reference-counted. unsafe impl crate ::sync::aref::AlwaysRefCounted for Device {
rust/kernel/usb.rs +8 -8
@@ -82,7 +82,7 @@ extern "C" fn probe_callback(// `struct usb_interface` and `struct usb_device_id`. // // INVARIANT: `intf` is valid for the duration of `probe_callback()`. -let intf =unsafe { &*intf.cast ::<Interface <device::CoreInternal >>() }; +let intf =unsafe { &*intf.cast ::<Interface <device::CoreInternal <'_>>>() };from_result (|| {// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct usb_device_id` and
@@ -92,7 +92,7 @@ extern "C" fn probe_callback(let info =T ::ID_TABLE .info (id.index ());let data =T ::probe (intf, id, info); -let dev: &device::Device <device::CoreInternal > = intf.as_ref (); +let dev: &device::Device <device::CoreInternal <'_>> = intf.as_ref (); dev.set_drvdata (data)?;Ok (0 ) })
@@ -103,9 +103,9 @@ extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) {// `struct usb_interface`. // // INVARIANT: `intf` is valid for the duration of `disconnect_callback()`. -let intf =unsafe { &*intf.cast ::<Interface <device::CoreInternal >>() }; +let intf =unsafe { &*intf.cast ::<Interface <device::CoreInternal <'_>>>() }; -let dev: &device::Device <device::CoreInternal > = intf.as_ref (); +let dev: &device::Device <device::CoreInternal <'_>> = intf.as_ref ();// SAFETY: `disconnect_callback` is only ever called after a successful call to // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
@@ -291,14 +291,14 @@ macro_rules! usb_device_table {/// const ID_TABLE: usb::IdTable<Self::IdInfo> = &USB_TABLE; /// /// fn probe( -/// _interface: &usb::Interface<Core>, +/// _interface: &usb::Interface<Core<'_>>, /// _id: &usb::DeviceId, /// _info: &Self::IdInfo, /// ) -> impl PinInit<Self::Data, Error> { /// Err(ENODEV) /// } /// -/// fn disconnect(_interface: &usb::Interface<Core>, _data: Pin<&Self::Data>) {} +/// fn disconnect(_interface: &usb::Interface<Core<'_>>, _data: Pin<&Self::Data>) {} /// } ///``` pub trait Driver {
@@ -316,7 +316,7 @@ 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 >, + interface: &Interface <device::Core <'_>>, id: &DeviceId , id_info: &Self ::IdInfo , ) ->impl PinInit <Self ::Data ,Error >;
@@ -324,7 +324,7 @@ fn probe(/// 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 (interface: &Interface <device::Core <'_>>, data:Pin <&Self ::Data >); }/// A USB interface.
samples/rust/rust_debugfs.rs +2 -2
@@ -122,7 +122,7 @@ impl platform::Driver for RustDebugFs {const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );fn probe ( - pdev: &platform::Device <Core >, + pdev: &platform::Device <Core <'_>>, _info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {RustDebugFs ::new (pdev).pin_chain (|this| {
@@ -147,7 +147,7 @@ fn build_inner(dir: &Dir) -> impl PinInit<File<Mutex<Inner>>> + '_ { dir.read_write_file (c"pair" ,new_mutex! (Inner { x:3 , y:10 })) } -fn new (pdev: &platform::Device <Core >) ->impl PinInit <Self ,Error > + '_ { +fn new <'a>(pdev: &'a platform::Device <Core <'_>>) ->impl PinInit <Self ,Error > + 'a {let debugfs =Dir ::new (c"sample_debugfs" );let dev = pdev.as_ref ();
samples/rust/rust_dma.rs +1 -1
@@ -61,7 +61,7 @@ impl pci::Driver for DmaSampleDriver {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 > { +fn probe (pdev: &pci::Device <Core <'_>>, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { pin_init::pin_init_scope (move || {dev_info! (pdev,"Probe DMA test driver.\n" );
samples/rust/rust_driver_auxiliary.rs +5 -2
@@ -35,7 +35,10 @@ impl auxiliary::Driver for AuxiliaryDriver {const ID_TABLE : auxiliary::IdTable <Self ::IdInfo > = &AUX_TABLE ; -fn probe (adev: &auxiliary::Device <Core >, _info: &Self ::IdInfo ) ->impl PinInit <Self ,Error > { +fn probe ( + adev: &auxiliary::Device <Core <'_>>, + _info: &Self ::IdInfo , + ) ->impl PinInit <Self ,Error > {dev_info! ( adev,"Probing auxiliary driver for auxiliary device with id={}\n" ,
@@ -70,7 +73,7 @@ impl pci::Driver for ParentDriver { const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe(pdev: &pci::Device<Core<'_>>, _info: &Self::IdInfo) -> impl PinInit<Self, Error> { Ok(Self { _reg0: auxiliary::Registration::new( pdev.as_ref(),
samples/rust/rust_driver_i2c.rs +3 -3
@@ -42,7 +42,7 @@ impl i2c::Driver for SampleDriver {const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE );fn probe ( - idev: &i2c::I2cClient <Core >, + idev: &i2c::I2cClient <Core <'_>>, info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {let dev = idev.as_ref ();
@@ -56,11 +56,11 @@ fn probe(Ok (Self ) } -fn shutdown (idev: &i2c::I2cClient <Core >, _this:Pin <&Self >) { +fn shutdown (idev: &i2c::I2cClient <Core <'_>>, _this:Pin <&Self >) {dev_info! (idev.as_ref (),"Shutdown Rust I2C driver sample.\n" ); } -fn unbind (idev: &i2c::I2cClient <Core >, _this:Pin <&Self >) { +fn unbind (idev: &i2c::I2cClient <Core <'_>>, _this:Pin <&Self >) {dev_info! (idev.as_ref (),"Unbind Rust I2C driver sample.\n" ); } }
samples/rust/rust_driver_pci.rs +2 -2
@@ -144,7 +144,7 @@ impl pci::Driver for SampleDriver { const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; - fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Error> { + fn probe(pdev: &pci::Device<Core<'_>>, info: &Self::IdInfo) -> impl PinInit<Self, Error> { pin_init::pin_init_scope(move || { let vendor = pdev.vendor_id(); dev_dbg!(
@@ -175,7 +175,7 @@ fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Er }) } -fn unbind (pdev: &pci::Device <Core >, this:Pin <&Self >) { +fn unbind (pdev: &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));
samples/rust/rust_driver_platform.rs +1 -1
@@ -106,7 +106,7 @@ impl platform::Driver for SampleDriver {const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );fn probe ( - pdev: &platform::Device <Core >, + pdev: &platform::Device <Core <'_>>, info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {let dev = pdev.as_ref ();
samples/rust/rust_driver_usb.rs +4 -4
@@ -30,18 +30,18 @@ impl usb::Driver for SampleDriver {const ID_TABLE : usb::IdTable <Self ::IdInfo > = &USB_TABLE ;fn probe ( - intf: &usb::Interface <Core >, + intf: &usb::Interface <Core <'_>>, _id: &usb::DeviceId , _info: &Self ::IdInfo , ) ->impl PinInit <Self ,Error > { -let dev: &device::Device <Core > = intf.as_ref (); +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 >) { -let dev: &device::Device <Core > = intf.as_ref (); +fn disconnect (intf: &usb::Interface <Core <'_>>, _data:Pin <&Self >) { +let dev: &device::Device <Core <'_>> = intf.as_ref ();dev_info! (dev,"Rust USB driver sample disconnected\n" ); } }
samples/rust/rust_i2c_client.rs +2 -2
@@ -111,7 +111,7 @@ impl platform::Driver for SampleDriver {const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );fn probe ( - pdev: &platform::Device <device::Core >, + pdev: &platform::Device <device::Core <'_>>, _info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {dev_info! (
@@ -130,7 +130,7 @@ fn probe( }) } -fn unbind (pdev: &platform::Device <device::Core >, _this:Pin <&Self >) { +fn unbind (pdev: &platform::Device <device::Core <'_>>, _this:Pin <&Self >) {dev_info! ( pdev.as_ref (),"Unbind Rust I2C Client registration sample.\n"
samples/rust/rust_soc.rs +1 -1
@@ -42,7 +42,7 @@ impl platform::Driver for SampleSocDriver {const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE );fn probe ( - pdev: &platform::Device <Core >, + pdev: &platform::Device <Core <'_>>, _info:Option <&Self ::IdInfo >, ) ->impl PinInit <Self ,Error > {dev_dbg! (pdev,"Probe Rust SoC driver sample.\n" );
Signature · 1 line
2.54.0
Re: [PATCH v4 10/27] rust: device: make Core and CoreInternal lifetime-parameterized
Quoted 7 lines · Danilo Krummrich
Device<Core> references in probe callbacks are scoped to the callback, not the full binding duration. Add a lifetime parameter to Core and CoreInternal to accurately represent this in the type system.
Suggested-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v4 10/27] rust: device: make Core and CoreInternal lifetime-parameterized
In reply to Danilo KrummrichQuoted 6 lines · Danilo Krummrich
Device<Core> references in probe callbacks are scoped to the callback, not the full binding duration. Add a lifetime parameter to Core and CoreInternal to accurately represent this in the type system.
Suggested-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerPATCH v4 11/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 | 26 +++++++++++++------------- 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(+), 22 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<Sel }) } -fn unbind (pdev: &pci::Device <Core <'_>>, this:Pin <&Self >) { +fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self >) { this.gpu.unbind (pdev.as_ref ()); } }
rust/kernel/pci.rs +13 -13
@@ -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 {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data :Send ; +type Data <'bound>:Send + 'bound;/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -311,10 +311,10 @@ pub trait Driver {/// /// 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. ///
@@ -326,7 +326,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 <&Self ::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
@@ -69,11 +69,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
[email protected]
AI reviewRe: [PATCH v4 11/27] rust: pci: make Driver trait lifetime-parameterized
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Outdated type reference in SAFETY comment. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Outdated type reference in SAFETY comment.
--
commit 45872ca21486aeb451f739fb1f9f5058f15c7ed8
Author: Danilo Krummrich <[email protected]>
rust: pci: make Driver trait lifetime-parameterized
This commit adds a 'bound lifetime parameter to the Data associated type of the pci::Driver trait, changing it to Data<'bound>. It updates the probe() and unbind() callbacks to use this lifetime parameter, allowing drivers to store bus device private data with a bounded lifetime directly by reference rather than requiring Devres.
Quoted 4 lines
rust/kernel/pci.rs +0
-0
[ ... ]
rust/kernel/pci.rs extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) { · line 132
Quoted 4 lines
rust/kernel/pci.rs +0
-0@@ -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>>`.
[Severity: Low]
This isn't a bug, but should this SAFETY comment be updated to reflect the new lifetime parameterization and use Pin<KBox<T::Data<'_>>>?
Quoted 5 lines
rust/kernel/pci.rs +1
-1-let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data >() }; +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() };T ::unbind (pdev, data); }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Danilo Krummrich
maintainerPATCH v4 12/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 {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data :Send ; +type Data <'bound>:Send + '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 {/// /// 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 <&Self ::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 <&Self ::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 v4 13/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 | 10 +++++----- rust/kernel/auxiliary.rs | 16 ++++++++-------- samples/rust/rust_driver_auxiliary.rs | 10 +++++----- 3 files changed, 18 insertions(+), 18 deletions(-)
drivers/gpu/drm/nova/driver.rs +5 -5
@@ -51,13 +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 -8
@@ -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 :Send ; +type Data <'bound>:Send + 'bound;/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >;
@@ -211,10 +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. ///
@@ -226,7 +226,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 <&Self ::Data <'bound>>) {let _ = (dev, this); } }
samples/rust/rust_driver_auxiliary.rs +5 -5
@@ -31,14 +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 v4 14/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<&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 :Send ; +type Data <'bound>:Send + '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 <&Self ::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 <&Self >) {let dev: &device::Device <Core <'_>> = intf.as_ref ();dev_info! (dev,"Rust USB driver sample disconnected\n" ); }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 14/27] rust: usb: make Driver trait lifetime-parameterized
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] The new `'bound` lifetime parameter incorrectly allows drivers to capture and store the…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] The new 'bound lifetime parameter incorrectly allows drivers to capture and store the dynamic usb_device_id pointer (id: &'bound DeviceId), which can be freed by userspace at any time, leading to a Use-After-Free.
- [Critical] The patch relies on unsound lifetime transmutation when storing and retrieving the lifetime-parameterized driver data via drvdata.
- [Low] The commit message incorrectly refers to the unbind() callback instead of disconnect().
- [Low] Stale comments refer to T::Data without its new lifetime parameter.
--
commit ca8bfff774a157ce3cf21956820d617a046e6a08
Author: Danilo Krummrich <[email protected]>
rust: usb: make Driver trait lifetime-parameterized
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.
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.
[Severity: Low]
The commit message states "unbind()", but the usb::Driver trait defines a disconnect() method. Should this say disconnect() instead?
Quoted 4 lines
rust/kernel/usb.rs +0
-0
[ ... ]
rust/kernel/usb.rs extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) { · line 112
Quoted 4 lines
rust/kernel/usb.rs +0
-0@@ -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>>`.
[Severity: Low]
This comment refers to T::Data without the new lifetime parameter. Should it be updated to Pin<KBox<T::Data<'_>>>?
rust/kernel/usb.rs extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) { · line 113
Quoted 2 lines
rust/kernel/usb.rs +1
-1-let data =unsafe { dev.drvdata_borrow ::<T ::Data >() }; +let data =unsafe { dev.drvdata_borrow ::<T ::Data <'_>>() };
[Severity: Critical]
Does this create an unsound lifetime transmutation?
The driver's data T::Data<'a> is instantiated with an ephemeral lifetime 'a in probe_callback and passed to dev.set_drvdata(), erasing it to a raw pointer.
Here, it is retrieved using a new, disjoint ephemeral lifetime. If T::Data is invariant over 'bound (for example, using Mutex<Cell<&'bound T>>), these represent completely different types.
ForeignOwnable::borrow requires an exact type match. Violating this might allow safe Rust code to write a short-lived reference into the driver data during disconnect, which would then dangle when disconnect returns.
Could this lead to a use-after-free when the Drop implementation runs during post_unbind_callback?
[ ... ]
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;
[Severity: Critical]
Can this lead to a use-after-free if userspace removes a dynamic ID?
The probe method receives id: &'bound DeviceId, allowing the driver to capture this reference into its T::Data<'bound>.
However, this id pointer can come from a dynamically allocated struct usb_dynid via usb_match_dynamic_id(). Userspace can trigger remove_id_store() via sysfs, which immediately frees the usb_dynid structure without unbinding existing devices.
If the driver's private data holds this reference, it seems it would be left with a dangling pointer.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Re: [PATCH v4 14/27] rust: usb: make Driver trait lifetime-parameterized
In reply to Danilo KrummrichQuoted 50 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.
Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/usb.rs | 39 +++++++++++++++++++-------------- samples/rust/rust_driver_usb.rs | 14 ++++++------ 2 files changed, 30 insertions(+), 23 deletions(-)rust/kernel/usb.rs +3
-3@@ -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; ///
rust/kernel/usb.rs macro_rules! usb_device_table { · line 297
Quoted 10 lines
rust/kernel/usb.rs +5
-5-/// 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 {
Are we sure that usb::DeviceId can have its lifetime extended to more than the callback lifetime?
if it's guaranteed safe to extend the lifetime, or if not, with removing the 'bound lifetime.
Danilo Krummrich
maintainerPATCH v4 15/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 | 35 ++++++++++++++++++--------------- samples/rust/rust_driver_i2c.rs | 14 ++++++------- 2 files changed, 26 insertions(+), 23 deletions(-)
rust/kernel/i2c.rs +19 -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<&Self::Data<'bound>>, +/// ) { /// } /// } ///```
@@ -320,7 +323,7 @@ pub trait Driver {type IdInfo : 'static;/// The type of the driver's bus device private data. -type Data :Send ; +type Data <'bound>:Send + '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 {/// /// 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,7 @@ fn probe(/// This callback is distinct from final resource cleanup, as the driver instance remains valid /// after it returns. Any deallocation or teardown of driver-owned resources should instead be /// handled in `Drop`. -fn shutdown (dev: &I2cClient <device::Core <'_>>, this:Pin <&Self ::Data >) { +fn shutdown <'bound>(dev: &'boundI2cClient <device::Core <'_>>, this:Pin <&Self ::Data <'bound>>) {let _ = (dev, this); }
@@ -365,7 +368,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 <&Self ::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 <&Self >) {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 <&Self >) {dev_info! (idev.as_ref (),"Unbind Rust I2C driver sample.\n" ); } }
Signature · 1 line
2.54.0
Danilo Krummrich
maintainerPATCH v4 16/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: Send; +//! type Data<'bound>: Send + '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<&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 v4 17/27 rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichConvert pci::Bar<SIZE> to pci::Bar<'a, SIZE>, storing &'a Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized() now returns Result<Bar<'a, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.
Add Bar::into_devres() to consume the bar and register it as a device-managed resource, returning Devres<Bar<'static, SIZE>>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind.
--- drivers/gpu/nova-core/driver.rs | 7 +++-- rust/kernel/devres.rs | 2 +- rust/kernel/pci/io.rs | 50 ++++++++++++++++++--------------- samples/rust/rust_driver_pci.rs | 5 ++-- 4 files changed, 35 insertions(+), 29 deletions(-)
drivers/gpu/nova-core/driver.rs +4 -3
@@ -45,7 +45,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 ,
@@ -92,8 +92,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 +27 -23
101 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
[email protected]
AI reviewRe: [PATCH v4 17/27] rust: pci: make Bar lifetime-parameterized
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] `Bar::into_devres` uses `unsafe { core::mem::transmute(self) }` to artificially erase the…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] Bar::into_devres uses unsafe { core::mem::transmute(self) } to artificially erase the local 'a borrow of the Device, which is unsound and causes a Use-After-Free during Devres destruction.
- [High] The name parameter in iomap_region and iomap_region_sized lacks a 'static or device-bound lifetime constraint, allowing temporary strings to be passed and leading to a dangling pointer in the kernel's resource tree. --
commit 00fb543eb5262d30a44ce3dd81c925a773732bd2
Author: Danilo Krummrich <[email protected]>
rust: pci: make Bar lifetime-parameterized
This patch parameterizes the lifetime of pci::Bar, tying its mapping lifetime directly to the device. It changes iomap_region_sized to return a Bar instead of a Devres, and adds an into_devres method to optionally register it as a device-managed resource with a static lifetime.
Quoted 1 line
rust/kernel/pci/io.rs +0
-0
[ ... ]
Quoted 7 lines
rust/kernel/pci/io.rs +2
-1@@ -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) }; + }
rust/kernel/pci/io.rs unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) { · line 228
Quoted 10 lines
rust/kernel/pci/io.rs +10
-0+ +/// Consume the `Bar` and register it as a device-managed resource. +/// +/// The returned `Devres<Bar<'static, SIZE>>` can outlive the original lifetime `'a`. 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) };
[Severity: Critical]
Is it safe to transmute this lifetime to 'static here?
Since Rust drops struct fields in declaration order, and Devres declares its
dev: ARef<Device> field before its inner: Arc<Inner<T>> data wrapper, dropping a Devres<Bar<'static>> will decrement the Device refcount first.
If this was the last reference, the underlying C struct pci_dev could be freed. When inner then drops, it triggers Bar::drop, which will access the now dangling pdev pointer to call pci_release_region().
Could this lead to memory corruption during error paths or unbinding?
Quoted 4 lines
rust/kernel/pci/io.rs +2
-0+let pdev = bar.pdev; +Devres ::new (pdev.as_ref (), bar) } }
[ ... ]
rust/kernel/pci/io.rs impl Device<device::Bound> { · line 263
Quoted 8 lines
rust/kernel/pci/io.rs +1
-3@@ -252,17 +260,13 @@ impl Device<device::Bound> {pub fn iomap_region_sized <'a,const SIZE :usize >( &'a 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,
[Severity: High]
Does removing the 'a lifetime bound from the name parameter allow temporary strings to be passed?
The underlying C function pci_request_region stores the provided string pointer directly into the name field of the allocated struct resource without making a copy.
If a caller passes a dynamically allocated temporary CString that drops after this function returns, could accessing the kernel's resource tree (for example, by reading /proc/iomem) dereference a freed string pointer?
rust/kernel/pci/io.rs impl Device<device::Bound> { · line 269
Quoted 11 lines
rust/kernel/pci/io.rs +3
-5+ ) -> Result<Bar<'a, 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 <'a>(&'a self, bar:u32 , name: &CStr ) ->Result <Bar <'a>> {
[Severity: High]
This seems to have the same lifetime issue with the name parameter as iomap_region_sized above.
Quoted 3 lines
rust/kernel/pci/io.rs +0
-0self.iomap_region_sized ::<0 >(bar, name) }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
Re: [PATCH v4 17/27] rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichQuoted 78 lines · Danilo Krummrich
Convert pci::Bar<SIZE> to pci::Bar<'a, SIZE>, storing &'a Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized()now returns Result<Bar<'a, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.Add
Bar::into_devres()to consume the bar and register it as a device-managed resource, returning Devres<Bar<'static, SIZE>>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind.Reviewed-by Eliot Courtney <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/driver.rs | 7 +++-- rust/kernel/devres.rs | 2 +- rust/kernel/pci/io.rs | 50 ++++++++++++++++++--------------- samples/rust/rust_driver_pci.rs | 5 ++-- 4 files changed, 35 insertions(+), 29 deletions(-)drivers/gpu/nova-core/driver.rs +4
-3@@ -45,7 +45,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 ,@@ -92,8 +92,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 +1
-4@@ -14,8 +14,7 @@ Mmio, MmioRaw, // }, - prelude::*, - sync::aref::ARef, // + prelude::*, // };use core::{ marker::PhantomData ,@@ -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 <'a,const SIZE :usize =0 > { + pdev: &'aDevice <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 <'a,const SIZE :usize >Bar <'a,SIZE > { +pub (super )fn new (pdev: &'aDevice <device::Bound >, num:u32 , name: &CStr ) ->Result <Self > {
I think Sashiko's comment w.r.t. &CStrs in this patch looks accurate and they should be 'static or at least 'a ish.
still
Gary Guo
reviewerRe: [PATCH v4 17/27] rust: pci: make Bar lifetime-parameterized
Quoted 85 lines · Eliot Courtney
Quoted 84 lines · Danilo Krummrich
Convert pci::Bar<SIZE> to pci::Bar<'a, SIZE>, storing &'a Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized()now returns Result<Bar<'a, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.Add
Bar::into_devres()to consume the bar and register it as a device-managed resource, returning Devres<Bar<'static, SIZE>>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind.Reviewed-by Eliot Courtney <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/driver.rs | 7 +++-- rust/kernel/devres.rs | 2 +- rust/kernel/pci/io.rs | 50 ++++++++++++++++++--------------- samples/rust/rust_driver_pci.rs | 5 ++-- 4 files changed, 35 insertions(+), 29 deletions(-)drivers/gpu/nova-core/driver.rs +4
-3@@ -45,7 +45,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 ,@@ -92,8 +92,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 +3
-4@@ -14,8 +14,7 @@ Mmio, MmioRaw, // }, - prelude::*, - sync::aref::ARef, // + prelude::*, // };use core::{ marker::PhantomData ,@@ -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 <'a,const SIZE :usize =0 > { + pdev: &'aDevice <device::Bound >, io:MmioRaw <SIZE >, num:i32 , }
Quoted 7 lines
rust/kernel/pci/io.rs impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> { · line 155
Quoted 4 lines
rust/kernel/pci/io.rs +2
-2-impl <const SIZE :usize >Bar <SIZE > { -pub (super )fn new (pdev: &Device , num:u32 , name: &CStr ) ->Result <Self > { +impl <'a,const SIZE :usize >Bar <'a,SIZE > { +pub (super )fn new (pdev: &'aDevice <device::Bound >, num:u32 , name: &CStr ) ->Result <Self > {I think Sashiko's comment w.r.t. &CStrs in this patch looks accurate and they should be 'static or at least 'a ish.
It needs to be 'static to be leak-safe.
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH v4 17/27] rust: pci: make Bar lifetime-parameterized
Quoted 9 lines · Gary Guo
Quoted 6 lines · Eliot Courtney
rust/kernel/pci/io.rs impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> { · line 155
Quoted 2 lines · Danilo Krummrich
rust/kernel/pci/io.rs +2
-0+impl <'a,const SIZE :usize >Bar <'a,SIZE > { +pub (super )fn new (pdev: &'aDevice <device::Bound >, num:u32 , name: &CStr ) ->Result <Self > {I think Sashiko's comment w.r.t. &CStrs in this patch looks accurate and they should be 'static or at least 'a ish.
It needs to be
'staticto be leak-safe.
Yes, it needs to be 'static as it is stored directly in struct resource. This has been a bug without this patch already; I will insert a small fix for this, so it can be picked by stable separately.
Thanks,
Danilo
Re: [PATCH v4 17/27] rust: pci: make Bar lifetime-parameterized
In reply to Danilo KrummrichQuoted 5 lines · Danilo Krummrich
Convert pci::Bar<SIZE> to pci::Bar<'a, SIZE>, storing &'a Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized()now returns Result<Bar<'a, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.
A small sentence explaining why that change happens here could be helpful.
Quoted 8 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.Reviewed-by Eliot Courtney <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Alexandre Courbot
maintainerRe: [PATCH v4 17/27] rust: pci: make Bar lifetime-parameterized
Quoted 9 lines · Alexandre Courbot
Quoted 5 lines · Danilo Krummrich
Convert pci::Bar<SIZE> to pci::Bar<'a, SIZE>, storing &'a Device<Bound> to tie the BAR mapping lifetime to the device.
iomap_region_sized()now returns Result<Bar<'a, SIZE>> directly instead of impl PinInit<Devres<Bar<SIZE>>, Error>.A small sentence explaining why that change happens here could be helpful.
... or not - it's clear that the lifetime makes the Devres irrelevant. But mentioning it explicitly can be helpful nonetheless.
Danilo Krummrich
maintainerPATCH v4 18/27 rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
In reply to Danilo KrummrichAdd a lifetime parameter to IoMem<'a, SIZE> and ExclusiveIoMem<'a, SIZE>, storing a &'a Device<Bound> reference to tie the mapping to the device's lifetime.
This mirrors the pci::Bar<'a, SIZE> design and enables drivers to hold I/O memory mappings directly in their HRT private data, tied to the device lifetime.
IoRequest::iomap_* methods now return the mapping directly instead of wrapping it in Devres. Callers that need device-managed revocation can call the new into_devres() method.
--- drivers/gpu/drm/tyr/driver.rs | 4 +- drivers/pwm/pwm_th1520.rs | 4 +- rust/kernel/io/mem.rs | 103 +++++++++++++++++----------------- 3 files changed, 56 insertions(+), 55 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 +52 -51
195 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 18/27] rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] Casting the `IoMem` lifetime to `'static` in `into_devres` bypasses the borrow checker…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] Casting the IoMem lifetime to 'static in into_devres bypasses the borrow checker, allowing I/O memory mappings to outlive the device and causing a Use-After-Free / Kernel Oops.
- [Low] Build failure in pwm_th1520.rs due to incorrect pin initialization syntax and missing error propagation.
--
commit 3931a89b7b114b4dfff952a928271744f2309ac3
Author: Danilo Krummrich <[email protected]>
Subject: rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
This patch adds a lifetime parameter to IoMem and ExclusiveIoMem to tie the mapping to the device's lifetime. It also introduces into_devres() for callers needing device-managed revocation.
Quoted 4 lines
drivers/pwm/pwm_th1520.rs +0
-0
[ ... ]
drivers/pwm/pwm_th1520.rs fn probe<'bound>( · line 358
Quoted 9 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 (), clk <- clk, }), )?;
[Severity: Low]
Will this compile correctly? The refactored into_devres() method returns a Result<Devres<IoMem<'static, SIZE>>> rather than an impl PinInit.
Since the <- operator in try_pin_init! requires the right-hand side to evaluate to an impl PinInit, should this use the : operator instead to initialize it by value? Also, it looks like a trailing ? is missing here to unwrap the Result.
Quoted 4 lines
rust/kernel/io/mem.rs +0
-0
[ ... ]
Quoted 1 line
rust/kernel/io/mem.rs +0
-0@@ -269,28 +265,33 @@ fn ioremap(resource: &Resource) -> Result<Self> {
[ ... ]
Quoted 10 lines
rust/kernel/io/mem.rs +4
-6-/// Creates a new `IoMem` instance from a previously acquired [`IoRequest`]. -pub fn new <'a>(io_request:IoRequest <'a>) ->impl PinInit <Devres <Self >,Error > + 'a { -let dev = io_request.device; -let res = io_request.resource; - -Devres ::new (dev,Self ::ioremap (res)) +/// Consume the `IoMem` and register it as a device-managed resource. +/// +/// The returned `Devres<IoMem<'static, SIZE>>` can outlive the original +/// lifetime `'a`. Access to the I/O memory is revoked when the device
rust/kernel/io/mem.rs fn ioremap(resource: &Resource) -> Result<Self> { · line 285
Quoted 10 lines
rust/kernel/io/mem.rs +8
-0+/// is unbound. +pub fn into_devres (self) ->Result <Devres <IoMem <'static,SIZE >>> { +// SAFETY: Casting to `'static` is sound because `Devres` guarantees the `IoMem` does not +// actually outlive the device -- access is revoked and the resource is released when the +// device is unbound. +let iomem:IoMem <'static,SIZE > =unsafe { core::mem::transmute (self) }; +let dev = iomem.dev; +Devres ::new (dev, iomem) } }
[Severity: Critical]
Does casting the IoMem lifetime to 'static bypass the borrow checker's protections?
Returning a Devres<IoMem<'static, SIZE>> allows safe Rust code to move this value into an Arc (as done in the tyr driver changes) and share it with background threads or workqueues.
Since devres only unmaps the memory (via iounmap) when the device unbinds, but cannot forcefully destroy the Rust object residing in an Arc on another thread, could a background thread still safely call read32() on it?
This would result in a direct read from unmapped memory, potentially causing a use-after-free or kernel oops, since IoMem and MmioRaw do not perform any runtime revocation state checks or locking during access.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
Re: [PATCH v4 18/27] rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized
In reply to Danilo KrummrichQuoted 8 lines · Danilo Krummrich
Add a lifetime parameter to IoMem<'a, SIZE> and ExclusiveIoMem<'a, SIZE>, storing a &'a Device<Bound> reference to tie the mapping to the device's lifetime.
This mirrors the pci::Bar<'a, SIZE> design and enables drivers to hold I/O memory mappings directly in their HRT private data, tied to the device lifetime.
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]>Reviewed-by Eliot Courtney <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerPATCH v4 19/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
[email protected]
AI reviewRe: [PATCH v4 19/27] samples: rust: rust_driver_pci: use HRT lifetime for Bar
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] The `unbind` method signature in `SampleDriver` is incompatible with the `pci::Driver` trait…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The unbind method signature in SampleDriver is incompatible with the pci::Driver trait, resulting in an E0053 compiler error. --
commit 831cba69e4ec48baa461ce6291b9b8ed80543fae
Author: Danilo Krummrich <[email protected]>
samples: rust: rust_driver_pci: use HRT lifetime for Bar
This commit converts the sample driver to SampleDriver<'bound>, taking advantage of the lifetime-parameterized Driver trait. It holds &'bound pci::Device and pci::Bar<'bound> directly, removing PinnedDrop and runtime revocation checks.
Quoted 4 lines
samples/rust/rust_driver_pci.rs +0
-0
[ ... ]
Quoted 1 line
samples/rust/rust_driver_pci.rs +0
-0@@ -140,56 +138,49 @@ fn config_space(pdev: &pci::Device<Bound>) {
[ ... ]
samples/rust/rust_driver_pci.rs fn config_space(pdev: &pci::Device<Bound>) { · line 176
Quoted 6 lines
samples/rust/rust_driver_pci.rs +1
-5-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>>) {
[Severity: High]
Does this method signature match the pci::Driver trait? The trait implementation here uses this: Pin<&'bound Self::Data<'bound>> which imposes a stricter lifetime constraint than the trait allows (an elided lifetime).
Will this cause an E0053 compiler error? Could we remove the explicit 'bound lifetime on the reference inside Pin?
Quoted 4 lines
samples/rust/rust_driver_pci.rs +2
-0+ this.bar + .write_reg (regs::TEST ::zeroed ().with_index (this.index)); } }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
Re: [PATCH v4 19/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.Reviewed-by Eliot Courtney <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerPATCH v4 20/27 gpu: nova-core: separate driver type from driver data
In reply to Danilo KrummrichIntroduce NovaCoreDriver as the driver type implementing pci::Driver, keeping NovaCore as the per-device data type. This prepares for making NovaCore lifetime-parameterized once auxiliary::Registration requires a lifetime for the binding scope.
--- drivers/gpu/nova-core/driver.rs | 14 ++++++++------ drivers/gpu/nova-core/nova_core.rs | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/driver.rs +8 -6
@@ -35,6 +35,8 @@ pub(crate) struct NovaCore { _reg: Devres<auxiliary::Registration<()>>, } +pub (crate )struct NovaCoreDriver ; +const BAR0_SIZE :usize =SZ_16M ;// For now we only support Ampere which can use up to 47-bit DMA addresses.
@@ -50,7 +52,7 @@ pub(crate) struct NovaCore { 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. (
@@ -72,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 ;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 <NovaCore ,Error > + 'bound { pin_init::pin_init_scope (move || {dev_dbg! (pdev,"Probe Nova Core GPU driver.\n" );
@@ -98,7 +100,7 @@ fn probe<'bound>( GFP_KERNEL, )?; - Ok(try_pin_init!(Self { + Ok(try_pin_init!(NovaCore { gpu <- Gpu::new(pdev, bar.clone(), bar.access(pdev.as_ref())?), _reg: auxiliary::Registration::new( pdev.as_ref(),
@@ -113,7 +115,7 @@ fn probe<'bound>( }) } -fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self >) { +fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&NovaCore >) { this.gpu.unbind (pdev.as_ref ()); } }
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
Re: [PATCH v4 20/27] gpu: nova-core: separate driver type from driver data
Quoted 7 lines · Danilo Krummrich
Introduce NovaCoreDriver as the driver type implementing
pci::Driver, keeping NovaCore as the per-device data type. This prepares for making NovaCore lifetime-parameterized onceauxiliary::Registrationrequires a lifetime for the binding scope.Signed-off-by Danilo Krummrich <[email protected]>---
Re: [PATCH v4 20/27] gpu: nova-core: separate driver type from driver data
In reply to Danilo KrummrichQuoted 6 lines · Danilo Krummrich
Introduce NovaCoreDriver as the driver type implementing
pci::Driver, keeping NovaCore as the per-device data type. This prepares for making NovaCore lifetime-parameterized onceauxiliary::Registrationrequires a lifetime for the binding scope.Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerPATCH v4 21/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.
[ Handle macro_rules! invocations in the ForLt! proc macro's covariance
and WF checks.
Proc macros cannot expand macro_rules! invocations, so the syn::Visit-based has_lifetime() and replace_lifetime() helpers cannot inspect types hidden behind macro calls. This caused the covariance proof to be silently skipped and lifetime substitution to fail for such types.
Add an explicit Type::Macro arm to Prover::prove to conservatively require a compiler-assisted covariance proof. Detect macro-containing types with has_macro() and use a WithLt trait projection for lifetime substitution instead of AST-level replacement. - Danilo ]
---
Gary, please let me know if I got those changes right or whether you prefer this handled in a different way.
--- rust/Makefile | 1 + rust/kernel/types.rs | 4 + rust/kernel/types/for_lt.rs | 117 +++++++++++++++ rust/macros/for_lt.rs | 274 ++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 12 ++ 5 files changed, 408 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 +274 -0
274 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
[email protected]
AI reviewRe: [PATCH v4 21/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] The `ForLt!` macro's covariance check can be bypassed when a lifetime is hidden inside a…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] The ForLt! macro's covariance check can be bypassed when a lifetime is hidden inside a nested macro invocation, leading to unsound implementations of the ForLt trait.
- [Critical] The safety architecture of ForLt is flawed because it allows safe code to bypass the macro's covariance proofs entirely, directly leading to soundness vulnerabilities.
- [Low] Incorrect usage of #[inline(always)] on cast_ref.
- [Low] expand_elided_lifetime fails to replace elided lifetimes ('_) hidden inside macro invocations.
--
commit a372a3dda5030ca04860c4057bb0215647faa34b
Author: Gary Guo <[email protected]>
rust: types: add ForLt trait for higher-ranked lifetime support
This commit introduces the ForLt trait and a corresponding macro to support types that are generic over lifetimes. The macro attempts to syntactically prove covariance or emits compiler checks to ensure the soundness of lifetime shortening casts.
Quoted 4 lines
rust/kernel/types/for_lt.rs new file +0
-0
[ ... ]
rust/kernel/types/for_lt.rs line 87
Quoted 7 lines
rust/kernel/types/for_lt.rs new file +7
-0+pub unsafe trait ForLt { +/// The type parameterized by the lifetime. +type Of <'a>: 'a; + +/// Cast a reference to a shorter lifetime. +#[inline(always)] +fn cast_ref <'r, 'short: 'r, 'long: 'short>(long: &'rSelf ::Of <'long>) -> &'rSelf ::Of <'short> {
[Severity: Low]
This isn't a bug, but according to the rust subsystem coding guidelines, #[inline(always)] should only be used for functions using build_assert!() that depend on function parameters. Should this be changed to #[inline]?
Quoted 4 lines
rust/kernel/types/for_lt.rs new file +4
-0+// SAFETY: This is sound as this trait guarantees covariance. +unsafe { core::mem::transmute (long) } + } +}
[ ... ]
Quoted 4 lines
rust/kernel/types/for_lt.rs new file +4
-0+#[doc(hidden)] +pub struct UnsafeForLtImpl <T : ?Sized ,WF ,const N :usize >(PhantomData <(WF ,T )>); + +// This is a helper trait for implementation `ForLt` to be able to use HRTB.
rust/kernel/types/for_lt.rs line 117
Quoted 10 lines
rust/kernel/types/for_lt.rs new file +10
-0+#[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 > { +type Of <'a> = <T as WithLt <'a>>::Of ; +}
[Severity: Critical]
Can safe downstream code implement the public WithLt trait for an invariant type (like Cell<&'a u32>), and then name <UnsafeForLtImpl<MyStruct, (), 0> as ForLt> to access ForLt::cast_ref?
If so, does this allow shortening lifetimes of invariant types entirely in safe code, bypassing the macro's covariance checks and breaking safety guarantees?
Quoted 4 lines
rust/macros/for_lt.rs new file +0
-0
[ ... ]
Quoted 14 lines
rust/macros/for_lt.rs new file +14
-0+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); +
rust/macros/for_lt.rs line 84
Quoted 10 lines
rust/macros/for_lt.rs new file +10
-0+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 + }
[Severity: Low]
If an elided lifetime is passed inside a macro invocation, such as ForLt!(Wrapper<SomeMacro!(<'_>)>), does VisitMut fail to traverse the TokenStream inside the Type::Macro?
Will this leave the elided lifetime unmodified and cause a missing lifetime specifier compiler error?
[ ... ]
Quoted 2 lines
rust/macros/for_lt.rs new file +2
-0+fn prove (&mut self, ty: &'aType ) { +match ty {
[ ... ]
rust/macros/for_lt.rs line 189
Quoted 12 lines
rust/macros/for_lt.rs new file +12
-0+// Macro invocations are opaque to proc macros; conservatively require +// a compiler proof since we cannot determine lifetime usage. + Type::Macro(_) => self.1.push(ty), + + // No mention of lifetime at all, no need to perform compiler check. + ty if !ty.has_lifetime(self.0) => (), + + // Otherwise, we need to emit checks so that compiler can determine if the types are + // actually covariant. + ty => self.1.push(ty), + } + }
[Severity: Critical]
If a lifetime is hidden within a macro invocation that is nested inside another type, for example ForLt!(for<'a> Cell<Mac!('a)>), will has_lifetime falsely return false because it doesn't traverse into the macro's TokenStream?
Since the Type::Macro arm only matches top-level macros, does the nested Type::Path (Cell) fall through to the ty if !ty.has_lifetime(self.0) arm?
If so, does this bypass the compiler-assisted covariance proof and allow unsound lifetime shortening casts?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
Danilo Krummrich
maintainerRe: [PATCH v4 21/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
In reply to Danilo KrummrichQuoted 9 lines · Danilo Krummrich
[ Handle
macro_rules! invocations in the ForLt! proc macro's covariance
and WF checks.Proc macros cannot expand
macro_rules! invocations, so the syn::Visit-basedhas_lifetime()andreplace_lifetime()helpers cannot inspect types hidden behind macro calls. This caused the covariance proof to be silently skipped and lifetime substitution to fail for such types.
Quoted 4 lines
Add an explicit
Type::Macroarm toProver::proveto conservatively require a compiler-assisted covariance proof. Detect macro-containing types withhas_macro()and use a WithLt trait projection for lifetime substitution instead of AST-level replacement. - Danilo ]
I was made aware by Gary that WFness is not actually being checked, which is why the static expansion was needed in the first place.
Thus macros will remain unsupported (even covariant macros are rejected), yet we can improve the error message by adding the following diff on top of the previous v3 patch.
rust/macros/for_lt.rs +6 -0
@@ -107,6 +107,12 @@ fn visit_lifetime(&mut self, lifetime: &Lifetime) { self.1 =true ; } } + +// Macro invocations are opaque; conservatively assume they may +// reference the lifetime. +fn visit_macro (&mut self, _: &syn::Macro ) { + self.1 =true ; + } }let mut visitor =HasLifetime (lt,false );
Eliot Courtney
Reviewed-byRe: [PATCH v4 21/27] rust: types: add `ForLt` trait for higher-ranked lifetime support
Quoted 29 lines · Danilo Krummrich
Quoted 9 lines · Danilo Krummrich
[ Handle
macro_rules! invocations in the ForLt! proc macro's covariance
and WF checks.Proc macros cannot expand
macro_rules! invocations, so the syn::Visit-basedhas_lifetime()andreplace_lifetime()helpers cannot inspect types hidden behind macro calls. This caused the covariance proof to be silently skipped and lifetime substitution to fail for such types.Quoted 4 lines
Add an explicit
Type::Macroarm toProver::proveto conservatively require a compiler-assisted covariance proof. Detect macro-containing types withhas_macro()and use a WithLt trait projection for lifetime substitution instead of AST-level replacement. - Danilo ]I was made aware by Gary that WFness is not actually being checked, which is why the static expansion was needed in the first place.
Thus macros will remain unsupported (even covariant macros are rejected), yet we can improve the error message by adding the following diff on top of the previous v3 patch.
rust/macros/for_lt.rs +0
-0@@ -107,6 +107,12 @@ fn visit_lifetime(&mut self, lifetime: &Lifetime) { self.1 =true ; }
rust/macros/for_lt.rs fn visit_lifetime(&mut self, lifetime: &Lifetime) { · line 118
Quoted 10 lines
rust/macros/for_lt.rs +6
-0} + +// Macro invocations are opaque; conservatively assume they may +// reference the lifetime. +fn visit_macro (&mut self, _: &syn::Macro ) { + self.1 =true ; + } }let mut visitor =HasLifetime (lt,false );
With this change,
I think also this implementation considers &'a mut dyn Trait to be covariant in 'a which isn't the case in general IIUC, but I can't see any way it could cause an issue currently.
Danilo Krummrich
maintainerPATCH v4 22/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 | 13 ++-- rust/kernel/auxiliary.rs | 108 +++++++++++++++++++------- samples/rust/rust_driver_auxiliary.rs | 19 +++-- 3 files changed, 96 insertions(+), 44 deletions(-)
drivers/gpu/nova-core/driver.rs +7 -6
@@ -3,7 +3,6 @@use kernel::{ auxiliary, device::Core , - devres::Devres , dma::Device , dma::DmaMask , pci,
@@ -21,6 +20,7 @@ }, Arc, }, + types::ForLt, };use crate ::gpu::Gpu ;
@@ -29,10 +29,11 @@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 , - _reg:Devres <auxiliary::Registration <()>>, +#[allow(clippy::type_complexity)] + _reg: auxiliary::Registration <'bound,ForLt! (())>, }pub (crate )struct NovaCoreDriver ;
@@ -76,13 +77,13 @@ pub(crate) struct NovaCore {impl pci::Driver for NovaCoreDriver {type IdInfo = (); -type Data <'bound> =NovaCore ; +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 <NovaCore ,Error > + 'bound { + ) ->impl PinInit <Self ::Data <'bound>,Error > + 'bound { pin_init::pin_init_scope (move || {dev_dbg! (pdev,"Probe Nova Core GPU driver.\n" );
@@ -115,7 +116,7 @@ fn probe<'bound>( }) } -fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&NovaCore >) { +fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self ::Data <'bound>>) { this.gpu.unbind (pdev.as_ref ()); } }
rust/kernel/auxiliary.rs +78 -30
203 lines not on this page · raw message
samples/rust/rust_driver_auxiliary.rs +11 -8
@@ -10,10 +10,10 @@ Bound, Core, // }, - devres::Devres, driver, pci, prelude::*, + types::ForLt, InPlaceModule, // };
@@ -55,9 +55,12 @@ struct Data { index: u32, } -struct ParentDriver { - _reg0:Devres <auxiliary::Registration <Data >>, - _reg1:Devres <auxiliary::Registration <Data >>, +struct ParentDriver ; + +#[allow(clippy::type_complexity)] +struct ParentData <'bound> { + _reg0: auxiliary::Registration <'bound,ForLt! (Data )>, + _reg1: auxiliary::Registration <'bound,ForLt! (Data )>, } kernel::pci_device_table!(
@@ -69,15 +72,15 @@ struct ParentDriver { impl pci::Driver for ParentDriver { type IdInfo = (); - type Data<'bound> = Self; + type Data<'bound> = ParentData<'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(ParentData { _reg0: auxiliary::Registration::new( pdev.as_ref(), AUXILIARY_NAME,
@@ -101,7 +104,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
[email protected]
AI reviewRe: [PATCH v4 22/27] rust: auxiliary: generalize Registration over ForLt
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
New issues:
- [Low] The Sync trait implementation for Registration incorrectly bounds F::Of<'a> with Send instead of Sync.
Pre-existing issues:
- [Critical] registration_data() unsoundly ties the returned reference's lifetime to &self (the auxiliary::Device), allowing safe Rust code to trigger a Use-After-Free.
- [High] Dangling pointer in auxiliary::Device after Registration is dropped allows Use-After-Free via registration_data().
- [High] The NovaCore driver tears down the parent GPU state before unregistering the child auxiliary device, leading to potential Use-After-Free. --
commit a5589ea6d6792c6af381c80c56bba4c3373a3001
Author: Danilo Krummrich <[email protected]>
rust: auxiliary: generalize Registration over ForLt
This commit generalizes Registration over ForLt to allow parameterized lifetimes. It shortens the stored static lifetime to the borrow lifetime of the device reference.
Quoted 4 lines
drivers/gpu/nova-core/driver.rs +0
-0
[ ... ]
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 122
Quoted 9 lines
drivers/gpu/nova-core/driver.rs +1
-1@@ -115,7 +116,7 @@ fn probe<'bound>( }) } -fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&NovaCore >) { +fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self ::Data <'bound>>) { this.gpu.unbind (pdev.as_ref ()); } }
[Severity: High]
This is a pre-existing issue, but does tearing down the parent GPU state here before unregistering the child auxiliary device lead to a potential use-after-free?
The child device represented by _reg is only deleted when NovaCore is subsequently dropped. This means the child device's remove callback is invoked after the parent's gpu is dismantled. If the child driver accesses the parent's GPU state during its removal, it might interact with a destroyed object.
Quoted 4 lines
rust/kernel/auxiliary.rs +0
-0
[ ... ]
Quoted 6 lines
rust/kernel/auxiliary.rs +1
-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
rust/kernel/auxiliary.rs pub fn parent(&self) -> &device::Device<device::Bound> { · line 284
Quoted 10 lines
rust/kernel/auxiliary.rs +5
-1+/// 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 + 'static>(&self) ->Result <Pin <&F ::Of <'_>>> {
[Severity: Critical]
This is a pre-existing issue, but does tying the returned reference's lifetime to &self (the auxiliary::Device) allow safe Rust code to trigger a use-after-free?
Because auxiliary::Device is reference-counted, safe Rust code can obtain an ARef<Device> that outlives the Registration of the parent driver. A user could call registration_data(), keep the ARef<Device> alive to keep the compiler happy about the reference's lifetime, wait for the parent driver to unload (which frees the memory), and then safely access the dangling reference.
[ ... ]
Quoted 6 lines
rust/kernel/auxiliary.rs +1
-1-impl <T : 'static>Drop for Registration <T > { +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`.
rust/kernel/auxiliary.rs fn drop(&mut self) { · line 540
Quoted 8 lines
rust/kernel/auxiliary.rs +1
-1@@ -486,7 +534,7 @@ fn drop(&mut self) {// SAFETY: `registration_data` was set in `new()` via `into_foreign()`. drop (unsafe { -Pin ::<KBox <RegistrationData <T >>>::from_foreign ( +Pin ::<KBox <RegistrationData <F ::Of <'static>>>>::from_foreign ( (*self.adev.as_ptr ()).registration_data_rust, ) });
[Severity: High]
This is a pre-existing issue, but does leaving registration_data_rust pointing to freed memory here allow a use-after-free via registration_data()?
Because auxiliary::Device can outlive the Registration instance if a user holds an ARef<Device>, if Device::registration_data() is called on such a surviving reference, it bypasses the NULL check, reads the TypeId from the freed memory, and returns a reference to the freed data. Should this set (*self.adev.as_ptr()).registration_data_rust to null after the drop?
rust/kernel/auxiliary.rs fn drop(&mut self) { · line 554
Quoted 10 lines
rust/kernel/auxiliary.rs +2
-2@@ -500,7 +548,7 @@ fn drop(&mut self) { }// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread. -unsafe impl <T :Send +Sync >Send for Registration <T > {} +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 <T :Send +Sync >Sync for Registration <T > {} +unsafe impl <F :ForLt >Sync for Registration <'_,F >where for <'a>F ::Of <'a>:Send {}
[Severity: Low]
Is this a copy-paste error where F::Of<'a> is bounded by Send instead of Sync?
Standard Rust semantics expect types that conceptually own data to require Sync on the inner type to implement Sync.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
Re: [PATCH v4 22/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichQuoted 8 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]>---
Re: [PATCH v4 22/27] rust: auxiliary: generalize Registration over ForLt
In reply to Danilo KrummrichQuoted 7 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]>
Danilo Krummrich
maintainerPATCH v4 23/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 | 58 ++++++++++++++++----------- 1 file changed, 35 insertions(+), 23 deletions(-)
samples/rust/rust_driver_auxiliary.rs +35 -23
@@ -51,16 +51,17 @@ fn probe<'bound>( } } -struct Data { +struct Data <'bound> { index:u32 , + parent: &'bound pci::Device <Bound >, }struct ParentDriver ;#[allow(clippy::type_complexity)] struct ParentData <'bound> { - _reg0: auxiliary::Registration <'bound,ForLt! (Data )>, - _reg1: auxiliary::Registration <'bound,ForLt! (Data )>, + _reg0: auxiliary::Registration <'bound,ForLt! (Data <'_>)>, + _reg1: auxiliary::Registration <'bound,ForLt! (Data <'_>)>, } kernel::pci_device_table!(
@@ -81,33 +82,44 @@ fn probe<'bound>( _info: &'bound Self::IdInfo, ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {Ok (ParentData { - _reg0: auxiliary::Registration ::new ( - pdev.as_ref (), -AUXILIARY_NAME , -0 , -MODULE_NAME , -Data { index:0 }, - )?, - _reg1: auxiliary::Registration ::new ( - pdev.as_ref (), -AUXILIARY_NAME , -1 , -MODULE_NAME , -Data { index:1 }, - )?, +// SAFETY: `ParentData` is the driver's private data, which is dropped when the +// device is unbound; i.e. `mem::forget()` is never called on it. + _reg0:unsafe { + auxiliary::Registration ::new_with_lt ( + pdev.as_ref (), +AUXILIARY_NAME , +0 , +MODULE_NAME , +Data { + index:0 , + parent: pdev, + }, + )? + }, +// SAFETY: See `_reg0` above. + _reg1:unsafe { + auxiliary::Registration ::new_with_lt ( + pdev.as_ref (), +AUXILIARY_NAME , +1 , +MODULE_NAME , +Data { + index:1 , + parent: pdev, + }, + )? + }, }) } }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 (),
@@ -115,7 +127,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
Re: [PATCH v4 23/27] samples: rust: rust_driver_auxiliary: showcase lifetime-bound registration data
Quoted 10 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().Reviewed-by Eliot Courtney <[email protected]>Reviewed-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerPATCH v4 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 | 32 +++++++++++++++----------------- drivers/gpu/nova-core/gpu.rs | 33 +++++++++++++-------------------- 2 files changed, 28 insertions(+), 37 deletions(-)
drivers/gpu/nova-core/driver.rs +15 -17
@@ -13,12 +13,9 @@ }, prelude::*, sizes::SZ_16M, - sync::{ - atomic::{ - Atomic, - Relaxed, // - }, - Arc, + sync::atomic::{ + Atomic, + Relaxed, // }, types::ForLt, };
@@ -31,7 +28,8 @@#[pin_data] 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: auxiliary::Registration <'bound,ForLt! (())>, }
@@ -48,7 +46,7 @@ pub(crate) struct NovaCore<'bound> {// DMA addresses. These systems should be quite rare. const GPU_DMA_BITS :u32 =47 ; -pub (crate )type Bar0 = pci::Bar <'static,BAR0_SIZE >; +pub (crate )type Bar0 = kernel::io::Mmio <BAR0_SIZE >; kernel::pci_device_table!(PCI_TABLE ,
@@ -95,14 +93,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!(NovaCore { - gpu <- Gpu::new(pdev, bar.clone(), bar.access(pdev.as_ref())?), + 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",
@@ -116,7 +114,7 @@ fn probe<'bound>( }) } -fn unbind <'bound>(pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self ::Data <'bound>>) { - this.gpu.unbind (pdev.as_ref ()); +fn unbind <'bound>(_pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self ::Data <'bound>>) { + this.gpu.unbind (); } }
drivers/gpu/nova-core/gpu.rs +13 -20
@@ -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 <'gpu> { spec:Spec , -/// MMIO mapping of PCI BAR 0 - bar:Arc <Devres <Bar0 >>, +/// MMIO mapping of PCI BAR 0. + bar: &'gpuBar0 ,/// 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,12 +238,11 @@ pub(crate) struct Gpu { gsp: Gsp, } -impl Gpu { - pub(crate) fn new<'a>( - pdev: &'a pci::Device<device::Bound>, - devres_bar: Arc<Devres<Bar0>>, - bar: &'a Bar0, - ) -> impl PinInit<Self, Error> + 'a { +impl<'gpu> Gpu<'gpu> { + pub(crate) fn new( + pdev: &'gpu pci::Device<device::Bound>, + bar: &'gpu Bar0, + ) -> impl PinInit<Self, Error> + 'gpu { try_pin_init!(Self { spec: Spec::new(pdev.as_ref(), bar).inspect(|spec| { dev_info!(pdev,"NVIDIA ({})\n", spec);
@@ -257,6 +254,8 @@ pub(crate) fn new<'a>( .inspect_err(|_| dev_err!(pdev, "GFW boot did not complete\n"))?; }, + bar, + sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?, gsp_falcon: Falcon::new(
@@ -270,19 +269,13 @@ pub(crate) fn new<'a>( gsp <- Gsp::new(pdev), _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)? }, - - bar: devres_bar, }) }/// Called when the corresponding [`Device`](device::Device) is unbound. /// /// Note: This method must only be called from `Driver::unbind`. -pub (crate )fn unbind (&self, dev: &device::Device <device::Core <'_>>) { - kernel::warn_on!(self - .bar - .access (dev) - .inspect (|bar| self.sysmem_flush.unregister (bar)) - .is_err ()); +pub (crate )fn unbind (&self) { + self.sysmem_flush.unregister (self.bar); } }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH REF v4 24/27] gpu: nova-core: use lifetime for Bar
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The raw pointer cast artificially extends a short-lived local reference to the `'bound` lifetime…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The raw pointer cast artificially extends a short-lived local reference to the 'bound lifetime, bypassing the borrow checker and causing undefined behavior.
- [High] Creating a self-reference to a standard, non-Opaque field violates Rust's aliasing rules and causes Undefined Behavior.
--
commit 324bc88b7f0822485a9eb9d34c17aabba9845b74
Author: Danilo Krummrich <[email protected]>
Subject: gpu: nova-core: use lifetime for Bar
This commit removes the Arc<Devres<Bar0>> indirection and replaces it with a lifetime-parameterized pci::Bar<'bound> in NovaCore. It passes a borrowed reference to Gpu<'bound> by attempting to use a self-reference during pin initialization.
Quoted 4 lines
drivers/gpu/nova-core/driver.rs +0
-0
[ ... ]
Quoted 9 lines
drivers/gpu/nova-core/driver.rs +0
-5@@ -95,14 +93,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 , - )?;
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 103
Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7
-2- Ok(try_pin_init!(NovaCore { - gpu <- Gpu::new(pdev, bar.clone(), bar.access(pdev.as_ref())?), + 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) }),
[Severity: High]
Does coercing this local reference through a raw pointer artificially extend its lifetime to 'bound?
Since Gpu<'bound> requires its bar reference to live for the 'bound lifetime (which is tied to the PCI device), and the NovaCore allocation has a strictly shorter lifespan than the device itself, could this forged lifetime bypass the borrow checker and cause undefined behavior?
[Severity: High]
Could creating a self-reference to a standard, non-Opaque field here violate Rust's aliasing rules?
Because bar is not wrapped in kernel::types::Opaque, any subsequent mutable borrow of the NovaCore struct (such as when the allocation is finalized into a Pin<Box<NovaCore>>) asserts exclusive mutable access over all its fields.
Wouldn't this recursively invalidate the shared reference to Bar0 stored inside gpu, leading to undefined behavior upon later access?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
Alexandre Courbot
maintainerRe: [PATCH REF v4 24/27] gpu: nova-core: use lifetime for Bar
In reply to Danilo KrummrichQuoted 8 lines · Danilo Krummrich
Take advantage of the lifetime-parameterized pci::Bar<'bound> to hold the BAR mapping directly in NovaCore<'bound>, and pass a borrowed reference to Gpu<'bound>.
This eliminates the Arc<Devres<Bar0>> indirection, removes runtime revocation checks for BAR access, and simplifies
Gpu::unbind().Signed-off-by Danilo Krummrich <[email protected]>
I see that this patch is not in v5 (and it is marked REF here), do you intend to push it soon? Knowing that would be useful to understand which base to use for work that depends on HRT.
Alexandre Courbot
maintainerRe: [PATCH REF v4 24/27] gpu: nova-core: use lifetime for Bar
Quoted 5 lines · Alexandre Courbot
Quoted 4 lines · Danilo Krummrich
Take advantage of the lifetime-parameterized pci::Bar<'bound> to hold the BAR mapping directly in NovaCore<'bound>, and pass a borrowed reference to Gpu<'bound>.
Quoted 8 lines
Quoted 4 lines
This eliminates the Arc<Devres<Bar0>> indirection, removes runtime revocation checks for BAR access, and simplifies
Gpu::unbind().Signed-off-by Danilo Krummrich <[email protected]>I see that this patch is not in v5 (and it is marked
REFhere), do you intend to push it soon? Knowing that would be useful to understand which base to use for work that depends on HRT.
Just noticed your "gpu: nova: adopt driver lifetime infrastructure" series. Sorry for the noise.
Danilo Krummrich
maintainerPATCH v4 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
@@ -113,8 +113,4 @@ fn probe<'bound>( })) }) } - -fn unbind <'bound>(_pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self ::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 <'sys> {/// Chipset we are operating on. chipset:Chipset , device:ARef <device::Device >, + bar: &'sysBar0 ,/// Keep the page alive as long as we need it. page:CoherentHandle , } -impl SysmemFlush { +impl <'sys>SysmemFlush <'sys> {/// Allocate a memory page and register it as the sysmem flush page. pub (crate )fn register ( dev: &device::Device <device::Bound >, - bar: &Bar0 , + bar: &'sysBar0 , 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<'gpu> { bar: &'gpu 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<'gpu>, /// 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
[email protected]
AI reviewRe: [PATCH REF v4 25/27] gpu: nova-core: unregister sysmem flush page from Drop
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
Pre-existing issues:
- [High] Missing MMIO readback after unregistering the sysmem flush page allows DMA to freed memory.
- [High] Incorrect teardown order causes child DRM drivers to be unregistered after GPU resources are freed.
- [High] GPU hardware is not halted before its DMA memory is freed during teardown.
--
commit 4d00660f7b8829d00187ed0c9645cb7d2b811fe2
Author: Danilo Krummrich <[email protected]>
gpu: nova-core: unregister sysmem flush page from Drop
Now that SysmemFlush can borrow the Bar via HRT lifetime, store a &'bound Bar0 reference and implement Drop to automatically unregister the sysmem flush page. This removes the need for manual unregister() calls and the Gpu::unbind() method.
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 119
Quoted 12 lines
drivers/gpu/nova-core/driver.rs +0
-4@@ -113,8 +113,4 @@ fn probe<'bound>( })) }) } - -fn unbind <'bound>(_pdev: &'bound pci::Device <Core <'_>>, this:Pin <&Self ::Data <'bound>>) { - this.gpu.unbind (); - }
[Severity: High]
This isn't a bug introduced by this patch, but by relying on Drop for teardown, does the struct field declaration order cause child DRM drivers to be unregistered after GPU resources are freed?
In Rust, struct fields are dropped in declaration order. If gpu and bar are declared before _reg (the auxiliary device registration) in NovaCore, dropping NovaCore will drop gpu first (freeing GSP DMA buffers and unmapping the sysmem flush page).
Later, _reg is dropped, which invokes auxiliary_device_delete and triggers the child DRM driver's remove callback. This means the child driver is unbound and executes its teardown after the GPU hardware state has been torn down and its backing DMA memory freed.
Could this lead to crashes or use-after-free?
[Severity: High]
This is a pre-existing issue, but is the GPU hardware halted before its DMA memory is freed during teardown?
When the Gpu struct is dropped, the DMA memory for the sysmem flush page and GSP is freed via their respective Drop implementations. However, neither Gpu, Gsp, nor Falcon appear to implement a Drop routine that actually halts the GSP firmware or resets the falcons.
Because the hardware is left running while its DMA backing memory is returned to the system allocator, could the GPU continue to execute and access the freed memory?
Quoted 5 lines
drivers/gpu/nova-core/driver.rs +0
-0}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| {
[Severity: High]
This is a pre-existing issue, but does this MMIO write need a readback?
When SysmemFlush::drop unregisters the flush page, it issues a PCIe MMIO write. PCIe writes are posted and can be buffered. Because there is no subsequent MMIO read to flush the posted write, the CPU can immediately proceed to drop self.page and free the DMA memory while the hardware's register update is still in flight.
If the GPU executes a sysmem flush before the register actually updates, could it write to freed memory?
Quoted 3 lines
drivers/gpu/nova-core/fb.rs +0
-0dev_warn! ( &self.device,"failed to unregister sysmem flush page: {:?}\n" ,
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
Danilo Krummrich
maintainerPATCH v4 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 <'sys> {/// Chipset we are operating on. chipset:Chipset , - device:ARef <device::Device >, + device: &'sys device::Device , bar: &'sysBar0 ,/// Keep the page alive as long as we need it. page:CoherentHandle ,
@@ -58,7 +57,7 @@ pub(crate) struct SysmemFlush<'sys> {impl <'sys>SysmemFlush <'sys> {/// Allocate a memory page and register it as the sysmem flush page. pub (crate )fn register ( - dev: &device::Device <device::Bound >, + dev: &'sys device::Device <device::Bound >, bar: &'sysBar0 , 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
[email protected]
AI reviewRe: [PATCH REF v4 26/27] gpu: nova-core: replace ARef<Device> with &'bound Device in SysmemFlush
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
Pre-existing issues:
- [Critical] The PCIe write to unregister the sysmem flush page is a posted write. Without a subsequent dummy read to flush the PCIe bus buffer, the DMA memory may be freed before the hardware processes the unregistration, risking a use-after-free by the GPU.
- [High] The sysmem flush page DMA address is restricted to 40 bits by the hardware register on some architectures, but the driver configures a 47-bit DMA mask, leading to potential driver probe failures on systems with >1TB of RAM. --
commit 4632ef4cc9c31d8529ab1675ddf82d3a2b423cef
Author: Danilo Krummrich <[email protected]>
gpu: nova-core: replace ARef<Device> with &'bound Device in SysmemFlush
This commit updates SysmemFlush to use a lifetime-parameterized reference to the device instead of an ARef. This removes the unnecessary reference counting overhead since the lifetime is statically bound.
Quoted 4 lines
drivers/gpu/nova-core/fb.rs +0
-0
[ ... ]
drivers/gpu/nova-core/fb.rs line 54
Quoted 9 lines
drivers/gpu/nova-core/fb.rs +1
-1@@ -49,7 +48,7 @@pub (crate )struct SysmemFlush <'sys> {/// Chipset we are operating on. chipset:Chipset , - device:ARef <device::Device >, + device: &'sys device::Device , bar: &'sysBar0 ,/// Keep the page alive as long as we need it. page:CoherentHandle ,
[Severity: Critical]
This is a pre-existing issue, but does the Drop implementation for SysmemFlush need a dummy read to flush the PCIe bus buffer?
When unregistering the sysmem flush page, the MMIO write is asynchronous and posted to the PCIe bus. Without a subsequent dummy read to flush the bus, could the Drop implementation return and free the CoherentHandle page before the unregistration reaches the hardware?
If the GPU executes a sysmem flush before the hardware processes the write, it might write to the freed DMA page, which could corrupt system memory or trigger an IOMMU fault.
drivers/gpu/nova-core/fb.rs pub(crate) struct SysmemFlush<'sys> { · line 63
Quoted 10 lines
}
impl<'sys> SysmemFlush<'sys> { /// Allocate a memory page and register it as the sysmem flush page. pub(crate) fn register(drivers/gpu/nova-core/fb.rs +1
-1- dev: &device::Device<device::Bound>, + dev: &'sys device::Device<device::Bound>, bar: &'sys Bar0, chipset: Chipset, ) -> Result<Self> {
[Severity: High]
This isn't a bug introduced by this patch, but is the DMA mask configured correctly for this allocation?
The driver configures a 47-bit coherent DMA mask, which allows the page physical or IOVA address to exceed 40 bits. However, the hardware register only accommodates 40 bits on some architectures.
When write_sysmem_flush_page_gm107() shifts the address by 8 and attempts to fit it into a u32 for the NV_PFB_NISO_FLUSH_SYSMEM_ADDR register, will this conversion fail if the allocated address is 1TB or higher?
If so, this might cause driver probe failures on systems with large amounts of RAM or IOMMUs issuing high IOVAs.
Quoted 9 lines
drivers/gpu/nova-core/fb.rs +1
-1@@ -68,7 +67,7 @@ pub(crate) fn register(Ok (Self { chipset, - device: dev.into (), + device: dev, bar, page, })
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=26
Danilo Krummrich
maintainerPATCH v4 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 REF v4 27/27] gpu: drm: tyr: use lifetime for IoMem
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Commit message and code discrepancy regarding the `IoMem` type. - [Low] Incomplete refactoring…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Commit message and code discrepancy regarding the IoMem type.
- [Low] Incomplete refactoring leaves an unused dev parameter in issue_soft_reset and l2_power_on. --
commit d5f1fb446208aa007978c5b149d5671f94e218d1
Author: Danilo Krummrich <[email protected]>
gpu: drm: tyr: use lifetime for IoMem
This commit simplifies the driver probe path by using the memory mapping directly instead of relying on an Arc<Devres<IoMem>> indirection. Register read and write operations are also updated to be infallible since the Devres access check is no longer needed.
Quoted 5 lines
gpu: drm: tyr: use lifetime for IoMem
Take advantage of the lifetime-parameterized IoMem<'bound> to use the memory mapping directly during probe, eliminating the Arc<Devres<IoMem>> indirection.
[Severity: Medium]
Is the commit message outdated? It explicitly mentions using the lifetime-parameterized IoMem<'bound>, but the code actually aliases IoMem to kernel::io::Mmio<SZ_2M>, which is not lifetime-parameterized.
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 );
[Severity: Low]
Does this leave the dev parameter unused? Since the Devres access check was removed, it appears dev is no longer needed here. In Rust, this triggers the unused_variables lint, which will cause a build failure with the kernel's -Dwarnings flag.
Quoted 7 lines
drivers/gpu/drm/tyr/driver.rs +1
-1poll::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),
[ ... ]
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 );
[Severity: Low]
Similarly, could the dev parameter be removed from this function signature to avoid an unused variable warning and subsequent build error?
Quoted 7 lines
drivers/gpu/drm/tyr/gpu.rs +1
-1poll::read_poll_timeout ( - || regs::L2_READY_LO .read (dev, iomem), + ||Ok (regs::L2_READY_LO .read (iomem)), |status| *status ==1 ,Delta ::from_millis (1 ), Delta::from_millis(100),
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=27
Quoted 90 lines · Danilo Krummrich
Currently, Rust device drivers access device resources such as PCI BAR mappings and I/O memory regions through Devres<T>.
Devres::access()provides zero-overhead access by taking a &Device<Bound> reference as proof that the device is still bound. Since a &Device<Bound> is available in almost all contexts by design, Devres is mostly a type-system level proof that the resource is valid, but it can also be used from scopes without this guarantee through itstry_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.
Quoted 6 lines
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.
Looks nice!