xref: /linux/rust/kernel/acpi.rs (revision 22c5696e3fe029f4fc2decbe7cc6663b5d281223)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Advanced Configuration and Power Interface abstractions.
4 
5 use crate::{
6     bindings,
7     device_id::{RawDeviceId, RawDeviceIdIndex},
8     prelude::*,
9 };
10 
11 /// IdTable type for ACPI drivers.
12 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
13 
14 /// An ACPI device id.
15 #[repr(transparent)]
16 #[derive(Clone, Copy)]
17 pub struct DeviceId(bindings::acpi_device_id);
18 
19 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `acpi_device_id` and does not add
20 // additional invariants, so it's safe to transmute to `RawType`.
21 unsafe impl RawDeviceId for DeviceId {
22     type RawType = bindings::acpi_device_id;
23 }
24 
25 // SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
26 unsafe impl RawDeviceIdIndex for DeviceId {
27     const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::acpi_device_id, driver_data);
28 
index(&self) -> usize29     fn index(&self) -> usize {
30         self.0.driver_data
31     }
32 }
33 
34 impl DeviceId {
35     const ACPI_ID_LEN: usize = 16;
36 
37     /// Create a new device id from an ACPI 'id' string.
38     #[inline(always)]
new(id: &'static CStr) -> Self39     pub const fn new(id: &'static CStr) -> Self {
40         build_assert!(
41             id.len_with_nul() <= Self::ACPI_ID_LEN,
42             "ID exceeds 16 bytes"
43         );
44         let src = id.as_bytes_with_nul();
45         // Replace with `bindings::acpi_device_id::default()` once stabilized for `const`.
46         // SAFETY: FFI type is valid to be zero-initialized.
47         let mut acpi: bindings::acpi_device_id = unsafe { core::mem::zeroed() };
48         let mut i = 0;
49         while i < src.len() {
50             acpi.id[i] = src[i];
51             i += 1;
52         }
53 
54         Self(acpi)
55     }
56 }
57 
58 /// Create an ACPI `IdTable` with an "alias" for modpost.
59 #[macro_export]
60 macro_rules! acpi_device_table {
61     ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {
62         const $table_name: $crate::device_id::IdArray<
63             $crate::acpi::DeviceId,
64             $id_info_type,
65             { $table_data.len() },
66         > = $crate::device_id::IdArray::new($table_data);
67 
68         $crate::module_device_table!("acpi", $module_table_name, $table_name);
69     };
70 }
71