xref: /linux/rust/kernel/auxiliary.rs (revision e727d1c382a0cb2e10fd7aabef9217d1a37c80c7)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Abstractions for the auxiliary bus.
4 //!
5 //! C header: [`include/linux/auxiliary_bus.h`](srctree/include/linux/auxiliary_bus.h)
6 
7 use crate::{
8     bindings,
9     container_of,
10     device,
11     device_id::{
12         RawDeviceId,
13         RawDeviceIdIndex, //
14     },
15 
16     driver,
17     error::{
18         from_result,
19         to_result, //
20     },
21     prelude::*,
22     types::{
23         CovariantForLt,
24         ForLt,
25         ForeignOwnable,
26         Opaque, //
27     },
28     ThisModule, //
29 };
30 use core::{
31     any::TypeId,
32     marker::PhantomData,
33     mem::offset_of,
34     pin::Pin,
35     ptr::{
36         addr_of_mut,
37         NonNull, //
38     },
39 };
40 
41 /// An adapter for the registration of auxiliary drivers.
42 pub struct Adapter<T: Driver>(T);
43 
44 // SAFETY:
45 // - `bindings::auxiliary_driver` is a C type declared as `repr(C)`.
46 // - `T::Data` is the type of the driver's device private data.
47 // - `struct auxiliary_driver` embeds a `struct device_driver`.
48 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
49 unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
50     type DriverType = bindings::auxiliary_driver;
51     type DriverData<'bound> = T::Data<'bound>;
52     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
53 }
54 
55 // SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
56 // a preceding call to `register` has been successful.
57 unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
58     unsafe fn register(
59         adrv: &Opaque<Self::DriverType>,
60         name: &'static CStr,
61         module: &'static ThisModule,
62     ) -> Result {
63         // SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.
64         unsafe {
65             (*adrv.get()).name = name.as_char_ptr();
66             (*adrv.get()).probe = Some(Self::probe_callback);
67             (*adrv.get()).remove = Some(Self::remove_callback);
68             (*adrv.get()).id_table = T::ID_TABLE.as_ptr();
69         }
70 
71         // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
72         to_result(unsafe {
73             bindings::__auxiliary_driver_register(adrv.get(), module.as_ptr(), name.as_char_ptr())
74         })
75     }
76 
77     unsafe fn unregister(adrv: &Opaque<Self::DriverType>) {
78         // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
79         unsafe { bindings::auxiliary_driver_unregister(adrv.get()) }
80     }
81 }
82 
83 impl<T: Driver> Adapter<T> {
84     extern "C" fn probe_callback(
85         adev: *mut bindings::auxiliary_device,
86         id: *const bindings::auxiliary_device_id,
87     ) -> c_int {
88         // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
89         // `struct auxiliary_device`.
90         //
91         // INVARIANT: `adev` is valid for the duration of `probe_callback()`.
92         let adev = unsafe { &*adev.cast::<Device<device::CoreInternal<'_>>>() };
93 
94         // SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id`
95         // and does not add additional invariants, so it's safe to transmute.
96         let id = unsafe { &*id.cast::<DeviceId>() };
97 
98         // SAFETY: `id` comes from `T::ID_TABLE` which is of type `IdArray<_, T::IdInfo>`.
99         let info = unsafe { id.info_unchecked::<T::IdInfo>() };
100 
101         from_result(|| {
102             let data = T::probe(adev, info);
103 
104             adev.as_ref().set_drvdata(data)?;
105             Ok(0)
106         })
107     }
108 
109     extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {
110         // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
111         // `struct auxiliary_device`.
112         //
113         // INVARIANT: `adev` is valid for the duration of `remove_callback()`.
114         let adev = unsafe { &*adev.cast::<Device<device::CoreInternal<'_>>>() };
115 
116         // SAFETY: `remove_callback` is only ever called after a successful call to
117         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
118         // and stored a `Pin<KBox<T::Data<'_>>>`.
119         let data = unsafe { adev.as_ref().drvdata_borrow::<T::Data<'_>>() };
120 
121         T::unbind(adev, data);
122     }
123 }
124 
125 /// Declares a kernel module that exposes a single auxiliary driver.
126 #[macro_export]
127 macro_rules! module_auxiliary_driver {
128     ($($f:tt)*) => {
129         $crate::module_driver!(<T>, $crate::auxiliary::Adapter<T>, { $($f)* });
130     };
131 }
132 
133 /// Abstraction for `bindings::auxiliary_device_id`.
134 #[repr(transparent)]
135 #[derive(Clone, Copy)]
136 pub struct DeviceId(bindings::auxiliary_device_id);
137 
138 impl DeviceId {
139     /// Create a new [`DeviceId`] from name.
140     pub const fn new(modname: &'static CStr, name: &'static CStr) -> Self {
141         let name = name.to_bytes_with_nul();
142         let modname = modname.to_bytes_with_nul();
143 
144         let mut id: bindings::auxiliary_device_id = pin_init::zeroed();
145         let mut i = 0;
146         while i < modname.len() {
147             id.name[i] = modname[i];
148             i += 1;
149         }
150 
151         // Reuse the space of the NULL terminator.
152         id.name[i - 1] = b'.';
153 
154         let mut j = 0;
155         while j < name.len() {
156             id.name[i] = name[j];
157             i += 1;
158             j += 1;
159         }
160 
161         Self(id)
162     }
163 }
164 
165 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `auxiliary_device_id` and does not add
166 // additional invariants, so it's safe to transmute to `RawType`.
167 unsafe impl RawDeviceId for DeviceId {
168     type RawType = bindings::auxiliary_device_id;
169 }
170 
171 // SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
172 unsafe impl RawDeviceIdIndex for DeviceId {
173     const DRIVER_DATA_OFFSET: usize =
174         core::mem::offset_of!(bindings::auxiliary_device_id, driver_data);
175 }
176 
177 /// IdTable type for auxiliary drivers.
178 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
179 
180 /// Create a auxiliary `IdTable` with its alias for modpost.
181 #[macro_export]
182 macro_rules! auxiliary_device_table {
183     ($($tt:tt)*) => {
184         $crate::module_device_table!("auxiliary", $crate::auxiliary::DeviceId, $($tt)*);
185     };
186 }
187 
188 /// The auxiliary driver trait.
189 ///
190 /// Drivers must implement this trait in order to get an auxiliary driver registered.
191 pub trait Driver {
192     /// The type holding information about each device id supported by the driver.
193     ///
194     /// TODO: Use associated_type_defaults once stabilized:
195     ///
196     /// type IdInfo: 'static = ();
197     type IdInfo: 'static;
198 
199     /// The type of the driver's bus device private data.
200     type Data<'bound>: Send + 'bound;
201 
202     /// The table of device ids supported by the driver.
203     const ID_TABLE: IdTable<Self::IdInfo>;
204 
205     /// Auxiliary driver probe.
206     ///
207     /// Called when an auxiliary device is matches a corresponding driver.
208     fn probe<'bound>(
209         dev: &'bound Device<device::Core<'_>>,
210         id_info: &'bound Self::IdInfo,
211     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
212 
213     /// Auxiliary driver unbind.
214     ///
215     /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
216     /// is optional.
217     ///
218     /// This callback serves as a place for drivers to perform teardown operations that require a
219     /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
220     /// operations to gracefully tear down the device.
221     ///
222     /// Otherwise, release operations for driver resources should be performed in `Drop`.
223     fn unbind<'bound>(dev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
224         let _ = (dev, this);
225     }
226 }
227 
228 /// The auxiliary device representation.
229 ///
230 /// This structure represents the Rust abstraction for a C `struct auxiliary_device`. The
231 /// implementation abstracts the usage of an already existing C `struct auxiliary_device` within
232 /// Rust code that we get passed from the C side.
233 ///
234 /// # Invariants
235 ///
236 /// A [`Device`] instance represents a valid `struct auxiliary_device` created by the C portion of
237 /// the kernel.
238 #[repr(transparent)]
239 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
240     Opaque<bindings::auxiliary_device>,
241     PhantomData<Ctx>,
242 );
243 
244 impl<Ctx: device::DeviceContext> Device<Ctx> {
245     fn as_raw(&self) -> *mut bindings::auxiliary_device {
246         self.0.get()
247     }
248 
249     /// Returns the auxiliary device' id.
250     pub fn id(&self) -> u32 {
251         // SAFETY: By the type invariant `self.as_raw()` is a valid pointer to a
252         // `struct auxiliary_device`.
253         unsafe { (*self.as_raw()).id }
254     }
255 }
256 
257 impl Device<device::Bound> {
258     /// Returns a bound reference to the parent [`device::Device`].
259     pub fn parent(&self) -> &device::Device<device::Bound> {
260         let parent = (**self).parent();
261 
262         // SAFETY: A bound auxiliary device always has a bound parent device.
263         unsafe { parent.as_bound() }
264     }
265 
266     /// Returns the stored registration data as a pinned reference.
267     ///
268     /// Performs null and [`TypeId`] checks, then borrows the stored [`KBox`].
269     ///
270     /// # Safety
271     ///
272     /// Callers must ensure that the lifetime shortening from the original `'static` storage to
273     /// `'_` is sound, e.g. via an HRTB closure or [`CovariantForLt`] guarantee.
274     unsafe fn registration_data_pinned<F: ForLt + 'static>(&self) -> Result<Pin<&F::Of<'_>>> {
275         // SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`.
276         let ptr = unsafe { (*self.as_raw()).registration_data_rust };
277         if ptr.is_null() {
278             dev_warn!(
279                 self.as_ref(),
280                 "No registration data set; parent is not a Rust driver.\n"
281             );
282             return Err(ENOENT);
283         }
284 
285         // SAFETY: `ptr` is non-null and was set via `into_foreign()` in `Registration::new()`;
286         // `RegistrationData` is `#[repr(C)]` with `type_id` at offset 0, so reading a `TypeId`
287         // at the start of the allocation is valid regardless of `F`.
288         let type_id = unsafe { ptr.cast::<TypeId>().read() };
289         if type_id != TypeId::of::<F>() {
290             return Err(EINVAL);
291         }
292 
293         // SAFETY: The `TypeId` check above confirms that the stored type matches `F`'s
294         // encoding; lifetimes are erased at runtime, so borrowing as `F::Of<'_>` is
295         // layout-compatible with the stored `F::Of<'static>`. `ptr` remains valid until
296         // `Registration::drop()` calls `from_foreign()`.
297         let wrapper = unsafe { Pin::<KBox<RegistrationData<F::Of<'_>>>>::borrow(ptr) };
298 
299         // SAFETY: `data` is a structurally pinned field of `RegistrationData`.
300         Ok(unsafe { wrapper.map_unchecked(|w| &w.data) })
301     }
302 
303     /// Access the registration data set by the registering (parent) driver through a closure.
304     ///
305     /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The closure receives a pinned
306     /// reference to the registration data.
307     ///
308     /// The outer reference carries the `&self` lifetime while the inner type carries the HRTB
309     /// lifetime `'a`, implying `'a` outlives `&self`. This allows the closure to coerce covariant
310     /// sub-fields (e.g. `&'a T` to the caller's lifetime) and return them directly in `R`.
311     ///
312     /// For covariant types that implement [`trait@CovariantForLt`], prefer
313     /// [`registration_data`](Self::registration_data) which returns a direct reference.
314     ///
315     /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling
316     /// [`Registration::new()`].
317     ///
318     /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was
319     /// registered by a C driver.
320     #[inline]
321     pub fn registration_data_with<'this, F: ForLt + 'static, R>(
322         &'this self,
323         f: impl for<'a> FnOnce(Pin<&'this F::Of<'a>>) -> R,
324     ) -> Result<R> {
325         // SAFETY: The HRTB on the inner type prevents the caller from exploiting a specific
326         // choice of `'a`. Covariant sub-fields can be safely coerced to `'this`, while
327         // invariant fields cannot be coerced and thus cannot escape with an incorrect
328         // lifetime.
329         let pinned = unsafe { self.registration_data_pinned::<F>()? };
330 
331         Ok(f(pinned))
332     }
333 
334     /// Returns a pinned reference to the registration data set by the registering (parent) driver.
335     ///
336     /// This method is only available when `F` implements [`trait@CovariantForLt`], which guarantees
337     /// that the lifetime shortening is sound.
338     ///
339     /// For non-covariant types, use the closure-based [`Self::registration_data_with`].
340     ///
341     /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling
342     /// [`Registration::new()`].
343     ///
344     /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was
345     /// registered by a C driver.
346     #[inline]
347     pub fn registration_data<F: CovariantForLt + 'static>(&self) -> Result<Pin<&F::Of<'_>>> {
348         // SAFETY: `CovariantForLt` guarantees covariance, which makes the lifetime shortening
349         // from `'static` to `'_` performed by `registration_data_pinned` sound.
350         unsafe { self.registration_data_pinned::<F>() }
351     }
352 }
353 
354 impl Device {
355     /// Returns a reference to the parent [`device::Device`].
356     pub fn parent(&self) -> &device::Device {
357         // SAFETY: A `struct auxiliary_device` always has a parent.
358         unsafe { self.as_ref().parent().unwrap_unchecked() }
359     }
360 
361     extern "C" fn release(dev: *mut bindings::device) {
362         // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
363         // embedded in `struct auxiliary_device`.
364         let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };
365 
366         // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
367         // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
368         let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
369     }
370 }
371 
372 // SAFETY: `auxiliary::Device` is a transparent wrapper of `struct auxiliary_device`.
373 // The offset is guaranteed to point to a valid device field inside `auxiliary::Device`.
374 unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
375     const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
376 }
377 
378 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
379 // argument.
380 kernel::impl_device_context_deref!(unsafe { Device });
381 kernel::impl_device_context_into_aref!(Device);
382 
383 // SAFETY: Instances of `Device` are always reference-counted.
384 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
385     fn inc_ref(&self) {
386         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
387         unsafe { bindings::get_device(self.as_ref().as_raw()) };
388     }
389 
390     unsafe fn dec_ref(obj: NonNull<Self>) {
391         // CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.
392         let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();
393 
394         // SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid
395         // `struct auxiliary_device`.
396         let dev = unsafe { addr_of_mut!((*adev).dev) };
397 
398         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
399         unsafe { bindings::put_device(dev) }
400     }
401 }
402 
403 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
404     fn as_ref(&self) -> &device::Device<Ctx> {
405         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
406         // `struct auxiliary_device`.
407         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
408 
409         // SAFETY: `dev` points to a valid `struct device`.
410         unsafe { device::Device::from_raw(dev) }
411     }
412 }
413 
414 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
415 unsafe impl Send for Device {}
416 
417 // SAFETY: `Device` can be shared among threads because all methods of `Device`
418 // (i.e. `Device<Normal>) are thread safe.
419 unsafe impl Sync for Device {}
420 
421 // SAFETY: Same as `Device<Normal>` -- the underlying `struct auxiliary_device` is the same;
422 // `Bound` is a zero-sized type-state marker that does not affect thread safety.
423 unsafe impl Sync for Device<device::Bound> {}
424 
425 /// Wrapper that stores a [`TypeId`] alongside the registration data for runtime type checking.
426 #[repr(C)]
427 #[pin_data]
428 struct RegistrationData<T> {
429     type_id: TypeId,
430     #[pin]
431     data: T,
432 }
433 
434 /// The registration of an auxiliary device.
435 ///
436 /// This type represents the registration of a [`struct auxiliary_device`]. When its parent device
437 /// is unbound, the corresponding auxiliary device will be unregistered from the system.
438 ///
439 /// The type parameter `F` is a [`ForLt`](trait@ForLt) encoding of the registration
440 /// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](macro@ForLt).
441 ///
442 /// The data can be accessed by the auxiliary driver through [`Device::registration_data()`] and
443 /// [`Device::registration_data_with()`].
444 ///
445 /// # Invariants
446 ///
447 /// `self.adev` always holds a valid pointer to an initialized and registered
448 /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a
449 /// valid `Pin<KBox<RegistrationData<F::Of<'static>>>>`.
450 pub struct Registration<'a, F: ForLt + 'static> {
451     adev: NonNull<bindings::auxiliary_device>,
452     _phantom: PhantomData<F::Of<'a>>,
453 }
454 
455 impl<'a, F: ForLt> Registration<'a, F>
456 where
457     for<'b> F::Of<'b>: Send + Sync,
458 {
459     /// Create and register a new auxiliary device with the given registration data.
460     ///
461     /// The `data` is owned by the registration and can be accessed through the auxiliary device
462     /// via [`Device::registration_data()`].
463     ///
464     /// # Safety
465     ///
466     /// The caller must not `mem::forget()` the returned [`Registration`] or otherwise prevent its
467     /// [`Drop`] implementation from running, since the registration data may contain borrowed
468     /// references that become invalid after `'a` ends.
469     ///
470     /// If the registration data is `'static`, use the safe [`Registration::new()`] instead.
471     pub unsafe fn new_with_lt<E>(
472         parent: &'a device::Device<device::Bound>,
473         name: &CStr,
474         id: u32,
475         modname: &CStr,
476         data: impl PinInit<F::Of<'a>, E>,
477     ) -> Result<Self>
478     where
479         Error: From<E>,
480     {
481         let data = KBox::pin_init::<Error>(
482             try_pin_init!(RegistrationData {
483                 type_id: TypeId::of::<F>(),
484                 data <- data,
485             }),
486             GFP_KERNEL,
487         )?;
488 
489         // SAFETY: `'a` is invariant (via `Registration`'s `PhantomData`). Lifetimes do not
490         // affect layout, so RegistrationData<F::Of<'a>> and RegistrationData<F::Of<'static>>
491         // have identical representation.
492         let data: Pin<KBox<RegistrationData<F::Of<'static>>>> =
493             unsafe { core::mem::transmute(data) };
494 
495         let boxed: KBox<Opaque<bindings::auxiliary_device>> = KBox::zeroed(GFP_KERNEL)?;
496         let adev = boxed.get();
497 
498         // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
499         unsafe {
500             (*adev).dev.parent = parent.as_raw();
501             (*adev).dev.release = Some(Device::release);
502             (*adev).name = name.as_char_ptr();
503             (*adev).id = id;
504             (*adev).registration_data_rust = data.into_foreign();
505         }
506 
507         // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
508         // which has not been initialized yet.
509         unsafe { bindings::auxiliary_device_init(adev) };
510 
511         // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be
512         // freed by `Device::release` when the last reference to the `struct auxiliary_device`
513         // is dropped.
514         let _ = KBox::into_raw(boxed);
515 
516         // SAFETY:
517         // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which
518         //   has been initialized,
519         // - `modname.as_char_ptr()` is a NULL terminated string.
520         let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
521         if ret != 0 {
522             // SAFETY: `registration_data` was set above via `into_foreign()`.
523             drop(unsafe {
524                 Pin::<KBox<RegistrationData<F::Of<'static>>>>::from_foreign(
525                     (*adev).registration_data_rust,
526                 )
527             });
528 
529             // SAFETY: `adev` is guaranteed to be a valid pointer to a
530             // `struct auxiliary_device`, which has been initialized.
531             unsafe { bindings::auxiliary_device_uninit(adev) };
532 
533             return Err(Error::from_errno(ret));
534         }
535 
536         // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is
537         // called, which happens in `Self::drop()`.
538         Ok(Self {
539             // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated
540             // successfully.
541             adev: unsafe { NonNull::new_unchecked(adev) },
542             _phantom: PhantomData,
543         })
544     }
545 
546     /// Create and register a new auxiliary device with `'static` registration data.
547     ///
548     /// Safe variant of [`Registration::new_with_lt()`] for registration data that does not contain
549     /// borrowed references.
550     pub fn new<E>(
551         parent: &'a device::Device<device::Bound>,
552         name: &CStr,
553         id: u32,
554         modname: &CStr,
555         data: impl PinInit<F::Of<'a>, E>,
556     ) -> Result<Self>
557     where
558         F::Of<'a>: 'static,
559         Error: From<E>,
560     {
561         // SAFETY: `F::Of<'a>: 'static` guarantees the data contains no borrowed references,
562         // so forgetting the `Registration` cannot cause use-after-free.
563         unsafe { Self::new_with_lt(parent, name, id, modname, data) }
564     }
565 }
566 
567 impl<F: ForLt> Drop for Registration<'_, F> {
568     fn drop(&mut self) {
569         // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered
570         // `struct auxiliary_device`.
571         unsafe { bindings::auxiliary_device_delete(self.adev.as_ptr()) };
572 
573         // SAFETY: `registration_data` was set in `new()` via `into_foreign()`.
574         drop(unsafe {
575             Pin::<KBox<RegistrationData<F::Of<'static>>>>::from_foreign(
576                 (*self.adev.as_ptr()).registration_data_rust,
577             )
578         });
579 
580         // This drops the reference we acquired through `auxiliary_device_init()`.
581         //
582         // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered
583         // `struct auxiliary_device`.
584         unsafe { bindings::auxiliary_device_uninit(self.adev.as_ptr()) };
585     }
586 }
587 
588 // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.
589 unsafe impl<F: ForLt> Send for Registration<'_, F> where for<'a> F::Of<'a>: Send {}
590 
591 // SAFETY: `Registration` does not expose any methods or fields that need synchronization.
592 unsafe impl<F: ForLt> Sync for Registration<'_, F> where for<'a> F::Of<'a>: Send {}
593