Skip to contentSkip to conversation

Implement "Bound" device context

PATCH In review Danilo Krummrich 4 participants 27 messages Apr 13, 2025 – Apr 17, 2025

Subsystems (5)
PCI Driver core Rust PCI Rust +1 more subsystems
lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

v2 cover Implement "Bound" device context

Currently, we do not ensure that APIs that require a bound device instance can only be called with a bound device.

Examples of such APIs are Devres, dma::CoherentAllocation and pci::Device::iomap_region().

This patch series introduces the "Bound" device context such that we can ensure to only ever pass a bound device to APIs that require this precondition.

In order to get there, we need some prerequisites:

(1) Implement macros to consistently derive Deref implementations for the different device contexts. For instance, Device<Core> can be dereferenced to Device<Bound>, since all device references we get from "core" bus callbacks are guaranteed to be from a bound device. Device<Bound> can always be dereferenced to Device (i.e. Device<Normal>), since the "Normal" device context has no specific requirements.

(2) Implement device context support for the generic Device type. Some APIs such as Devres and dma::CoherentAllocation work with generic devices.

(3) Preserve device context generics in bus specific device' AsRef implementation, such that we can derive the device context when converting from a bus specific device reference to a generic device reference.

With this, Devres::new(), for instance, can take a &Device<Bound> argument and hence ensure that it can't be called with a Device reference that is not guaranteed to be bound to a driver.

A branch containing the patches can be found in [1].

[1] https://web.git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=rust/device-bound

Changes in v2:
- add a safety requirement for impl_device_context_deref! (thanks to Benno for working this out)

Danilo Krummrich (9):
rust: device: implement impl_device_context_deref!
rust: device: implement impl_device_context_into_aref!
rust: device: implement device context for Device
rust: platform: preserve device context in AsRef
rust: pci: preserve device context in AsRef
rust: device: implement Bound device context
rust: pci: move iomap_region() to impl Device<Bound>
rust: devres: require a bound device
rust: dma: require a bound device

 rust/kernel/device.rs   | 90 ++++++++++++++++++++++++++++++++++++++++-
 rust/kernel/devres.rs   | 17 ++++----
 rust/kernel/dma.rs      | 14 +++----
 rust/kernel/pci.rs      | 33 +++++----------
 rust/kernel/platform.rs | 32 ++++-----------
 5 files changed, 121 insertions(+), 65 deletions(-)

base-commit: 0af2f6be1b4281385b618cb86ad946eded089ac8

Signature · 1 line
2.49.0
author maintainer
#1 lore raw

PATCH v2 1/9 rust: device: implement impl_device_context_deref!

The Deref hierarchy for device context generics is the same for every (bus specific) device.

Implement those with a generic macro to avoid duplicated boiler plate code and ensure the correct Deref hierarchy for every device implementation.

---
 rust/kernel/device.rs   | 44 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/pci.rs      | 16 +++------------
 rust/kernel/platform.rs | 17 +++-------------
 3 files changed, 50 insertions(+), 27 deletions(-)
rust/kernel/device.rs +44 -0
index 21b343a1dc4d..7cb6f0fc005d 100644
@@ -235,6 +235,50 @@ impl Sealed for super::Normal {}
 impl DeviceContext for Core {}
 impl DeviceContext for Normal {}
 
+/// # Safety
+///
+/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
+/// generic argument of `$device`.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __impl_device_context_deref {
+    (unsafe { $device:ident, $src:ty => $dst:ty }) => {
+        impl ::core::ops::Deref for $device<$src> {
+            type Target = $device<$dst>;
+
+            fn deref(&self) -> &Self::Target {
+                let ptr: *const Self = self;
+
+                // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
+                // safety requirement of the macro.
+                let ptr = ptr.cast::<Self::Target>();
+
+                // SAFETY: `ptr` was derived from `&self`.
+                unsafe { &*ptr }
+            }
+        }
+    };
+}
+
+/// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus
+/// specific) device.
+///
+/// # Safety
+///
+/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
+/// generic argument of `$device`.
+#[macro_export]
+macro_rules! impl_device_context_deref {
+    (unsafe { $device:ident }) => {
+        // SAFETY: This macro has the exact same safety requirement as
+        // `__impl_device_context_deref!`.
+        kernel::__impl_device_context_deref!(unsafe {
+            $device,
+            $crate::device::Core => $crate::device::Normal
+        });
+    };
+}
+
 #[doc(hidden)]
 #[macro_export]
 macro_rules! dev_printk {
rust/kernel/pci.rs +3 -13
index c97d6d470b28..8474608e7a90 100644
@@ -422,19 +422,9 @@ pub fn set_master(&self) {
     }
 }
 
-impl Deref for Device<device::Core> {
-    type Target = Device;
-
-    fn deref(&self) -> &Self::Target {
-        let ptr: *const Self = self;
-
-        // CAST: `Device<Ctx>` is a transparent wrapper of `Opaque<bindings::pci_dev>`.
-        let ptr = ptr.cast::<Device>();
-
-        // SAFETY: `ptr` was derived from `&self`.
-        unsafe { &*ptr }
-    }
-}
+// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
+// argument.
+kernel::impl_device_context_deref!(unsafe { Device });
 
 impl From<&Device<device::Core>> for ARef<Device> {
     fn from(dev: &Device<device::Core>) -> Self {
rust/kernel/platform.rs +3 -14
index 4917cb34e2fe..22590bdff7bb 100644
@@ -16,7 +16,6 @@
 
 use core::{
     marker::PhantomData,
-    ops::Deref,
     ptr::{addr_of_mut, NonNull},
 };
 
@@ -190,19 +189,9 @@ fn as_raw(&self) -> *mut bindings::platform_device {
     }
 }
 
-impl Deref for Device<device::Core> {
-    type Target = Device;
-
-    fn deref(&self) -> &Self::Target {
-        let ptr: *const Self = self;
-
-        // CAST: `Device<Ctx>` is a transparent wrapper of `Opaque<bindings::platform_device>`.
-        let ptr = ptr.cast::<Device>();
-
-        // SAFETY: `ptr` was derived from `&self`.
-        unsafe { &*ptr }
-    }
-}
+// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
+// argument.
+kernel::impl_device_context_deref!(unsafe { Device });
 
 impl From<&Device<device::Core>> for ARef<Device> {
     fn from(dev: &Device<device::Core>) -> Self {
Signature · 1 line
2.49.0
Reviewed-by on v2 1/9
#2 lore raw

Re: [PATCH v2 1/9] rust: device: implement impl_device_context_deref!

Quoted 21 lines · Danilo Krummrich

The Deref hierarchy for device context generics is the same for every (bus specific) device.

Implement those with a generic macro to avoid duplicated boiler plate code and ensure the correct Deref hierarchy for every device implementation.

---
 rust/kernel/device.rs   | 44 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/pci.rs      | 16 +++------------
 rust/kernel/platform.rs | 17 +++-------------
 3 files changed, 50 insertions(+), 27 deletions(-)
rust/kernel/device.rs +0 -0
index 21b343a1dc4d..7cb6f0fc005d 100644

rust/kernel/device.rs impl Sealed for super::Normal {} · line 241

Quoted 7 lines
rust/kernel/device.rs +4 -0
@@ -235,6 +235,50 @@ impl Sealed for super::Normal {}
 impl DeviceContext for Core {}
 impl DeviceContext for Normal {}
 
+/// # Safety
+///
+/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
+/// generic argument of `$device`.

Maybe explicitly mention that the memory layout/representation therefore doesn't depend on the generic arguments.

Either way:

Cheers
Christian

#3 lore raw

Re: [PATCH v2 1/9] rust: device: implement impl_device_context_deref!

In reply to Danilo Krummrich

rust/kernel/device.rs impl Sealed for super::Normal {} · line 275

Quoted 13 lines · Danilo Krummrich
rust/kernel/device.rs +13 -0
+/// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus
+/// specific) device.
+///
+/// # Safety
+///
+/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
+/// generic argument of `$device`.
+#[macro_export]
+macro_rules! impl_device_context_deref {
+    (unsafe { $device:ident }) => {
+        // SAFETY: This macro has the exact same safety requirement as
+        // `__impl_device_context_deref!`.
+        kernel::__impl_device_context_deref!(unsafe {

Missing :: in front of kernel.

---
Cheers,
Benno

Quoted 9 lines
rust/kernel/device.rs +6 -0
+            $device,
+            $crate::device::Core => $crate::device::Normal
+        });
+    };
+}
+
 #[doc(hidden)]
 #[macro_export]
 macro_rules! dev_printk {
author maintainer
#4 lore raw

PATCH v2 2/9 rust: device: implement impl_device_context_into_aref!

In reply to Danilo Krummrich

Implement a macro to implement all From conversions of a certain device to ARef<Device>.

This avoids unnecessary boiler plate code for every device implementation.

---
 rust/kernel/device.rs   | 21 +++++++++++++++++++++
 rust/kernel/pci.rs      |  7 +------
 rust/kernel/platform.rs |  9 ++-------
 3 files changed, 24 insertions(+), 13 deletions(-)
rust/kernel/device.rs +21 -0
index 7cb6f0fc005d..26e71224460b 100644
@@ -279,6 +279,27 @@ macro_rules! impl_device_context_deref {
     };
 }
 
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __impl_device_context_into_aref {
+    ($src:ty, $device:tt) => {
+        impl core::convert::From<&$device<$src>> for $crate::types::ARef<$device> {
+            fn from(dev: &$device<$src>) -> Self {
+                (&**dev).into()
+            }
+        }
+    };
+}
+
+/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
+/// `ARef<Device>`.
+#[macro_export]
+macro_rules! impl_device_context_into_aref {
+    ($device:tt) => {
+        kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
+    };
+}
+
 #[doc(hidden)]
 #[macro_export]
 macro_rules! dev_printk {
rust/kernel/pci.rs +1 -6
index 8474608e7a90..7c6ec05383e0 100644
@@ -425,12 +425,7 @@ pub fn set_master(&self) {
 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
 // argument.
 kernel::impl_device_context_deref!(unsafe { Device });
-
-impl From<&Device<device::Core>> for ARef<Device> {
-    fn from(dev: &Device<device::Core>) -> Self {
-        (&**dev).into()
-    }
-}
+kernel::impl_device_context_into_aref!(Device);
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::types::AlwaysRefCounted for Device {
rust/kernel/platform.rs +2 -7
index 22590bdff7bb..9476b717c425 100644
@@ -10,7 +10,7 @@
     of,
     prelude::*,
     str::CStr,
-    types::{ARef, ForeignOwnable, Opaque},
+    types::{ForeignOwnable, Opaque},
     ThisModule,
 };
 
@@ -192,12 +192,7 @@ fn as_raw(&self) -> *mut bindings::platform_device {
 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
 // argument.
 kernel::impl_device_context_deref!(unsafe { Device });
-
-impl From<&Device<device::Core>> for ARef<Device> {
-    fn from(dev: &Device<device::Core>) -> Self {
-        (&**dev).into()
-    }
-}
+kernel::impl_device_context_into_aref!(Device);
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::types::AlwaysRefCounted for Device {
Signature · 1 line
2.49.0
Reviewed-by on v2 2/9
#5 lore raw

Re: [PATCH v2 2/9] rust: device: implement impl_device_context_into_aref!

Quoted 7 lines · Danilo Krummrich

Implement a macro to implement all From conversions of a certain device to ARef<Device>.

This avoids unnecessary boiler plate code for every device implementation.

One nit below, with that fixed:

Quoted 11 lines
---
 rust/kernel/device.rs   | 21 +++++++++++++++++++++
 rust/kernel/pci.rs      |  7 +------
 rust/kernel/platform.rs |  9 ++-------
 3 files changed, 24 insertions(+), 13 deletions(-)
rust/kernel/device.rs +0 -0
index 7cb6f0fc005d..26e71224460b 100644

rust/kernel/device.rs macro_rules! impl_device_context_deref { · line 286

Quoted 8 lines
rust/kernel/device.rs +5 -0
@@ -279,6 +279,27 @@ macro_rules! impl_device_context_deref {
     };
 }
 
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __impl_device_context_into_aref {
+    ($src:ty, $device:tt) => {
+        impl core::convert::From<&$device<$src>> for $crate::types::ARef<$device> {

Missing :: in front of core.

Quoted 19 lines
rust/kernel/device.rs +16 -0
+            fn from(dev: &$device<$src>) -> Self {
+                (&**dev).into()
+            }
+        }
+    };
+}
+
+/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
+/// `ARef<Device>`.
+#[macro_export]
+macro_rules! impl_device_context_into_aref {
+    ($device:tt) => {
+        kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
+    };
+}
+
 #[doc(hidden)]
 #[macro_export]
 macro_rules! dev_printk {
author maintainer
#6 lore raw

PATCH v2 3/9 rust: device: implement device context for Device

In reply to Danilo Krummrich

Analogous to bus specific device, implement the DeviceContext generic for generic devices.

This is used for APIs that work with generic devices (such as Devres) to evaluate the device' context.

---
 rust/kernel/device.rs | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
rust/kernel/device.rs +9 -2
index 26e71224460b..487211842f77 100644
@@ -9,7 +9,7 @@
     str::CStr,
     types::{ARef, Opaque},
 };
-use core::{fmt, ptr};
+use core::{fmt, marker::PhantomData, ptr};
 
 #[cfg(CONFIG_PRINTK)]
 use crate::c_str;
@@ -42,7 +42,7 @@
 /// `bindings::device::release` is valid to be called from any thread, hence `ARef<Device>` can be
 /// dropped from any thread.
 #[repr(transparent)]
-pub struct Device(Opaque<bindings::device>);
+pub struct Device<Ctx: DeviceContext = Normal>(Opaque<bindings::device>, PhantomData<Ctx>);
 
 impl Device {
     /// Creates a new reference-counted abstraction instance of an existing `struct device` pointer.
@@ -59,7 +59,9 @@ pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> {
         // SAFETY: By the safety requirements ptr is valid
         unsafe { Self::as_ref(ptr) }.into()
     }
+}
 
+impl<Ctx: DeviceContext> Device<Ctx> {
     /// Obtain the raw `struct device *`.
     pub(crate) fn as_raw(&self) -> *mut bindings::device {
         self.0.get()
@@ -189,6 +191,11 @@ pub fn property_present(&self, name: &CStr) -> bool {
     }
 }
 
+// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
+// argument.
+kernel::impl_device_context_deref!(unsafe { Device });
+kernel::impl_device_context_into_aref!(Device);
+
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::types::AlwaysRefCounted for Device {
     fn inc_ref(&self) {
Signature · 1 line
2.49.0
Reviewed-by on v2 3/9
#7 lore raw

Re: [PATCH v2 3/9] rust: device: implement device context for Device

Quoted 7 lines · Danilo Krummrich

Analogous to bus specific device, implement the DeviceContext generic for generic devices.

This is used for APIs that work with generic devices (such as Devres) to evaluate the device' context.

---
Cheers,
Benno

Quoted 3 lines
---
 rust/kernel/device.rs | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
#8 lore raw

Re: [PATCH v2 3/9] rust: device: implement device context for Device

In reply to Danilo Krummrich
Quoted 5 lines · Danilo Krummrich

Analogous to bus specific device, implement the DeviceContext generic for generic devices.

This is used for APIs that work with generic devices (such as Devres) to evaluate the device' context.

Looks like a stray ', but maybe it's some rust thing I don't know about.

author maintainer
#9 lore raw

PATCH v2 4/9 rust: platform: preserve device context in AsRef

In reply to Danilo Krummrich

Since device::Device has a generic over its context, preserve this device context in AsRef.

For instance, when calling platform::Device<Core> the new AsRef implementation returns device::Device<Core>.

---
 rust/kernel/platform.rs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
rust/kernel/platform.rs +3 -3
index 9476b717c425..b1c48cd95cd6 100644
@@ -183,7 +183,7 @@ pub struct Device<Ctx: device::DeviceContext = device::Normal>(
     PhantomData<Ctx>,
 );
 
-impl Device {
+impl<Ctx: device::DeviceContext> Device<Ctx> {
     fn as_raw(&self) -> *mut bindings::platform_device {
         self.0.get()
     }
@@ -207,8 +207,8 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
     }
 }
 
-impl AsRef<device::Device> for Device {
-    fn as_ref(&self) -> &device::Device {
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
+    fn as_ref(&self) -> &device::Device<Ctx> {
         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
         // `struct platform_device`.
         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
Signature · 1 line
2.49.0
Reviewed-by on v2 4/9
#10 lore raw

Re: [PATCH v2 4/9] rust: platform: preserve device context in AsRef

Quoted 7 lines · Danilo Krummrich

Since device::Device has a generic over its context, preserve this device context in AsRef.

For instance, when calling platform::Device<Core> the new AsRef implementation returns device::Device<Core>.

---
Cheers,
Benno

Quoted 3 lines
---
 rust/kernel/platform.rs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
author maintainer
#11 lore raw

PATCH v2 5/9 rust: pci: preserve device context in AsRef

In reply to Danilo Krummrich

Since device::Device has a generic over its context, preserve this device context in AsRef.

For instance, when calling pci::Device<Core> the new AsRef implementation returns device::Device<Core>.

---
 rust/kernel/pci.rs | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
rust/kernel/pci.rs +5 -3
index 7c6ec05383e0..1234b0c4a403 100644
@@ -360,11 +360,13 @@ fn deref(&self) -> &Self::Target {
     }
 }
 
-impl Device {
+impl<Ctx: device::DeviceContext> Device<Ctx> {
     fn as_raw(&self) -> *mut bindings::pci_dev {
         self.0.get()
     }
+}
 
+impl Device {
     /// Returns the PCI vendor ID.
     pub fn vendor_id(&self) -> u16 {
         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
@@ -440,8 +442,8 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
     }
 }
 
-impl AsRef<device::Device> for Device {
-    fn as_ref(&self) -> &device::Device {
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
+    fn as_ref(&self) -> &device::Device<Ctx> {
         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
         // `struct pci_dev`.
         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
Signature · 1 line
2.49.0
Reviewed-by on v2 5/9
#12 lore raw

Re: [PATCH v2 5/9] rust: pci: preserve device context in AsRef

Quoted 7 lines · Danilo Krummrich

Since device::Device has a generic over its context, preserve this device context in AsRef.

For instance, when calling pci::Device<Core> the new AsRef implementation returns device::Device<Core>.

---
Cheers,
Benno

Quoted 3 lines
---
 rust/kernel/pci.rs | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
author maintainer
#13 lore raw

PATCH v2 6/9 rust: device: implement Bound device context

In reply to Danilo Krummrich

The Bound device context indicates that a device is bound to a driver. It must be used for APIs that require the device to be bound, such as Devres or dma::CoherentAllocation.

Implement Bound and add the corresponding Deref hierarchy, as well as the corresponding ARef conversion for this device context.

---
 rust/kernel/device.rs | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
rust/kernel/device.rs +15 -1
index 487211842f77..585a3fcfeea3 100644
@@ -232,13 +232,19 @@ pub trait DeviceContext: private::Sealed {}
 /// any of the bus callbacks, such as `probe()`.
 pub struct Core;
 
+/// The [`Bound`] context is the context of a bus specific device reference when it is guranteed to
+/// be bound for the duration of its lifetime.
+pub struct Bound;
+
 mod private {
     pub trait Sealed {}
 
+    impl Sealed for super::Bound {}
     impl Sealed for super::Core {}
     impl Sealed for super::Normal {}
 }
 
+impl DeviceContext for Bound {}
 impl DeviceContext for Core {}
 impl DeviceContext for Normal {}
 
@@ -281,7 +287,14 @@ macro_rules! impl_device_context_deref {
         // `__impl_device_context_deref!`.
         kernel::__impl_device_context_deref!(unsafe {
             $device,
-            $crate::device::Core => $crate::device::Normal
+            $crate::device::Core => $crate::device::Bound
+        });
+
+        // SAFETY: This macro has the exact same safety requirement as
+        // `__impl_device_context_deref!`.
+        kernel::__impl_device_context_deref!(unsafe {
+            $device,
+            $crate::device::Bound => $crate::device::Normal
         });
     };
 }
@@ -304,6 +317,7 @@ fn from(dev: &$device<$src>) -> Self {
 macro_rules! impl_device_context_into_aref {
     ($device:tt) => {
         kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
+        kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);
     };
 }
 
Signature · 1 line
2.49.0
Reviewed-by on v2 6/9
#14 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

Quoted 8 lines · Danilo Krummrich

The Bound device context indicates that a device is bound to a driver. It must be used for APIs that require the device to be bound, such as Devres or dma::CoherentAllocation.

Implement Bound and add the corresponding Deref hierarchy, as well as the corresponding ARef conversion for this device context.

One suggestion below, feel free to make it its own patch or fold it into the correct ones. Also two :: nits below, with those fixed:

Quoted 10 lines
---
 rust/kernel/device.rs | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
rust/kernel/device.rs +0 -0
index 487211842f77..585a3fcfeea3 100644

rust/kernel/device.rs macro_rules! impl_device_context_deref { · line 295

Quoted 10 lines
rust/kernel/device.rs +6 -1
@@ -281,7 +287,14 @@ macro_rules! impl_device_context_deref {
         // `__impl_device_context_deref!`.
         kernel::__impl_device_context_deref!(unsafe {
             $device,
-            $crate::device::Core => $crate::device::Normal
+            $crate::device::Core => $crate::device::Bound
+        });
+
+        // SAFETY: This macro has the exact same safety requirement as
+        // `__impl_device_context_deref!`.
+        kernel::__impl_device_context_deref!(unsafe {

Missing ::.

rust/kernel/device.rs macro_rules! impl_device_context_deref { · line 297

Quoted 2 lines
rust/kernel/device.rs +2 -0
+            $device,
+            $crate::device::Bound => $crate::device::Normal

IIUC, all "devices" (so eg pci::Device) will use this macro, right? In that case, I think we can document this behavior a bit better, possibly on the DeviceContext context trait and/or on the different type states. So on Core we could say "The Core context is a supercontext of the [Bound] context and devices also expose operations available in that context while in Core." and similarly on Bound with Normal.

rust/kernel/device.rs fn from(dev: &$device<$src>) -> Self { · line 320

Quoted 8 lines
rust/kernel/device.rs +1 -0
         });
     };
 }
@@ -304,6 +317,7 @@ fn from(dev: &$device<$src>) -> Self {
 macro_rules! impl_device_context_into_aref {
     ($device:tt) => {
         kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
+        kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);

Missing ::.

---
Cheers,
Benno

Quoted 3 lines
rust/kernel/device.rs +0 -0
     };
 }
 
author maintainer
#15 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

Quoted 11 lines · Benno Lossin

rust/kernel/device.rs macro_rules! impl_device_context_deref { · line 297

Quoted 2 lines · Danilo Krummrich
rust/kernel/device.rs +2 -0
+            $device,
+            $crate::device::Bound => $crate::device::Normal

IIUC, all "devices" (so eg pci::Device) will use this macro, right? In that case, I think we can document this behavior a bit better, possibly on the DeviceContext context trait and/or on the different type states. So on Core we could say "The Core context is a supercontext of the [Bound] context and devices also expose operations available in that context while in Core." and similarly on Bound with Normal.

Fully agree, I absolutely want to have this documented. I wasn't yet sure where I want to document this though. device::DeviceContext seems to be a reasonable place.

Besides that, I think I also want to rename it to device::Context, not sure if it's worth though.

I will send a subsequent patch for the documentation on DeviceContext.

#16 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

Quoted 13 lines · Danilo Krummrich
Quoted 11 lines · Benno Lossin

rust/kernel/device.rs macro_rules! impl_device_context_deref { · line 297

Quoted 2 lines · Danilo Krummrich
rust/kernel/device.rs +2 -0
+            $device,
+            $crate::device::Bound => $crate::device::Normal

IIUC, all "devices" (so eg pci::Device) will use this macro, right? In that case, I think we can document this behavior a bit better, possibly on the DeviceContext context trait and/or on the different type states. So on Core we could say "The Core context is a supercontext of the [Bound] context and devices also expose operations available in that context while in Core." and similarly on Bound with Normal.

Quoted 6 lines

Fully agree, I absolutely want to have this documented. I wasn't yet sure where I want to document this though. device::DeviceContext seems to be a reasonable place.

Besides that, I think I also want to rename it to device::Context, not sure if it's worth though.

Sounds reasonable to me.

---
Cheers,
Benno

#17 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

In reply to Danilo Krummrich
Quoted 17 lines · Danilo Krummrich

The Bound device context indicates that a device is bound to a driver. It must be used for APIs that require the device to be bound, such as Devres or dma::CoherentAllocation.

Implement Bound and add the corresponding Deref hierarchy, as well as the corresponding ARef conversion for this device context.

---
 rust/kernel/device.rs | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
rust/kernel/device.rs +0 -0
index 487211842f77..585a3fcfeea3 100644

rust/kernel/device.rs pub trait DeviceContext: private::Sealed {} · line 237

Quoted 6 lines
rust/kernel/device.rs +3 -0
@@ -232,13 +232,19 @@ pub trait DeviceContext: private::Sealed {}
 /// any of the bus callbacks, such as `probe()`.
 pub struct Core;
 
+/// The [`Bound`] context is the context of a bus specific device reference when it is guranteed to
+/// be bound for the duration of its lifetime.
+pub struct Bound;

One question about this: is it possible for me to
1. have access to a ARef<Device<Bound>> (or Core) via some callback,
2. store a clone of the ARef in some datastructure,
3. wait for the device to become unbound,
4. use a Bound-only context function and blow something up?

Depending on the severity of the "blow something up" we probably need to change the design. If it's "only a bug" (and not a memory vulnerability), then this is fine, since people should then "just not do that" (and I think this design makes that painfully obvious when someone tries to do something funny with a Device<Bound>).

---
Cheers,
Benno

author maintainer
#18 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

Quoted 21 lines · Benno Lossin
Quoted 20 lines · Danilo Krummrich

The Bound device context indicates that a device is bound to a driver. It must be used for APIs that require the device to be bound, such as Devres or dma::CoherentAllocation.

Implement Bound and add the corresponding Deref hierarchy, as well as the corresponding ARef conversion for this device context.

---
 rust/kernel/device.rs | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
rust/kernel/device.rs +0 -0
index 487211842f77..585a3fcfeea3 100644
@@ -232,13 +232,19 @@ pub trait DeviceContext: private::Sealed {}
 /// any of the bus callbacks, such as `probe()`.
 pub struct Core;
 
Quoted 9 lines

rust/kernel/device.rs pub trait DeviceContext: private::Sealed {} · line 237

Quoted 3 lines
rust/kernel/device.rs +3 -0
+/// The [`Bound`] context is the context of a bus specific device reference when it is guranteed to
+/// be bound for the duration of its lifetime.
+pub struct Bound;

One question about this: is it possible for me to
1. have access to a ARef<Device<Bound>> (or Core) via some callback,
2. store a clone of the ARef in some datastructure,
3. wait for the device to become unbound,
4. use a Bound-only context function and blow something up?

You can never get an ARef<Device> that has a different device context than Normal.

A device must only ever implement AlwaysRefCounted for Device (i.e. Device<Normal>).

This is why patch 2 ("rust: device: implement impl_device_context_into_aref!") implements conversions from Device<Ctx> to ARef<Device>.

#19 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

Quoted 32 lines · Danilo Krummrich
Quoted 21 lines · Benno Lossin
Quoted 20 lines · Danilo Krummrich

The Bound device context indicates that a device is bound to a driver. It must be used for APIs that require the device to be bound, such as Devres or dma::CoherentAllocation.

Implement Bound and add the corresponding Deref hierarchy, as well as the corresponding ARef conversion for this device context.

---
 rust/kernel/device.rs | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
rust/kernel/device.rs +0 -0
index 487211842f77..585a3fcfeea3 100644
@@ -232,13 +232,19 @@ pub trait DeviceContext: private::Sealed {}
 /// any of the bus callbacks, such as `probe()`.
 pub struct Core;
 
Quoted 9 lines

rust/kernel/device.rs pub trait DeviceContext: private::Sealed {} · line 237

Quoted 3 lines
rust/kernel/device.rs +3 -0
+/// The [`Bound`] context is the context of a bus specific device reference when it is guranteed to
+/// be bound for the duration of its lifetime.
+pub struct Bound;

One question about this: is it possible for me to
1. have access to a ARef<Device<Bound>> (or Core) via some callback,
2. store a clone of the ARef in some datastructure,
3. wait for the device to become unbound,
4. use a Bound-only context function and blow something up?

Quoted 5 lines

You can never get an ARef<Device> that has a different device context than Normal.

A device must only ever implement AlwaysRefCounted for Device (i.e. Device<Normal>).

Ah yes, I thought there was something there, that's perfect. Might also be a good idea to write this down before it becomes tribal knowledge :)

---
Cheers,
Benno

#20 lore raw

Re: [PATCH v2 6/9] rust: device: implement Bound device context

In reply to Danilo Krummrich
Quoted 17 lines · Danilo Krummrich

The Bound device context indicates that a device is bound to a driver. It must be used for APIs that require the device to be bound, such as Devres or dma::CoherentAllocation.

Implement Bound and add the corresponding Deref hierarchy, as well as the corresponding ARef conversion for this device context.

---
 rust/kernel/device.rs | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
rust/kernel/device.rs +0 -0
index 487211842f77..585a3fcfeea3 100644

rust/kernel/device.rs pub trait DeviceContext: private::Sealed {} · line 236

Quoted 5 lines
rust/kernel/device.rs +2 -0
@@ -232,13 +232,19 @@ pub trait DeviceContext: private::Sealed {}
 /// any of the bus callbacks, such as `probe()`.
 pub struct Core;
 
+/// The [`Bound`] context is the context of a bus specific device reference when it is guranteed to
+/// be bound for the duration of its lifetime.

s/guranteed/guaranteed/

author maintainer
#21 lore raw

PATCH v2 7/9 rust: pci: move iomap_region() to impl Device<Bound>

In reply to Danilo Krummrich

Require the Bound device context to be able to call iomap_region() and iomap_region_sized(). Creating I/O mapping requires the device to be bound.

---
 rust/kernel/pci.rs | 2 ++
 1 file changed, 2 insertions(+)
rust/kernel/pci.rs +2 -0
index 1234b0c4a403..3664d35b8e79 100644
@@ -390,7 +390,9 @@ pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
         // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
         Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) })
     }
+}
 
+impl Device<device::Bound> {
     /// Mapps an entire PCI-BAR after performing a region-request on it. I/O operation bound checks
     /// can be performed on compile time for offsets (plus the requested type size) < SIZE.
     pub fn iomap_region_sized<const SIZE: usize>(
Signature · 1 line
2.49.0
Reviewed-by on v2 7/9
#22 lore raw

Re: [PATCH v2 7/9] rust: pci: move iomap_region() to impl Device<Bound>

Quoted 5 lines · Danilo Krummrich

Require the Bound device context to be able to call iomap_region() and iomap_region_sized(). Creating I/O mapping requires the device to be bound.

---
Cheers,
Benno

Quoted 3 lines
---
 rust/kernel/pci.rs | 2 ++
 1 file changed, 2 insertions(+)
#23 lore raw

Re: [PATCH v2 7/9] rust: pci: move iomap_region() to impl Device<Bound>

In reply to Danilo Krummrich
Quoted 14 lines · Danilo Krummrich

Require the Bound device context to be able to call iomap_region() and iomap_region_sized(). Creating I/O mapping requires the device to be bound.

---
 rust/kernel/pci.rs | 2 ++
 1 file changed, 2 insertions(+)
rust/kernel/pci.rs +0 -0
index 1234b0c4a403..3664d35b8e79 100644

rust/kernel/pci.rs pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> { · line 397

Quoted 8 lines
rust/kernel/pci.rs +2 -0
@@ -390,7 +390,9 @@ pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
         // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
         Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) })
     }
+}
 
+impl Device<device::Bound> {
     /// Mapps an entire PCI-BAR after performing a region-request on it. I/O operation bound checks
     /// can be performed on compile time for offsets (plus the requested type size) < SIZE.

You didn't add these typos here, but

s/Mapps/Maps/
s/on compile time/at compile time/

Quoted 4 lines
rust/kernel/pci.rs +0 -0
     pub fn iomap_region_sized<const SIZE: usize>(
Signature · 1 line
2.49.0
author maintainer
#24 lore raw

PATCH v2 8/9 rust: devres: require a bound device

In reply to Danilo Krummrich

Require the Bound device context to be able to a new Devres container. This ensures that we can't register devres callbacks for unbound devices.

---
 rust/kernel/devres.rs | 17 +++++++----------
 1 file changed, 7 insertions(+), 10 deletions(-)
rust/kernel/devres.rs +7 -10
index ddb1ce4a78d9..1e58f5d22044 100644
@@ -8,7 +8,7 @@
 use crate::{
     alloc::Flags,
     bindings,
-    device::Device,
+    device::{Bound, Device},
     error::{Error, Result},
     ffi::c_void,
     prelude::*,
@@ -45,7 +45,7 @@ struct DevresInner<T> {
 /// # Example
 ///
 /// ```no_run
-/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::{Io, IoRaw}};
+/// # use kernel::{bindings, c_str, device::{Bound, Device}, devres::Devres, io::{Io, IoRaw}};
 /// # use core::ops::Deref;
 ///
 /// // See also [`pci::Bar`] for a real example.
@@ -83,13 +83,10 @@ struct DevresInner<T> {
 ///         unsafe { Io::from_raw(&self.0) }
 ///    }
 /// }
-/// # fn no_run() -> Result<(), Error> {
-/// # // SAFETY: Invalid usage; just for the example to get an `ARef<Device>` instance.
-/// # let dev = unsafe { Device::get_device(core::ptr::null_mut()) };
-///
+/// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
 /// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
-/// let devres = Devres::new(&dev, iomem, GFP_KERNEL)?;
+/// let devres = Devres::new(dev, iomem, GFP_KERNEL)?;
 ///
 /// let res = devres.try_access().ok_or(ENXIO)?;
 /// res.write8(0x42, 0x0);
@@ -99,7 +96,7 @@ struct DevresInner<T> {
 pub struct Devres<T>(Arc<DevresInner<T>>);
 
 impl<T> DevresInner<T> {
-    fn new(dev: &Device, data: T, flags: Flags) -> Result<Arc<DevresInner<T>>> {
+    fn new(dev: &Device<Bound>, data: T, flags: Flags) -> Result<Arc<DevresInner<T>>> {
         let inner = Arc::pin_init(
             pin_init!( DevresInner {
                 dev: dev.into(),
@@ -171,7 +168,7 @@ fn remove_action(this: &Arc<Self>) {
 impl<T> Devres<T> {
     /// Creates a new [`Devres`] instance of the given `data`. The `data` encapsulated within the
     /// returned `Devres` instance' `data` will be revoked once the device is detached.
-    pub fn new(dev: &Device, data: T, flags: Flags) -> Result<Self> {
+    pub fn new(dev: &Device<Bound>, data: T, flags: Flags) -> Result<Self> {
         let inner = DevresInner::new(dev, data, flags)?;
 
         Ok(Devres(inner))
@@ -179,7 +176,7 @@ pub fn new(dev: &Device, data: T, flags: Flags) -> Result<Self> {
 
     /// Same as [`Devres::new`], but does not return a `Devres` instance. Instead the given `data`
     /// is owned by devres and will be revoked / dropped, once the device is detached.
-    pub fn new_foreign_owned(dev: &Device, data: T, flags: Flags) -> Result {
+    pub fn new_foreign_owned(dev: &Device<Bound>, data: T, flags: Flags) -> Result {
         let _ = DevresInner::new(dev, data, flags)?;
 
         Ok(())
Signature · 1 line
2.49.0
author maintainer
#25 lore raw

PATCH v2 9/9 rust: dma: require a bound device

In reply to Danilo Krummrich

Require the Bound device context to be able to create new dma::CoherentAllocation instances.

DMA memory allocations are only valid to be created for bound devices.

---
 rust/kernel/dma.rs | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
rust/kernel/dma.rs +7 -7
index 8cdc76043ee7..605e01e35715 100644
@@ -6,7 +6,7 @@
 
 use crate::{
     bindings, build_assert,
-    device::Device,
+    device::{Bound, Device},
     error::code::*,
     error::Result,
     transmute::{AsBytes, FromBytes},
@@ -22,10 +22,10 @@
 /// # Examples
 ///
 /// ```
-/// use kernel::device::Device;
+/// # use kernel::device::{Bound, Device};
 /// use kernel::dma::{attrs::*, CoherentAllocation};
 ///
-/// # fn test(dev: &Device) -> Result {
+/// # fn test(dev: &Device<Bound>) -> Result {
 /// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
 /// let c: CoherentAllocation<u64> =
 ///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;
@@ -143,16 +143,16 @@ impl<T: AsBytes + FromBytes> CoherentAllocation<T> {
     /// # Examples
     ///
     /// ```
-    /// use kernel::device::Device;
+    /// # use kernel::device::{Bound, Device};
     /// use kernel::dma::{attrs::*, CoherentAllocation};
     ///
-    /// # fn test(dev: &Device) -> Result {
+    /// # fn test(dev: &Device<Bound>) -> Result {
     /// let c: CoherentAllocation<u64> =
     ///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
     /// # Ok::<(), Error>(()) }
     /// ```
     pub fn alloc_attrs(
-        dev: &Device,
+        dev: &Device<Bound>,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -194,7 +194,7 @@ pub fn alloc_attrs(
     /// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the
     /// `dma_attrs` is 0 by default.
     pub fn alloc_coherent(
-        dev: &Device,
+        dev: &Device<Bound>,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
     ) -> Result<CoherentAllocation<T>> {
Signature · 1 line
2.49.0
author maintainer
#26 lore raw
In reply to Danilo Krummrich
Quoted 25 lines · Danilo Krummrich

Currently, we do not ensure that APIs that require a bound device instance can only be called with a bound device.

Examples of such APIs are Devres, dma::CoherentAllocation and pci::Device::iomap_region().

This patch series introduces the "Bound" device context such that we can ensure to only ever pass a bound device to APIs that require this precondition.

In order to get there, we need some prerequisites:

(1) Implement macros to consistently derive Deref implementations for the different device contexts. For instance, Device<Core> can be dereferenced to Device<Bound>, since all device references we get from "core" bus callbacks are guaranteed to be from a bound device. Device<Bound> can always be dereferenced to Device (i.e. Device<Normal>), since the "Normal" device context has no specific requirements.

(2) Implement device context support for the generic Device type. Some APIs such as Devres and dma::CoherentAllocation work with generic devices.

(3) Preserve device context generics in bus specific device' AsRef implementation, such that we can derive the device context when converting from a bus specific device reference to a generic device reference.

Quoted 7 lines

With this, Devres::new(), for instance, can take a &Device<Bound> argument and hence ensure that it can't be called with a Device reference that is not guaranteed to be bound to a driver.

A branch containing the patches can be found in [1].

[1] https://web.git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=rust/device-bound

With the following changes, applied to driver-core/topic/device-context, thanks!

* Add missing :: prefix in macros.
* Fix typos pointed out by Bjorn.

- Danilo