// 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) -> Result<Pin<KBox<Self>>>;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 [`auxiliary::Driver`], [`pci::Driver`] and [`platform::Driver`].36//!37//! The `probe()` callback should return a `Result<Pin<KBox<Self>>>`, i.e. the driver's private38//! data. The bus abstraction should store the pointer in the corresponding bus device. The generic39//! [`Device`] infrastructure provides common helpers for this purpose on its40//! [`Device<CoreInternal>`] implementation.41//!42//! All driver callbacks should provide a reference to the driver's private data. Once the driver43//! is unbound from the device, the bus abstraction should take back the ownership of the driver's44//! private data from the corresponding [`Device`] and [`drop`] it.45//!46//! All driver callbacks should provide a [`Device<Core>`] reference (see also [`device::Core`]).47//!48//! # Adapter49//!50//! The adapter implementation of a bus represents the abstraction layer between the C bus51//! callbacks and the Rust bus callbacks. It therefore has to be generic over an implementation of52//! the [driver trait](#driver-trait).53//!54//! ```ignore55//! pub struct Adapter<T: Driver>;56//! ```57//!58//! There's a common [`Adapter`] trait that can be implemented to inherit common driver59//! infrastructure, such as finding the ID info from an [`of::IdTable`] or [`acpi::IdTable`].60//!61//! # Driver Registration62//!63//! In order to register C driver types (such as `struct platform_driver`) the [adapter](#adapter)64//! should implement the [`RegistrationOps`] trait.65//!66//! This trait implementation can be used to create the actual registration with the common67//! [`Registration`] type.68//!69//! Typically, bus abstractions want to provide a bus specific `module_bus_driver!` macro, which70//! creates a kernel module with exactly one [`Registration`] for the bus specific adapter.71//!72//! The generic driver infrastructure provides a helper for this with the [`module_driver`] macro.73//!74//! # Device IDs75//!76//! Besides the common device ID types, such as [`of::DeviceId`] and [`acpi::DeviceId`], most buses77//! may need to implement their own device ID types.78//!79//! For this purpose the generic infrastructure in [`device_id`] should be used.80//!81//! [`auxiliary::Driver`]: kernel::auxiliary::Driver82//! [`Core`]: device::Core83//! [`Device`]: device::Device84//! [`Device<Core>`]: device::Device<device::Core>85//! [`Device<CoreInternal>`]: device::Device<device::CoreInternal>86//! [`DeviceContext`]: device::DeviceContext87//! [`device_id`]: kernel::device_id88//! [`module_driver`]: kernel::module_driver89//! [`pci::Driver`]: kernel::pci::Driver90//! [`platform::Driver`]: kernel::platform::Driver9192use crate::error::{Error, Result};93use crate::{acpi, device, of, str::CStr, try_pin_init, types::Opaque, ThisModule};94use core::pin::Pin;95use pin_init::{pin_data, pinned_drop, PinInit};9697/// The [`RegistrationOps`] trait serves as generic interface for subsystems (e.g., PCI, Platform,98/// Amba, etc.) to provide the corresponding subsystem specific implementation to register /99/// unregister a driver of the particular type (`RegType`).100///101/// For instance, the PCI subsystem would set `RegType` to `bindings::pci_driver` and call102/// `bindings::__pci_register_driver` from `RegistrationOps::register` and103/// `bindings::pci_unregister_driver` from `RegistrationOps::unregister`.104///105/// # Safety106///107/// A call to [`RegistrationOps::unregister`] for a given instance of `RegType` is only valid if a108/// preceding call to [`RegistrationOps::register`] has been successful.109pub unsafe trait RegistrationOps {110/// The type that holds information about the registration. This is typically a struct defined111/// by the C portion of the kernel.112type RegType: Default;113114/// Registers a driver.115///116/// # Safety117///118/// On success, `reg` must remain pinned and valid until the matching call to119/// [`RegistrationOps::unregister`].120unsafe fn register(121reg: &Opaque<Self::RegType>,122name: &'static CStr,123module: &'static ThisModule,124) -> Result;125126/// Unregisters a driver previously registered with [`RegistrationOps::register`].127///128/// # Safety129///130/// Must only be called after a preceding successful call to [`RegistrationOps::register`] for131/// the same `reg`.132unsafe fn unregister(reg: &Opaque<Self::RegType>);133}134135/// A [`Registration`] is a generic type that represents the registration of some driver type (e.g.136/// `bindings::pci_driver`). Therefore a [`Registration`] must be initialized with a type that137/// implements the [`RegistrationOps`] trait, such that the generic `T::register` and138/// `T::unregister` calls result in the subsystem specific registration calls.139///140///Once the `Registration` structure is dropped, the driver is unregistered.141#[pin_data(PinnedDrop)]142pub struct Registration<T: RegistrationOps> {143#[pin]144reg: Opaque<T::RegType>,145}146147// SAFETY: `Registration` has no fields or methods accessible via `&Registration`, so it is safe to148// share references to it with multiple threads as nothing can be done.149unsafe impl<T: RegistrationOps> Sync for Registration<T> {}150151// SAFETY: Both registration and unregistration are implemented in C and safe to be performed from152// any thread, so `Registration` is `Send`.153unsafe impl<T: RegistrationOps> Send for Registration<T> {}154155impl<T: RegistrationOps> Registration<T> {156/// Creates a new instance of the registration object.157pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> {158try_pin_init!(Self {159reg <- Opaque::try_ffi_init(|ptr: *mut T::RegType| {160// SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.161unsafe { ptr.write(T::RegType::default()) };162163// SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write, and it has164// just been initialised above, so it's also valid for read.165let drv = unsafe { &*(ptr as *const Opaque<T::RegType>) };166167// SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.168unsafe { T::register(drv, name, module) }169}),170})171}172}173174#[pinned_drop]175impl<T: RegistrationOps> PinnedDrop for Registration<T> {176fn drop(self: Pin<&mut Self>) {177// SAFETY: The existence of `self` guarantees that `self.reg` has previously been178// successfully registered with `T::register`179unsafe { T::unregister(&self.reg) };180}181}182183/// Declares a kernel module that exposes a single driver.184///185/// It is meant to be used as a helper by other subsystems so they can more easily expose their own186/// macros.187#[macro_export]188macro_rules! module_driver {189(<$gen_type:ident>, $driver_ops:ty, { type: $type:ty, $($f:tt)* }) => {190type Ops<$gen_type> = $driver_ops;191192#[$crate::prelude::pin_data]193struct DriverModule {194#[pin]195_driver: $crate::driver::Registration<Ops<$type>>,196}197198impl $crate::InPlaceModule for DriverModule {199fn init(200module: &'static $crate::ThisModule201) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {202$crate::try_pin_init!(Self {203_driver <- $crate::driver::Registration::new(204<Self as $crate::ModuleMetadata>::NAME,205module,206),207})208}209}210211$crate::prelude::module! {212type: DriverModule,213$($f)*214}215}216}217218/// The bus independent adapter to match a drivers and a devices.219///220/// This trait should be implemented by the bus specific adapter, which represents the connection221/// of a device and a driver.222///223/// It provides bus independent functions for device / driver interactions.224pub trait Adapter {225/// The type holding driver private data about each device id supported by the driver.226type IdInfo: 'static;227228/// The [`acpi::IdTable`] of the corresponding driver229fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>>;230231/// Returns the driver's private data from the matching entry in the [`acpi::IdTable`], if any.232///233/// If this returns `None`, it means there is no match with an entry in the [`acpi::IdTable`].234fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {235#[cfg(not(CONFIG_ACPI))]236{237let _ = dev;238None239}240241#[cfg(CONFIG_ACPI)]242{243let table = Self::acpi_id_table()?;244245// SAFETY:246// - `table` has static lifetime, hence it's valid for read,247// - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.248let raw_id = unsafe { bindings::acpi_match_device(table.as_ptr(), dev.as_raw()) };249250if raw_id.is_null() {251None252} else {253// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct acpi_device_id`254// and does not add additional invariants, so it's safe to transmute.255let id = unsafe { &*raw_id.cast::<acpi::DeviceId>() };256257Some(table.info(<acpi::DeviceId as crate::device_id::RawDeviceIdIndex>::index(id)))258}259}260}261262/// The [`of::IdTable`] of the corresponding driver.263fn of_id_table() -> Option<of::IdTable<Self::IdInfo>>;264265/// Returns the driver's private data from the matching entry in the [`of::IdTable`], if any.266///267/// If this returns `None`, it means there is no match with an entry in the [`of::IdTable`].268fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {269#[cfg(not(CONFIG_OF))]270{271let _ = dev;272None273}274275#[cfg(CONFIG_OF)]276{277let table = Self::of_id_table()?;278279// SAFETY:280// - `table` has static lifetime, hence it's valid for read,281// - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.282let raw_id = unsafe { bindings::of_match_device(table.as_ptr(), dev.as_raw()) };283284if raw_id.is_null() {285None286} else {287// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct of_device_id`288// and does not add additional invariants, so it's safe to transmute.289let id = unsafe { &*raw_id.cast::<of::DeviceId>() };290291Some(292table.info(<of::DeviceId as crate::device_id::RawDeviceIdIndex>::index(293id,294)),295)296}297}298}299300/// Returns the driver's private data from the matching entry of any of the ID tables, if any.301///302/// If this returns `None`, it means that there is no match in any of the ID tables directly303/// associated with a [`device::Device`].304fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> {305let id = Self::acpi_id_info(dev);306if id.is_some() {307return id;308}309310let id = Self::of_id_info(dev);311if id.is_some() {312return id;313}314315None316}317}318319320