Skip to contentSkip to conversation

rust: auxiliary: replace drvdata() with registration data

PATCH Applied Danilo Krummrich 3 participants 13 messages May 5 – May 11

Subsystems (8)
lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

v2 cover rust: auxiliary: replace drvdata() with registration data

When drvdata() was introduced in commit 6f61a2637abe ("rust: device: introduce Device::drvdata()"), its commit message already noted that a direct accessor to the driver's bus device private data is not commonly required -- bus callbacks provide access through &self, and other entry points (IRQs, workqueues, IOCTLs, etc.) carry their own private data.

The sole motivation for drvdata() was inter-driver interaction, e.g. a parent driver deriving its bus device private data from the child driver via the auxiliary bus.

However, drvdata() exposes the driver's bus device private data beyond the driver's own scope. This creates ordering constraints -- drvdata may not be set yet when the first caller of drvdata() can appear -- and forces the driver's bus device private data to outlive all registrations that access it; a requirement that causes unnecessary complications.

Private data should be private to the entity that issues it; bus device private data belongs to bus callbacks, class device private data to class callbacks, IRQ private data to the IRQ handler, etc.

This series replaces drvdata() with a dedicated registration_data pointer on struct auxiliary_device. The parent stores its private data explicitly during registration; the data is private to the registration and lives as long as the Registration object.

On teardown, Registration::drop() first triggers auxiliary_device_delete() (unbinding the child), then frees the registration data. Ordering constraints are structural -- the child's lifecycle is scoped to the registration by construction, not by convention.

With no remaining use case for drvdata(), drvdata(), match_type_id(), set_type_id() and struct driver_type are removed.

This is a prerequisite for [1], which builds on the removal of drvdata() to enable Higher-Ranked Lifetime Types (HRT) for Rust device drivers.

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

Changes in v2:
- Introduce Box::zeroed()
- Add Sync bound to Registration<T> impl block
- Use KBox::zeroed() instead of KBox::new(Opaque::zeroed(), ...)
- Use drop() instead of let _ = { ... }
- Fix invariant doc reference

Danilo Krummrich (3):
rust: alloc: add Box::zeroed()
rust: auxiliary: add registration data to auxiliary devices
rust: driver core: remove drvdata() and driver_type

 drivers/base/base.h                   |  16 --
 drivers/gpu/nova-core/driver.rs       |  10 +-
 include/linux/auxiliary_bus.h         |   4 +
 rust/kernel/alloc/kbox.rs             |  22 +++
 rust/kernel/auxiliary.rs              | 208 ++++++++++++++++++--------
 rust/kernel/device.rs                 |  60 --------
 samples/rust/rust_driver_auxiliary.rs |  40 +++--
 7 files changed, 202 insertions(+), 158 deletions(-)

base-commit: 30c878ed169983190f77940594f8ba8948debe6b

Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH v2 1/3 rust: alloc: add Box::zeroed()

Add Box::zeroed() for T: Zeroable types.

This allocates with __GFP_ZERO directly, letting the underlying allocator deal with zeroing out the memory compared to Box::new(T::zeroed(), flags).

---
 rust/kernel/alloc/kbox.rs | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
rust/kernel/alloc/kbox.rs +22 -0
index bd6da02c7ab8..c824ed6e1523 100644
@@ -19,6 +19,7 @@
 use crate::fmt;
 use crate::init::InPlaceInit;
 use crate::page::AsPageIter;
+use crate::prelude::*;
 use crate::types::ForeignOwnable;
 use pin_init::{InPlaceWrite, Init, PinInit, ZeroableOption};
 
@@ -256,6 +257,27 @@ pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
         Ok(Box(ptr.cast(), PhantomData))
     }
 
+    /// Creates a new zero-initialized `Box<T, A>`.
+    ///
+    /// New memory is allocated with `A` and the [`__GFP_ZERO`] flag. The allocation may fail, in
+    /// which case an error is returned. For ZSTs no memory is allocated.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let b = KBox::<[u8; 128]>::zeroed(GFP_KERNEL)?;
+    /// assert_eq!(*b, [0; 128]);
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn zeroed(flags: Flags) -> Result<Self, AllocError>
+    where
+        T: Zeroable,
+    {
+        // SAFETY: `__GFP_ZERO` guarantees the memory is zeroed; `T: Zeroable` guarantees that
+        // all-zeroes is a valid bit pattern for `T`.
+        Ok(unsafe { Self::new_uninit(flags | __GFP_ZERO)?.assume_init() })
+    }
+
     /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then `x` will be
     /// pinned in memory and can't be moved.
     #[inline]
Signature · 1 line
2.54.0
maintainer Reviewed-by on v2 1/3
#2 lore raw

Re: [PATCH v2 1/3] rust: alloc: add Box::zeroed()

Quoted 7 lines · Danilo Krummrich

Add Box::zeroed() for T: Zeroable types.

This allocates with __GFP_ZERO directly, letting the underlying allocator deal with zeroing out the memory compared to Box::new(T::zeroed(), flags).

Quoted 8 lines
 rust/kernel/alloc/kbox.rs | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
rust/kernel/alloc/kbox.rs +0 -0
index bd6da02c7ab8..c824ed6e1523 100644

rust/kernel/alloc/kbox.rs line 24

Quoted 6 lines
rust/kernel/alloc/kbox.rs +1 -0
@@ -19,6 +19,7 @@
 use crate::fmt;
 use crate::init::InPlaceInit;
 use crate::page::AsPageIter;
+use crate::prelude::*;
 use crate::types::ForeignOwnable;
 use pin_init::{InPlaceWrite, Init, PinInit, ZeroableOption};

I suspect some of these imports can be removed when you add the prelude.

Quoted 7 lines
rust/kernel/alloc/kbox.rs +3 -0
@@ -256,6 +257,27 @@ pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
         Ok(Box(ptr.cast(), PhantomData))
     }
 
+    /// Creates a new zero-initialized `Box<T, A>`.
+    ///
+    /// New memory is allocated with `A` and the [`__GFP_ZERO`] flag. The allocation may fail, in

rust/kernel/alloc/kbox.rs pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> { · line 272

Quoted 10 lines
rust/kernel/alloc/kbox.rs +10 -0
+    /// which case an error is returned. For ZSTs no memory is allocated.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let b = KBox::<[u8; 128]>::zeroed(GFP_KERNEL)?;
+    /// assert_eq!(*b, [0; 128]);
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn zeroed(flags: Flags) -> Result<Self, AllocError>

#[inline]?

Alice

author maintainer
#3 lore raw

Re: [PATCH v2 1/3] rust: alloc: add Box::zeroed()

Quoted 1 line · Alice Ryhl

I suspect some of these imports can be removed when you add the prelude.

Yes, but I want to convert the imports separately, so keeping the change minimal.

reviewer
#4 lore raw

Re: [PATCH v2 1/3] rust: alloc: add Box::zeroed()

Quoted 5 lines · Danilo Krummrich
Quoted 1 line · Alice Ryhl

I suspect some of these imports can be removed when you add the prelude.

Yes, but I want to convert the imports separately, so keeping the change minimal.

So far we've been asking people to convert import styles whenever imports are being touched. What's the reason for doing that in this specific case?

Best,
Gary

author maintainer
#5 lore raw

Re: [PATCH v2 1/3] rust: alloc: add Box::zeroed()

Quoted 9 lines · Gary Guo
Quoted 5 lines · Danilo Krummrich
Quoted 1 line · Alice Ryhl

I suspect some of these imports can be removed when you add the prelude.

Yes, but I want to convert the imports separately, so keeping the change minimal.

So far we've been asking people to convert import styles whenever imports are being touched. What's the reason for doing that in this specific case?

I will take this through the driver-core tree as a dependency; the import update for the alloc module will go through the alloc tree. A minimal change avoids unnecessary conflicts.

author maintainer
#6 lore raw

PATCH v2 2/3 rust: auxiliary: add registration data to auxiliary devices

In reply to Danilo Krummrich

Add a registration_data pointer to struct auxiliary_device, allowing the registering (parent) driver to attach private data to the device at registration time and retrieve it later when called back by the auxiliary (child) driver.

By tying the data to the device's registration, Rust drivers can bind the lifetime of device resources to it, since the auxiliary bus guarantees that the parent driver remains bound while the auxiliary device is bound.

On the Rust side, Registration<T> takes ownership of the data via ForeignOwnable. A TypeId is stored alongside the data for runtime type checking, making Device::registration_data<T>() a safe method.

---
 drivers/gpu/nova-core/driver.rs       |  10 +-
 include/linux/auxiliary_bus.h         |   4 +
 rust/kernel/auxiliary.rs              | 208 ++++++++++++++++++--------
 samples/rust/rust_driver_auxiliary.rs |  40 +++--
 4 files changed, 180 insertions(+), 82 deletions(-)
drivers/gpu/nova-core/driver.rs +5 -5
index 84b0e1703150..8fe484d357f6 100644
@@ -32,8 +32,7 @@
 pub(crate) struct NovaCore {
     #[pin]
     pub(crate) gpu: Gpu,
-    #[pin]
-    _reg: Devres<auxiliary::Registration>,
+    _reg: Devres<auxiliary::Registration<()>>,
 }
 
 const BAR0_SIZE: usize = SZ_16M;
@@ -96,14 +95,15 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, E
 
             Ok(try_pin_init!(Self {
                 gpu <- Gpu::new(pdev, bar.clone(), bar.access(pdev.as_ref())?),
-                _reg <- auxiliary::Registration::new(
+                _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c"nova-drm",
                     // TODO[XARR]: Use XArray or perhaps IDA for proper ID allocation/recycling. For
                     // now, use a simple atomic counter that never recycles IDs.
                     AUXILIARY_ID_COUNTER.fetch_add(1, Relaxed),
-                    crate::MODULE_NAME
-                ),
+                    crate::MODULE_NAME,
+                    (),
+                )?,
             }))
         })
     }
include/linux/auxiliary_bus.h +4 -0
index bc09b55e3682..4e1ad8ccbcdd 100644
@@ -62,6 +62,9 @@
  * @sysfs.irqs: irqs xarray contains irq indices which are used by the device,
  * @sysfs.lock: Synchronize irq sysfs creation,
  * @sysfs.irq_dir_exists: whether "irqs" directory exists,
+ * @registration_data_rust: private data owned by the registering (parent)
+ *                          driver; valid for as long as the device is
+ *                          registered with the driver core,
  *
  * An auxiliary_device represents a part of its parent device's functionality.
  * It is given a name that, combined with the registering drivers
@@ -148,6 +151,7 @@ struct auxiliary_device {
 		struct mutex lock; /* Synchronize irq sysfs creation */
 		bool irq_dir_exists;
 	} sysfs;
+	void *registration_data_rust;
 };
 
 /**
rust/kernel/auxiliary.rs +146 -62

251 lines not on this page · raw message

samples/rust/rust_driver_auxiliary.rs +25 -15
index 5c5a5105a3ff..319ef734c02b 100644
@@ -17,8 +17,6 @@
     InPlaceModule, //
 };
 
-use core::any::TypeId;
-
 const MODULE_NAME: &CStr = <LocalModule as kernel::ModuleMetadata>::NAME;
 const AUXILIARY_NAME: &CStr = c"auxiliary";
 
@@ -49,13 +47,13 @@ fn probe(adev: &auxiliary::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<S
     }
 }
 
-#[pin_data]
+struct Data {
+    index: u32,
+}
+
 struct ParentDriver {
-    private: TypeId,
-    #[pin]
-    _reg0: Devres<auxiliary::Registration>,
-    #[pin]
-    _reg1: Devres<auxiliary::Registration>,
+    _reg0: Devres<auxiliary::Registration<Data>>,
+    _reg1: Devres<auxiliary::Registration<Data>>,
 }
 
 kernel::pci_device_table!(
@@ -71,10 +69,21 @@ 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> {
-        try_pin_init!(Self {
-            private: TypeId::of::<Self>(),
-            _reg0 <- auxiliary::Registration::new(pdev.as_ref(), AUXILIARY_NAME, 0, MODULE_NAME),
-            _reg1 <- auxiliary::Registration::new(pdev.as_ref(), AUXILIARY_NAME, 1, MODULE_NAME),
+        Ok(Self {
+            _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 },
+            )?,
         })
     }
 }
@@ -83,7 +92,8 @@ impl ParentDriver {
     fn connect(adev: &auxiliary::Device<Bound>) -> Result {
         let dev = adev.parent();
         let pdev: &pci::Device<Bound> = dev.try_into()?;
-        let drvdata = dev.drvdata::<Self>()?;
+
+        let data = adev.registration_data::<Data>()?;
 
         dev_info!(
             dev,
@@ -95,8 +105,8 @@ fn connect(adev: &auxiliary::Device<Bound>) -> Result {
 
         dev_info!(
             dev,
-            "We have access to the private data of {:?}.\n",
-            drvdata.private
+            "Connected to auxiliary device with index {}.\n",
+            data.index
         );
 
         Ok(())
Signature · 1 line
2.54.0
maintainer Reviewed-by on v2 2/3
#7 lore raw

Re: [PATCH v2 2/3] rust: auxiliary: add registration data to auxiliary devices

Quoted 10 lines · Danilo Krummrich

Add a registration_data pointer to struct auxiliary_device, allowing the registering (parent) driver to attach private data to the device at registration time and retrieve it later when called back by the auxiliary (child) driver.

By tying the data to the device's registration, Rust drivers can bind the lifetime of device resources to it, since the auxiliary bus guarantees that the parent driver remains bound while the auxiliary device is bound.

Quoted 5 lines

On the Rust side, Registration<T> takes ownership of the data via ForeignOwnable. A TypeId is stored alongside the data for runtime type checking, making Device::registration_data<T>() a safe method.

The change itself LGTM.

But I'm not entirely convinced that this is the most convenient user-interface. I'm wondering if the auxiliary driver trait could specify which type the parent driver data is using in an associated type, and whether you could eliminate the check and error path that way. But then again, AuxiliaryDriver does not appear as a generic parameter in auxiliary::Driver, so it might not work.

Alice

reviewer
#8 lore raw

Re: [PATCH v2 2/3] rust: auxiliary: add registration data to auxiliary devices

Quoted 19 lines · Alice Ryhl
Quoted 10 lines · Danilo Krummrich

Add a registration_data pointer to struct auxiliary_device, allowing the registering (parent) driver to attach private data to the device at registration time and retrieve it later when called back by the auxiliary (child) driver.

By tying the data to the device's registration, Rust drivers can bind the lifetime of device resources to it, since the auxiliary bus guarantees that the parent driver remains bound while the auxiliary device is bound.

Quoted 5 lines

On the Rust side, Registration<T> takes ownership of the data via ForeignOwnable. A TypeId is stored alongside the data for runtime type checking, making Device::registration_data<T>() a safe method.

The change itself LGTM.

Quoted 8 lines

But I'm not entirely convinced that this is the most convenient user-interface. I'm wondering if the auxiliary driver trait could specify which type the parent driver data is using in an associated type, and whether you could eliminate the check and error path that way. But then again, AuxiliaryDriver does not appear as a generic parameter in auxiliary::Driver, so it might not work.

I think that's similar to what I'm suggesting in
https://lore.kernel.org/rust-for-linux/[email protected]/.

This does still require the type ID to exist and that probe of auxiliary drivers need to fail if type ID mismatches during probing.

Best,
Gary

author maintainer
#9 lore raw

Re: [PATCH v2 2/3] rust: auxiliary: add registration data to auxiliary devices

Quoted 16 lines · Gary Guo
Quoted 15 lines · Alice Ryhl
Quoted 14 lines · Danilo Krummrich

Add a registration_data pointer to struct auxiliary_device, allowing the registering (parent) driver to attach private data to the device at registration time and retrieve it later when called back by the auxiliary (child) driver.

By tying the data to the device's registration, Rust drivers can bind the lifetime of device resources to it, since the auxiliary bus guarantees that the parent driver remains bound while the auxiliary device is bound.

On the Rust side, Registration<T> takes ownership of the data via ForeignOwnable. A TypeId is stored alongside the data for runtime type checking, making Device::registration_data<T>() a safe method.

Quoted 5 lines
Quoted 5 lines
Quoted 1 line

The change itself LGTM.

Thanks!

Quoted 7 lines
Quoted 6 lines

But I'm not entirely convinced that this is the most convenient user-interface. I'm wondering if the auxiliary driver trait could specify which type the parent driver data is using in an associated type, and whether you could eliminate the check and error path that way. But then again, AuxiliaryDriver does not appear as a generic parameter in auxiliary::Driver, so it might not work.

Quoted 5 lines

I think that's similar to what I'm suggesting in
https://lore.kernel.org/rust-for-linux/[email protected]/.

This does still require the type ID to exist and that probe of auxiliary drivers need to fail if type ID mismatches during probing.

Technically, this would be an additional driver match criteria, i.e. the name string in struct auxiliary_device_id *and* the asserted type of the parent's registration data must match.

Given that drivers can match against multiple entries in the auxiliary_device_id table, we must consider that they can have different registration data types (depending on the specific parent driver that exposed the auxiliary device).

Thus, I don't think we can solve this without a runtime dispatch (over all types that would need to be listed in the ID table) anyway; and having this dispatch in the child driver - essentially leaking an implementation detail of each of the parents into the child - does not seem to add any value; quite the opposite unfortunately.

(OOC, I hacked up the statically typed version -- I think it turns out OK, despite the fact that it still leaks the parent's registration private data type to the child, which I dislike, plus a few hiccups with the generic device context infrastructure. But as mentioned, I don't think that's an option in the first place.)

author maintainer
#10 lore raw

Re: [PATCH v2 2/3] rust: auxiliary: add registration data to auxiliary devices

Quoted 14 lines · Danilo Krummrich

Technically, this would be an additional driver match criteria, i.e. the name string in struct auxiliary_device_id *and* the asserted type of the parent's registration data must match.

Given that drivers can match against multiple entries in the auxiliary_device_id table, we must consider that they can have different registration data types (depending on the specific parent driver that exposed the auxiliary device).

Thus, I don't think we can solve this without a runtime dispatch (over all types that would need to be listed in the ID table) anyway; and having this dispatch in the child driver - essentially leaking an implementation detail of each of the parents into the child - does not seem to add any value; quite the opposite unfortunately.

Quoted 5 lines

(OOC, I hacked up the statically typed version -- I think it turns out OK, despite the fact that it still leaks the parent's registration private data type to the child, which I dislike, plus a few hiccups with the generic device context infrastructure. But as mentioned, I don't think that's an option in the first place.)

One additional note: It would however be possible to support this as an additional special case (it is special implementation wise, but usage wise it is the common case) when there's only a single entry in the match table, and otherwise provide the option to fall back on the existing runtime dispatch.

That said, I'm still not convinced about exposing the type and whether it is worth the extra complexity on the child driver side, but I'd also like to further consider it as a potential subsequent improvement.

The draft implementation I mentioned previously can be found in [1]; it is based on top of the HRT rework, as it provides a much better picture of how it turns out eventually.

For now, I'll pick this up as is.

Thanks,
Danilo

[1] https://git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=poc/aux-typed

author maintainer
#11 lore raw

PATCH v2 3/3 rust: driver core: remove drvdata() and driver_type

In reply to Danilo Krummrich

When drvdata() was introduced in commit 6f61a2637abe ("rust: device:
introduce Device::drvdata()"), its commit message already noted that a direct accessor to the driver's bus device private data is not commonly required -- bus callbacks provide access through &self, and other entry points (IRQs, workqueues, IOCTLs, etc.) carry their own private data.

The sole motivation for drvdata() was inter-driver interaction -- an auxiliary driver deriving the parent's bus device private data from the parent device.

However, drvdata() exposes the driver's bus device private data beyond the driver's own scope. This creates ordering constraints; for instance drvdata may not be set yet when the first caller of drvdata() can appear. It also forces the driver's bus device private data to outlive all registrations that access it, which causes unnecessary complications.

Private data should be private to the entity that issues it, i.e. bus device private data belongs to bus callbacks, class device private data to class callbacks, IRQ private data to the IRQ handler, etc.

With registration-private data now available through the auxiliary bus, there is no remaining user of drvdata(), thus remove it.

---
 drivers/base/base.h   | 16 ------------
 rust/kernel/device.rs | 60 -------------------------------------------
 2 files changed, 76 deletions(-)
drivers/base/base.h +0 -16
index 0ed1e278b957..483b99b4fa3d 100644
@@ -86,18 +86,6 @@ struct driver_private {
 };
 #define to_driver(obj) container_of(obj, struct driver_private, kobj)
 
-#ifdef CONFIG_RUST
-/**
- * struct driver_type - Representation of a Rust driver type.
- */
-struct driver_type {
-	/**
-	 * @id: Representation of core::any::TypeId.
-	 */
-	u8 id[16];
-} __packed;
-#endif
-
 /**
  * struct device_private - structure to hold the private to the driver core
  *			   portions of the device structure.
@@ -115,7 +103,6 @@ struct driver_type {
  *			   dev_err_probe() for later retrieval via debugfs
  * @device: pointer back to the struct device that this structure is
  *	    associated with.
- * @driver_type: The type of the bound Rust driver.
  * @dead: This device is currently either in the process of or has been
  *	  removed from the system. Any asynchronous events scheduled for this
  *	  device should exit without taking any action.
@@ -132,9 +119,6 @@ struct device_private {
 	const struct device_driver *async_driver;
 	char *deferred_probe_reason;
 	struct device *device;
-#ifdef CONFIG_RUST
-	struct driver_type driver_type;
-#endif
 	u8 dead:1;
 };
 #define to_device_private_parent(obj)	\
rust/kernel/device.rs +0 -60

90 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer Applied
#12 lore raw
In reply to Danilo Krummrich
Quoted 1 line · Danilo Krummrich

[PATCH v2 0/3] rust: auxiliary: replace drvdata() with registration data

Applied, thanks!

Branch: topic/dd-lifetimes
Tree: git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git

[1/3] rust: alloc: add Box::zeroed()

      commit: abb21500e7e5
[2/3] rust: auxiliary: add registration data to auxiliary devices
      commit: fd3b87ff0232
[3/3] rust: driver core: remove drvdata() and driver_type
      commit: 95ade775c4ab

The patches are in the topic/dd-lifetimes topic branch and will be merged into the corresponding target branch soon.