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::{
23 ForeignOwnable,
24 Opaque, //
25 },
26 ThisModule, //
27};
28use core::{
29 any::TypeId,
30 marker::PhantomData,
31 mem::offset_of,
32 pin::Pin,
33 ptr::{
34 addr_of_mut,
35 NonNull, //
36 },
37};
38
39/// An adapter for the registration of auxiliary drivers.
40pub struct Adapter<T: Driver>(T);
41
42// SAFETY:
43// - `bindings::auxiliary_driver` is a C type declared as `repr(C)`.
44// - `T` is the type of the driver's device private data.
45// - `struct auxiliary_driver` embeds a `struct device_driver`.
46// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
47unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {
48 type DriverType = bindings::auxiliary_driver;
49 type DriverData = T;
50 const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
51}
52
53// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
54// a preceding call to `register` has been successful.
55unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
56 unsafe fn register(
57 adrv: &Opaque<Self::DriverType>,
58 name: &'static CStr,
59 module: &'static ThisModule,
60 ) -> Result {
61 // SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.
62 unsafe {
63 (*adrv.get()).name = name.as_char_ptr();
64 (*adrv.get()).probe = Some(Self::probe_callback);
65 (*adrv.get()).remove = Some(Self::remove_callback);
66 (*adrv.get()).id_table = T::ID_TABLE.as_ptr();
67 }
68
69 // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
70 to_result(unsafe {
71 bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())
72 })
73 }
74
75 unsafe fn unregister(adrv: &Opaque<Self::DriverType>) {
76 // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
77 unsafe { bindings::auxiliary_driver_unregister(adrv.get()) }
78 }
79}
80
81impl<T: Driver + 'static> Adapter<T> {
82 extern "C" fn probe_callback(
83 adev: *mut bindings::auxiliary_device,
84 id: *const bindings::auxiliary_device_id,
85 ) -> c_int {
86 // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
87 // `struct auxiliary_device`.
88 //
89 // INVARIANT: `adev` is valid for the duration of `probe_callback()`.
90 let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };
91
92 // SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id`
93 // and does not add additional invariants, so it's safe to transmute.
94 let id = unsafe { &*id.cast::<DeviceId>() };
95 let info = T::ID_TABLE.info(id.index());
96
97 from_result(|| {
98 let data = T::probe(adev, info);
99
100 adev.as_ref().set_drvdata(data)?;
101 Ok(0)
102 })
103 }
104
105 extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {
106 // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
107 // `struct auxiliary_device`.
108 //
109 // INVARIANT: `adev` is valid for the duration of `remove_callback()`.
110 let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };
111
112 // SAFETY: `remove_callback` is only ever called after a successful call to
113 // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
114 // and stored a `Pin<KBox<T>>`.
115 let data = unsafe { adev.as_ref().drvdata_borrow::<T>() };
116
117 T::unbind(adev, data);
118 }
119}
120
121/// Declares a kernel module that exposes a single auxiliary driver.
122#[macro_export]
123macro_rules! module_auxiliary_driver {
124 ($($f:tt)*) => {
125 $crate::module_driver!(<T>, $crate::auxiliary::Adapter<T>, { $($f)* });
126 };
127}
128
129/// Abstraction for `bindings::auxiliary_device_id`.
130#[repr(transparent)]
131#[derive(Clone, Copy)]
132pub struct DeviceId(bindings::auxiliary_device_id);
133
134impl DeviceId {
135 /// Create a new [`DeviceId`] from name.
136 pub const fn new(modname: &'static CStr, name: &'static CStr) -> Self {
137 let name = name.to_bytes_with_nul();
138 let modname = modname.to_bytes_with_nul();
139
140 let mut id: bindings::auxiliary_device_id = pin_init::zeroed();
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 /// Returns a pinned reference to the registration data set by the registering (parent) driver.
267 ///
268 /// Returns [`EINVAL`] if `T` does not match the type used by the parent driver when calling
269 /// [`Registration::new()`].
270 ///
271 /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was
272 /// registered by a C driver.
273 pub fn registration_data<T: 'static>(&self) -> Result<Pin<&T>> {
274 // SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`.
275 let ptr = unsafe { (*self.as_raw()).registration_data_rust };
276 if ptr.is_null() {
277 dev_warn!(
278 self.as_ref(),
279 "No registration data set; parent is not a Rust driver.\n"
280 );
281 return Err(ENOENT);
282 }
283
284 // SAFETY: `ptr` is non-null and was set via `into_foreign()` in `Registration::new()`;
285 // `RegistrationData` is `#[repr(C)]` with `type_id` at offset 0, so reading a `TypeId`
286 // at the start of the allocation is valid regardless of `T`.
287 let type_id = unsafe { ptr.cast::<TypeId>().read() };
288 if type_id != TypeId::of::<T>() {
289 return Err(EINVAL);
290 }
291
292 // SAFETY: The `TypeId` check above confirms that the stored type is `T`; `ptr` remains
293 // valid until `Registration::drop()` calls `from_foreign()`.
294 let wrapper = unsafe { Pin::<KBox<RegistrationData<T>>>::borrow(ptr) };
295
296 // SAFETY: `data` is a structurally pinned field of `RegistrationData`.
297 Ok(unsafe { wrapper.map_unchecked(|w| &w.data) })
298 }
299}
300
301impl Device {
302 /// Returns a reference to the parent [`device::Device`].
303 pub fn parent(&self) -> &device::Device {
304 // SAFETY: A `struct auxiliary_device` always has a parent.
305 unsafe { self.as_ref().parent().unwrap_unchecked() }
306 }
307
308 extern "C" fn release(dev: *mut bindings::device) {
309 // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
310 // embedded in `struct auxiliary_device`.
311 let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };
312
313 // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
314 // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
315 let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
316 }
317}
318
319// SAFETY: `auxiliary::Device` is a transparent wrapper of `struct auxiliary_device`.
320// The offset is guaranteed to point to a valid device field inside `auxiliary::Device`.
321unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
322 const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
323}
324
325// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
326// argument.
327kernel::impl_device_context_deref!(unsafe { Device });
328kernel::impl_device_context_into_aref!(Device);
329
330// SAFETY: Instances of `Device` are always reference-counted.
331unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
332 fn inc_ref(&self) {
333 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
334 unsafe { bindings::get_device(self.as_ref().as_raw()) };
335 }
336
337 unsafe fn dec_ref(obj: NonNull<Self>) {
338 // CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.
339 let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();
340
341 // SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid
342 // `struct auxiliary_device`.
343 let dev = unsafe { addr_of_mut!((*adev).dev) };
344
345 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
346 unsafe { bindings::put_device(dev) }
347 }
348}
349
350impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
351 fn as_ref(&self) -> &device::Device<Ctx> {
352 // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
353 // `struct auxiliary_device`.
354 let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
355
356 // SAFETY: `dev` points to a valid `struct device`.
357 unsafe { device::Device::from_raw(dev) }
358 }
359}
360
361// SAFETY: A `Device` is always reference-counted and can be released from any thread.
362unsafe impl Send for Device {}
363
364// SAFETY: `Device` can be shared among threads because all methods of `Device`
365// (i.e. `Device<Normal>) are thread safe.
366unsafe impl Sync for Device {}
367
368/// Wrapper that stores a [`TypeId`] alongside the registration data for runtime type checking.
369#[repr(C)]
370#[pin_data]
371struct RegistrationData<T> {
372 type_id: TypeId,
373 #[pin]
374 data: T,
375}
376
377/// The registration of an auxiliary device.
378///
379/// This type represents the registration of a [`struct auxiliary_device`]. When its parent device
380/// is unbound, the corresponding auxiliary device will be unregistered from the system.
381///
382/// The type parameter `T` is the type of the registration data owned by the registering (parent)
383/// driver. It can be accessed by the auxiliary driver through
384/// [`Device::registration_data()`].
385///
386/// # Invariants
387///
388/// `self.adev` always holds a valid pointer to an initialized and registered
389/// [`struct auxiliary_device`] whose `registration_data_rust` field points to a
390/// valid `Pin<KBox<RegistrationData<T>>>`.
391pub struct Registration<T: 'static> {
392 adev: NonNull<bindings::auxiliary_device>,
393 _data: PhantomData<T>,
394}
395
396impl<T: Send + Sync + 'static> Registration<T> {
397 /// Create and register a new auxiliary device with the given registration data.
398 ///
399 /// The `data` is owned by the registration and can be accessed through the auxiliary device
400 /// via [`Device::registration_data()`].
401 pub fn new<E>(
402 parent: &device::Device<device::Bound>,
403 name: &CStr,
404 id: u32,
405 modname: &CStr,
406 data: impl PinInit<T, E>,
407 ) -> Result<Devres<Self>>
408 where
409 Error: From<E>,
410 {
411 let data = KBox::pin_init::<Error>(
412 try_pin_init!(RegistrationData {
413 type_id: TypeId::of::<T>(),
414 data <- data,
415 }),
416 GFP_KERNEL,
417 )?;
418
419 let boxed: KBox<Opaque<bindings::auxiliary_device>> = KBox::zeroed(GFP_KERNEL)?;
420 let adev = boxed.get();
421
422 // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
423 unsafe {
424 (*adev).dev.parent = parent.as_raw();
425 (*adev).dev.release = Some(Device::release);
426 (*adev).name = name.as_char_ptr();
427 (*adev).id = id;
428 (*adev).registration_data_rust = data.into_foreign();
429 }
430
431 // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
432 // which has not been initialized yet.
433 unsafe { bindings::auxiliary_device_init(adev) };
434
435 // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be
436 // freed by `Device::release` when the last reference to the `struct auxiliary_device`
437 // is dropped.
438 let _ = KBox::into_raw(boxed);
439
440 // SAFETY:
441 // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which
442 // has been initialized,
443 // - `modname.as_char_ptr()` is a NULL terminated string.
444 let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
445 if ret != 0 {
446 // SAFETY: `registration_data` was set above via `into_foreign()`.
447 drop(unsafe {
448 Pin::<KBox<RegistrationData<T>>>::from_foreign((*adev).registration_data_rust)
449 });
450
451 // SAFETY: `adev` is guaranteed to be a valid pointer to a
452 // `struct auxiliary_device`, which has been initialized.
453 unsafe { bindings::auxiliary_device_uninit(adev) };
454
455 return Err(Error::from_errno(ret));
456 }
457
458 // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is
459 // called, which happens in `Self::drop()`.
460 let reg = Self {
461 // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated
462 // successfully.
463 adev: unsafe { NonNull::new_unchecked(adev) },
464 _data: PhantomData,
465 };
466
467 Devres::new::<core::convert::Infallible>(parent, reg)
468 }
469}
470
471impl<T: 'static> Drop for Registration<T> {
472 fn drop(&mut self) {
473 // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered
474 // `struct auxiliary_device`.
475 unsafe { bindings::auxiliary_device_delete(self.adev.as_ptr()) };
476
477 // SAFETY: `registration_data` was set in `new()` via `into_foreign()`.
478 drop(unsafe {
479 Pin::<KBox<RegistrationData<T>>>::from_foreign(
480 (*self.adev.as_ptr()).registration_data_rust,
481 )
482 });
483
484 // This drops the reference we acquired through `auxiliary_device_init()`.
485 //
486 // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered
487 // `struct auxiliary_device`.
488 unsafe { bindings::auxiliary_device_uninit(self.adev.as_ptr()) };
489 }
490}
491
492// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.
493unsafe impl<T: Send + Sync> Send for Registration<T> {}
494
495// SAFETY: `Registration` does not expose any methods or fields that need synchronization.
496unsafe impl<T: Send + Sync> Sync for Registration<T> {}