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