xref: /linux/rust/kernel/driver.rs (revision 24799831d631239ff21ea1bf7feee832df48b81f)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Generic support for drivers of different buses (e.g., PCI, Platform, Amba, etc.).
4 //!
5 //! This documentation describes how to implement a bus specific driver API and how to align it with
6 //! the design of (bus specific) devices.
7 //!
8 //! Note: Readers are expected to know the content of the documentation of [`Device`] and
9 //! [`DeviceContext`].
10 //!
11 //! # Driver Trait
12 //!
13 //! The main driver interface is defined by a bus specific driver trait. For instance:
14 //!
15 //! ```ignore
16 //! pub trait Driver {
17 //!     /// The type holding information about each device ID supported by the driver.
18 //!     type IdInfo: 'static;
19 //!
20 //!     /// The type of the driver's bus device private data.
21 //!     type Data: Send;
22 //!
23 //!     /// The table of OF device ids supported by the driver.
24 //!     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
25 //!
26 //!     /// The table of ACPI device ids supported by the driver.
27 //!     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
28 //!
29 //!     /// Driver probe.
30 //!     fn probe(dev: &Device<device::Core<'_>>, id_info: &Self::IdInfo)
31 //!         -> impl PinInit<Self::Data, Error>;
32 //!
33 //!     /// Driver unbind (optional).
34 //!     fn unbind(dev: &Device<device::Core<'_>>, this: Pin<&Self::Data>) {
35 //!         let _ = (dev, this);
36 //!     }
37 //! }
38 //! ```
39 //!
40 //! For specific examples see:
41 //!
42 //! * [`platform::Driver`](kernel::platform::Driver)
43 #![cfg_attr(
44     CONFIG_AUXILIARY_BUS,
45     doc = "* [`auxiliary::Driver`](kernel::auxiliary::Driver)"
46 )]
47 #![cfg_attr(CONFIG_PCI, doc = "* [`pci::Driver`](kernel::pci::Driver)")]
48 //!
49 //! The `probe()` callback should return a `impl PinInit<Self::Data, Error>`, i.e. the driver's
50 //! private data. The bus abstraction should store the pointer in the corresponding bus device. The
51 //! generic [`Device`] infrastructure provides common helpers for this purpose on its
52 //! [`Device<CoreInternal>`] implementation.
53 //!
54 //! All driver callbacks should provide a reference to the driver's private data. Once the driver
55 //! is unbound from the device, the bus abstraction should take back the ownership of the driver's
56 //! private data from the corresponding [`Device`] and [`drop`] it.
57 //!
58 //! All driver callbacks should provide a [`Device<Core>`] reference (see also [`device::Core`]).
59 //!
60 //! # Adapter
61 //!
62 //! The adapter implementation of a bus represents the abstraction layer between the C bus
63 //! callbacks and the Rust bus callbacks. It therefore has to be generic over an implementation of
64 //! the [driver trait](#driver-trait).
65 //!
66 //! ```ignore
67 //! pub struct Adapter<T: Driver>;
68 //! ```
69 //!
70 //! There's a common [`Adapter`] trait that can be implemented to inherit common driver
71 //! infrastructure, such as finding the ID info from an [`of::IdTable`] or [`acpi::IdTable`].
72 //!
73 //! # Driver Registration
74 //!
75 //! In order to register C driver types (such as `struct platform_driver`) the [adapter](#adapter)
76 //! should implement the [`RegistrationOps`] trait.
77 //!
78 //! This trait implementation can be used to create the actual registration with the common
79 //! [`Registration`] type.
80 //!
81 //! Typically, bus abstractions want to provide a bus specific `module_bus_driver!` macro, which
82 //! creates a kernel module with exactly one [`Registration`] for the bus specific adapter.
83 //!
84 //! The generic driver infrastructure provides a helper for this with the [`module_driver`] macro.
85 //!
86 //! # Device IDs
87 //!
88 //! Besides the common device ID types, such as [`of::DeviceId`] and [`acpi::DeviceId`], most buses
89 //! may need to implement their own device ID types.
90 //!
91 //! For this purpose the generic infrastructure in [`device_id`] should be used.
92 //!
93 //! [`Core`]: device::Core
94 //! [`Device`]: device::Device
95 //! [`Device<Core>`]: device::Device<device::Core>
96 //! [`Device<CoreInternal>`]: device::Device<device::CoreInternal>
97 //! [`DeviceContext`]: device::DeviceContext
98 //! [`device_id`]: kernel::device_id
99 //! [`module_driver`]: kernel::module_driver
100 
101 use crate::{
102     acpi,
103     device,
104     of,
105     prelude::*,
106     types::Opaque,
107     ThisModule, //
108 };
109 
110 /// Trait describing the layout of a specific device driver.
111 ///
112 /// This trait describes the layout of a specific driver structure, such as `struct pci_driver` or
113 /// `struct platform_driver`.
114 ///
115 /// # Safety
116 ///
117 /// Implementors must guarantee that:
118 /// - `DriverType` is `repr(C)`,
119 /// - `DriverData` is the type of the driver's device private data.
120 /// - `DriverType` embeds a valid `struct device_driver` at byte offset `DEVICE_DRIVER_OFFSET`.
121 pub unsafe trait DriverLayout {
122     /// The specific driver type embedding a `struct device_driver`.
123     type DriverType: Default;
124 
125     /// The type of the driver's bus device private data.
126     type DriverData<'bound>;
127 
128     /// Byte offset of the embedded `struct device_driver` within `DriverType`.
129     ///
130     /// This must correspond exactly to the location of the embedded `struct device_driver` field.
131     const DEVICE_DRIVER_OFFSET: usize;
132 }
133 
134 /// The [`RegistrationOps`] trait serves as generic interface for subsystems (e.g., PCI, Platform,
135 /// Amba, etc.) to provide the corresponding subsystem specific implementation to register /
136 /// unregister a driver of the particular type (`DriverType`).
137 ///
138 /// For instance, the PCI subsystem would set `DriverType` to `bindings::pci_driver` and call
139 /// `bindings::__pci_register_driver` from `RegistrationOps::register` and
140 /// `bindings::pci_unregister_driver` from `RegistrationOps::unregister`.
141 ///
142 /// # Safety
143 ///
144 /// A call to [`RegistrationOps::unregister`] for a given instance of `DriverType` is only valid if
145 /// a preceding call to [`RegistrationOps::register`] has been successful.
146 pub unsafe trait RegistrationOps: DriverLayout {
147     /// Registers a driver.
148     ///
149     /// # Safety
150     ///
151     /// On success, `reg` must remain pinned and valid until the matching call to
152     /// [`RegistrationOps::unregister`].
153     unsafe fn register(
154         reg: &Opaque<Self::DriverType>,
155         name: &'static CStr,
156         module: &'static ThisModule,
157     ) -> Result;
158 
159     /// Unregisters a driver previously registered with [`RegistrationOps::register`].
160     ///
161     /// # Safety
162     ///
163     /// Must only be called after a preceding successful call to [`RegistrationOps::register`] for
164     /// the same `reg`.
165     unsafe fn unregister(reg: &Opaque<Self::DriverType>);
166 }
167 
168 /// A [`Registration`] is a generic type that represents the registration of some driver type (e.g.
169 /// `bindings::pci_driver`). Therefore a [`Registration`] must be initialized with a type that
170 /// implements the [`RegistrationOps`] trait, such that the generic `T::register` and
171 /// `T::unregister` calls result in the subsystem specific registration calls.
172 ///
173 ///Once the `Registration` structure is dropped, the driver is unregistered.
174 #[pin_data(PinnedDrop)]
175 pub struct Registration<T: RegistrationOps> {
176     #[pin]
177     reg: Opaque<T::DriverType>,
178 }
179 
180 // SAFETY: `Registration` has no fields or methods accessible via `&Registration`, so it is safe to
181 // share references to it with multiple threads as nothing can be done.
182 unsafe impl<T: RegistrationOps> Sync for Registration<T> {}
183 
184 // SAFETY: Both registration and unregistration are implemented in C and safe to be performed from
185 // any thread, so `Registration` is `Send`.
186 unsafe impl<T: RegistrationOps> Send for Registration<T> {}
187 
188 impl<T: RegistrationOps> Registration<T> {
189     extern "C" fn post_unbind_callback(dev: *mut bindings::device) {
190         // SAFETY: The driver core only ever calls the post unbind callback with a valid pointer to
191         // a `struct device`.
192         //
193         // INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`.
194         let dev = unsafe { &*dev.cast::<device::Device<device::CoreInternal<'_>>>() };
195 
196         // `remove()` has been completed at this point; devres resources are still valid and will
197         // be released after the driver's bus device private data is dropped.
198         //
199         // SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the
200         // driver's bus device private data type.
201         drop(unsafe { dev.drvdata_obtain::<T::DriverData<'_>>() });
202     }
203 
204     /// Attach generic `struct device_driver` callbacks.
205     fn callbacks_attach(drv: &Opaque<T::DriverType>) {
206         let ptr = drv.get().cast::<u8>();
207 
208         // SAFETY:
209         // - `drv.get()` yields a valid pointer to `Self::DriverType`.
210         // - Adding `DEVICE_DRIVER_OFFSET` yields the address of the embedded `struct device_driver`
211         //   as guaranteed by the safety requirements of the `Driver` trait.
212         let base = unsafe { ptr.add(T::DEVICE_DRIVER_OFFSET) };
213 
214         // CAST: `base` points to the offset of the embedded `struct device_driver`.
215         let base = base.cast::<bindings::device_driver>();
216 
217         // SAFETY: It is safe to set the fields of `struct device_driver` on initialization.
218         unsafe { (*base).p_cb.post_unbind_rust = Some(Self::post_unbind_callback) };
219     }
220 
221     /// Creates a new instance of the registration object.
222     pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error>
223     where
224         T: 'static,
225     {
226         try_pin_init!(Self {
227             reg <- Opaque::try_ffi_init(|ptr: *mut T::DriverType| {
228                 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.
229                 unsafe { ptr.write(T::DriverType::default()) };
230 
231                 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write, and it has
232                 // just been initialised above, so it's also valid for read.
233                 let drv = unsafe { &*(ptr as *const Opaque<T::DriverType>) };
234 
235                 Self::callbacks_attach(drv);
236 
237                 // SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.
238                 unsafe { T::register(drv, name, module) }
239             }),
240         })
241     }
242 }
243 
244 #[pinned_drop]
245 impl<T: RegistrationOps> PinnedDrop for Registration<T> {
246     fn drop(self: Pin<&mut Self>) {
247         // SAFETY: The existence of `self` guarantees that `self.reg` has previously been
248         // successfully registered with `T::register`
249         unsafe { T::unregister(&self.reg) };
250     }
251 }
252 
253 /// Declares a kernel module that exposes a single driver.
254 ///
255 /// It is meant to be used as a helper by other subsystems so they can more easily expose their own
256 /// macros.
257 #[macro_export]
258 macro_rules! module_driver {
259     (<$gen_type:ident>, $driver_ops:ty, { type: $type:ty, $($f:tt)* }) => {
260         type Ops<$gen_type> = $driver_ops;
261 
262         #[$crate::prelude::pin_data]
263         struct DriverModule {
264             #[pin]
265             _driver: $crate::driver::Registration<Ops<$type>>,
266         }
267 
268         impl $crate::InPlaceModule for DriverModule {
269             fn init(
270                 module: &'static $crate::ThisModule
271             ) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {
272                 $crate::try_pin_init!(Self {
273                     _driver <- $crate::driver::Registration::new(
274                         <Self as $crate::ModuleMetadata>::NAME,
275                         module,
276                     ),
277                 })
278             }
279         }
280 
281         $crate::prelude::module! {
282             type: DriverModule,
283             $($f)*
284         }
285     }
286 }
287 
288 /// The bus independent adapter to match a drivers and a devices.
289 ///
290 /// This trait should be implemented by the bus specific adapter, which represents the connection
291 /// of a device and a driver.
292 ///
293 /// It provides bus independent functions for device / driver interactions.
294 pub trait Adapter {
295     /// The type holding driver private data about each device id supported by the driver.
296     type IdInfo: 'static;
297 
298     /// The [`acpi::IdTable`] of the corresponding driver
299     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>>;
300 
301     /// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.
302     ///
303     /// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].
304     fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
305         #[cfg(not(CONFIG_ACPI))]
306         {
307             let _ = dev;
308             None
309         }
310 
311         #[cfg(CONFIG_ACPI)]
312         {
313             let table = Self::acpi_id_table()?;
314 
315             // SAFETY:
316             // - `table` has static lifetime, hence it's valid for read,
317             // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
318             let raw_id = unsafe { bindings::acpi_match_device(table.as_ptr(), dev.as_raw()) };
319 
320             if raw_id.is_null() {
321                 None
322             } else {
323                 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct acpi_device_id`
324                 // and does not add additional invariants, so it's safe to transmute.
325                 let id = unsafe { &*raw_id.cast::<acpi::DeviceId>() };
326 
327                 Some(table.info(<acpi::DeviceId as crate::device_id::RawDeviceIdIndex>::index(id)))
328             }
329         }
330     }
331 
332     /// The [`of::IdTable`] of the corresponding driver.
333     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>>;
334 
335     /// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.
336     ///
337     /// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].
338     fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
339         #[cfg(not(CONFIG_OF))]
340         {
341             let _ = dev;
342             None
343         }
344 
345         #[cfg(CONFIG_OF)]
346         {
347             let table = Self::of_id_table()?;
348 
349             // SAFETY:
350             // - `table` has static lifetime, hence it's valid for read,
351             // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
352             let raw_id = unsafe { bindings::of_match_device(table.as_ptr(), dev.as_raw()) };
353 
354             if raw_id.is_null() {
355                 None
356             } else {
357                 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct of_device_id`
358                 // and does not add additional invariants, so it's safe to transmute.
359                 let id = unsafe { &*raw_id.cast::<of::DeviceId>() };
360 
361                 Some(
362                     table.info(<of::DeviceId as crate::device_id::RawDeviceIdIndex>::index(
363                         id,
364                     )),
365                 )
366             }
367         }
368     }
369 
370     /// Returns the driver's private data from the matching entry of any of the ID tables, if any.
371     ///
372     /// If this returns `None`, it means that there is no match in any of the ID tables directly
373     /// associated with a [`device::Device`].
374     fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
375         let id = Self::acpi_id_info(dev);
376         if id.is_some() {
377             return id;
378         }
379 
380         let id = Self::of_id_info(dev);
381         if id.is_some() {
382             return id;
383         }
384 
385         None
386     }
387 }
388