xref: /linux/rust/kernel/auxiliary.rs (revision 589b061975db3c7e87b819cc9a8006eb99ac4b5f)
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     driver,
11     error::{from_result, to_result, Result},
12     prelude::*,
13     types::Opaque,
14     ThisModule,
15 };
16 use core::{
17     marker::PhantomData,
18     ptr::{addr_of_mut, NonNull},
19 };
20 
21 /// An adapter for the registration of auxiliary drivers.
22 pub 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.
26 unsafe 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 
54 impl<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     ) -> 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::<T>() });
89     }
90 }
91 
92 /// Declares a kernel module that exposes a single auxiliary driver.
93 #[macro_export]
94 macro_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)]
103 pub struct DeviceId(bindings::auxiliary_device_id);
104 
105 impl DeviceId {
106     /// Create a new [`DeviceId`] from name.
107     pub const fn new(modname: &'static CStr, name: &'static CStr) -> Self {
108         let name = name.to_bytes_with_nul();
109         let modname = modname.to_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: `DeviceId` is a `#[repr(transparent)]` wrapper of `auxiliary_device_id` and does not add
138 // additional invariants, so it's safe to transmute to `RawType`.
139 unsafe impl RawDeviceId for DeviceId {
140     type RawType = bindings::auxiliary_device_id;
141 }
142 
143 // SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
144 unsafe impl RawDeviceIdIndex for DeviceId {
145     const DRIVER_DATA_OFFSET: usize =
146         core::mem::offset_of!(bindings::auxiliary_device_id, driver_data);
147 
148     fn index(&self) -> usize {
149         self.0.driver_data
150     }
151 }
152 
153 /// IdTable type for auxiliary drivers.
154 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
155 
156 /// Create a auxiliary `IdTable` with its alias for modpost.
157 #[macro_export]
158 macro_rules! auxiliary_device_table {
159     ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {
160         const $table_name: $crate::device_id::IdArray<
161             $crate::auxiliary::DeviceId,
162             $id_info_type,
163             { $table_data.len() },
164         > = $crate::device_id::IdArray::new($table_data);
165 
166         $crate::module_device_table!("auxiliary", $module_table_name, $table_name);
167     };
168 }
169 
170 /// The auxiliary driver trait.
171 ///
172 /// Drivers must implement this trait in order to get an auxiliary driver registered.
173 pub trait Driver {
174     /// The type holding information about each device id supported by the driver.
175     ///
176     /// TODO: Use associated_type_defaults once stabilized:
177     ///
178     /// type IdInfo: 'static = ();
179     type IdInfo: 'static;
180 
181     /// The table of device ids supported by the driver.
182     const ID_TABLE: IdTable<Self::IdInfo>;
183 
184     /// Auxiliary driver probe.
185     ///
186     /// Called when an auxiliary device is matches a corresponding driver.
187     fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> impl PinInit<Self, Error>;
188 }
189 
190 /// The auxiliary device representation.
191 ///
192 /// This structure represents the Rust abstraction for a C `struct auxiliary_device`. The
193 /// implementation abstracts the usage of an already existing C `struct auxiliary_device` within
194 /// Rust code that we get passed from the C side.
195 ///
196 /// # Invariants
197 ///
198 /// A [`Device`] instance represents a valid `struct auxiliary_device` created by the C portion of
199 /// the kernel.
200 #[repr(transparent)]
201 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
202     Opaque<bindings::auxiliary_device>,
203     PhantomData<Ctx>,
204 );
205 
206 impl<Ctx: device::DeviceContext> Device<Ctx> {
207     fn as_raw(&self) -> *mut bindings::auxiliary_device {
208         self.0.get()
209     }
210 
211     /// Returns the auxiliary device' id.
212     pub fn id(&self) -> u32 {
213         // SAFETY: By the type invariant `self.as_raw()` is a valid pointer to a
214         // `struct auxiliary_device`.
215         unsafe { (*self.as_raw()).id }
216     }
217 
218     /// Returns a reference to the parent [`device::Device`].
219     pub fn parent(&self) -> &device::Device {
220         // SAFETY: A `struct auxiliary_device` always has a parent.
221         unsafe { self.as_ref().parent().unwrap_unchecked() }
222     }
223 }
224 
225 impl Device {
226     extern "C" fn release(dev: *mut bindings::device) {
227         // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
228         // embedded in `struct auxiliary_device`.
229         let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };
230 
231         // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
232         // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
233         let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
234     }
235 }
236 
237 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
238 // argument.
239 kernel::impl_device_context_deref!(unsafe { Device });
240 kernel::impl_device_context_into_aref!(Device);
241 
242 // SAFETY: Instances of `Device` are always reference-counted.
243 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
244     fn inc_ref(&self) {
245         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
246         unsafe { bindings::get_device(self.as_ref().as_raw()) };
247     }
248 
249     unsafe fn dec_ref(obj: NonNull<Self>) {
250         // CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.
251         let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();
252 
253         // SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid
254         // `struct auxiliary_device`.
255         let dev = unsafe { addr_of_mut!((*adev).dev) };
256 
257         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
258         unsafe { bindings::put_device(dev) }
259     }
260 }
261 
262 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
263     fn as_ref(&self) -> &device::Device<Ctx> {
264         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
265         // `struct auxiliary_device`.
266         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
267 
268         // SAFETY: `dev` points to a valid `struct device`.
269         unsafe { device::Device::from_raw(dev) }
270     }
271 }
272 
273 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
274 unsafe impl Send for Device {}
275 
276 // SAFETY: `Device` can be shared among threads because all methods of `Device`
277 // (i.e. `Device<Normal>) are thread safe.
278 unsafe impl Sync for Device {}
279 
280 /// The registration of an auxiliary device.
281 ///
282 /// This type represents the registration of a [`struct auxiliary_device`]. When an instance of this
283 /// type is dropped, its respective auxiliary device will be unregistered from the system.
284 ///
285 /// # Invariants
286 ///
287 /// `self.0` always holds a valid pointer to an initialized and registered
288 /// [`struct auxiliary_device`].
289 pub struct Registration(NonNull<bindings::auxiliary_device>);
290 
291 impl Registration {
292     /// Create and register a new auxiliary device.
293     pub fn new(parent: &device::Device, name: &CStr, id: u32, modname: &CStr) -> Result<Self> {
294         let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
295         let adev = boxed.get();
296 
297         // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
298         unsafe {
299             (*adev).dev.parent = parent.as_raw();
300             (*adev).dev.release = Some(Device::release);
301             (*adev).name = name.as_char_ptr();
302             (*adev).id = id;
303         }
304 
305         // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
306         // which has not been initialized yet.
307         unsafe { bindings::auxiliary_device_init(adev) };
308 
309         // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be freed
310         // by `Device::release` when the last reference to the `struct auxiliary_device` is dropped.
311         let _ = KBox::into_raw(boxed);
312 
313         // SAFETY:
314         // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which has
315         //   been initialialized,
316         // - `modname.as_char_ptr()` is a NULL terminated string.
317         let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
318         if ret != 0 {
319             // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
320             // which has been initialialized.
321             unsafe { bindings::auxiliary_device_uninit(adev) };
322 
323             return Err(Error::from_errno(ret));
324         }
325 
326         // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated successfully.
327         //
328         // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is called,
329         // which happens in `Self::drop()`.
330         Ok(Self(unsafe { NonNull::new_unchecked(adev) }))
331     }
332 }
333 
334 impl Drop for Registration {
335     fn drop(&mut self) {
336         // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
337         // `struct auxiliary_device`.
338         unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };
339 
340         // This drops the reference we acquired through `auxiliary_device_init()`.
341         //
342         // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
343         // `struct auxiliary_device`.
344         unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };
345     }
346 }
347 
348 // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.
349 unsafe impl Send for Registration {}
350 
351 // SAFETY: `Registration` does not expose any methods or fields that need synchronization.
352 unsafe impl Sync for Registration {}
353