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