// SPDX-License-Identifier: GPL-2.012//! Generic support for drivers of different buses (e.g., PCI, Platform, Amba, etc.).3//!4//! This documentation describes how to implement a bus specific driver API and how to align it with5//! the design of (bus specific) devices.6//!7//! Note: Readers are expected to know the content of the documentation of [`Device`] and8//! [`DeviceContext`].9//!10//! # Driver Trait11//!12//! The main driver interface is defined by a bus specific driver trait. For instance:13//!14//! ```ignore15//! pub trait Driver: Send {16//! /// The type holding information about each device ID supported by the driver.17//! type IdInfo: 'static;18//!19//! /// The table of OF device ids supported by the driver.20//! const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;21//!22//! /// The table of ACPI device ids supported by the driver.23//! const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;24//!25//! /// Driver probe.26//! fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> impl PinInit<Self, Error>;27//!28//! /// Driver unbind (optional).29//! fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {30//! let _ = (dev, this);31//! }32//! }33//! ```34//!35//! For specific examples see:36//!37//! * [`platform::Driver`](kernel::platform::Driver)38#"41)]42#")]43//!44//! The `probe()` callback should return a `impl PinInit<Self, Error>`, i.e. the driver's private45//! data. The bus abstraction should store the pointer in the corresponding bus device. The generic46//! [`Device`] infrastructure provides common helpers for this purpose on its47//! [`Device<CoreInternal>`] implementation.48//!49//! All driver callbacks should provide a reference to the driver's private data. Once the driver50//! is unbound from the device, the bus abstraction should take back the ownership of the driver's51//! private data from the corresponding [`Device`] and [`drop`] it.52//!53//! All driver callbacks should provide a [`Device<Core>`] reference (see also [`device::Core`]).54//!55//! # Adapter56//!57//! The adapter implementation of a bus represents the abstraction layer between the C bus58//! callbacks and the Rust bus callbacks. It therefore has to be generic over an implementation of59//! the [driver trait](#driver-trait).60//!61//! ```ignore62//! pub struct Adapter<T: Driver>;63//! ```64//!65//! There's a common [`Adapter`] trait that can be implemented to inherit common driver66//! infrastructure, such as finding the ID info from an [`of::IdTable`] or [`acpi::IdTable`].67//!68//! # Driver Registration69//!70//! In order to register C driver types (such as `struct platform_driver`) the [adapter](#adapter)71//! should implement the [`RegistrationOps`] trait.72//!73//! This trait implementation can be used to create the actual registration with the common74//! [`Registration`] type.75//!76//! Typically, bus abstractions want to provide a bus specific `module_bus_driver!` macro, which77//! creates a kernel module with exactly one [`Registration`] for the bus specific adapter.78//!79//! The generic driver infrastructure provides a helper for this with the [`module_driver`] macro.80//!81//! # Device IDs82//!83//! Besides the common device ID types, such as [`of::DeviceId`] and [`acpi::DeviceId`], most buses84//! may need to implement their own device ID types.85//!86//! For this purpose the generic infrastructure in [`device_id`] should be used.87//!88//! [`Core`]: device::Core89//! [`Device`]: device::Device90//! [`Device<Core>`]: device::Device<device::Core>91//! [`Device<CoreInternal>`]: device::Device<device::CoreInternal>92//! [`DeviceContext`]: device::DeviceContext93//! [`device_id`]: kernel::device_id94//! [`module_driver`]: kernel::module_driver9596use crate::error::{Error, Result};97use crate::{acpi, device, of, str::CStr, try_pin_init, types::Opaque, ThisModule};98use core::pin::Pin;99use pin_init::{pin_data, pinned_drop, PinInit};100101/// Trait describing the layout of a specific device driver.102///103/// This trait describes the layout of a specific driver structure, such as `struct pci_driver` or104/// `struct platform_driver`.105///106/// # Safety107///108/// Implementors must guarantee that:109/// - `DriverType` is `repr(C)`,110/// - `DriverData` is the type of the driver's device private data.111/// - `DriverType` embeds a valid `struct device_driver` at byte offset `DEVICE_DRIVER_OFFSET`.112pub unsafe trait DriverLayout {113/// The specific driver type embedding a `struct device_driver`.114type DriverType: Default;115116/// The type of the driver's device private data.117type DriverData;118119/// Byte offset of the embedded `struct device_driver` within `DriverType`.120///121/// This must correspond exactly to the location of the embedded `struct device_driver` field.122const DEVICE_DRIVER_OFFSET: usize;123}124125/// The [`RegistrationOps`] trait serves as generic interface for subsystems (e.g., PCI, Platform,126/// Amba, etc.) to provide the corresponding subsystem specific implementation to register /127/// unregister a driver of the particular type (`DriverType`).128///129/// For instance, the PCI subsystem would set `DriverType` to `bindings::pci_driver` and call130/// `bindings::__pci_register_driver` from `RegistrationOps::register` and131/// `bindings::pci_unregister_driver` from `RegistrationOps::unregister`.132///133/// # Safety134///135/// A call to [`RegistrationOps::unregister`] for a given instance of `DriverType` is only valid if136/// a preceding call to [`RegistrationOps::register`] has been successful.137pub unsafe trait RegistrationOps: DriverLayout {138/// Registers a driver.139///140/// # Safety141///142/// On success, `reg` must remain pinned and valid until the matching call to143/// [`RegistrationOps::unregister`].144unsafe fn register(145reg: &Opaque<Self::DriverType>,146name: &'static CStr,147module: &'static ThisModule,148) -> Result;149150/// Unregisters a driver previously registered with [`RegistrationOps::register`].151///152/// # Safety153///154/// Must only be called after a preceding successful call to [`RegistrationOps::register`] for155/// the same `reg`.156unsafe fn unregister(reg: &Opaque<Self::DriverType>);157}158159/// A [`Registration`] is a generic type that represents the registration of some driver type (e.g.160/// `bindings::pci_driver`). Therefore a [`Registration`] must be initialized with a type that161/// implements the [`RegistrationOps`] trait, such that the generic `T::register` and162/// `T::unregister` calls result in the subsystem specific registration calls.163///164///Once the `Registration` structure is dropped, the driver is unregistered.165#[pin_data(PinnedDrop)]166pub struct Registration<T: RegistrationOps> {167#[pin]168reg: Opaque<T::DriverType>,169}170171// SAFETY: `Registration` has no fields or methods accessible via `&Registration`, so it is safe to172// share references to it with multiple threads as nothing can be done.173unsafe impl<T: RegistrationOps> Sync for Registration<T> {}174175// SAFETY: Both registration and unregistration are implemented in C and safe to be performed from176// any thread, so `Registration` is `Send`.177unsafe impl<T: RegistrationOps> Send for Registration<T> {}178179impl<T: RegistrationOps + 'static> Registration<T> {180extern "C" fn post_unbind_callback(dev: *mut bindings::device) {181// SAFETY: The driver core only ever calls the post unbind callback with a valid pointer to182// a `struct device`.183//184// INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`.185let dev = unsafe { &*dev.cast::<device::Device<device::CoreInternal>>() };186187// `remove()` and all devres callbacks have been completed at this point, hence drop the188// driver's device private data.189//190// SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the191// driver's device private data type.192drop(unsafe { dev.drvdata_obtain::<T::DriverData>() });193}194195/// Attach generic `struct device_driver` callbacks.196fn callbacks_attach(drv: &Opaque<T::DriverType>) {197let ptr = drv.get().cast::<u8>();198199// SAFETY:200// - `drv.get()` yields a valid pointer to `Self::DriverType`.201// - Adding `DEVICE_DRIVER_OFFSET` yields the address of the embedded `struct device_driver`202// as guaranteed by the safety requirements of the `Driver` trait.203let base = unsafe { ptr.add(T::DEVICE_DRIVER_OFFSET) };204205// CAST: `base` points to the offset of the embedded `struct device_driver`.206let base = base.cast::<bindings::device_driver>();207208// SAFETY: It is safe to set the fields of `struct device_driver` on initialization.209unsafe { (*base).p_cb.post_unbind_rust = Some(Self::post_unbind_callback) };210}211212/// Creates a new instance of the registration object.213pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> {214try_pin_init!(Self {215reg <- Opaque::try_ffi_init(|ptr: *mut T::DriverType| {216// SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.217unsafe { ptr.write(T::DriverType::default()) };218219// SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write, and it has220// just been initialised above, so it's also valid for read.221let drv = unsafe { &*(ptr as *const Opaque<T::DriverType>) };222223Self::callbacks_attach(drv);224225// SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.226unsafe { T::register(drv, name, module) }227}),228})229}230}231232#[pinned_drop]233impl<T: RegistrationOps> PinnedDrop for Registration<T> {234fn drop(self: Pin<&mut Self>) {235// SAFETY: The existence of `self` guarantees that `self.reg` has previously been236// successfully registered with `T::register`237unsafe { T::unregister(&self.reg) };238}239}240241/// Declares a kernel module that exposes a single driver.242///243/// It is meant to be used as a helper by other subsystems so they can more easily expose their own244/// macros.245#[macro_export]246macro_rules! module_driver {247(<$gen_type:ident>, $driver_ops:ty, { type: $type:ty, $($f:tt)* }) => {248type Ops<$gen_type> = $driver_ops;249250#[$crate::prelude::pin_data]251struct DriverModule {252#[pin]253_driver: $crate::driver::Registration<Ops<$type>>,254}255256impl $crate::InPlaceModule for DriverModule {257fn init(258module: &'static $crate::ThisModule259) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {260$crate::try_pin_init!(Self {261_driver <- $crate::driver::Registration::new(262<Self as $crate::ModuleMetadata>::NAME,263module,264),265})266}267}268269$crate::prelude::module! {270type: DriverModule,271$($f)*272}273}274}275276/// The bus independent adapter to match a drivers and a devices.277///278/// This trait should be implemented by the bus specific adapter, which represents the connection279/// of a device and a driver.280///281/// It provides bus independent functions for device / driver interactions.282pub trait Adapter {283/// The type holding driver private data about each device id supported by the driver.284type IdInfo: 'static;285286/// The [`acpi::IdTable`] of the corresponding driver287fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>>;288289/// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.290///291/// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].292fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {293#[cfg(not(CONFIG_ACPI))]294{295let _ = dev;296None297}298299#[cfg(CONFIG_ACPI)]300{301let table = Self::acpi_id_table()?;302303// SAFETY:304// - `table` has static lifetime, hence it's valid for read,305// - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.306let raw_id = unsafe { bindings::acpi_match_device(table.as_ptr(), dev.as_raw()) };307308if raw_id.is_null() {309None310} else {311// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct acpi_device_id`312// and does not add additional invariants, so it's safe to transmute.313let id = unsafe { &*raw_id.cast::<acpi::DeviceId>() };314315Some(table.info(<acpi::DeviceId as crate::device_id::RawDeviceIdIndex>::index(id)))316}317}318}319320/// The [`of::IdTable`] of the corresponding driver.321fn of_id_table() -> Option<of::IdTable<Self::IdInfo>>;322323/// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.324///325/// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].326fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {327#[cfg(not(CONFIG_OF))]328{329let _ = dev;330None331}332333#[cfg(CONFIG_OF)]334{335let table = Self::of_id_table()?;336337// SAFETY:338// - `table` has static lifetime, hence it's valid for read,339// - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.340let raw_id = unsafe { bindings::of_match_device(table.as_ptr(), dev.as_raw()) };341342if raw_id.is_null() {343None344} else {345// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct of_device_id`346// and does not add additional invariants, so it's safe to transmute.347let id = unsafe { &*raw_id.cast::<of::DeviceId>() };348349Some(350table.info(<of::DeviceId as crate::device_id::RawDeviceIdIndex>::index(351id,352)),353)354}355}356}357358/// Returns the driver's private data from the matching entry of any of the ID tables, if any.359///360/// If this returns `None`, it means that there is no match in any of the ID tables directly361/// associated with a [`device::Device`].362fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {363let id = Self::acpi_id_info(dev);364if id.is_some() {365return id;366}367368let id = Self::of_id_info(dev);369if id.is_some() {370return id;371}372373None374}375}376377378