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