Skip to main content

strat9_kernel/acpi/
mod.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! ACPI (Advanced Configuration and Power Interface) support.
24//! Inspired by Theseus OS, MaestroOS, Aero, and Redox.
25//!
26//! Features:
27//! - RSDP/RSDT/XSDT parsing
28//! - MADT (interrupts, APICs)
29//! - FADT (power management, DSDT)
30//! - HPET (timers)
31//! - MCFG (PCIe MMCONFIG)
32//! - DMAR (IOMMU)
33//! - WAET (VM optimization hints)
34//! - BGRT (boot graphics)
35//! - SLIT (NUMA distances)
36//!
37//! TODO : take a look at the v6 :
38//! https://uefi.org/sites/default/files/resources/ACPI_Spec_6.6.pdf
39//! https://uefi.org/specs/ACPI/6.6/
40
41pub mod bgrt;
42pub mod dmar;
43pub mod fadt;
44pub mod hpet;
45pub mod ivrs;
46pub mod madt;
47pub mod mcfg;
48pub mod rsdt;
49pub mod sdt;
50pub mod slit;
51pub mod waet;
52
53use crate::{memory, sync::SpinLock};
54use alloc::{collections::BTreeMap, vec::Vec};
55use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
56use sdt::Sdt;
57
58/// Stored RSDP virtual address (set during init)
59static RSDP_VADDR: AtomicU64 = AtomicU64::new(0);
60
61/// RSDP revision (0 = ACPI 1.0, 2+ = ACPI 2.0+)
62static RSDP_REVISION: AtomicU64 = AtomicU64::new(0);
63
64/// RSDP (Root System Descriptor Pointer) : ACPI 1.0
65#[repr(C, packed)]
66struct Rsdp {
67    signature: [u8; 8],
68    checksum: u8,
69    oem_id: [u8; 6],
70    revision: u8,
71    rsdt_address: u32,
72}
73
74/// RSDP extended : ACPI 2.0+
75#[repr(C, packed)]
76struct Rsdp2 {
77    base: Rsdp,
78    length: u32,
79    xsdt_address: u64,
80    extended_checksum: u8,
81    _reserved: [u8; 3],
82}
83
84/// Table storage to keep track of discovered ACPI tables
85pub struct AcpiTables {
86    tables: BTreeMap<[u8; 4], Vec<*const Sdt>>,
87}
88
89unsafe impl Send for AcpiTables {}
90unsafe impl Sync for AcpiTables {}
91
92static ACPI_TABLES: SpinLock<AcpiTables> = SpinLock::new(AcpiTables {
93    tables: BTreeMap::new(),
94});
95
96/// ACPI initialization status
97static ACPI_INITIALIZED: AtomicBool = AtomicBool::new(false);
98
99/// Get ACPI revision
100pub fn revision() -> u8 {
101    RSDP_REVISION.load(Ordering::Relaxed) as u8
102}
103
104/// Check if ACPI is initialized
105pub fn is_available() -> bool {
106    ACPI_INITIALIZED.load(Ordering::Relaxed)
107}
108
109/// Get RSDP address
110pub fn rsdp_address() -> u64 {
111    RSDP_VADDR.load(Ordering::Relaxed)
112}
113
114/// Get BGRT table (boot graphics)
115pub fn get_bgrt() -> Option<&'static bgrt::Bgrt> {
116    bgrt::Bgrt::get()
117}
118
119/// Get DMAR table (Intel IOMMU)
120pub fn get_dmar() -> Option<dmar::Dmar> {
121    dmar::Dmar::get()
122}
123
124/// Get IVRS table (AMD IOMMU)
125pub fn get_ivrs() -> Option<ivrs::Ivrs> {
126    ivrs::Ivrs::get()
127}
128
129/// Get SLIT table (NUMA distances)
130pub fn get_slit() -> Option<&'static slit::Slit> {
131    slit::Slit::get()
132}
133
134/// Get HPET table
135pub fn get_hpet() -> Option<&'static hpet::HpetAcpiTable> {
136    hpet::HpetAcpiTable::get()
137}
138
139/// Get FADT table
140pub fn get_fadt() -> Option<&'static fadt::Fadt> {
141    fadt::Fadt::get()
142}
143
144/// Get MADT table
145pub fn get_madt() -> Option<&'static madt::MadtAcpiTable> {
146    madt::MadtAcpiTable::get()
147}
148
149/// Get MCFG table
150pub fn get_mcfg() -> Option<&'static mcfg::Mcfg> {
151    mcfg::Mcfg::get()
152}
153
154/// Initialize the ACPI subsystem.
155pub fn init(rsdp_vaddr: u64) -> Result<bool, &'static str> {
156    if rsdp_vaddr == 0 {
157        log::warn!("ACPI: No RSDP provided by bootloader");
158        return Ok(false);
159    }
160
161    let rsdp = rsdp_vaddr as *const Rsdp;
162
163    // Validate signature "RSD PTR "
164    let sig = unsafe { (*rsdp).signature };
165    if &sig != b"RSD PTR " {
166        return Err("ACPI: Invalid RSDP signature");
167    }
168
169    // Validate RSDP checksum (first 20 bytes)
170    if !validate_checksum(rsdp as *const u8, 20) {
171        return Err("ACPI: RSDP checksum failed");
172    }
173
174    let revision = unsafe { (*rsdp).revision };
175
176    // For ACPI 2.0+, validate extended checksum
177    if revision >= 2 {
178        let rsdp2 = rsdp_vaddr as *const Rsdp2;
179        let length = unsafe { (*rsdp2).length } as usize;
180        if !validate_checksum(rsdp as *const u8, length) {
181            return Err("ACPI: RSDP extended checksum failed");
182        }
183    }
184
185    RSDP_VADDR.store(rsdp_vaddr, Ordering::Relaxed);
186    RSDP_REVISION.store(revision as u64, Ordering::Relaxed);
187
188    log::info!("ACPI: RSDP validated (revision {})", revision);
189
190    // Discover all tables via root RSDT/XSDT pointed by RSDP.
191    discover_tables(rsdp_vaddr, revision)?;
192
193    // Mark ACPI as initialized
194    ACPI_INITIALIZED.store(true, Ordering::SeqCst);
195
196    Ok(true)
197}
198
199/// Performs the validate checksum operation.
200fn validate_checksum(ptr: *const u8, len: usize) -> bool {
201    let mut sum: u8 = 0;
202    for i in 0..len {
203        sum = sum.wrapping_add(unsafe { *ptr.add(i) });
204    }
205    sum == 0
206}
207
208/// Performs the discover tables operation.
209fn discover_tables(rsdp_vaddr: u64, revision: u8) -> Result<(), &'static str> {
210    let rxsdt = rsdt::RsdtXsdt::from_rsdp(rsdp_vaddr, revision)
211        .ok_or("ACPI: Failed to find RSDT/XSDT from RSDP")?;
212    let root_sdt = rxsdt.sdt();
213    if root_sdt.length < core::mem::size_of::<Sdt>() as u32 {
214        return Err("ACPI: Root SDT has invalid length");
215    }
216    let root_phys = memory::virt_to_phys(root_sdt as *const Sdt as u64);
217    let root_len = root_sdt.length;
218    memory::paging::ensure_identity_map_range(root_phys, root_len as u64);
219    let root_sig = root_sdt.signature;
220    let root_sig_str = core::str::from_utf8(&root_sig).unwrap_or("????");
221    log::info!(
222        "ACPI: root table {} phys={:#x} len={}",
223        root_sig_str,
224        root_phys,
225        root_len
226    );
227
228    let mut acpi_tables = ACPI_TABLES.lock();
229    let mut discovered = 0usize;
230
231    for sdt_phys in rxsdt.addresses() {
232        if sdt_phys == 0 {
233            continue;
234        }
235
236        let (signature, sdt) = validate_sdt_at_phys(sdt_phys)?;
237
238        // Keep all tables with the same signature (e.g., multiple SSDT).
239        acpi_tables
240            .tables
241            .entry(signature)
242            .or_insert_with(Vec::new)
243            .push(sdt);
244        discovered += 1;
245
246        log::debug!(
247            "ACPI: Discovered table {:?} at phys {:#x}",
248            core::str::from_utf8(&signature).unwrap_or("????"),
249            sdt_phys
250        );
251    }
252
253    let unique = acpi_tables.tables.len();
254    log::info!(
255        "ACPI: discovered {} table entries ({} unique signatures)",
256        discovered,
257        unique
258    );
259
260    Ok(())
261}
262
263/// Performs the validate sdt at phys operation.
264fn validate_sdt_at_phys(sdt_phys: u64) -> Result<([u8; 4], *const Sdt), &'static str> {
265    // Map header first to read SDT length.
266    memory::paging::ensure_identity_map_range(sdt_phys, core::mem::size_of::<Sdt>() as u64);
267    let sdt_virt = memory::phys_to_virt(sdt_phys);
268    let sdt = sdt_virt as *const Sdt;
269    let length = unsafe { (*sdt).length as usize };
270    if length < core::mem::size_of::<Sdt>() {
271        return Err("ACPI: SDT length smaller than header");
272    }
273    memory::paging::ensure_identity_map_range(sdt_phys, length as u64);
274    if !validate_checksum(sdt as *const u8, length) {
275        return Err("ACPI: SDT checksum failed");
276    }
277    let signature = unsafe { (*sdt).signature };
278    Ok((signature, sdt))
279}
280
281/// Find the first ACPI table by its 4-byte signature.
282pub fn find_table(signature: &[u8; 4]) -> Option<*const Sdt> {
283    let acpi_tables = ACPI_TABLES.lock();
284    acpi_tables
285        .tables
286        .get(signature)
287        .and_then(|tables| tables.first().copied())
288}
289
290/// Find all ACPI tables with the given 4-byte signature.
291pub fn find_tables(signature: &[u8; 4]) -> Option<Vec<*const Sdt>> {
292    let acpi_tables = ACPI_TABLES.lock();
293    acpi_tables.tables.get(signature).cloned()
294}
295
296/// Get a typed reference to an ACPI table.
297pub fn get_table<T>(signature: &[u8; 4]) -> Option<&'static T> {
298    let ptr = find_table(signature)?;
299    let sdt = unsafe { &*ptr };
300    if (sdt.length as usize) < core::mem::size_of::<T>() {
301        return None;
302    }
303    Some(unsafe { &*(ptr as *const T) })
304}