1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Device Tree / Open Firmware abstractions. 4 5 use crate::{bindings, device_id::RawDeviceId, prelude::*}; 6 7 /// IdTable type for OF drivers. 8 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>; 9 10 /// An open firmware device id. 11 #[repr(transparent)] 12 #[derive(Clone, Copy)] 13 pub struct DeviceId(bindings::of_device_id); 14 15 // SAFETY: 16 // * `DeviceId` is a `#[repr(transparent)` wrapper of `struct of_device_id` and does not add 17 // additional invariants, so it's safe to transmute to `RawType`. 18 // * `DRIVER_DATA_OFFSET` is the offset to the `data` field. 19 unsafe impl RawDeviceId for DeviceId { 20 type RawType = bindings::of_device_id; 21 22 const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::of_device_id, data); 23 index(&self) -> usize24 fn index(&self) -> usize { 25 self.0.data as _ 26 } 27 } 28 29 impl DeviceId { 30 /// Create a new device id from an OF 'compatible' string. new(compatible: &'static CStr) -> Self31 pub const fn new(compatible: &'static CStr) -> Self { 32 let src = compatible.as_bytes_with_nul(); 33 // Replace with `bindings::of_device_id::default()` once stabilized for `const`. 34 // SAFETY: FFI type is valid to be zero-initialized. 35 let mut of: bindings::of_device_id = unsafe { core::mem::zeroed() }; 36 37 // TODO: Use `clone_from_slice` once the corresponding types do match. 38 let mut i = 0; 39 while i < src.len() { 40 of.compatible[i] = src[i] as _; 41 i += 1; 42 } 43 44 Self(of) 45 } 46 } 47 48 /// Create an OF `IdTable` with an "alias" for modpost. 49 #[macro_export] 50 macro_rules! of_device_table { 51 ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => { 52 const $table_name: $crate::device_id::IdArray< 53 $crate::of::DeviceId, 54 $id_info_type, 55 { $table_data.len() }, 56 > = $crate::device_id::IdArray::new($table_data); 57 58 $crate::module_device_table!("of", $module_table_name, $table_name); 59 }; 60 } 61