xref: /linux/rust/kernel/device_id.rs (revision 0074281bb6316108e0cff094bd4db78ab3eee236) !
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Generic implementation of device IDs.
4 //!
5 //! Each bus / subsystem that matches device and driver through a bus / subsystem specific ID is
6 //! expected to implement [`RawDeviceId`].
7 
8 use core::mem::MaybeUninit;
9 
10 /// Marker trait to indicate a Rust device ID type represents a corresponding C device ID type.
11 ///
12 /// This is meant to be implemented by buses/subsystems so that they can use [`IdTable`] to
13 /// guarantee (at compile-time) zero-termination of device id tables provided by drivers.
14 ///
15 /// # Safety
16 ///
17 /// Implementers must ensure that `Self` is layout-compatible with [`RawDeviceId::RawType`];
18 /// i.e. it's safe to transmute to `RawDeviceId`.
19 ///
20 /// This requirement is needed so `IdArray::new` can convert `Self` to `RawType` when building
21 /// the ID table.
22 ///
23 /// Ideally, this should be achieved using a const function that does conversion instead of
24 /// transmute; however, const trait functions relies on `const_trait_impl` unstable feature,
25 /// which is broken/gone in Rust 1.73.
26 pub unsafe trait RawDeviceId {
27     /// The raw type that holds the device id.
28     ///
29     /// Id tables created from [`Self`] are going to hold this type in its zero-terminated array.
30     type RawType: Copy;
31 }
32 
33 /// Extension trait for [`RawDeviceId`] for devices that embed an index or context value.
34 ///
35 /// This is typically used when the device ID struct includes a field like `driver_data`
36 /// that is used to store a pointer-sized value (e.g., an index or context pointer).
37 ///
38 /// # Safety
39 ///
40 /// Implementers must ensure that `DRIVER_DATA_OFFSET` is the correct offset (in bytes) to
41 /// the context/data field (e.g., the `driver_data` field) within the raw device ID structure.
42 /// This field must be correctly sized to hold a `usize`.
43 ///
44 /// Ideally, the data should be added during `Self` to `RawType` conversion,
45 /// but there's currently no way to do it when using traits in const.
46 pub unsafe trait RawDeviceIdIndex: RawDeviceId {
47     /// The offset (in bytes) to the context/data field in the raw device ID.
48     const DRIVER_DATA_OFFSET: usize;
49 
50     /// The index stored at `DRIVER_DATA_OFFSET` of the implementor of the [`RawDeviceIdIndex`]
51     /// trait.
index(&self) -> usize52     fn index(&self) -> usize;
53 }
54 
55 /// A zero-terminated device id array.
56 #[repr(C)]
57 pub struct RawIdArray<T: RawDeviceId, const N: usize> {
58     ids: [T::RawType; N],
59     sentinel: MaybeUninit<T::RawType>,
60 }
61 
62 impl<T: RawDeviceId, const N: usize> RawIdArray<T, N> {
63     #[doc(hidden)]
size(&self) -> usize64     pub const fn size(&self) -> usize {
65         core::mem::size_of::<Self>()
66     }
67 }
68 
69 /// A zero-terminated device id array, followed by context data.
70 #[repr(C)]
71 pub struct IdArray<T: RawDeviceId, U, const N: usize> {
72     raw_ids: RawIdArray<T, N>,
73     id_infos: [U; N],
74 }
75 
76 impl<T: RawDeviceId, U, const N: usize> IdArray<T, U, N> {
77     /// Creates a new instance of the array.
78     ///
79     /// The contents are derived from the given identifiers and context information.
80     ///
81     /// # Safety
82     ///
83     /// `data_offset` as `None` is always safe.
84     /// If `data_offset` is `Some(data_offset)`, then:
85     /// - `data_offset` must be the correct offset (in bytes) to the context/data field
86     ///   (e.g., the `driver_data` field) within the raw device ID structure.
87     /// - The field at `data_offset` must be correctly sized to hold a `usize`.
build(ids: [(T, U); N], data_offset: Option<usize>) -> Self88     const unsafe fn build(ids: [(T, U); N], data_offset: Option<usize>) -> Self {
89         let mut raw_ids = [const { MaybeUninit::<T::RawType>::uninit() }; N];
90         let mut infos = [const { MaybeUninit::uninit() }; N];
91 
92         let mut i = 0usize;
93         while i < N {
94             // SAFETY: by the safety requirement of `RawDeviceId`, we're guaranteed that `T` is
95             // layout-wise compatible with `RawType`.
96             raw_ids[i] = unsafe { core::mem::transmute_copy(&ids[i].0) };
97             if let Some(data_offset) = data_offset {
98                 // SAFETY: by the safety requirement of this function, this would be effectively
99                 // `raw_ids[i].driver_data = i;`.
100                 unsafe {
101                     raw_ids[i]
102                         .as_mut_ptr()
103                         .byte_add(data_offset)
104                         .cast::<usize>()
105                         .write(i);
106                 }
107             }
108 
109             // SAFETY: this is effectively a move: `infos[i] = ids[i].1`. We make a copy here but
110             // later forget `ids`.
111             infos[i] = MaybeUninit::new(unsafe { core::ptr::read(&ids[i].1) });
112             i += 1;
113         }
114 
115         core::mem::forget(ids);
116 
117         Self {
118             raw_ids: RawIdArray {
119                 // SAFETY: this is effectively `array_assume_init`, which is unstable, so we use
120                 // `transmute_copy` instead. We have initialized all elements of `raw_ids` so this
121                 // `array_assume_init` is safe.
122                 ids: unsafe { core::mem::transmute_copy(&raw_ids) },
123                 sentinel: MaybeUninit::zeroed(),
124             },
125             // SAFETY: We have initialized all elements of `infos` so this `array_assume_init` is
126             // safe.
127             id_infos: unsafe { core::mem::transmute_copy(&infos) },
128         }
129     }
130 
131     /// Creates a new instance of the array without writing index values.
132     ///
133     /// The contents are derived from the given identifiers and context information.
134     /// If the device implements [`RawDeviceIdIndex`], consider using [`IdArray::new`] instead.
new_without_index(ids: [(T, U); N]) -> Self135     pub const fn new_without_index(ids: [(T, U); N]) -> Self {
136         // SAFETY: Calling `Self::build` with `offset = None` is always safe,
137         // because no raw memory writes are performed in this case.
138         unsafe { Self::build(ids, None) }
139     }
140 
141     /// Reference to the contained [`RawIdArray`].
raw_ids(&self) -> &RawIdArray<T, N>142     pub const fn raw_ids(&self) -> &RawIdArray<T, N> {
143         &self.raw_ids
144     }
145 }
146 
147 impl<T: RawDeviceId + RawDeviceIdIndex, U, const N: usize> IdArray<T, U, N> {
148     /// Creates a new instance of the array.
149     ///
150     /// The contents are derived from the given identifiers and context information.
new(ids: [(T, U); N]) -> Self151     pub const fn new(ids: [(T, U); N]) -> Self {
152         // SAFETY: by the safety requirement of `RawDeviceIdIndex`,
153         // `T::DRIVER_DATA_OFFSET` is guaranteed to be the correct offset (in bytes) to
154         // a field within `T::RawType`.
155         unsafe { Self::build(ids, Some(T::DRIVER_DATA_OFFSET)) }
156     }
157 }
158 
159 /// A device id table.
160 ///
161 /// This trait is only implemented by `IdArray`.
162 ///
163 /// The purpose of this trait is to allow `&'static dyn IdArray<T, U>` to be in context when `N` in
164 /// `IdArray` doesn't matter.
165 pub trait IdTable<T: RawDeviceId, U> {
166     /// Obtain the pointer to the ID table.
as_ptr(&self) -> *const T::RawType167     fn as_ptr(&self) -> *const T::RawType;
168 
169     /// Obtain the pointer to the bus specific device ID from an index.
id(&self, index: usize) -> &T::RawType170     fn id(&self, index: usize) -> &T::RawType;
171 
172     /// Obtain the pointer to the driver-specific information from an index.
info(&self, index: usize) -> &U173     fn info(&self, index: usize) -> &U;
174 }
175 
176 impl<T: RawDeviceId, U, const N: usize> IdTable<T, U> for IdArray<T, U, N> {
as_ptr(&self) -> *const T::RawType177     fn as_ptr(&self) -> *const T::RawType {
178         // This cannot be `self.ids.as_ptr()`, as the return pointer must have correct provenance
179         // to access the sentinel.
180         core::ptr::from_ref(self).cast()
181     }
182 
id(&self, index: usize) -> &T::RawType183     fn id(&self, index: usize) -> &T::RawType {
184         &self.raw_ids.ids[index]
185     }
186 
info(&self, index: usize) -> &U187     fn info(&self, index: usize) -> &U {
188         &self.id_infos[index]
189     }
190 }
191 
192 /// Create device table alias for modpost.
193 #[macro_export]
194 macro_rules! module_device_table {
195     ($table_type: literal, $module_table_name:ident, $table_name:ident) => {
196         #[rustfmt::skip]
197         #[export_name =
198             concat!("__mod_device_table__", $table_type,
199                     "__", module_path!(),
200                     "_", line!(),
201                     "_", stringify!($table_name))
202         ]
203         static $module_table_name: [::core::mem::MaybeUninit<u8>; $table_name.raw_ids().size()] =
204             unsafe { ::core::mem::transmute_copy($table_name.raw_ids()) };
205     };
206 }
207