Re: [PATCH v4 4/5] rust: auxiliary: add auxiliary registration
From: Danilo Krummrich
Date: Tue Apr 15 2025 - 08:50:19 EST
On Tue, Apr 15, 2025 at 12:11:16PM +0000, Alice Ryhl wrote:
> On Mon, Apr 14, 2025 at 03:18:07PM +0200, Danilo Krummrich 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)?;
> > + 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) };
>
> Does this error-path actually free the box?
Yes, auxiliary_device_uninit() calls put_device() on the underlying struct
device, hence the release() callback is called at this point, which frees the
Box.