ostd/arch/x86/kernel/acpi/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2
3pub(in crate::arch) mod dmar;
4pub(in crate::arch) mod remapping;
5
6use core::{num::NonZeroU8, ptr::NonNull};
7
8use acpi::{
9    AcpiHandler, AcpiTables,
10    address::AddressSpace,
11    fadt::{Fadt, IaPcBootArchFlags},
12    mcfg::Mcfg,
13    rsdp::Rsdp,
14};
15use log::warn;
16use spin::Once;
17
18use crate::{
19    boot::{self, BootloaderAcpiArg},
20    mm::paddr_to_vaddr,
21};
22
23#[derive(Debug, Clone)]
24pub(crate) struct AcpiMemoryHandler {}
25
26impl AcpiHandler for AcpiMemoryHandler {
27    unsafe fn map_physical_region<T>(
28        &self,
29        physical_address: usize,
30        size: usize,
31    ) -> acpi::PhysicalMapping<Self, T> {
32        let virtual_address = NonNull::new(paddr_to_vaddr(physical_address) as *mut T).unwrap();
33
34        // SAFETY: The caller should guarantee that `physical_address..physical_address + size` is
35        // part of the ACPI table. Then the memory region is mapped to `virtual_address` and is
36        // valid for read and immutable dereferencing.
37        // FIXME: The caller guarantee only holds if we trust the hardware to provide a valid ACPI
38        // table. Otherwise, if the table is corrupted, it may reference arbitrary memory regions.
39        unsafe {
40            acpi::PhysicalMapping::new(physical_address, virtual_address, size, size, self.clone())
41        }
42    }
43
44    fn unmap_physical_region<T>(_region: &acpi::PhysicalMapping<Self, T>) {}
45}
46
47pub(crate) fn get_acpi_tables() -> Option<AcpiTables<AcpiMemoryHandler>> {
48    let acpi_tables = match boot::EARLY_INFO.get().unwrap().acpi_arg {
49        BootloaderAcpiArg::Rsdp(addr) => unsafe {
50            AcpiTables::from_rsdp(AcpiMemoryHandler {}, addr).unwrap()
51        },
52        BootloaderAcpiArg::Rsdt(addr) => unsafe {
53            AcpiTables::from_rsdt(AcpiMemoryHandler {}, 0, addr).unwrap()
54        },
55        BootloaderAcpiArg::Xsdt(addr) => unsafe {
56            AcpiTables::from_rsdt(AcpiMemoryHandler {}, 1, addr).unwrap()
57        },
58        BootloaderAcpiArg::NotProvided => {
59            // We search by ourselves if the bootloader decides not to provide a rsdp location.
60            let rsdp = unsafe { Rsdp::search_for_on_bios(AcpiMemoryHandler {}) };
61            match rsdp {
62                Ok(map) => unsafe {
63                    AcpiTables::from_rsdp(AcpiMemoryHandler {}, map.physical_start()).unwrap()
64                },
65                Err(_) => {
66                    warn!("ACPI info not found!");
67                    return None;
68                }
69            }
70        }
71    };
72
73    Some(acpi_tables)
74}
75
76/// The platform information provided by the ACPI tables.
77///
78/// Currently, this structure contains only a limited set of fields, far fewer than those in all
79/// ACPI tables. However, the goal is to expand it properly to keep the simplicity of the OSTD code
80/// while enabling OSTD users to safely retrieve information from the ACPI tables.
81#[derive(Debug)]
82pub struct AcpiInfo {
83    /// The RTC CMOS RAM index to the century of data value; the "CENTURY" field in the FADT.
84    pub century_register: Option<NonZeroU8>,
85    /// IA-PC Boot Architecture Flags; the "IAPC_BOOT_ARCH" field in the FADT.
86    pub boot_flags: Option<IaPcBootArchFlags>,
87    /// An I/O port to reset the machine by writing the specified value.
88    pub reset_port_and_val: Option<(u16, u8)>,
89    /// A memory region that is stolen for PCI configuration space.
90    pub pci_ecam_region: Option<PciEcamRegion>,
91}
92
93/// A memory region that is stolen for PCI configuration space.
94#[derive(Debug)]
95pub struct PciEcamRegion {
96    /// The base address of the memory region.
97    pub base_address: u64,
98    /// The start of the bus number.
99    pub bus_start: u8,
100    /// The end of the bus number.
101    pub bus_end: u8,
102}
103
104/// The [`AcpiInfo`] singleton.
105pub static ACPI_INFO: Once<AcpiInfo> = Once::new();
106
107pub(in crate::arch) fn init() {
108    let mut acpi_info = AcpiInfo {
109        century_register: None,
110        boot_flags: None,
111        reset_port_and_val: None,
112        pci_ecam_region: None,
113    };
114
115    let Some(acpi_tables) = get_acpi_tables() else {
116        ACPI_INFO.call_once(|| acpi_info);
117        return;
118    };
119
120    if let Ok(fadt) = acpi_tables.find_table::<Fadt>() {
121        // A zero means that the century register does not exist.
122        acpi_info.century_register = NonZeroU8::new(fadt.century);
123        acpi_info.boot_flags = Some(fadt.iapc_boot_arch);
124        if let Ok(reset_reg) = fadt.reset_register()
125            && reset_reg.address_space == AddressSpace::SystemIo
126            && let Ok(reset_port) = reset_reg.address.try_into()
127        {
128            acpi_info.reset_port_and_val = Some((reset_port, fadt.reset_value));
129        }
130    };
131
132    if let Ok(mcfg) = acpi_tables.find_table::<Mcfg>()
133        // TODO: Support multiple PCIe segment groups instead of assuming only one
134        // PCIe segment group is in use.
135        && let Some(mcfg_entry) = mcfg.entries().first()
136    {
137        acpi_info.pci_ecam_region = Some(PciEcamRegion {
138            base_address: mcfg_entry.base_address,
139            bus_start: mcfg_entry.bus_number_start,
140            bus_end: mcfg_entry.bus_number_end,
141        });
142    }
143
144    log::info!("[ACPI]: Collected information {:?}", acpi_info);
145
146    ACPI_INFO.call_once(|| acpi_info);
147}