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