[PATCH v6 1/2] rust: Add trait to convert a device reference to a bus device reference

Markus Probst posted 2 patches 3 months, 2 weeks ago
There is a newer version of this series
[PATCH v6 1/2] rust: Add trait to convert a device reference to a bus device reference
Posted by Markus Probst 3 months, 2 weeks ago
Implement the `AsBusDevice` trait for converting a `Device` reference to a
bus device reference for all bus devices.

The `AsBusDevice` trait allows abstractions to provide the bus device in
class device callbacks. It must not be used by drivers and is intended for
bus and class device abstractions only.

Signed-off-by: Markus Probst <markus.probst@posteo.de>
---
 rust/kernel/auxiliary.rs |  7 +++++++
 rust/kernel/device.rs    | 30 ++++++++++++++++++++++++++++++
 rust/kernel/pci.rs       |  7 +++++++
 rust/kernel/platform.rs  |  7 +++++++
 rust/kernel/usb.rs       |  6 ++++++
 5 files changed, 57 insertions(+)

diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs
index e11848bbf206..cd1121191137 100644
--- a/rust/kernel/auxiliary.rs
+++ b/rust/kernel/auxiliary.rs
@@ -15,6 +15,7 @@
 };
 use core::{
     marker::PhantomData,
+    mem::offset_of,
     ptr::{addr_of_mut, NonNull},
 };
 
@@ -239,6 +240,12 @@ extern "C" fn release(dev: *mut bindings::device) {
     }
 }
 
+// SAFETY: `auxilary::Device` is a transparent wrapper of `struct auxiliary_device`.
+// The offset is guaranteed to point to a valid device field inside `auxilary::Device`.
+unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
+    const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
+}
+
 // 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 });
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 1321e6f0b53c..d7024c2bb90f 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -511,6 +511,36 @@ impl DeviceContext for Core {}
 impl DeviceContext for CoreInternal {}
 impl DeviceContext for Normal {}
 
+/// Bus devices can implement this trait to allow abstractions to provide the bus device in
+/// class device callbacks.
+///
+/// This must not be used by drivers and is intended for bus and class device abstractions only.
+///
+/// # Safety
+///
+/// `AsBusDevice::OFFSET` must be a offset to a device field in the implemented struct.
+pub(crate) unsafe trait AsBusDevice<Ctx: DeviceContext>: AsRef<Device<Ctx>> {
+    /// The relative offset to the device field.
+    ///
+    /// Use `offset_of!(bindings, field)` macro to avoid breakage.
+    const OFFSET: usize;
+
+    /// Convert a reference to [`Device`] into `Self`.
+    ///
+    /// # Safety
+    ///
+    /// `dev` must be contained in `Self`.
+    unsafe fn from_device(dev: &Device<Ctx>) -> &Self
+    where
+        Self: Sized,
+    {
+        let raw = dev.as_raw();
+        // SAFETY: `raw - Self::OFFSET` is guaranteed by the safety requirements
+        // to be a valid pointer to `Self`.
+        unsafe { &*raw.byte_sub(Self::OFFSET).cast::<Self>() }
+    }
+}
+
 /// # Safety
 ///
 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 7fcc5f6022c1..d78f6feeaae9 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -19,6 +19,7 @@
 };
 use core::{
     marker::PhantomData,
+    mem::offset_of,
     ops::Deref,
     ptr::{addr_of_mut, NonNull},
 };
@@ -593,6 +594,12 @@ pub fn set_master(&self) {
     }
 }
 
+// SAFETY: `pci::Device` is a transparent wrapper of `struct pci_dev`.
+// The offset is guaranteed to point to a valid device field inside `pci::Device`.
+unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
+    const OFFSET: usize = offset_of!(bindings::pci_dev, dev);
+}
+
 // 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 });
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index 7205fe3416d3..7197264b5a53 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -19,6 +19,7 @@
 
 use core::{
     marker::PhantomData,
+    mem::offset_of,
     ptr::{addr_of_mut, NonNull},
 };
 
@@ -285,6 +286,12 @@ pub fn io_request_by_name(&self, name: &CStr) -> Option<IoRequest<'_>> {
     }
 }
 
+// SAFETY: `platform::Device` is a transparent wrapper of `struct platform_device`.
+// The offset is guaranteed to point to a valid device field inside `platform::Device`.
+unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
+    const OFFSET: usize = offset_of!(bindings::platform_device, dev);
+}
+
 macro_rules! define_irq_accessor_by_index {
     (
         $(#[$meta:meta])* $fn_name:ident,
diff --git a/rust/kernel/usb.rs b/rust/kernel/usb.rs
index 14ddb711bab3..ec21261baf6a 100644
--- a/rust/kernel/usb.rs
+++ b/rust/kernel/usb.rs
@@ -324,6 +324,12 @@ fn as_raw(&self) -> *mut bindings::usb_interface {
     }
 }
 
+// SAFETY: `usb::Interface` is a transparent wrapper of `struct usb_interface`.
+// The offset is guaranteed to point to a valid device field inside `usb::Interface`.
+unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Interface<Ctx> {
+    const OFFSET: usize = offset_of!(bindings::usb_interface, dev);
+}
+
 // SAFETY: `Interface` is a transparent wrapper of a type that doesn't depend on
 // `Interface`'s generic argument.
 kernel::impl_device_context_deref!(unsafe { Interface });
-- 
2.51.0
Re: [PATCH v6 1/2] rust: Add trait to convert a device reference to a bus device reference
Posted by Danilo Krummrich 3 months, 2 weeks ago
On 10/23/25 7:28 PM, Markus Probst wrote:
> +// SAFETY: `auxilary::Device` is a transparent wrapper of `struct auxiliary_device`.
> +// The offset is guaranteed to point to a valid device field inside `auxilary::Device`.

s/auxilary/auxiliary/

> +unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
> +    const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
> +}

<snip>

> +/// Bus devices can implement this trait to allow abstractions to provide the bus device in
> +/// class device callbacks.

In the first line, please briefly mention what the trait represents.
Subsequently, you can mention the use-case below as a more general description.

> +///
> +/// This must not be used by drivers and is intended for bus and class device abstractions only.
> +///
> +/// # Safety
> +///
> +/// `AsBusDevice::OFFSET` must be a offset to a device field in the implemented struct.

"... the offset of the embedded base `struct device` field within a bus device
structure"

> +pub(crate) unsafe trait AsBusDevice<Ctx: DeviceContext>: AsRef<Device<Ctx>> {
> +    /// The relative offset to the device field.
> +    ///
> +    /// Use `offset_of!(bindings, field)` macro to avoid breakage.
> +    const OFFSET: usize;
> +
> +    /// Convert a reference to [`Device`] into `Self`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `dev` must be contained in `Self`.
> +    unsafe fn from_device(dev: &Device<Ctx>) -> &Self
> +    where
> +        Self: Sized,
> +    {
> +        let raw = dev.as_raw();
> +        // SAFETY: `raw - Self::OFFSET` is guaranteed by the safety requirements
> +        // to be a valid pointer to `Self`.
> +        unsafe { &*raw.byte_sub(Self::OFFSET).cast::<Self>() }
> +    }
> +}