kernel/
auxiliary.rs

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
7use crate::{
8    bindings,
9    container_of,
10    device,
11    device_id::{
12        RawDeviceId,
13        RawDeviceIdIndex, //
14    },
15    devres::Devres,
16    driver,
17    error::{
18        from_result,
19        to_result, //
20    },
21    prelude::*,
22    types::Opaque,
23    ThisModule, //
24};
25use core::{
26    marker::PhantomData,
27    mem::offset_of,
28    ptr::{
29        addr_of_mut,
30        NonNull, //
31    },
32};
33
34/// An adapter for the registration of auxiliary drivers.
35pub struct Adapter<T: Driver>(T);
36
37// SAFETY:
38// - `bindings::auxiliary_driver` is a C type declared as `repr(C)`.
39// - `T` is the type of the driver's device private data.
40// - `struct auxiliary_driver` embeds a `struct device_driver`.
41// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
42unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
43    type DriverType = bindings::auxiliary_driver;
44    type DriverData = T;
45    const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
46}
47
48// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
49// a preceding call to `register` has been successful.
50unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
51    unsafe fn register(
52        adrv: &Opaque<Self::DriverType>,
53        name: &'static CStr,
54        module: &'static ThisModule,
55    ) -> Result {
56        // SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.
57        unsafe {
58            (*adrv.get()).name = name.as_char_ptr();
59            (*adrv.get()).probe = Some(Self::probe_callback);
60            (*adrv.get()).remove = Some(Self::remove_callback);
61            (*adrv.get()).id_table = T::ID_TABLE.as_ptr();
62        }
63
64        // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
65        to_result(unsafe {
66            bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())
67        })
68    }
69
70    unsafe fn unregister(adrv: &Opaque<Self::DriverType>) {
71        // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
72        unsafe { bindings::auxiliary_driver_unregister(adrv.get()) }
73    }
74}
75
76impl<T: Driver + 'static> Adapter<T> {
77    extern "C" fn probe_callback(
78        adev: *mut bindings::auxiliary_device,
79        id: *const bindings::auxiliary_device_id,
80    ) -> c_int {
81        // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
82        // `struct auxiliary_device`.
83        //
84        // INVARIANT: `adev` is valid for the duration of `probe_callback()`.
85        let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };
86
87        // SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id`
88        // and does not add additional invariants, so it's safe to transmute.
89        let id = unsafe { &*id.cast::<DeviceId>() };
90        let info = T::ID_TABLE.info(id.index());
91
92        from_result(|| {
93            let data = T::probe(adev, info);
94
95            adev.as_ref().set_drvdata(data)?;
96            Ok(0)
97        })
98    }
99
100    extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {
101        // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
102        // `struct auxiliary_device`.
103        //
104        // INVARIANT: `adev` is valid for the duration of `remove_callback()`.
105        let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };
106
107        // SAFETY: `remove_callback` is only ever called after a successful call to
108        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
109        // and stored a `Pin<KBox<T>>`.
110        let data = unsafe { adev.as_ref().drvdata_borrow::<T>() };
111
112        T::unbind(adev, data);
113    }
114}
115
116/// Declares a kernel module that exposes a single auxiliary driver.
117#[macro_export]
118macro_rules! module_auxiliary_driver {
119    ($($f:tt)*) => {
120        $crate::module_driver!(<T>, $crate::auxiliary::Adapter<T>, { $($f)* });
121    };
122}
123
124/// Abstraction for `bindings::auxiliary_device_id`.
125#[repr(transparent)]
126#[derive(Clone, Copy)]
127pub struct DeviceId(bindings::auxiliary_device_id);
128
129impl DeviceId {
130    /// Create a new [`DeviceId`] from name.
131    pub const fn new(modname: &'static CStr, name: &'static CStr) -> Self {
132        let name = name.to_bytes_with_nul();
133        let modname = modname.to_bytes_with_nul();
134
135        // TODO: Replace with `bindings::auxiliary_device_id::default()` once stabilized for
136        // `const`.
137        //
138        // SAFETY: FFI type is valid to be zero-initialized.
139        let mut id: bindings::auxiliary_device_id = unsafe { core::mem::zeroed() };
140
141        let mut i = 0;
142        while i < modname.len() {
143            id.name[i] = modname[i];
144            i += 1;
145        }
146
147        // Reuse the space of the NULL terminator.
148        id.name[i - 1] = b'.';
149
150        let mut j = 0;
151        while j < name.len() {
152            id.name[i] = name[j];
153            i += 1;
154            j += 1;
155        }
156
157        Self(id)
158    }
159}
160
161// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `auxiliary_device_id` and does not add
162// additional invariants, so it's safe to transmute to `RawType`.
163unsafe impl RawDeviceId for DeviceId {
164    type RawType = bindings::auxiliary_device_id;
165}
166
167// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
168unsafe impl RawDeviceIdIndex for DeviceId {
169    const DRIVER_DATA_OFFSET: usize =
170        core::mem::offset_of!(bindings::auxiliary_device_id, driver_data);
171
172    fn index(&self) -> usize {
173        self.0.driver_data
174    }
175}
176
177/// IdTable type for auxiliary drivers.
178pub 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]
182macro_rules! auxiliary_device_table {
183    ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {
184        const $table_name: $crate::device_id::IdArray<
185            $crate::auxiliary::DeviceId,
186            $id_info_type,
187            { $table_data.len() },
188        > = $crate::device_id::IdArray::new($table_data);
189
190        $crate::module_device_table!("auxiliary", $module_table_name, $table_name);
191    };
192}
193
194/// The auxiliary driver trait.
195///
196/// Drivers must implement this trait in order to get an auxiliary driver registered.
197pub trait Driver {
198    /// The type holding information about each device id supported by the driver.
199    ///
200    /// TODO: Use associated_type_defaults once stabilized:
201    ///
202    /// type IdInfo: 'static = ();
203    type IdInfo: 'static;
204
205    /// The table of device ids supported by the driver.
206    const ID_TABLE: IdTable<Self::IdInfo>;
207
208    /// Auxiliary driver probe.
209    ///
210    /// Called when an auxiliary device is matches a corresponding driver.
211    fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> impl PinInit<Self, Error>;
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 `Self::drop`.
223    fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
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)]
239pub struct Device<Ctx: device::DeviceContext = device::Normal>(
240    Opaque<bindings::auxiliary_device>,
241    PhantomData<Ctx>,
242);
243
244impl<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
257impl 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
267impl Device {
268    /// Returns a reference to the parent [`device::Device`].
269    pub fn parent(&self) -> &device::Device {
270        // SAFETY: A `struct auxiliary_device` always has a parent.
271        unsafe { self.as_ref().parent().unwrap_unchecked() }
272    }
273
274    extern "C" fn release(dev: *mut bindings::device) {
275        // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
276        // embedded in `struct auxiliary_device`.
277        let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };
278
279        // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
280        // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
281        let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
282    }
283}
284
285// SAFETY: `auxiliary::Device` is a transparent wrapper of `struct auxiliary_device`.
286// The offset is guaranteed to point to a valid device field inside `auxiliary::Device`.
287unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
288    const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
289}
290
291// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
292// argument.
293kernel::impl_device_context_deref!(unsafe { Device });
294kernel::impl_device_context_into_aref!(Device);
295
296// SAFETY: Instances of `Device` are always reference-counted.
297unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
298    fn inc_ref(&self) {
299        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
300        unsafe { bindings::get_device(self.as_ref().as_raw()) };
301    }
302
303    unsafe fn dec_ref(obj: NonNull<Self>) {
304        // CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.
305        let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();
306
307        // SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid
308        // `struct auxiliary_device`.
309        let dev = unsafe { addr_of_mut!((*adev).dev) };
310
311        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
312        unsafe { bindings::put_device(dev) }
313    }
314}
315
316impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
317    fn as_ref(&self) -> &device::Device<Ctx> {
318        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
319        // `struct auxiliary_device`.
320        let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
321
322        // SAFETY: `dev` points to a valid `struct device`.
323        unsafe { device::Device::from_raw(dev) }
324    }
325}
326
327// SAFETY: A `Device` is always reference-counted and can be released from any thread.
328unsafe impl Send for Device {}
329
330// SAFETY: `Device` can be shared among threads because all methods of `Device`
331// (i.e. `Device<Normal>) are thread safe.
332unsafe impl Sync for Device {}
333
334/// The registration of an auxiliary device.
335///
336/// This type represents the registration of a [`struct auxiliary_device`]. When its parent device
337/// is unbound, the corresponding auxiliary device will be unregistered from the system.
338///
339/// # Invariants
340///
341/// `self.0` always holds a valid pointer to an initialized and registered
342/// [`struct auxiliary_device`].
343pub struct Registration(NonNull<bindings::auxiliary_device>);
344
345impl Registration {
346    /// Create and register a new auxiliary device.
347    pub fn new<'a>(
348        parent: &'a device::Device<device::Bound>,
349        name: &'a CStr,
350        id: u32,
351        modname: &'a CStr,
352    ) -> impl PinInit<Devres<Self>, Error> + 'a {
353        pin_init::pin_init_scope(move || {
354            let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
355            let adev = boxed.get();
356
357            // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
358            unsafe {
359                (*adev).dev.parent = parent.as_raw();
360                (*adev).dev.release = Some(Device::release);
361                (*adev).name = name.as_char_ptr();
362                (*adev).id = id;
363            }
364
365            // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
366            // which has not been initialized yet.
367            unsafe { bindings::auxiliary_device_init(adev) };
368
369            // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be
370            // freed by `Device::release` when the last reference to the `struct auxiliary_device`
371            // is dropped.
372            let _ = KBox::into_raw(boxed);
373
374            // SAFETY:
375            // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which
376            //   has been initialized,
377            // - `modname.as_char_ptr()` is a NULL terminated string.
378            let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
379            if ret != 0 {
380                // SAFETY: `adev` is guaranteed to be a valid pointer to a
381                // `struct auxiliary_device`, which has been initialized.
382                unsafe { bindings::auxiliary_device_uninit(adev) };
383
384                return Err(Error::from_errno(ret));
385            }
386
387            // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is
388            // called, which happens in `Self::drop()`.
389            Ok(Devres::new(
390                parent,
391                // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated
392                // successfully.
393                Self(unsafe { NonNull::new_unchecked(adev) }),
394            ))
395        })
396    }
397}
398
399impl Drop for Registration {
400    fn drop(&mut self) {
401        // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
402        // `struct auxiliary_device`.
403        unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };
404
405        // This drops the reference we acquired through `auxiliary_device_init()`.
406        //
407        // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
408        // `struct auxiliary_device`.
409        unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };
410    }
411}
412
413// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.
414unsafe impl Send for Registration {}
415
416// SAFETY: `Registration` does not expose any methods or fields that need synchronization.
417unsafe impl Sync for Registration {}