garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/x86_64/acpi.rs

raw

//! ACPI's tables, as far as the kernel reads them: from the root pointer
//! (RSDP) to the root table (XSDT, or the older RSDT) to the MADT, which
//! names every core's local APIC and the I/O APICs. This is how a PC says
//! how many cores it has: nothing is counted or assumed.

use alloc::vec::Vec;

/// What the MADT says.
pub struct Madt {
    /// The local APIC's registers, physical.
    pub local_apic: u64,
    /// Each usable core's APIC ID, the booting one among them.
    pub cores: Vec<u32>,
    /// Each I/O APIC: its registers (physical) and its first interrupt.
    pub io_apics: Vec<(u64, u32)>,
    /// Each ISA interrupt not on the pin of its number, or not edge and
    /// active high: its IRQ, its GSI, its MPS flags.
    pub overrides: Vec<(u8, u32, u16)>,
}

fn bytes(physical: u64, len: usize) -> &'static [u8] {
    // SAFETY: firmware tables in RAM below 4 GiB, mapped by boot and never
    // handed out (the first MiB) or, above it, ACPI's own ranges, which the
    // RAM map does not list.
    unsafe { core::slice::from_raw_parts(crate::mmu::virt(physical as usize) as *const u8, len) }
}

fn u32_at(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
}

fn u64_at(b: &[u8], at: usize) -> u64 {
    u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
}

fn checksum(b: &[u8]) -> bool {
    b.iter().fold(0u8, |sum, &x| sum.wrapping_add(x)) == 0
}

/// The root pointer: where the loader said, else found in the BIOS's area
/// (0xe0000 to 0xfffff, on a 16-byte boundary), as legacy firmware leaves
/// it.
fn rsdp(given: u64) -> Option<u64> {
    if given != 0 {
        return Some(given);
    }
    let area = bytes(0xe0000, 0x20000);
    (0..area.len() - 20)
        .step_by(16)
        .find(|&at| &area[at..at + 8] == b"RSD PTR " && checksum(&area[at..at + 20]))
        .map(|at| 0xe0000 + at as u64)
}

/// A table at `physical`, whole, if its checksum holds.
fn table(physical: u64) -> Option<&'static [u8]> {
    let len = u32_at(bytes(physical, 8), 4) as usize;
    let t = bytes(physical, len);
    checksum(t).then_some(t)
}

/// The tables the root table lists, by signature.
fn find(rsdp_given: u64, signature: &[u8; 4]) -> Option<&'static [u8]> {
    let rsdp = bytes(rsdp(rsdp_given)?, 36);
    let (root, entry) = if rsdp[15] >= 2 && u64_at(rsdp, 24) != 0 {
        (u64_at(rsdp, 24), 8)
    } else {
        (u64::from(u32_at(rsdp, 16)), 4)
    };
    let root = table(root)?;
    root[36..]
        .chunks_exact(entry)
        .map(|e| {
            if entry == 8 {
                u64_at(e, 0)
            } else {
                u64::from(u32_at(e, 0))
            }
        })
        .filter_map(table)
        .find(|t| &t[..4] == signature)
}

/// The tables of AML: the DSDT the FADT names, then every SSDT, in the
/// root table's order.
pub fn aml_tables(rsdp_given: u64) -> Vec<&'static [u8]> {
    let mut tables = Vec::new();
    if let Some(fadt) = find(rsdp_given, b"FACP") {
        let dsdt = if fadt.len() >= 148 && u64_at(fadt, 140) != 0 {
            u64_at(fadt, 140)
        } else {
            u64::from(u32_at(fadt, 40))
        };
        tables.extend(table(dsdt).filter(|t| t.starts_with(b"DSDT")));
    }
    tables.extend(all(rsdp_given).filter(|t| t.starts_with(b"SSDT")));
    tables
}

/// Every table the root table lists.
fn all(rsdp_given: u64) -> impl Iterator<Item = &'static [u8]> {
    let root = rsdp(rsdp_given).map(|r| bytes(r, 36)).and_then(|rsdp| {
        let (root, entry) = if rsdp[15] >= 2 && u64_at(rsdp, 24) != 0 {
            (u64_at(rsdp, 24), 8)
        } else {
            (u64::from(u32_at(rsdp, 16)), 4)
        };
        Some((table(root)?, entry))
    });
    root.into_iter().flat_map(|(root, entry)| {
        root[36..]
            .chunks_exact(entry)
            .map(move |e| {
                if entry == 8 {
                    u64_at(e, 0)
                } else {
                    u64::from(u32_at(e, 0))
                }
            })
            .filter_map(table)
    })
}

/// The MCFG: each PCI segment's configuration space (ECAM): its physical
/// base and its first and last bus.
pub fn mcfg(rsdp_given: u64) -> Vec<(u64, u8, u8)> {
    let Some(t) = find(rsdp_given, b"MCFG") else {
        return Vec::new();
    };
    t[44..]
        .as_chunks::<16>()
        .0
        .iter()
        .map(|e| (u64_at(e, 0), e[10], e[11]))
        .collect()
}

/// The MADT ("APIC"): the cores and the interrupt controllers.
pub fn madt(rsdp_given: u64) -> Option<Madt> {
    let t = find(rsdp_given, b"APIC")?;
    let mut madt = Madt {
        local_apic: u64::from(u32_at(t, 36)),
        cores: Vec::new(),
        io_apics: Vec::new(),
        overrides: Vec::new(),
    };
    let mut at = 44;
    while at + 2 <= t.len() {
        let (kind, len) = (t[at], t[at + 1] as usize);
        if len < 2 || at + len > t.len() {
            break;
        }
        let e = &t[at..at + len];
        // Enabled. "Online capable" alone is a socket a core may be put in
        // later: a laptop's firmware lists such entries, with no core
        // behind them to answer a wake.
        let usable = |flags: u32| flags & 1 != 0;
        // Firmware may name a core both as a local APIC and an x2APIC:
        // woken twice, it is reset under the running kernel.
        let mut push = |id: u32| {
            if !madt.cores.contains(&id) {
                madt.cores.push(id);
            }
        };
        match kind {
            0 if usable(u32_at(e, 4)) => push(u32::from(e[3])),
            1 => madt.io_apics.push((u64::from(u32_at(e, 4)), u32_at(e, 8))),
            2 if len >= 10 => madt
                .overrides
                .push((e[3], u32_at(e, 4), u16::from_le_bytes([e[8], e[9]]))),
            5 => madt.local_apic = u64_at(e, 4),
            9 if usable(u32_at(e, 8)) => push(u32_at(e, 4)),
            _ => {}
        }
        at += len;
    }
    Some(madt)
}

/// A register as ACPI's Generic Address Structure names it, as far as the
/// kernel uses one: in I/O space or in memory, its address.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Register {
    Port(u16),
    Memory(u64),
}

impl Register {
    /// A GAS's 12 bytes: space (0 memory, 1 I/O), widths, address. None
    /// when it names nothing, or a space the kernel does not reach.
    fn from_gas(gas: &[u8]) -> Option<Register> {
        let address = u64_at(gas, 4);
        match (gas[0], address) {
            (_, 0) => None,
            (0, a) => Some(Register::Memory(a)),
            (1, a) => u16::try_from(a).ok().map(Register::Port),
            _ => None,
        }
    }

    fn read16(self) -> u16 {
        match self {
            Register::Port(p) => crate::arch::in16(p),
            // SAFETY: a register the FADT names, in the uncached direct map.
            Register::Memory(a) => unsafe { (crate::mmu::virt(a as usize) as *const u16).read_volatile() },
        }
    }

    fn write16(self, value: u16) {
        match self {
            Register::Port(p) => crate::arch::out16(p, value),
            // SAFETY: as in `read16`.
            Register::Memory(a) => unsafe {
                (crate::mmu::virt(a as usize) as *mut u16).write_volatile(value)
            },
        }
    }

    fn write8(self, value: u8) {
        match self {
            Register::Port(p) => crate::arch::out8(p, value),
            // SAFETY: as in `read16`.
            Register::Memory(a) => unsafe { (crate::mmu::virt(a as usize) as *mut u8).write_volatile(value) },
        }
    }
}

/// What the FADT ("FACP") says about power: how to turn the machine off,
/// restart it, and hear its power button. Every laptop's firmware has one.
#[derive(Clone, Copy, Debug)]
pub struct Power {
    /// The ACPI interrupt (SCI), an ISA IRQ number.
    pub sci: u16,
    /// Where to ask the firmware for ACPI mode, and the value to write.
    smi_command: u16,
    acpi_enable: u8,
    /// PM1's event blocks (status, then enable, each half of `event_len`)
    /// and control blocks; b is often absent.
    event: [Option<Register>; 2],
    event_len: u8,
    control: [Option<Register>; 2],
    /// The general-purpose event blocks (status, then enable, each half of
    /// its length): all turned off at boot, then on one by one for what
    /// answers them ([`gpe_enable`]: the embedded controller's, the
    /// firmware's `_Lxx`/`_Exx` methods).
    gpe: [(Option<Register>, u8); 2],
    /// The number of GPE1's first event.
    gpe1_base: u8,
    /// A hardware-reduced machine (no PM1 blocks): its sleep control
    /// register instead.
    reduced: bool,
    sleep_control: Option<Register>,
    /// The reset register and what to write to it.
    reset: Option<(Register, u8)>,
    /// The power button is a control method's (its press a Notify from
    /// AML, not PM1's fixed event).
    pub button_by_method: bool,
    /// The firmware's preferred profile: 2 is a laptop ("mobile").
    pub profile: u8,
    /// \_S5's sleep types for PM1a and PM1b, found in the DSDT.
    pub s5: Option<(u8, u8)>,
}

/// PM1 control: the sleep type (bits 10–12), sleep enable, and SCI_EN
/// (the machine in ACPI mode).
const SLP_TYP_SHIFT: u16 = 10;
const SLP_EN: u16 = 1 << 13;
const SCI_EN: u16 = 1;
/// PM1 status and enable: the power button's fixed event.
const PWRBTN: u16 = 1 << 8;

/// Reads the FADT, and \_S5 from its DSDT.
pub fn power(rsdp_given: u64) -> Option<Power> {
    let t = find(rsdp_given, b"FACP")?;
    let len = t.len();
    let u8_at = |at: usize| t.get(at).copied().unwrap_or(0);
    let u32_or = |at: usize| if at + 4 <= len { u32_at(t, at) } else { 0 };
    let port = |at: usize| {
        u16::try_from(u32_or(at))
            .ok()
            .filter(|&p| p != 0)
            .map(Register::Port)
    };
    // ACPI 2's 64-bit forms where the table has them, else the 32-bit.
    let gas = |at: usize| {
        (at + 12 <= len)
            .then(|| Register::from_gas(&t[at..at + 12]))
            .flatten()
    };
    let either = |wide: usize, narrow: usize| gas(wide).or_else(|| port(narrow));
    let flags = u32_or(112);
    let dsdt = if len >= 148 && u64_at(t, 140) != 0 {
        u64_at(t, 140)
    } else {
        u64::from(u32_or(40))
    };
    let reset = (flags & (1 << 10) != 0)
        .then(|| gas(116))
        .flatten()
        .map(|r| (r, u8_at(128)));
    Some(Power {
        sci: u16::from_le_bytes([u8_at(46), u8_at(47)]),
        smi_command: u16::try_from(u32_or(48)).unwrap_or(0),
        acpi_enable: u8_at(52),
        event: [either(148, 56), either(160, 60)],
        event_len: u8_at(88),
        control: [either(172, 64), either(184, 68)],
        gpe: [(port(80), u8_at(92)), (port(84), u8_at(93))],
        gpe1_base: u8_at(94),
        reduced: flags & (1 << 20) != 0,
        sleep_control: gas(244),
        reset,
        button_by_method: flags & (1 << 4) != 0,
        profile: u8_at(45),
        s5: table(dsdt).and_then(|d| sleep_types(&d[36..], b"_S5_")),
    })
}

/// A sleep state's package (`Name (_S5, Package () { a, b, ... })`) in
/// AML: its first two numbers, PM1a's and PM1b's sleep types. Found by its
/// name, not by running the AML: every firmware writes it as such a
/// package.
fn sleep_types(aml: &[u8], name: &[u8; 4]) -> Option<(u8, u8)> {
    const NAME_OP: u8 = 0x08;
    const PACKAGE_OP: u8 = 0x12;
    let at = (1..aml.len().saturating_sub(4)).find(|&i| {
        &aml[i..i + 4] == name
            && (aml[i - 1] == NAME_OP || (aml[i - 1] == b'\\' && i >= 2 && aml[i - 2] == NAME_OP))
    })?;
    let mut p = at + 4;
    if *aml.get(p)? != PACKAGE_OP {
        return None;
    }
    p += 1;
    // PkgLength: its first byte's top two bits say how many follow.
    p += 1 + usize::from(*aml.get(p)? >> 6);
    // The number of elements.
    p += 1;
    let mut number = || -> Option<u8> {
        let (value, size) = match *aml.get(p)? {
            // ZeroOp, OneOp, OnesOp.
            0x00 => (0, 1),
            0x01 => (1, 1),
            0xff => (0xff, 1),
            // BytePrefix, WordPrefix, DWordPrefix: the low byte is the type.
            0x0a => (*aml.get(p + 1)?, 2),
            0x0b => (*aml.get(p + 1)?, 3),
            0x0c => (*aml.get(p + 1)?, 5),
            _ => return None,
        };
        p += size;
        Some(value)
    };
    let a = number()?;
    let b = number().unwrap_or(0);
    Some((a & 7, b & 7))
}

/// The FADT once read, for the power button's interrupt and power-off.
static POWER: crate::sync::SpinLock<Option<Power>> = crate::sync::SpinLock::new(None);

/// The SCI's vector, once routed.
static SCI_VECTOR: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);

impl Power {
    fn status(&self, i: usize) -> Option<Register> {
        self.event[i]
    }

    fn enable(&self, i: usize) -> Option<Register> {
        let half = u64::from(self.event_len / 2);
        self.event[i].map(|r| match r {
            Register::Port(p) => Register::Port(p + half as u16),
            Register::Memory(a) => Register::Memory(a + half),
        })
    }

    /// Whether the machine is in ACPI mode (SCI_EN), asking the firmware
    /// for it where it is not; true on a hardware-reduced one.
    fn acpi_mode(&self) -> bool {
        let Some(control) = self.control[0] else {
            return self.reduced;
        };
        if control.read16() & SCI_EN != 0 {
            return true;
        }
        if self.smi_command == 0 || self.acpi_enable == 0 {
            return false;
        }
        crate::arch::out8(self.smi_command, self.acpi_enable);
        let deadline = crate::timer::now_ms() + 1000;
        while control.read16() & SCI_EN == 0 && crate::timer::now_ms() < deadline {
            core::hint::spin_loop();
        }
        control.read16() & SCI_EN != 0
    }
}

/// Takes the FADT: ACPI mode on, every general-purpose event off (nothing
/// here answers them: one left on would raise the SCI for ever), and the
/// power button's fixed event on, its SCI routed. What it found, for the
/// boot log.
pub fn init_power(rsdp_given: u64) -> Option<Power> {
    let power = power(rsdp_given)?;
    let acpi_mode = power.acpi_mode();
    for &(block, len) in &power.gpe {
        if let Some(Register::Port(p)) = block {
            for i in 0..u16::from(len / 2) {
                // The enable half off, then the status half cleared.
                crate::arch::out8(p + u16::from(len / 2) + i, 0);
                crate::arch::out8(p + i, 0xff);
            }
        }
    }
    let mut button = false;
    if acpi_mode && !power.reduced && power.status(0).is_some() {
        for i in 0..2 {
            if let (Some(status), Some(enable)) = (power.status(i), power.enable(i)) {
                enable.write16(0);
                status.write16(0xffff);
            }
        }
        let (gsi, trigger) = crate::ioapic::isa(power.sci as u8, crate::ioapic::SCI);
        if let Some(vector) = crate::gic::wired_interrupt(gsi, trigger) {
            SCI_VECTOR.store(vector, core::sync::atomic::Ordering::Relaxed);
            if !power.button_by_method
                && let Some(enable) = power.enable(0)
            {
                enable.write16(PWRBTN);
                button = true;
            }
        }
    }
    crate::println!(
        "acpi: {}, {}; off by {}; restart by {}; the power button {}",
        if power.profile == 2 {
            "a laptop"
        } else {
            "a computer"
        },
        if power.reduced {
            "hardware-reduced"
        } else if acpi_mode {
            "in ACPI mode"
        } else {
            "not in ACPI mode"
        },
        match power.s5 {
            Some(_) if power.reduced && power.sleep_control.is_some() => "its sleep register",
            Some(_) if power.control[0].is_some() => "\\_S5",
            _ => "nothing (no \\_S5)",
        },
        if power.reset.is_some() {
            "its reset register"
        } else {
            "the chipset"
        },
        if button {
            "heard"
        } else if power.button_by_method {
            "a control method's, not heard yet"
        } else {
            "not heard"
        }
    );
    *POWER.lock() = Some(power);
    Some(power)
}

impl Power {
    /// The status and enable ports of GPE `n`, and its bit there.
    fn gpe_ports(&self, n: u32) -> Option<(u16, u16, u8)> {
        let in_block = |(block, len): (Option<Register>, u8), first: u32| {
            let Some(Register::Port(p)) = block else {
                return None;
            };
            let half = u32::from(len / 2);
            let i = n.checked_sub(first)?;
            (i < half * 8).then(|| (p + (i / 8) as u16, p + (half + i / 8) as u16, (i % 8) as u8))
        };
        in_block(self.gpe[0], 0).or_else(|| in_block(self.gpe[1], u32::from(self.gpe1_base)))
    }

    /// How many GPEs the blocks hold, numbered from 0 (GPE1's from its
    /// base).
    fn gpe_count(&self) -> u32 {
        let (_, len1) = self.gpe[1];
        if self.gpe[1].0.is_some() && len1 > 0 {
            u32::from(self.gpe1_base) + u32::from(len1 / 2) * 8
        } else {
            u32::from(self.gpe[0].1 / 2) * 8
        }
    }
}

/// The GPEs turned on, by number: bit `n % 64` of word `n / 64`.
static GPE_ON: [core::sync::atomic::AtomicU64; 4] = [const { core::sync::atomic::AtomicU64::new(0) }; 4];
/// The GPEs that fired and wait for [`GPE_HANDLER`]: turned off until
/// it has run their method.
static GPE_FIRED: [core::sync::atomic::AtomicU64; 4] = [const { core::sync::atomic::AtomicU64::new(0) }; 4];
/// What runs a fired GPE's method: woken from the SCI, as AML cannot run
/// in an interrupt.
pub static GPE_HANDLER: crate::sync::SpinLock<Option<fn()>> = crate::sync::SpinLock::new(None);

/// How many GPEs there are (0 with no FADT).
pub fn gpe_count() -> u32 {
    POWER.lock().map_or(0, |p| p.gpe_count().min(256))
}

/// Turns GPE `n` on or off. False when there is no such GPE.
pub fn gpe_enable(n: u32, on: bool) -> bool {
    let Some(power) = *POWER.lock() else { return false };
    let Some((status, enable, bit)) = power.gpe_ports(n) else {
        return false;
    };
    let word = &GPE_ON[(n / 64) as usize % 4];
    if on {
        word.fetch_or(1 << (n % 64), core::sync::atomic::Ordering::Relaxed);
        crate::arch::out8(status, 1 << bit);
        crate::arch::out8(enable, crate::arch::in8(enable) | 1 << bit);
    } else {
        word.fetch_and(!(1 << (n % 64)), core::sync::atomic::Ordering::Relaxed);
        crate::arch::out8(enable, crate::arch::in8(enable) & !(1 << bit));
    }
    true
}

/// Clears GPE `n`'s status (a level one, after its method quieted its
/// source).
pub fn gpe_clear(n: u32) {
    if let Some((status, _, bit)) = POWER.lock().and_then(|p| p.gpe_ports(n)) {
        crate::arch::out8(status, 1 << bit);
    }
}

/// The GPEs that fired since last asked, each turned off until
/// [`gpe_enable`] turns it on again.
pub fn gpe_take_fired() -> Vec<u32> {
    let mut fired = Vec::new();
    for (w, word) in GPE_FIRED.iter().enumerate() {
        let bits = word.swap(0, core::sync::atomic::Ordering::Relaxed);
        fired.extend(
            (0..64)
                .filter(|b| bits >> b & 1 != 0)
                .map(|b| (w * 64 + b) as u32),
        );
    }
    fired
}

/// The SCI. False when `vector` is not its. The power button pressed:
/// the system turns off, as Settings' restart restarts it. A GPE turned
/// on that fired: turned off, noted, and its handler woken.
pub fn interrupt(vector: u32) -> bool {
    if vector != SCI_VECTOR.load(core::sync::atomic::Ordering::Relaxed) || vector == 0 {
        return false;
    }
    let Some(power) = *POWER.lock() else { return true };
    let mut any = false;
    for (w, word) in GPE_ON.iter().enumerate() {
        let on = word.load(core::sync::atomic::Ordering::Relaxed);
        for b in (0..64).filter(|b| on >> b & 1 != 0) {
            let n = (w * 64 + b) as u32;
            let Some((status, enable, bit)) = power.gpe_ports(n) else {
                continue;
            };
            if crate::arch::in8(status) & (1 << bit) != 0 {
                crate::arch::out8(enable, crate::arch::in8(enable) & !(1 << bit));
                word.fetch_and(!(1 << b), core::sync::atomic::Ordering::Relaxed);
                GPE_FIRED[w].fetch_or(1 << b, core::sync::atomic::Ordering::Relaxed);
                any = true;
            }
        }
    }
    if any && let Some(handler) = *GPE_HANDLER.lock() {
        handler();
    }
    let mut pressed = false;
    for i in 0..2 {
        if let Some(status) = power.status(i) {
            let s = status.read16();
            pressed |= s & PWRBTN != 0;
            // Each set bit is cleared by writing it.
            if s != 0 {
                status.write16(s);
            }
        }
    }
    if pressed {
        crate::println!("acpi: the power button");
        crate::chain::power_off();
    }
    true
}

/// Turns the machine off by ACPI (S5): returns only if it cannot.
pub fn power_off() {
    let Some(power) = *POWER.lock() else { return };
    let Some((a, b)) = power.s5 else { return };
    let _masked = crate::irq::Masked::new();
    if power.reduced {
        if let Some(control) = power.sleep_control {
            // SLP_TYPx in bits 2–4, SLP_EN bit 5.
            control.write8((a << 2) | (1 << 5));
        }
    } else {
        for (control, kind) in power.control.iter().zip([a, b]) {
            if let Some(control) = control {
                let value = control.read16() & !(7 << SLP_TYP_SHIFT);
                control.write16(value | u16::from(kind) << SLP_TYP_SHIFT | SLP_EN);
            }
        }
    }
    // The machine takes a moment to go.
    let deadline = crate::timer::now_ms() + 1000;
    while crate::timer::now_ms() < deadline {
        core::hint::spin_loop();
    }
}

/// Restarts the machine by the FADT's reset register: returns only if it
/// cannot (none, or it did nothing).
pub fn restart() {
    let Some(power) = *POWER.lock() else { return };
    let Some((register, value)) = power.reset else {
        return;
    };
    register.write8(value);
    let deadline = crate::timer::now_ms() + 500;
    while crate::timer::now_ms() < deadline {
        core::hint::spin_loop();
    }
}