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