kernel/driver.rs
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#"
42)]
43#")]
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
97use crate::error::{Error, Result};
98use crate::{acpi, device, of, str::CStr, try_pin_init, types::Opaque, ThisModule};
99use core::pin::Pin;
100use pin_init::{pin_data, pinned_drop, PinInit};
101
102/// Trait describing the layout of a specific device driver.
103///
104/// This trait describes the layout of a specific driver structure, such as `struct pci_driver` or
105/// `struct platform_driver`.
106///
107/// # Safety
108///
109/// Implementors must guarantee that:
110/// - `DriverType` is `repr(C)`,
111/// - `DriverData` is the type of the driver's device private data.
112/// - `DriverType` embeds a valid `struct device_driver` at byte offset `DEVICE_DRIVER_OFFSET`.
113pub unsafe trait DriverLayout {
114 /// The specific driver type embedding a `struct device_driver`.
115 type DriverType: Default;
116
117 /// The type of the driver's device private data.
118 type DriverData;
119
120 /// Byte offset of the embedded `struct device_driver` within `DriverType`.
121 ///
122 /// This must correspond exactly to the location of the embedded `struct device_driver` field.
123 const DEVICE_DRIVER_OFFSET: usize;
124}
125
126/// The [`RegistrationOps`] trait serves as generic interface for subsystems (e.g., PCI, Platform,
127/// Amba, etc.) to provide the corresponding subsystem specific implementation to register /
128/// unregister a driver of the particular type (`DriverType`).
129///
130/// For instance, the PCI subsystem would set `DriverType` to `bindings::pci_driver` and call
131/// `bindings::__pci_register_driver` from `RegistrationOps::register` and
132/// `bindings::pci_unregister_driver` from `RegistrationOps::unregister`.
133///
134/// # Safety
135///
136/// A call to [`RegistrationOps::unregister`] for a given instance of `DriverType` is only valid if
137/// a preceding call to [`RegistrationOps::register`] has been successful.
138pub unsafe trait RegistrationOps: DriverLayout {
139 /// Registers a driver.
140 ///
141 /// # Safety
142 ///
143 /// On success, `reg` must remain pinned and valid until the matching call to
144 /// [`RegistrationOps::unregister`].
145 unsafe fn register(
146 reg: &Opaque<Self::DriverType>,
147 name: &'static CStr,
148 module: &'static ThisModule,
149 ) -> Result;
150
151 /// Unregisters a driver previously registered with [`RegistrationOps::register`].
152 ///
153 /// # Safety
154 ///
155 /// Must only be called after a preceding successful call to [`RegistrationOps::register`] for
156 /// the same `reg`.
157 unsafe fn unregister(reg: &Opaque<Self::DriverType>);
158}
159
160/// A [`Registration`] is a generic type that represents the registration of some driver type (e.g.
161/// `bindings::pci_driver`). Therefore a [`Registration`] must be initialized with a type that
162/// implements the [`RegistrationOps`] trait, such that the generic `T::register` and
163/// `T::unregister` calls result in the subsystem specific registration calls.
164///
165///Once the `Registration` structure is dropped, the driver is unregistered.
166#[pin_data(PinnedDrop)]
167pub struct Registration<T: RegistrationOps> {
168 #[pin]
169 reg: Opaque<T::DriverType>,
170}
171
172// SAFETY: `Registration` has no fields or methods accessible via `&Registration`, so it is safe to
173// share references to it with multiple threads as nothing can be done.
174unsafe impl<T: RegistrationOps> Sync for Registration<T> {}
175
176// SAFETY: Both registration and unregistration are implemented in C and safe to be performed from
177// any thread, so `Registration` is `Send`.
178unsafe impl<T: RegistrationOps> Send for Registration<T> {}
179
180impl<T: RegistrationOps + 'static> Registration<T> {
181 extern "C" fn post_unbind_callback(dev: *mut bindings::device) {
182 // SAFETY: The driver core only ever calls the post unbind callback with a valid pointer to
183 // a `struct device`.
184 //
185 // INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`.
186 let dev = unsafe { &*dev.cast::<device::Device<device::CoreInternal>>() };
187
188 // `remove()` and all devres callbacks have been completed at this point, hence drop the
189 // driver's device private data.
190 //
191 // SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the
192 // driver's device private data type.
193 drop(unsafe { dev.drvdata_obtain::<T::DriverData>() });
194 }
195
196 /// Attach generic `struct device_driver` callbacks.
197 fn callbacks_attach(drv: &Opaque<T::DriverType>) {
198 let ptr = drv.get().cast::<u8>();
199
200 // SAFETY:
201 // - `drv.get()` yields a valid pointer to `Self::DriverType`.
202 // - Adding `DEVICE_DRIVER_OFFSET` yields the address of the embedded `struct device_driver`
203 // as guaranteed by the safety requirements of the `Driver` trait.
204 let base = unsafe { ptr.add(T::DEVICE_DRIVER_OFFSET) };
205
206 // CAST: `base` points to the offset of the embedded `struct device_driver`.
207 let base = base.cast::<bindings::device_driver>();
208
209 // SAFETY: It is safe to set the fields of `struct device_driver` on initialization.
210 unsafe { (*base).p_cb.post_unbind_rust = Some(Self::post_unbind_callback) };
211 }
212
213 /// Creates a new instance of the registration object.
214 pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> {
215 try_pin_init!(Self {
216 reg <- Opaque::try_ffi_init(|ptr: *mut T::DriverType| {
217 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.
218 unsafe { ptr.write(T::DriverType::default()) };
219
220 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write, and it has
221 // just been initialised above, so it's also valid for read.
222 let drv = unsafe { &*(ptr as *const Opaque<T::DriverType>) };
223
224 Self::callbacks_attach(drv);
225
226 // SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.
227 unsafe { T::register(drv, name, module) }
228 }),
229 })
230 }
231}
232
233#[pinned_drop]
234impl<T: RegistrationOps> PinnedDrop for Registration<T> {
235 fn drop(self: Pin<&mut Self>) {
236 // SAFETY: The existence of `self` guarantees that `self.reg` has previously been
237 // successfully registered with `T::register`
238 unsafe { T::unregister(&self.reg) };
239 }
240}
241
242/// Declares a kernel module that exposes a single driver.
243///
244/// It is meant to be used as a helper by other subsystems so they can more easily expose their own
245/// macros.
246#[macro_export]
247macro_rules! module_driver {
248 (<$gen_type:ident>, $driver_ops:ty, { type: $type:ty, $($f:tt)* }) => {
249 type Ops<$gen_type> = $driver_ops;
250
251 #[$crate::prelude::pin_data]
252 struct DriverModule {
253 #[pin]
254 _driver: $crate::driver::Registration<Ops<$type>>,
255 }
256
257 impl $crate::InPlaceModule for DriverModule {
258 fn init(
259 module: &'static $crate::ThisModule
260 ) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {
261 $crate::try_pin_init!(Self {
262 _driver <- $crate::driver::Registration::new(
263 <Self as $crate::ModuleMetadata>::NAME,
264 module,
265 ),
266 })
267 }
268 }
269
270 $crate::prelude::module! {
271 type: DriverModule,
272 $($f)*
273 }
274 }
275}
276
277/// The bus independent adapter to match a drivers and a devices.
278///
279/// This trait should be implemented by the bus specific adapter, which represents the connection
280/// of a device and a driver.
281///
282/// It provides bus independent functions for device / driver interactions.
283pub trait Adapter {
284 /// The type holding driver private data about each device id supported by the driver.
285 type IdInfo: 'static;
286
287 /// The [`acpi::IdTable`] of the corresponding driver
288 fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>>;
289
290 /// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.
291 ///
292 /// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].
293 fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
294 #[cfg(not(CONFIG_ACPI))]
295 {
296 let _ = dev;
297 None
298 }
299
300 #[cfg(CONFIG_ACPI)]
301 {
302 let table = Self::acpi_id_table()?;
303
304 // SAFETY:
305 // - `table` has static lifetime, hence it's valid for read,
306 // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
307 let raw_id = unsafe { bindings::acpi_match_device(table.as_ptr(), dev.as_raw()) };
308
309 if raw_id.is_null() {
310 None
311 } else {
312 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct acpi_device_id`
313 // and does not add additional invariants, so it's safe to transmute.
314 let id = unsafe { &*raw_id.cast::<acpi::DeviceId>() };
315
316 Some(table.info(<acpi::DeviceId as crate::device_id::RawDeviceIdIndex>::index(id)))
317 }
318 }
319 }
320
321 /// The [`of::IdTable`] of the corresponding driver.
322 fn of_id_table() -> Option<of::IdTable<Self::IdInfo>>;
323
324 /// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.
325 ///
326 /// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].
327 fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
328 #[cfg(not(CONFIG_OF))]
329 {
330 let _ = dev;
331 None
332 }
333
334 #[cfg(CONFIG_OF)]
335 {
336 let table = Self::of_id_table()?;
337
338 // SAFETY:
339 // - `table` has static lifetime, hence it's valid for read,
340 // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
341 let raw_id = unsafe { bindings::of_match_device(table.as_ptr(), dev.as_raw()) };
342
343 if raw_id.is_null() {
344 None
345 } else {
346 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct of_device_id`
347 // and does not add additional invariants, so it's safe to transmute.
348 let id = unsafe { &*raw_id.cast::<of::DeviceId>() };
349
350 Some(
351 table.info(<of::DeviceId as crate::device_id::RawDeviceIdIndex>::index(
352 id,
353 )),
354 )
355 }
356 }
357 }
358
359 /// Returns the driver's private data from the matching entry of any of the ID tables, if any.
360 ///
361 /// If this returns `None`, it means that there is no match in any of the ID tables directly
362 /// associated with a [`device::Device`].
363 fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {
364 let id = Self::acpi_id_info(dev);
365 if id.is_some() {
366 return id;
367 }
368
369 let id = Self::of_id_info(dev);
370 if id.is_some() {
371 return id;
372 }
373
374 None
375 }
376}