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