// 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},9driver,10error::{from_result, to_result, Result},11prelude::*,12types::Opaque,13ThisModule,14};15use core::{16marker::PhantomData,17ptr::{addr_of_mut, NonNull},18};1920/// An adapter for the registration of auxiliary drivers.21pub struct Adapter<T: Driver>(T);2223// SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if24// a preceding call to `register` has been successful.25unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {26type RegType = bindings::auxiliary_driver;2728unsafe fn register(29adrv: &Opaque<Self::RegType>,30name: &'static CStr,31module: &'static ThisModule,32) -> Result {33// SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.34unsafe {35(*adrv.get()).name = name.as_char_ptr();36(*adrv.get()).probe = Some(Self::probe_callback);37(*adrv.get()).remove = Some(Self::remove_callback);38(*adrv.get()).id_table = T::ID_TABLE.as_ptr();39}4041// SAFETY: `adrv` is guaranteed to be a valid `RegType`.42to_result(unsafe {43bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())44})45}4647unsafe fn unregister(adrv: &Opaque<Self::RegType>) {48// SAFETY: `adrv` is guaranteed to be a valid `RegType`.49unsafe { bindings::auxiliary_driver_unregister(adrv.get()) }50}51}5253impl<T: Driver + 'static> Adapter<T> {54extern "C" fn probe_callback(55adev: *mut bindings::auxiliary_device,56id: *const bindings::auxiliary_device_id,57) -> c_int {58// SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a59// `struct auxiliary_device`.60//61// INVARIANT: `adev` is valid for the duration of `probe_callback()`.62let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };6364// SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `struct auxiliary_device_id`65// and does not add additional invariants, so it's safe to transmute.66let id = unsafe { &*id.cast::<DeviceId>() };67let info = T::ID_TABLE.info(id.index());6869from_result(|| {70let data = T::probe(adev, info)?;7172adev.as_ref().set_drvdata(data);73Ok(0)74})75}7677extern "C" fn remove_callback(adev: *mut bindings::auxiliary_device) {78// SAFETY: The auxiliary bus only ever calls the probe callback with a valid pointer to a79// `struct auxiliary_device`.80//81// INVARIANT: `adev` is valid for the duration of `probe_callback()`.82let adev = unsafe { &*adev.cast::<Device<device::CoreInternal>>() };8384// SAFETY: `remove_callback` is only ever called after a successful call to85// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called86// and stored a `Pin<KBox<T>>`.87drop(unsafe { adev.as_ref().drvdata_obtain::<Pin<KBox<T>>>() });88}89}9091/// Declares a kernel module that exposes a single auxiliary driver.92#[macro_export]93macro_rules! module_auxiliary_driver {94($($f:tt)*) => {95$crate::module_driver!(<T>, $crate::auxiliary::Adapter<T>, { $($f)* });96};97}9899/// Abstraction for `bindings::auxiliary_device_id`.100#[repr(transparent)]101#[derive(Clone, Copy)]102pub struct DeviceId(bindings::auxiliary_device_id);103104impl DeviceId {105/// Create a new [`DeviceId`] from name.106pub const fn new(modname: &'static CStr, name: &'static CStr) -> Self {107let name = name.to_bytes_with_nul();108let modname = modname.to_bytes_with_nul();109110// TODO: Replace with `bindings::auxiliary_device_id::default()` once stabilized for111// `const`.112//113// SAFETY: FFI type is valid to be zero-initialized.114let mut id: bindings::auxiliary_device_id = unsafe { core::mem::zeroed() };115116let mut i = 0;117while i < modname.len() {118id.name[i] = modname[i];119i += 1;120}121122// Reuse the space of the NULL terminator.123id.name[i - 1] = b'.';124125let mut j = 0;126while j < name.len() {127id.name[i] = name[j];128i += 1;129j += 1;130}131132Self(id)133}134}135136// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `auxiliary_device_id` and does not add137// additional invariants, so it's safe to transmute to `RawType`.138unsafe impl RawDeviceId for DeviceId {139type RawType = bindings::auxiliary_device_id;140}141142// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.143unsafe impl RawDeviceIdIndex for DeviceId {144const DRIVER_DATA_OFFSET: usize =145core::mem::offset_of!(bindings::auxiliary_device_id, driver_data);146147fn index(&self) -> usize {148self.0.driver_data149}150}151152/// IdTable type for auxiliary drivers.153pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;154155/// Create a auxiliary `IdTable` with its alias for modpost.156#[macro_export]157macro_rules! auxiliary_device_table {158($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {159const $table_name: $crate::device_id::IdArray<160$crate::auxiliary::DeviceId,161$id_info_type,162{ $table_data.len() },163> = $crate::device_id::IdArray::new($table_data);164165$crate::module_device_table!("auxiliary", $module_table_name, $table_name);166};167}168169/// The auxiliary driver trait.170///171/// Drivers must implement this trait in order to get an auxiliary driver registered.172pub trait Driver {173/// The type holding information about each device id supported by the driver.174///175/// TODO: Use associated_type_defaults once stabilized:176///177/// type IdInfo: 'static = ();178type IdInfo: 'static;179180/// The table of device ids supported by the driver.181const ID_TABLE: IdTable<Self::IdInfo>;182183/// Auxiliary driver probe.184///185/// Called when an auxiliary device is matches a corresponding driver.186fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> Result<Pin<KBox<Self>>>;187}188189/// The auxiliary device representation.190///191/// This structure represents the Rust abstraction for a C `struct auxiliary_device`. The192/// implementation abstracts the usage of an already existing C `struct auxiliary_device` within193/// Rust code that we get passed from the C side.194///195/// # Invariants196///197/// A [`Device`] instance represents a valid `struct auxiliary_device` created by the C portion of198/// the kernel.199#[repr(transparent)]200pub struct Device<Ctx: device::DeviceContext = device::Normal>(201Opaque<bindings::auxiliary_device>,202PhantomData<Ctx>,203);204205impl<Ctx: device::DeviceContext> Device<Ctx> {206fn as_raw(&self) -> *mut bindings::auxiliary_device {207self.0.get()208}209210/// Returns the auxiliary device' id.211pub fn id(&self) -> u32 {212// SAFETY: By the type invariant `self.as_raw()` is a valid pointer to a213// `struct auxiliary_device`.214unsafe { (*self.as_raw()).id }215}216217/// Returns a reference to the parent [`device::Device`], if any.218pub fn parent(&self) -> Option<&device::Device> {219let ptr: *const Self = self;220// CAST: `Device<Ctx: DeviceContext>` types are transparent to each other.221let ptr: *const Device = ptr.cast();222// SAFETY: `ptr` was derived from `&self`.223let this = unsafe { &*ptr };224225this.as_ref().parent()226}227}228229impl Device {230extern "C" fn release(dev: *mut bindings::device) {231// SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`232// embedded in `struct auxiliary_device`.233let adev = unsafe { container_of!(dev, bindings::auxiliary_device, dev) };234235// SAFETY: `adev` points to the memory that has been allocated in `Registration::new`, via236// `KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)`.237let _ = unsafe { KBox::<Opaque<bindings::auxiliary_device>>::from_raw(adev.cast()) };238}239}240241// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic242// argument.243kernel::impl_device_context_deref!(unsafe { Device });244kernel::impl_device_context_into_aref!(Device);245246// SAFETY: Instances of `Device` are always reference-counted.247unsafe impl crate::sync::aref::AlwaysRefCounted for Device {248fn inc_ref(&self) {249// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.250unsafe { bindings::get_device(self.as_ref().as_raw()) };251}252253unsafe fn dec_ref(obj: NonNull<Self>) {254// CAST: `Self` a transparent wrapper of `bindings::auxiliary_device`.255let adev: *mut bindings::auxiliary_device = obj.cast().as_ptr();256257// SAFETY: By the type invariant of `Self`, `adev` is a pointer to a valid258// `struct auxiliary_device`.259let dev = unsafe { addr_of_mut!((*adev).dev) };260261// SAFETY: The safety requirements guarantee that the refcount is non-zero.262unsafe { bindings::put_device(dev) }263}264}265266impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {267fn as_ref(&self) -> &device::Device<Ctx> {268// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid269// `struct auxiliary_device`.270let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };271272// SAFETY: `dev` points to a valid `struct device`.273unsafe { device::Device::from_raw(dev) }274}275}276277// SAFETY: A `Device` is always reference-counted and can be released from any thread.278unsafe impl Send for Device {}279280// SAFETY: `Device` can be shared among threads because all methods of `Device`281// (i.e. `Device<Normal>) are thread safe.282unsafe impl Sync for Device {}283284/// The registration of an auxiliary device.285///286/// This type represents the registration of a [`struct auxiliary_device`]. When an instance of this287/// type is dropped, its respective auxiliary device will be unregistered from the system.288///289/// # Invariants290///291/// `self.0` always holds a valid pointer to an initialized and registered292/// [`struct auxiliary_device`].293pub struct Registration(NonNull<bindings::auxiliary_device>);294295impl Registration {296/// Create and register a new auxiliary device.297pub fn new(parent: &device::Device, name: &CStr, id: u32, modname: &CStr) -> Result<Self> {298let boxed = KBox::new(Opaque::<bindings::auxiliary_device>::zeroed(), GFP_KERNEL)?;299let adev = boxed.get();300301// SAFETY: It's safe to set the fields of `struct auxiliary_device` on initialization.302unsafe {303(*adev).dev.parent = parent.as_raw();304(*adev).dev.release = Some(Device::release);305(*adev).name = name.as_char_ptr();306(*adev).id = id;307}308309// SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,310// which has not been initialized yet.311unsafe { bindings::auxiliary_device_init(adev) };312313// Now that `adev` is initialized, leak the `Box`; the corresponding memory will be freed314// by `Device::release` when the last reference to the `struct auxiliary_device` is dropped.315let _ = KBox::into_raw(boxed);316317// SAFETY:318// - `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`, which has319// been initialialized,320// - `modname.as_char_ptr()` is a NULL terminated string.321let ret = unsafe { bindings::__auxiliary_device_add(adev, modname.as_char_ptr()) };322if ret != 0 {323// SAFETY: `adev` is guaranteed to be a valid pointer to a `struct auxiliary_device`,324// which has been initialialized.325unsafe { bindings::auxiliary_device_uninit(adev) };326327return Err(Error::from_errno(ret));328}329330// SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated successfully.331//332// INVARIANT: The device will remain registered until `auxiliary_device_delete()` is called,333// which happens in `Self::drop()`.334Ok(Self(unsafe { NonNull::new_unchecked(adev) }))335}336}337338impl Drop for Registration {339fn drop(&mut self) {340// SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered341// `struct auxiliary_device`.342unsafe { bindings::auxiliary_device_delete(self.0.as_ptr()) };343344// This drops the reference we acquired through `auxiliary_device_init()`.345//346// SAFETY: By the type invariant of `Self`, `self.0.as_ptr()` is a valid registered347// `struct auxiliary_device`.348unsafe { bindings::auxiliary_device_uninit(self.0.as_ptr()) };349}350}351352// SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread.353unsafe impl Send for Registration {}354355// SAFETY: `Registration` does not expose any methods or fields that need synchronization.356unsafe impl Sync for Registration {}357358359