garage44.eu/jeroen/pinnacle

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

.. /aml/src/lib.rs

raw

//! ACPI Machine Language (ACPI 6.5, chapters 19 and 20), loaded and run,
//! with no outside crate: how a PC's firmware says what a laptop has that
//! no bus enumerates. The battery (`_BIF`/`_BIX`, `_BST`), the lid
//! (`_LID`), the touchpad's I²C address and interrupt (`_CRS`), whether a
//! device is there at all (`_STA`) are methods in the DSDT and SSDTs, run
//! against the hardware through operation regions.
//!
//! [`Namespace::load`] runs a table's top level: every object it declares
//! (devices, names, methods, regions, fields) goes into the namespace, and
//! a method's body is kept as bytes, parsed only when it runs, once every
//! table is in (a method's argument count is known only from its
//! declaration, and a call may come before it). [`Namespace::evaluate`]
//! runs a method or reads an object. The hardware is reached only through
//! a [`Host`]: the interpreter itself touches nothing.
//!
//! Firmware is trusted to mean well and not to be right: every read is
//! bounded, a loop runs at most [`MAX_LOOPS`] times, calls nest at most
//! [`MAX_DEPTH`] deep, and a statement that fails while a table loads
//! loses its own scope, not the table.

#![no_std]

extern crate alloc;

pub mod asm;
pub mod battery;
mod interp;
mod namespace;
pub mod resource;

pub use namespace::{Namespace, Object, Path};

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

/// How deep method calls may nest.
pub const MAX_DEPTH: usize = 64;
/// How many times one `While` may go round: firmware polling hardware
/// that is not there must not hang the kernel.
pub const MAX_LOOPS: u64 = 1_000_000;

/// An address space an operation region is in (ACPI 6.5, 19.6.100).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Space {
    Memory,
    Io,
    /// The address is `segment << 32 | bus << 20 | device << 15 |
    /// function << 12 | offset`, as ECAM lays it out.
    PciConfig,
    /// A byte of the embedded controller's space.
    EmbeddedControl,
    SmBus,
    Cmos,
    PciBar,
    Ipmi,
    Gpio,
    SerialBus,
    Pcc,
    Other(u8),
}

impl Space {
    pub fn from_byte(b: u8) -> Space {
        match b {
            0 => Space::Memory,
            1 => Space::Io,
            2 => Space::PciConfig,
            3 => Space::EmbeddedControl,
            4 => Space::SmBus,
            5 => Space::Cmos,
            6 => Space::PciBar,
            7 => Space::Ipmi,
            8 => Space::Gpio,
            9 => Space::SerialBus,
            10 => Space::Pcc,
            b => Space::Other(b),
        }
    }

    pub fn number(self) -> u8 {
        match self {
            Space::Memory => 0,
            Space::Io => 1,
            Space::PciConfig => 2,
            Space::EmbeddedControl => 3,
            Space::SmBus => 4,
            Space::Cmos => 5,
            Space::PciBar => 6,
            Space::Ipmi => 7,
            Space::Gpio => 8,
            Space::SerialBus => 9,
            Space::Pcc => 10,
            Space::Other(b) => b,
        }
    }
}

/// What the interpreter asks of the machine it runs on.
pub trait Host {
    /// Reads `bits` (8, 16, 32 or 64) at `address` in `space`.
    fn read(&mut self, space: Space, address: u64, bits: u8) -> u64;
    /// Writes `bits` of `value` at `address` in `space`.
    fn write(&mut self, space: Space, address: u64, bits: u8, value: u64);
    /// `Sleep`: the caller may be descheduled.
    fn sleep(&mut self, _ms: u64) {}
    /// `Stall`: a busy wait.
    fn stall(&mut self, _us: u64) {}
    /// `Timer`: a count of 100 ns that only goes up.
    fn timer(&mut self) -> u64 {
        0
    }
    /// `Notify(object, value)`: the firmware telling the system something
    /// changed (0x80 on a battery: its status).
    fn notify(&mut self, _object: &Path, _value: u64) {}
    /// What was stored to the `Debug` object.
    fn debug(&mut self, _value: &Value) {}
    /// `_OSI("…")`: whether the system says it is that one. Firmware
    /// tested against Windows switches its devices on for the Windows it
    /// knows, so the default answers yes to every Windows, as Linux does.
    fn osi(&mut self, name: &str) -> bool {
        name.starts_with("Windows ") || name == "Module Device" || name == "3.0 Thermal Model"
    }
}

/// An AML value.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// Uninitialised: a local not yet stored to, a package's missing tail.
    None,
    Integer(u64),
    String(String),
    Buffer(Vec<u8>),
    Package(Vec<Value>),
    /// A reference: `RefOf`, `Index`, a name in a package.
    Reference(Box<Ref>),
}

impl Value {
    pub fn integer(&self) -> Option<u64> {
        match self {
            Value::Integer(v) => Some(*v),
            Value::Buffer(b) => Some(
                b.iter()
                    .take(8)
                    .enumerate()
                    .fold(0, |v, (i, &x)| v | u64::from(x) << (8 * i)),
            ),
            _ => None,
        }
    }

    pub fn str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn buffer(&self) -> Option<&[u8]> {
        match self {
            Value::Buffer(b) => Some(b),
            _ => None,
        }
    }

    pub fn package(&self) -> Option<&[Value]> {
        match self {
            Value::Package(p) => Some(p),
            _ => None,
        }
    }

    /// `ObjectType`'s number for a value.
    fn type_number(&self) -> u64 {
        match self {
            Value::None => 0,
            Value::Integer(_) => 1,
            Value::String(_) => 2,
            Value::Buffer(_) => 3,
            Value::Package(_) => 4,
            Value::Reference(_) => 20,
        }
    }
}

/// Where a value is, as a target or a reference.
#[derive(Clone, Debug, PartialEq)]
pub enum Ref {
    /// No target (`NullName`): the result is dropped.
    None,
    Name(Path),
    /// A local or an argument of the method running.
    Local(u8),
    Arg(u8),
    Debug,
    /// An element of what another reference names (`Index`).
    Element(Box<Ref>, usize),
    /// An element of a value with no place of its own: read only.
    Temporary(Box<Value>, usize),
}

/// Why loading or running stopped.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// The code ended inside something, at this offset.
    Truncated(usize),
    /// An opcode the interpreter does not know, at this offset.
    Opcode(u16, usize),
    /// A name that is not in the namespace.
    Name(String),
    /// A value of the wrong type for what was asked of it.
    Type(&'static str),
    DivideByZero,
    /// Calls nested deeper than [`MAX_DEPTH`].
    Depth,
    /// A `While` went round [`MAX_LOOPS`] times.
    Loop,
    /// The firmware's own `Fatal`.
    Fatal(u8, u32),
    /// A table that is not a DSDT or SSDT, or whose checksum fails.
    Table,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::Truncated(at) => write!(f, "the code ends early, at {at:#x}"),
            Error::Opcode(op, at) => write!(f, "opcode {op:#x} unknown, at {at:#x}"),
            Error::Name(n) => write!(f, "no {n} in the namespace"),
            Error::Type(what) => write!(f, "{what}"),
            Error::DivideByZero => write!(f, "a division by zero"),
            Error::Depth => write!(f, "calls nested too deep"),
            Error::Loop => write!(f, "a loop that did not end"),
            Error::Fatal(kind, code) => write!(f, "the firmware's Fatal({kind:#x}, {code:#x})"),
            Error::Table => write!(f, "not a DSDT or SSDT, or its checksum fails"),
        }
    }
}

/// An EISA ID as `_HID` compresses it (`PNP0C0A`).
pub fn eisa_id(v: u64) -> String {
    let id = (v as u32).swap_bytes();
    let mut s = String::new();
    for shift in [26, 21, 16] {
        s.push(char::from(((id >> shift) & 0x1f) as u8 + 0x40));
    }
    for shift in [12, 8, 4, 0] {
        s.push(
            char::from_digit((id >> shift) & 0xf, 16)
                .unwrap()
                .to_ascii_uppercase(),
        );
    }
    s
}

#[cfg(test)]
mod tests;