xref: /linux/rust/kernel/auxiliary.rs (revision e4e679c8608e5c747081cc6ce63ee0b0e524c68d)
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     /// Returns a reference to the parent [`device::Device`].
220     pub fn parent(&self) -> &device::Device {
221         // SAFETY: A `struct auxiliary_device` always has a parent.
222         unsafe { self.as_ref().parent().unwrap_unchecked() }
223     }
224 }
225 
226 impl Device {
227     extern "C" fn release(dev: *mut bindings::device) {
228         // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
229         // embedded in `struct auxiliary_device`.
230         let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };
231 
232         // SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via
233         // `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.
234         let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };
235     }
236 }
237 
238 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
239 // argument.
240 kernel::impl_device_context_deref!(unsafe { Device });
241 kernel::impl_device_context_into_aref!(Device);
242 
243 // SAFETY: Instances of `Device` are always reference-counted.
244 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
245     fn inc_ref(&self) {
246         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
247         unsafe { bindings::get_device(self.as_ref().as_raw()) };
248     }
249 
250     unsafe fn dec_ref(obj: NonNull<Self>) {
251         // CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.
252         let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();
253 
254         // SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid
255         // `struct auxiliary_device`.
256         let dev = unsafe { addr_of_mut!((*adev).dev) };
257 
258         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
259         unsafe { bindings::put_device(dev) }
260     }
261 }
262 
263 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
264     fn as_ref(&self) -> &device::Device<Ctx> {
265         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
266         // `struct auxiliary_device`.
267         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
268 
269         // SAFETY: `dev` points to a valid `struct device`.
270         unsafe { device::Device::from_raw(dev) }
271     }
272 }
273 
274 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
275 unsafe impl Send for Device {}
276 
277 // SAFETY: `Device` can be shared among threads because all methods of `Device`
278 // (i.e. `Device<Normal>) are thread safe.
279 unsafe impl Sync for Device {}
280 
281 /// The registration of an auxiliary device.
282 ///
283 /// This type represents the registration of a [`struct auxiliary_device`]. When its parent device
284 /// is unbound, the corresponding auxiliary device will be unregistered from the system.
285 ///
286 /// # Invariants
287 ///
288 /// `self.0` always holds a valid pointer to an initialized and registered
289 /// [`struct auxiliary_device`].
290 pub struct Registration(NonNull<bindings::auxiliary_device>);
291 
292 impl Registration {
293     /// Create and register a new auxiliary device.
294     pub fn new<'a>(
295         parent: &'a device::Device<device::Bound>,
296         name: &'a CStr,
297         id: u32,
298         modname: &'a CStr,
299     ) -> impl PinInit<Devres<Self>, Error> + 'a {
300         pin_init::pin_init_scope(move || {
301             let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;
302             let adev = boxed.get();
303 
304             // SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.
305             unsafe {
306                 (*adev).dev.parent = parent.as_raw();
307                 (*adev).dev.release = Some(Device::release);
308                 (*adev).name = name.as_char_ptr();
309                 (*adev).id = id;
310             }
311 
312             // SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,
313             // which has not been initialized yet.
314             unsafe { bindings::auxiliary_device_init(adev) };
315 
316             // Now that `adev` is initialized, leak the `Box`; the corresponding memory will be
317             // freed by `Device::release` when the last reference to the `struct auxiliary_device`
318             // is dropped.
319             let _ = KBox::into_raw(boxed);
320 
321             // SAFETY:
322             // - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which
323             //   has been initialized,
324             // - `modname.as_char_ptr()` is a NULL terminated string.
325             let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };
326             if ret != 0 {
327                 // SAFETY: `adev` is guaranteed to be a valid pointer to a
328                 // `struct auxiliary_device`, which has been initialized.
329                 unsafe { bindings::auxiliary_device_uninit(adev) };
330 
331                 return Err(Error::from_errno(ret));
332             }
333 
334             // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated
335             // successfully.
336             //
337             // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is
338             // called, which happens in `Self::drop()`.
339             Ok(Devres::new(
340                 parent,
341                 Self(unsafe { NonNull::new_unchecked(adev) }),
342             ))
343         })
344     }
345 }
346 
347 impl Drop for Registration {
348     fn drop(&mut self) {
349         // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
350         // `struct auxiliary_device`.
351         unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };
352 
353         // This drops the reference we acquired through `auxiliary_device_init()`.
354         //
355         // SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered
356         // `struct auxiliary_device`.
357         unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };
358     }
359 }
360 
361 // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.
362 unsafe impl Send for Registration {}
363 
364 // SAFETY: `Registration` does not expose any methods or fields that need synchronization.
365 unsafe impl Sync for Registration {}
366