// SPDX-License-Identifier: GPL-2.012//! Abstractions for the auxiliary bus.3//!4//! C header: [`include/linux/auxiliary_bus.h`](srctree/include/linux/auxiliary_bus.h)56use crate::{7bindings, container_of, device,8device_id::{RawDeviceId, RawDeviceIdIndex},9devres::Devres,10driver,11error::{from_result, to_result, Result},12prelude::*,13types::Opaque,14ThisModule,15};16use core::{17marker::PhantomData,18mem::offset_of,19ptr::{addr_of_mut, NonNull},20};2122/// An adapter for the registration of auxiliary drivers.23pub struct Adapter<T: Driver>(T);2425// SAFETY:26// - `bindings::auxiliary_driver` is a C type declared as `repr(C)`.27// - `T` is the type of the driver's device private data.28// - `struct auxiliary_driver` embeds a `struct device_driver`.29// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.30unsafe impl<T: Driver + 'static> driver::DriverLayout for Adapter<T> {31type DriverType = bindings::auxiliary_driver;32type DriverData = T;33const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);34}3536// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if37// a preceding call to `register` has been successful.38unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {39unsafe fn register(40adrv: &Opaque<Self::DriverType>,41name: &'static CStr,42module: &'static ThisModule,43) -> Result {44// SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.45unsafe {46(*adrv.get()).name = name.as_char_ptr();47(*adrv.get()).probe = Some(Self::probe_callback);48(*adrv.get()).remove = Some(Self::remove_callback);49(*adrv.get()).id_table = T::ID_TABLE.as_ptr();50}5152// SAFETY: `adrv` is guaranteed to be a valid `DriverType`.53to_result(unsafe {54bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())55})56}5758unsafe fn unregister(adrv: &Opaque<Self::DriverType>) {59// SAFETY: `adrv` is guaranteed to be a valid `DriverType`.60unsafe { bindings::auxiliary_driver_unregister(adrv.get()) }61}62}6364impl<T: Driver + 'static> Adapter<T> {65extern "C" fn probe_callback(66adev: *mut bindings::auxiliary_device,67id: *const bindings::auxiliary_device_id,68) -> c_int {69// SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a70// `struct auxiliary_device`.71//72// INVARIANT: `adev` is valid for the duration of `probe_callback()`.73let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };7475// SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id`76// and does not add additional invariants, so it's safe to transmute.77let id = unsafe { &*id.cast::<DeviceId>() };78let info = T::ID_TABLE.info(id.index());7980from_result(|| {81let data = T::probe(adev, info);8283adev.as_ref().set_drvdata(data)?;84Ok(0)85})86}8788extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {89// SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a90// `struct auxiliary_device`.91//92// INVARIANT: `adev` is valid for the duration of `probe_callback()`.93let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };9495// SAFETY: `remove_callback` is only ever called after a successful call to96// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called97// and stored a `Pin<KBox<T>>`.98let data = unsafe { adev.as_ref().drvdata_borrow::<T>() };99100T::unbind(adev, data);101}102}103104/// Declares a kernel module that exposes a single auxiliary driver.105#[macro_export]106macro_rules! module_auxiliary_driver {107($($f:tt)*) => {108$crate::module_driver!(<T>, $crate::auxiliary::Adapter<T>, { $($f)* });109};110}111112/// Abstraction for `bindings::auxiliary_device_id`.113#[repr(transparent)]114#[derive(Clone, Copy)]115pub struct DeviceId(bindings::auxiliary_device_id);116117impl DeviceId {118/// Create a new [`DeviceId`] from name.119pub const fn new(modname: &'static CStr, name: &'static CStr) -> Self {120let name = name.to_bytes_with_nul();121let modname = modname.to_bytes_with_nul();122123// TODO: Replace with `bindings::auxiliary_device_id::default()` once stabilized for124// `const`.125//126// SAFETY: FFI type is valid to be zero-initialized.127let mut id: bindings::auxiliary_device_id = unsafe { core::mem::zeroed() };128129let mut i = 0;130while i < modname.len() {131id.name[i] = modname[i];132i += 1;133}134135// Reuse the space of the NULL terminator.136id.name[i - 1] = b'.';137138let mut j = 0;139while j < name.len() {140id.name[i] = name[j];141i += 1;142j += 1;143}144145Self(id)146}147}148149// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `auxiliary_device_id` and does not add150// additional invariants, so it's safe to transmute to `RawType`.151unsafe impl RawDeviceId for DeviceId {152type RawType = bindings::auxiliary_device_id;153}154155// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.156unsafe impl RawDeviceIdIndex for DeviceId {157const DRIVER_DATA_OFFSET: usize =158core::mem::offset_of!(bindings::auxiliary_device_id, driver_data);159160fn index(&self) -> usize {161self.0.driver_data162}163}164165/// IdTable type for auxiliary drivers.166pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;167168/// Create a auxiliary `IdTable` with its alias for modpost.169#[macro_export]170macro_rules! auxiliary_device_table {171($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {172const $table_name: $crate::device_id::IdArray<173$crate::auxiliary::DeviceId,174$id_info_type,175{ $table_data.len() },176> = $crate::device_id::IdArray::new($table_data);177178$crate::module_device_table!("auxiliary", $module_table_name, $table_name);179};180}181182/// The auxiliary driver trait.183///184/// Drivers must implement this trait in order to get an auxiliary driver registered.185pub trait Driver {186/// The type holding information about each device id supported by the driver.187///188/// TODO: Use associated_type_defaults once stabilized:189///190/// type IdInfo: 'static = ();191type IdInfo: 'static;192193/// The table of device ids supported by the driver.194const ID_TABLE: IdTable<Self::IdInfo>;195196/// Auxiliary driver probe.197///198/// Called when an auxiliary device is matches a corresponding driver.199fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> impl PinInit<Self, Error>;200201/// Auxiliary driver unbind.202///203/// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback204/// is optional.205///206/// This callback serves as a place for drivers to perform teardown operations that require a207/// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O208/// operations to gracefully tear down the device.209///210/// Otherwise, release operations for driver resources should be performed in `Self::drop`.211fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {212let _ = (dev, this);213}214}215216/// The auxiliary device representation.217///218/// This structure represents the Rust abstraction for a C `struct auxiliary_device`. The219/// implementation abstracts the usage of an already existing C `struct auxiliary_device` within220/// Rust code that we get passed from the C side.221///222/// # Invariants223///224/// A [`Device`] instance represents a valid `struct auxiliary_device` created by the C portion of225/// the kernel.226#[repr(transparent)]227pub struct Device<Ctx: device::DeviceContext = device::Normal>(228Opaque<bindings::auxiliary_device>,229PhantomData<Ctx>,230);231232impl<Ctx: device::DeviceContext> Device<Ctx> {233fn as_raw(&self) -> *mut bindings::auxiliary_device {234self.0.get()235}236237/// Returns the auxiliary device' id.238pub fn id(&self) -> u32 {239// SAFETY: By the type invariant `self.as_raw()` is a valid pointer to a240// `struct auxiliary_device`.241unsafe { (*self.as_raw()).id }242}243}244245impl Device<device::Bound> {246/// Returns a bound reference to the parent [`device::Device`].247pub fn parent(&self) -> &device::Device<device::Bound> {248let parent = (**self).parent();249250// SAFETY: A bound auxiliary device always has a bound parent device.251unsafe { parent.as_bound() }252}253}254255impl Device {256/// Returns a reference to the parent [`device::Device`].257pub fn parent(&self) -> &device::Device {258// SAFETY: A `struct auxiliary_device` always has a parent.259unsafe { self.as_ref().parent().unwrap_unchecked() }260}261262extern "C" fn release(dev: *mut bindings::device) {263// SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`264// embedded in `struct auxiliary_device`.265let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };266267// SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via268// `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.269let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };270}271}272273// SAFETY: `auxiliary::Device` is a transparent wrapper of `struct auxiliary_device`.274// The offset is guaranteed to point to a valid device field inside `auxiliary::Device`.275unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {276const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);277}278279// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic280// argument.281kernel::impl_device_context_deref!(unsafe { Device });282kernel::impl_device_context_into_aref!(Device);283284// SAFETY: Instances of `Device` are always reference-counted.285unsafe impl crate::sync::aref::AlwaysRefCounted for Device {286fn inc_ref(&self) {287// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.288unsafe { bindings::get_device(self.as_ref().as_raw()) };289}290291unsafe fn dec_ref(obj: NonNull<Self>) {292// CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.293let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();294295// SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid296// `struct auxiliary_device`.297let dev = unsafe { addr_of_mut!((*adev).dev) };298299// SAFETY: The safety requirements guarantee that the refcount is non-zero.300unsafe { bindings::put_device(dev) }301}302}303304impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {305fn as_ref(&self) -> &device::Device<Ctx> {306// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid307// `struct auxiliary_device`.308let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };309310// SAFETY: `dev` points to a valid `struct device`.311unsafe { device::Device::from_raw(dev) }312}313}314315// SAFETY: A `Device` is always reference-counted and can be released from any thread.316unsafe impl Send for Device {}317318// SAFETY: `Device` can be shared among threads because all methods of `Device`319// (i.e. `Device<Normal>) are thread safe.320unsafe impl Sync for Device {}321322/// The registration of an auxiliary device.323///324/// This type represents the registration of a [`struct auxiliary_device`]. When its parent device325/// is unbound, the corresponding auxiliary device will be unregistered from the system.326///327/// # Invariants328///329/// `self.0` always holds a valid pointer to an initialized and registered330/// [`struct auxiliary_device`].331pub struct Registration(NonNull<bindings::auxiliary_device>);332333impl Registration {334/// Create and register a new auxiliary device.335pub fn new<'a>(336parent: &'a device::Device<device::Bound>,337name: &'a CStr,338id: u32,339modname: &'a CStr,340) -> impl PinInit<Devres<Self>, Error> + 'a {341pin_init::pin_init_scope(move || {342let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;343let adev = boxed.get();344345// SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.346unsafe {347(*adev).dev.parent = parent.as_raw();348(*adev).dev.release = Some(Device::release);349(*adev).name = name.as_char_ptr();350(*adev).id = id;351}352353// SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,354// which has not been initialized yet.355unsafe { bindings::auxiliary_device_init(adev) };356357// Now that `adev` is initialized, leak the `Box`; the corresponding memory will be358// freed by `Device::release` when the last reference to the `struct auxiliary_device`359// is dropped.360let _ = KBox::into_raw(boxed);361362// SAFETY:363// - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which364// has been initialized,365// - `modname.as_char_ptr()` is a NULL terminated string.366let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };367if ret != 0 {368// SAFETY: `adev` is guaranteed to be a valid pointer to a369// `struct auxiliary_device`, which has been initialized.370unsafe { bindings::auxiliary_device_uninit(adev) };371372return Err(Error::from_errno(ret));373}374375// INVARIANT: The device will remain registered until `auxiliary_device_delete()` is376// called, which happens in `Self::drop()`.377Ok(Devres::new(378parent,379// SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated380// successfully.381Self(unsafe { NonNull::new_unchecked(adev) }),382))383})384}385}386387impl Drop for Registration {388fn drop(&mut self) {389// SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered390// `struct auxiliary_device`.391unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };392393// This drops the reference we acquired through `auxiliary_device_init()`.394//395// SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered396// `struct auxiliary_device`.397unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };398}399}400401// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.402unsafe impl Send for Registration {}403404// SAFETY: `Registration` does not expose any methods or fields that need synchronization.405unsafe impl Sync for Registration {}406407408