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