// SPDX-License-Identifier: GPL-2.012//! Generic implementation of device IDs.3//!4//! Each bus / subsystem that matches device and driver through a bus / subsystem specific ID is5//! expected to implement [`RawDeviceId`].67use core::mem::MaybeUninit;89/// Marker trait to indicate a Rust device ID type represents a corresponding C device ID type.10///11/// This is meant to be implemented by buses/subsystems so that they can use [`IdTable`] to12/// guarantee (at compile-time) zero-termination of device id tables provided by drivers.13///14/// # Safety15///16/// Implementers must ensure that `Self` is layout-compatible with [`RawDeviceId::RawType`];17/// i.e. it's safe to transmute to `RawDeviceId`.18///19/// This requirement is needed so `IdArray::new` can convert `Self` to `RawType` when building20/// the ID table.21///22/// Ideally, this should be achieved using a const function that does conversion instead of23/// transmute; however, const trait functions relies on `const_trait_impl` unstable feature,24/// which is broken/gone in Rust 1.73.25pub unsafe trait RawDeviceId {26/// The raw type that holds the device id.27///28/// Id tables created from [`Self`] are going to hold this type in its zero-terminated array.29type RawType: Copy;30}3132/// Extension trait for [`RawDeviceId`] for devices that embed an index or context value.33///34/// This is typically used when the device ID struct includes a field like `driver_data`35/// that is used to store a pointer-sized value (e.g., an index or context pointer).36///37/// # Safety38///39/// Implementers must ensure that `DRIVER_DATA_OFFSET` is the correct offset (in bytes) to40/// the context/data field (e.g., the `driver_data` field) within the raw device ID structure.41/// This field must be correctly sized to hold a `usize`.42///43/// Ideally, the data should be added during `Self` to `RawType` conversion,44/// but there's currently no way to do it when using traits in const.45pub unsafe trait RawDeviceIdIndex: RawDeviceId {46/// The offset (in bytes) to the context/data field in the raw device ID.47const DRIVER_DATA_OFFSET: usize;4849/// The index stored at `DRIVER_DATA_OFFSET` of the implementor of the [`RawDeviceIdIndex`]50/// trait.51fn index(&self) -> usize;52}5354/// A zero-terminated device id array.55#[repr(C)]56pub struct RawIdArray<T: RawDeviceId, const N: usize> {57ids: [T::RawType; N],58sentinel: MaybeUninit<T::RawType>,59}6061impl<T: RawDeviceId, const N: usize> RawIdArray<T, N> {62#[doc(hidden)]63pub const fn size(&self) -> usize {64core::mem::size_of::<Self>()65}66}6768/// A zero-terminated device id array, followed by context data.69#[repr(C)]70pub struct IdArray<T: RawDeviceId, U, const N: usize> {71raw_ids: RawIdArray<T, N>,72id_infos: [U; N],73}7475impl<T: RawDeviceId, U, const N: usize> IdArray<T, U, N> {76/// Creates a new instance of the array.77///78/// The contents are derived from the given identifiers and context information.79///80/// # Safety81///82/// `data_offset` as `None` is always safe.83/// If `data_offset` is `Some(data_offset)`, then:84/// - `data_offset` must be the correct offset (in bytes) to the context/data field85/// (e.g., the `driver_data` field) within the raw device ID structure.86/// - The field at `data_offset` must be correctly sized to hold a `usize`.87const unsafe fn build(ids: [(T, U); N], data_offset: Option<usize>) -> Self {88let mut raw_ids = [const { MaybeUninit::<T::RawType>::uninit() }; N];89let mut infos = [const { MaybeUninit::uninit() }; N];9091let mut i = 0usize;92while i < N {93// SAFETY: by the safety requirement of `RawDeviceId`, we're guaranteed that `T` is94// layout-wise compatible with `RawType`.95raw_ids[i] = unsafe { core::mem::transmute_copy(&ids[i].0) };96if let Some(data_offset) = data_offset {97// SAFETY: by the safety requirement of this function, this would be effectively98// `raw_ids[i].driver_data = i;`.99unsafe {100raw_ids[i]101.as_mut_ptr()102.byte_add(data_offset)103.cast::<usize>()104.write(i);105}106}107108// SAFETY: this is effectively a move: `infos[i] = ids[i].1`. We make a copy here but109// later forget `ids`.110infos[i] = MaybeUninit::new(unsafe { core::ptr::read(&ids[i].1) });111i += 1;112}113114core::mem::forget(ids);115116Self {117raw_ids: RawIdArray {118// SAFETY: this is effectively `array_assume_init`, which is unstable, so we use119// `transmute_copy` instead. We have initialized all elements of `raw_ids` so this120// `array_assume_init` is safe.121ids: unsafe { core::mem::transmute_copy(&raw_ids) },122sentinel: MaybeUninit::zeroed(),123},124// SAFETY: We have initialized all elements of `infos` so this `array_assume_init` is125// safe.126id_infos: unsafe { core::mem::transmute_copy(&infos) },127}128}129130/// Creates a new instance of the array without writing index values.131///132/// The contents are derived from the given identifiers and context information.133/// If the device implements [`RawDeviceIdIndex`], consider using [`IdArray::new`] instead.134pub const fn new_without_index(ids: [(T, U); N]) -> Self {135// SAFETY: Calling `Self::build` with `offset = None` is always safe,136// because no raw memory writes are performed in this case.137unsafe { Self::build(ids, None) }138}139140/// Reference to the contained [`RawIdArray`].141pub const fn raw_ids(&self) -> &RawIdArray<T, N> {142&self.raw_ids143}144}145146impl<T: RawDeviceId + RawDeviceIdIndex, U, const N: usize> IdArray<T, U, N> {147/// Creates a new instance of the array.148///149/// The contents are derived from the given identifiers and context information.150pub const fn new(ids: [(T, U); N]) -> Self {151// SAFETY: by the safety requirement of `RawDeviceIdIndex`,152// `T::DRIVER_DATA_OFFSET` is guaranteed to be the correct offset (in bytes) to153// a field within `T::RawType`.154unsafe { Self::build(ids, Some(T::DRIVER_DATA_OFFSET)) }155}156}157158/// A device id table.159///160/// This trait is only implemented by `IdArray`.161///162/// The purpose of this trait is to allow `&'static dyn IdArray<T, U>` to be in context when `N` in163/// `IdArray` doesn't matter.164pub trait IdTable<T: RawDeviceId, U> {165/// Obtain the pointer to the ID table.166fn as_ptr(&self) -> *const T::RawType;167168/// Obtain the pointer to the bus specific device ID from an index.169fn id(&self, index: usize) -> &T::RawType;170171/// Obtain the pointer to the driver-specific information from an index.172fn info(&self, index: usize) -> &U;173}174175impl<T: RawDeviceId, U, const N: usize> IdTable<T, U> for IdArray<T, U, N> {176fn as_ptr(&self) -> *const T::RawType {177// This cannot be `self.ids.as_ptr()`, as the return pointer must have correct provenance178// to access the sentinel.179core::ptr::from_ref(self).cast()180}181182fn id(&self, index: usize) -> &T::RawType {183&self.raw_ids.ids[index]184}185186fn info(&self, index: usize) -> &U {187&self.id_infos[index]188}189}190191/// Create device table alias for modpost.192#[macro_export]193macro_rules! module_device_table {194($table_type: literal, $module_table_name:ident, $table_name:ident) => {195#[rustfmt::skip]196#[export_name =197concat!("__mod_device_table__", line!(),198"__kmod_", module_path!(),199"__", $table_type,200"__", stringify!($table_name))201]202static $module_table_name: [::core::mem::MaybeUninit<u8>; $table_name.raw_ids().size()] =203unsafe { ::core::mem::transmute_copy($table_name.raw_ids()) };204};205}206207208