xref: /linux/rust/kernel/driver.rs (revision 52025b8fc992972168128be40bffee7eafa532b5)
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: Send {
17 //!     /// The type holding information about each device ID supported by the driver.
18 //!     type IdInfo: 'static;
19 //!
20 //!     /// The table of OF device ids supported by the driver.
21 //!     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
22 //!
23 //!     /// The table of ACPI device ids supported by the driver.
24 //!     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
25 //!
26 //!     /// Driver probe.
27 //!     fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> Result<Pin<KBox<Self>>>;
28 //!
29 //!     /// Driver unbind (optional).
30 //!     fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
31 //!         let _ = (dev, this);
32 //!     }
33 //! }
34 //! ```
35 //!
36 //! For specific examples see [`auxiliary::Driver`], [`pci::Driver`] and [`platform::Driver`].
37 //!
38 //! The `probe()` callback should return a `Result<Pin<KBox<Self>>>`, i.e. the driver's private
39 //! data. The bus abstraction should store the pointer in the corresponding bus device. The generic
40 //! [`Device`] infrastructure provides common helpers for this purpose on its
41 //! [`Device<CoreInternal>`] implementation.
42 //!
43 //! All driver callbacks should provide a reference to the driver's private data. Once the driver
44 //! is unbound from the device, the bus abstraction should take back the ownership of the driver's
45 //! private data from the corresponding [`Device`] and [`drop`] it.
46 //!
47 //! All driver callbacks should provide a [`Device<Core>`] reference (see also [`device::Core`]).
48 //!
49 //! # Adapter
50 //!
51 //! The adapter implementation of a bus represents the abstraction layer between the C bus
52 //! callbacks and the Rust bus callbacks. It therefore has to be generic over an implementation of
53 //! the [driver trait](#driver-trait).
54 //!
55 //! ```ignore
56 //! pub struct Adapter<T: Driver>;
57 //! ```
58 //!
59 //! There's a common [`Adapter`] trait that can be implemented to inherit common driver
60 //! infrastructure, such as finding the ID info from an [`of::IdTable`] or [`acpi::IdTable`].
61 //!
62 //! # Driver Registration
63 //!
64 //! In order to register C driver types (such as `struct platform_driver`) the [adapter](#adapter)
65 //! should implement the [`RegistrationOps`] trait.
66 //!
67 //! This trait implementation can be used to create the actual registration with the common
68 //! [`Registration`] type.
69 //!
70 //! Typically, bus abstractions want to provide a bus specific `module_bus_driver!` macro, which
71 //! creates a kernel module with exactly one [`Registration`] for the bus specific adapter.
72 //!
73 //! The generic driver infrastructure provides a helper for this with the [`module_driver`] macro.
74 //!
75 //! # Device IDs
76 //!
77 //! Besides the common device ID types, such as [`of::DeviceId`] and [`acpi::DeviceId`], most buses
78 //! may need to implement their own device ID types.
79 //!
80 //! For this purpose the generic infrastructure in [`device_id`] should be used.
81 //!
82 //! [`auxiliary::Driver`]: kernel::auxiliary::Driver
83 //! [`Core`]: device::Core
84 //! [`Device`]: device::Device
85 //! [`Device<Core>`]: device::Device<device::Core>
86 //! [`Device<CoreInternal>`]: device::Device<device::CoreInternal>
87 //! [`DeviceContext`]: device::DeviceContext
88 //! [`device_id`]: kernel::device_id
89 //! [`module_driver`]: kernel::module_driver
90 //! [`pci::Driver`]: kernel::pci::Driver
91 //! [`platform::Driver`]: kernel::platform::Driver
92 
93 use crate::error::{Error, Result};
94 use crate::{acpi, device, of, str::CStr, try_pin_init, types::Opaque, ThisModule};
95 use core::pin::Pin;
96 use pin_init::{pin_data, pinned_drop, PinInit};
97 
98 /// The [`RegistrationOps`] trait serves as generic interface for subsystems (e.g., PCI, Platform,
99 /// Amba, etc.) to provide the corresponding subsystem specific implementation to register /
100 /// unregister a driver of the particular type (`RegType`).
101 ///
102 /// For instance, the PCI subsystem would set `RegType` to `bindings::pci_driver` and call
103 /// `bindings::__pci_register_driver` from `RegistrationOps::register` and
104 /// `bindings::pci_unregister_driver` from `RegistrationOps::unregister`.
105 ///
106 /// # Safety
107 ///
108 /// A call to [`RegistrationOps::unregister`] for a given instance of `RegType` is only valid if a
109 /// preceding call to [`RegistrationOps::register`] has been successful.
110 pub unsafe trait RegistrationOps {
111     /// The type that holds information about the registration. This is typically a struct defined
112     /// by the C portion of the kernel.
113     type RegType: Default;
114 
115     /// Registers a driver.
116     ///
117     /// # Safety
118     ///
119     /// On success, `reg` must remain pinned and valid until the matching call to
120     /// [`RegistrationOps::unregister`].
register( reg: &Opaque<Self::RegType>, name: &'static CStr, module: &'static ThisModule, ) -> Result121     unsafe fn register(
122         reg: &Opaque<Self::RegType>,
123         name: &'static CStr,
124         module: &'static ThisModule,
125     ) -> Result;
126 
127     /// Unregisters a driver previously registered with [`RegistrationOps::register`].
128     ///
129     /// # Safety
130     ///
131     /// Must only be called after a preceding successful call to [`RegistrationOps::register`] for
132     /// the same `reg`.
unregister(reg: &Opaque<Self::RegType>)133     unsafe fn unregister(reg: &Opaque<Self::RegType>);
134 }
135 
136 /// A [`Registration`] is a generic type that represents the registration of some driver type (e.g.
137 /// `bindings::pci_driver`). Therefore a [`Registration`] must be initialized with a type that
138 /// implements the [`RegistrationOps`] trait, such that the generic `T::register` and
139 /// `T::unregister` calls result in the subsystem specific registration calls.
140 ///
141 ///Once the `Registration` structure is dropped, the driver is unregistered.
142 #[pin_data(PinnedDrop)]
143 pub struct Registration<T: RegistrationOps> {
144     #[pin]
145     reg: Opaque<T::RegType>,
146 }
147 
148 // SAFETY: `Registration` has no fields or methods accessible via `&Registration`, so it is safe to
149 // share references to it with multiple threads as nothing can be done.
150 unsafe impl<T: RegistrationOps> Sync for Registration<T> {}
151 
152 // SAFETY: Both registration and unregistration are implemented in C and safe to be performed from
153 // any thread, so `Registration` is `Send`.
154 unsafe impl<T: RegistrationOps> Send for Registration<T> {}
155 
156 impl<T: RegistrationOps> Registration<T> {
157     /// Creates a new instance of the registration object.
new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error>158     pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> {
159         try_pin_init!(Self {
160             reg <- Opaque::try_ffi_init(|ptr: *mut T::RegType| {
161                 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.
162                 unsafe { ptr.write(T::RegType::default()) };
163 
164                 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write, and it has
165                 // just been initialised above, so it's also valid for read.
166                 let drv = unsafe { &*(ptr as *const Opaque<T::RegType>) };
167 
168                 // SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.
169                 unsafe { T::register(drv, name, module) }
170             }),
171         })
172     }
173 }
174 
175 #[pinned_drop]
176 impl<T: RegistrationOps> PinnedDrop for Registration<T> {
drop(self: Pin<&mut Self>)177     fn drop(self: Pin<&mut Self>) {
178         // SAFETY: The existence of `self` guarantees that `self.reg` has previously been
179         // successfully registered with `T::register`
180         unsafe { T::unregister(&self.reg) };
181     }
182 }
183 
184 /// Declares a kernel module that exposes a single driver.
185 ///
186 /// It is meant to be used as a helper by other subsystems so they can more easily expose their own
187 /// macros.
188 #[macro_export]
189 macro_rules! module_driver {
190     (<$gen_type:ident>, $driver_ops:ty, { type: $type:ty, $($f:tt)* }) => {
191         type Ops<$gen_type> = $driver_ops;
192 
193         #[$crate::prelude::pin_data]
194         struct DriverModule {
195             #[pin]
196             _driver: $crate::driver::Registration<Ops<$type>>,
197         }
198 
199         impl $crate::InPlaceModule for DriverModule {
200             fn init(
201                 module: &'static $crate::ThisModule
202             ) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {
203                 $crate::try_pin_init!(Self {
204                     _driver <- $crate::driver::Registration::new(
205                         <Self as $crate::ModuleMetadata>::NAME,
206                         module,
207                     ),
208                 })
209             }
210         }
211 
212         $crate::prelude::module! {
213             type: DriverModule,
214             $($f)*
215         }
216     }
217 }
218 
219 /// The bus independent adapter to match a drivers and a devices.
220 ///
221 /// This trait should be implemented by the bus specific adapter, which represents the connection
222 /// of a device and a driver.
223 ///
224 /// It provides bus independent functions for device / driver interactions.
225 pub trait Adapter {
226     /// The type holding driver private data about each device id supported by the driver.
227     type IdInfo: 'static;
228 
229     /// The [`acpi::IdTable`] of the corresponding driver
acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>>230     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>>;
231 
232     /// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.
233     ///
234     /// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].
acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo>235     fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
236         #[cfg(not(CONFIG_ACPI))]
237         {
238             let _ = dev;
239             None
240         }
241 
242         #[cfg(CONFIG_ACPI)]
243         {
244             let table = Self::acpi_id_table()?;
245 
246             // SAFETY:
247             // - `table` has static lifetime, hence it's valid for read,
248             // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
249             let raw_id = unsafe { bindings::acpi_match_device(table.as_ptr(), dev.as_raw()) };
250 
251             if raw_id.is_null() {
252                 None
253             } else {
254                 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct acpi_device_id`
255                 // and does not add additional invariants, so it's safe to transmute.
256                 let id = unsafe { &*raw_id.cast::<acpi::DeviceId>() };
257 
258                 Some(table.info(<acpi::DeviceId as crate::device_id::RawDeviceIdIndex>::index(id)))
259             }
260         }
261     }
262 
263     /// The [`of::IdTable`] of the corresponding driver.
of_id_table() -> Option<of::IdTable<Self::IdInfo>>264     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>>;
265 
266     /// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.
267     ///
268     /// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].
of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo>269     fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
270         #[cfg(not(CONFIG_OF))]
271         {
272             let _ = dev;
273             None
274         }
275 
276         #[cfg(CONFIG_OF)]
277         {
278             let table = Self::of_id_table()?;
279 
280             // SAFETY:
281             // - `table` has static lifetime, hence it's valid for read,
282             // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
283             let raw_id = unsafe { bindings::of_match_device(table.as_ptr(), dev.as_raw()) };
284 
285             if raw_id.is_null() {
286                 None
287             } else {
288                 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct of_device_id`
289                 // and does not add additional invariants, so it's safe to transmute.
290                 let id = unsafe { &*raw_id.cast::<of::DeviceId>() };
291 
292                 Some(
293                     table.info(<of::DeviceId as crate::device_id::RawDeviceIdIndex>::index(
294                         id,
295                     )),
296                 )
297             }
298         }
299     }
300 
301     /// Returns the driver's private data from the matching entry of any of the ID tables, if any.
302     ///
303     /// If this returns `None`, it means that there is no match in any of the ID tables directly
304     /// associated with a [`device::Device`].
id_info(dev: &device::Device) -> Option<&'static Self::IdInfo>305     fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
306         let id = Self::acpi_id_info(dev);
307         if id.is_some() {
308             return id;
309         }
310 
311         let id = Self::of_id_info(dev);
312         if id.is_some() {
313             return id;
314         }
315 
316         None
317     }
318 }
319