xref: /linux/rust/kernel/auxiliary.rs (revision 121d87b28e1d9061d3aaa156c43a627d3cb5e620)
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 
7 use 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::Opaque,
23     ThisModule, //
24 };
25 use core::{
26     marker::PhantomData,
27     mem::offset_of,
28     ptr::{
29         addr_of_mut,
30         NonNull, //
31     },
32 };
33 
34 /// An adapter for the registration of auxiliary drivers.
35 pub struct Adapter<T: Driver>(T);
36 
37 // SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if
38 // a preceding call to `register` has been successful.
39 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
40     type RegType = bindings::auxiliary_driver;
41 
42     unsafe fn register(
43         adrv: &Opaque<Self::RegType>,
44         name: &'static CStr,
45         module: &'static ThisModule,
46     ) -> Result {
47         // SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.
48         unsafe {
49             (*adrv.get()).name = name.as_char_ptr();
50             (*adrv.get()).probe = Some(Self::probe_callback);
51             (*adrv.get()).remove = Some(Self::remove_callback);
52             (*adrv.get()).id_table = T::ID_TABLE.as_ptr();
53         }
54 
55         // SAFETY: `adrv` is guaranteed to be a valid `RegType`.
56         to_result(unsafe {
57             bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())
58         })
59     }
60 
61     unsafe fn unregister(adrv: &Opaque<Self::RegType>) {
62         // SAFETY: `adrv` is guaranteed to be a valid `RegType`.
63         unsafe { bindings::auxiliary_driver_unregister(adrv.get()) }
64     }
65 }
66 
67 impl<T: Driver + 'static> Adapter<T> {
68     extern "C" fn probe_callback(
69         adev: *mut bindings::auxiliary_device,
70         id: *const bindings::auxiliary_device_id,
71     ) -> c_int {
72         // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
73         // `struct auxiliary_device`.
74         //
75         // INVARIANT: `adev` is valid for the duration of `probe_callback()`.
76         let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };
77 
78         // SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id`
79         // and does not add additional invariants, so it's safe to transmute.
80         let id = unsafe { &*id.cast::<DeviceId>() };
81         let info = T::ID_TABLE.info(id.index());
82 
83         from_result(|| {
84             let data = T::probe(adev, info);
85 
86             adev.as_ref().set_drvdata(data)?;
87             Ok(0)
88         })
89     }
90 
91     extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {
92         // SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a
93         // `struct auxiliary_device`.
94         //
95         // INVARIANT: `adev` is valid for the duration of `remove_callback()`.
96         let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };
97 
98         // SAFETY: `remove_callback` is only ever called after a successful call to
99         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
100         // and stored a `Pin<KBox<T>>`.
101         drop(unsafe { adev.as_ref().drvdata_obtain::<T>() });
102     }
103 }
104 
105 /// Declares a kernel module that exposes a single auxiliary driver.
106 #[macro_export]
107 macro_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)]
116 pub struct DeviceId(bindings::auxiliary_device_id);
117 
118 impl 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`.
152 unsafe 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.
157 unsafe 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.
167 pub 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]
171 macro_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.
186 pub 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 
203 /// The auxiliary device representation.
204 ///
205 /// This structure represents the Rust abstraction for a C `struct auxiliary_device`. The
206 /// implementation abstracts the usage of an already existing C `struct auxiliary_device` within
207 /// Rust code that we get passed from the C side.
208 ///
209 /// # Invariants
210 ///
211 /// A [`Device`] instance represents a valid `struct auxiliary_device` created by the C portion of
212 /// the kernel.
213 #[repr(transparent)]
214 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
215     Opaque<bindings::auxiliary_device>,
216     PhantomData<Ctx>,
217 );
218 
219 impl<Ctx: device::DeviceContext> Device<Ctx> {
220     fn as_raw(&self) -> *mut bindings::auxiliary_device {
221         self.0.get()
222     }
223 
224     /// Returns the auxiliary device' id.
225     pub fn id(&self) -> u32 {
226         // SAFETY: By the type invariant `self.as_raw()` is a valid pointer to a
227         // `struct auxiliary_device`.
228         unsafe { (*self.as_raw()).id }
229     }
230 }
231 
232 impl Device<device::Bound> {
233     /// Returns a bound reference to the parent [`device::Device`].
234     pub fn parent(&self) -> &device::Device<device::Bound> {
235         let parent = (**self).parent();
236 
237         // SAFETY: A bound auxiliary device always has a bound parent device.
238         unsafe { parent.as_bound() }
239     }
240 }
241 
242 impl Device {
243     /// Returns a reference to the parent [`device::Device`].
244     pub fn parent(&self) -> &device::Device {
245         // SAFETY: A `struct auxiliary_device` always has a parent.
246         unsafe { self.as_ref().parent().unwrap_unchecked() }
247     }
248 
249     extern "C" fn release(dev: *mut bindings::device) {
250         // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
251         // embedded in `struct auxiliary_device`.
252         let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };
253 
254         // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
255         // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
256         let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
257     }
258 }
259 
260 // SAFETY: `auxiliary::Device` is a transparent wrapper of `struct auxiliary_device`.
261 // The offset is guaranteed to point to a valid device field inside `auxiliary::Device`.
262 unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
263     const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
264 }
265 
266 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
267 // argument.
268 kernel::impl_device_context_deref!(unsafe { Device });
269 kernel::impl_device_context_into_aref!(Device);
270 
271 // SAFETY: Instances of `Device` are always reference-counted.
272 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
273     fn inc_ref(&self) {
274         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
275         unsafe { bindings::get_device(self.as_ref().as_raw()) };
276     }
277 
278     unsafe fn dec_ref(obj: NonNull<Self>) {
279         // CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.
280         let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();
281 
282         // SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid
283         // `struct auxiliary_device`.
284         let dev = unsafe { addr_of_mut!((*adev).dev) };
285 
286         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
287         unsafe { bindings::put_device(dev) }
288     }
289 }
290 
291 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
292     fn as_ref(&self) -> &device::Device<Ctx> {
293         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
294         // `struct auxiliary_device`.
295         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
296 
297         // SAFETY: `dev` points to a valid `struct device`.
298         unsafe { device::Device::from_raw(dev) }
299     }
300 }
301 
302 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
303 unsafe impl Send for Device {}
304 
305 // SAFETY: `Device` can be shared among threads because all methods of `Device`
306 // (i.e. `Device<Normal>) are thread safe.
307 unsafe impl Sync for Device {}
308 
309 /// The registration of an auxiliary device.
310 ///
311 /// This type represents the registration of a [`struct auxiliary_device`]. When its parent device
312 /// is unbound, the corresponding auxiliary device will be unregistered from the system.
313 ///
314 /// # Invariants
315 ///
316 /// `self.0` always holds a valid pointer to an initialized and registered
317 /// [`struct auxiliary_device`].
318 pub struct Registration(NonNull<bindings::auxiliary_device>);
319 
320 impl Registration {
321     /// Create and register a new auxiliary device.
322     pub fn new<'a>(
323         parent: &'a device::Device<device::Bound>,
324         name: &'a CStr,
325         id: u32,
326         modname: &'a CStr,
327     ) -> impl PinInit<Devres<Self>, Error> + 'a {
328         pin_init::pin_init_scope(move || {
329             let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
330             let adev = boxed.get();
331 
332             // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
333             unsafe {
334                 (*adev).dev.parent = parent.as_raw();
335                 (*adev).dev.release = Some(Device::release);
336                 (*adev).name = name.as_char_ptr();
337                 (*adev).id = id;
338             }
339 
340             // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
341             // which has not been initialized yet.
342             unsafe { bindings::auxiliary_device_init(adev) };
343 
344             // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be
345             // freed by `Device::release` when the last reference to the `struct auxiliary_device`
346             // is dropped.
347             let _ = KBox::into_raw(boxed);
348 
349             // SAFETY:
350             // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which
351             //   has been initialized,
352             // - `modname.as_char_ptr()` is a NULL terminated string.
353             let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
354             if ret != 0 {
355                 // SAFETY: `adev` is guaranteed to be a valid pointer to a
356                 // `struct auxiliary_device`, which has been initialized.
357                 unsafe { bindings::auxiliary_device_uninit(adev) };
358 
359                 return Err(Error::from_errno(ret));
360             }
361 
362             // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is
363             // called, which happens in `Self::drop()`.
364             Ok(Devres::new(
365                 parent,
366                 // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated
367                 // successfully.
368                 Self(unsafe { NonNull::new_unchecked(adev) }),
369             ))
370         })
371     }
372 }
373 
374 impl Drop for Registration {
375     fn drop(&mut self) {
376         // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
377         // `struct auxiliary_device`.
378         unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };
379 
380         // This drops the reference we acquired through `auxiliary_device_init()`.
381         //
382         // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
383         // `struct auxiliary_device`.
384         unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };
385     }
386 }
387 
388 // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.
389 unsafe impl Send for Registration {}
390 
391 // SAFETY: `Registration` does not expose any methods or fields that need synchronization.
392 unsafe impl Sync for Registration {}
393