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