[PATCH v2 3/4] rust: auxiliary: add auxiliary registration

Danilo Krummrich posted 4 patches 9 months, 1 week ago
There is a newer version of this series
[PATCH v2 3/4] rust: auxiliary: add auxiliary registration
Posted by Danilo Krummrich 9 months, 1 week ago
Implement the `auxiliary::Registration` type, which provides an API to
create and register new auxiliary devices in the system.

Signed-off-by: Danilo Krummrich <dakr@kernel.org>
---
 rust/kernel/auxiliary.rs | 80 +++++++++++++++++++++++++++++++++++++++-
 1 file changed, 79 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs
index e453f821f7cb..fc4bb5388a9b 100644
--- a/rust/kernel/auxiliary.rs
+++ b/rust/kernel/auxiliary.rs
@@ -5,7 +5,7 @@
 //! C header: [`include/linux/auxiliary_bus.h`](srctree/include/linux/auxiliary_bus.h)
 
 use crate::{
-    bindings, device,
+    bindings, container_of, device,
     device_id::RawDeviceId,
     driver,
     error::{to_result, Result},
@@ -219,6 +219,16 @@ pub fn id(&self) -> u32 {
         // `struct auxiliary_device`.
         unsafe { (*self.as_raw()).id }
     }
+
+    extern "C" fn release(dev: *mut bindings::device) {
+        // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
+        // embedded in `struct auxiliary_device`.
+        let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) }.cast_mut();
+
+        // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
+        // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
+        let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
+    }
 }
 
 impl Deref for Device<device::Core> {
@@ -265,3 +275,71 @@ fn as_ref(&self) -> &device::Device {
         unsafe { device::Device::as_ref(dev) }
     }
 }
+
+/// The registration of an auxiliary device.
+///
+/// This type represents the registration of a [`struct auxiliary_device`]. When an instance of this
+/// type is dropped, its respective auxiliary device will be unregistered from the system.
+///
+/// # Invariants
+///
+/// `self.0` always holds a valid pointer to an initialized and registered
+/// [`struct auxiliary_device`].
+pub struct Registration(NonNull<bindings::auxiliary_device>);
+
+impl Registration {
+    /// Create and register a new auxiliary device.
+    pub fn new(parent: &device::Device, name: &CStr, id: u32, modname: &CStr) -> Result<Self> {
+        let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
+        let adev = boxed.get();
+
+        // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
+        unsafe {
+            (*adev).dev.parent = parent.as_raw();
+            (*adev).dev.release = Some(Device::release);
+            (*adev).name = name.as_char_ptr();
+            (*adev).id = id;
+        }
+
+        // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
+        // which has not been initialized yet.
+        unsafe { bindings::auxiliary_device_init(adev) };
+
+        // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be freed
+        // by `Device::release` when the last reference to the `struct auxiliary_device` is dropped.
+        let _ = KBox::into_raw(boxed);
+
+        // SAFETY:
+        // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which has
+        //   been initialialized,
+        // - `modname.as_char_ptr()` is a NULL terminated string.
+        let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
+        if ret != 0 {
+            // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
+            // which has been initialialized.
+            unsafe { bindings::auxiliary_device_uninit(adev) };
+
+            return Err(Error::from_errno(ret));
+        }
+
+        // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated successfully.
+        //
+        // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is called,
+        // which happens in `Self::drop()`.
+        Ok(Self(unsafe { NonNull::new_unchecked(adev) }))
+    }
+}
+
+impl Drop for Registration {
+    fn drop(&mut self) {
+        // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
+        // `struct auxiliary_device`.
+        unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };
+
+        // This drops the reference we acquired through `auxiliary_device_init()`.
+        //
+        // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
+        // `struct auxiliary_device`.
+        unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };
+    }
+}
-- 
2.48.1
Re: [PATCH v2 3/4] rust: auxiliary: add auxiliary registration
Posted by Benoît du Garreau 9 months ago
On Thu, 13 Mar 2025 03:23:52 +0100 Danilo Krummrich <dakr@kernel.org> wrote:

> Implement the `auxiliary::Registration` type, which provides an API to
> create and register new auxiliary devices in the system.
> 
> Signed-off-by: Danilo Krummrich <dakr@kernel.org>
> ---
>  rust/kernel/auxiliary.rs | 80 +++++++++++++++++++++++++++++++++++++++-
>  1 file changed, 79 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs
> index e453f821f7cb..fc4bb5388a9b 100644
> --- a/rust/kernel/auxiliary.rs
> +++ b/rust/kernel/auxiliary.rs
> @@ -5,7 +5,7 @@
>  //! C header: [`include/linux/auxiliary_bus.h`](srctree/include/linux/auxiliary_bus.h)
>  
>  use crate::{
> -    bindings, device,
> +    bindings, container_of, device,
>      device_id::RawDeviceId,
>      driver,
>      error::{to_result, Result},
> @@ -219,6 +219,16 @@ pub fn id(&self) -> u32 {
>          // `struct auxiliary_device`.
>          unsafe { (*self.as_raw()).id }
>      }
> +
> +    extern "C" fn release(dev: *mut bindings::device) {
> +        // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
> +        // embedded in `struct auxiliary_device`.
> +        let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) }.cast_mut();
> +
> +        // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
> +        // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
> +        let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
> +    }
>  }
>  
>  impl Deref for Device<device::Core> {
> @@ -265,3 +275,71 @@ fn as_ref(&self) -> &device::Device {
>          unsafe { device::Device::as_ref(dev) }
>      }
>  }
> +
> +/// The registration of an auxiliary device.
> +///
> +/// This type represents the registration of a [`struct auxiliary_device`]. When an instance of this
> +/// type is dropped, its respective auxiliary device will be unregistered from the system.
> +///
> +/// # Invariants
> +///
> +/// `self.0` always holds a valid pointer to an initialized and registered
> +/// [`struct auxiliary_device`].
> +pub struct Registration(NonNull<bindings::auxiliary_device>);
> +
> +impl Registration {
> +    /// Create and register a new auxiliary device.
> +    pub fn new(parent: &device::Device, name: &CStr, id: u32, modname: &CStr) -> Result<Self> {
> +        let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;

You can use `KBox::init(kernel::init::zeroed(), GFP_KERNEL)` here. It avoids
the need for the first patch.

> +        let adev = boxed.get();
> +
> +        // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
> +        unsafe {
> +            (*adev).dev.parent = parent.as_raw();
> +            (*adev).dev.release = Some(Device::release);
> +            (*adev).name = name.as_char_ptr();
> +            (*adev).id = id;
> +        }
> +
> +        // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
> +        // which has not been initialized yet.
> +        unsafe { bindings::auxiliary_device_init(adev) };
> +
> +        // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be freed
> +        // by `Device::release` when the last reference to the `struct auxiliary_device` is dropped.
> +        let _ = KBox::into_raw(boxed);
> +
> +        // SAFETY:
> +        // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which has
> +        //   been initialialized,
> +        // - `modname.as_char_ptr()` is a NULL terminated string.
> +        let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
> +        if ret != 0 {
> +            // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
> +            // which has been initialialized.
> +            unsafe { bindings::auxiliary_device_uninit(adev) };
> +
> +            return Err(Error::from_errno(ret));
> +        }
> +
> +        // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated successfully.
> +        //
> +        // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is called,
> +        // which happens in `Self::drop()`.
> +        Ok(Self(unsafe { NonNull::new_unchecked(adev) }))
> +    }
> +}
> +
> +impl Drop for Registration {
> +    fn drop(&mut self) {
> +        // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
> +        // `struct auxiliary_device`.
> +        unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };
> +
> +        // This drops the reference we acquired through `auxiliary_device_init()`.
> +        //
> +        // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
> +        // `struct auxiliary_device`.
> +        unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };
> +    }
> +}
> -- 
> 2.48.1
> 
> 

Benoît du Garreau
Re: [PATCH v2 3/4] rust: auxiliary: add auxiliary registration
Posted by Benno Lossin 9 months ago
On Mon Mar 17, 2025 at 9:42 PM CET, Benoît du Garreau wrote:
> On Thu, 13 Mar 2025 03:23:52 +0100 Danilo Krummrich <dakr@kernel.org> wrote:
>> Implement the `auxiliary::Registration` type, which provides an API to
>> +impl Registration {
>> +    /// Create and register a new auxiliary device.
>> +    pub fn new(parent: &device::Device, name: &CStr, id: u32, modname: &CStr) -> Result<Self> {
>> +        let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
>
> You can use `KBox::init(kernel::init::zeroed(), GFP_KERNEL)` here. It avoids
> the need for the first patch.

We probably should have the zeroed function on the `Zeroable` trait...

---
Cheers,
Benno
Re: [PATCH v2 3/4] rust: auxiliary: add auxiliary registration
Posted by Danilo Krummrich 9 months ago
On Mon, Mar 17, 2025 at 09:42:51PM +0100, Benoît du Garreau wrote:
> On Thu, 13 Mar 2025 03:23:52 +0100 Danilo Krummrich <dakr@kernel.org> wrote:
> 
> > +impl Registration {
> > +    /// Create and register a new auxiliary device.
> > +    pub fn new(parent: &device::Device, name: &CStr, id: u32, modname: &CStr) -> Result<Self> {
> > +        let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
> 
> You can use `KBox::init(kernel::init::zeroed(), GFP_KERNEL)` here. It avoids
> the need for the first patch.

You're right, that works indeed, the full call looks like this.

	let boxed = KBox::init(kernel::init::zeroed::<Opaque::<bindings::auxiliary_device>>(), GFP_KERNEL)?;

However, I think Opaque::zeroed() reads a bit better. Unless anything speaks
against adding it, I think I prefer it as it is.