garage44.eu/jeroen/pinnacle

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

.. /aml/src/namespace.rs

raw

//! The namespace: every object the tables declared, by its absolute path,
//! and what a system asks of it.

use crate::interp::Machine;
use crate::{Error, Host, Ref, Value, resource};
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;

/// An absolute path: its 4-byte segments from the root (`\_SB_.PCI0`).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct Path(pub Vec<[u8; 4]>);

impl Path {
    pub fn root() -> Path {
        Path(Vec::new())
    }

    /// A path as people write it, from the root: `\_SB.BAT0._BST`, each
    /// segment padded with `_` to four.
    pub fn parse(text: &str) -> Path {
        let text = text.trim_start_matches('\\');
        Path(
            text.split('.')
                .filter(|s| !s.is_empty())
                .map(|s| {
                    let mut seg = [b'_'; 4];
                    for (i, b) in s.bytes().take(4).enumerate() {
                        seg[i] = b;
                    }
                    seg
                })
                .collect(),
        )
    }

    pub fn child(&self, seg: [u8; 4]) -> Path {
        let mut p = self.0.clone();
        p.push(seg);
        Path(p)
    }

    /// One level up; the root's parent is the root.
    pub fn parent(&self) -> Path {
        let mut p = self.0.clone();
        p.pop();
        Path(p)
    }

    /// Its last segment.
    pub fn last(&self) -> Option<[u8; 4]> {
        self.0.last().copied()
    }

    pub fn starts_with(&self, other: &Path) -> bool {
        self.0.starts_with(&other.0)
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("\\")?;
        for (i, seg) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_str(".")?;
            }
            let mut len = 4;
            while len > 1 && seg[len - 1] == b'_' {
                len -= 1;
            }
            for &b in &seg[..len] {
                write!(f, "{}", char::from(b))?;
            }
        }
        Ok(())
    }
}

impl fmt::Debug for Path {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

/// A field's place: a region, a register reached through an index and a
/// data field, or a bank of a region chosen by a bank field.
#[derive(Clone, Debug)]
pub enum FieldPlace {
    Region(Path),
    Index { index: Path, data: Path },
    Bank { region: Path, bank: Path, value: u64 },
}

/// A field unit: bits of an operation region.
#[derive(Clone, Debug)]
pub struct Field {
    pub place: FieldPlace,
    pub bit: u64,
    pub bits: u64,
    /// Bytes read or written at once.
    pub access: u8,
    /// 0: preserve the bits around it, 1: write them as ones, 2: as zeros.
    pub update: u8,
    /// A GPIO or serial bus field's `Connection`, as its resource.
    pub connection: Option<Vec<u8>>,
}

/// An object in the namespace.
#[derive(Clone, Debug)]
pub enum Object {
    /// A scope with nothing of its own (`\_SB`, a `Scope` opened on a path
    /// no table declared).
    Scope,
    Device,
    Processor,
    PowerResource,
    ThermalZone,
    Name(Value),
    Method {
        table: usize,
        start: usize,
        end: usize,
        args: u8,
    },
    /// A method the interpreter answers itself (`\_OSI`).
    Native(Native),
    Region {
        space: u8,
        offset: u64,
        len: u64,
    },
    Field(Field),
    /// Bits of a buffer (`CreateDWordField` and its kin).
    BufferField {
        source: Ref,
        bit: u64,
        bits: u64,
    },
    Mutex,
    Event,
    Alias(Path),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Native {
    Osi,
}

impl Object {
    /// `ObjectType`'s number.
    pub fn type_number(&self) -> u64 {
        match self {
            Object::Scope => 0,
            Object::Name(v) => v.type_number(),
            Object::Field(_) => 5,
            Object::Device => 6,
            Object::Event => 7,
            Object::Method { .. } | Object::Native(_) => 8,
            Object::Mutex => 9,
            Object::Region { .. } => 10,
            Object::PowerResource => 11,
            Object::Processor => 12,
            Object::ThermalZone => 13,
            Object::BufferField { .. } => 14,
            Object::Alias(_) => 0,
        }
    }
}

/// Every object the tables declared, and the tables' code.
pub struct Namespace {
    pub(crate) objects: BTreeMap<Path, Object>,
    pub(crate) tables: Vec<Arc<[u8]>>,
    /// Integers are 64 bits from a DSDT of revision 2 on, else 32.
    pub(crate) wide: bool,
    /// What went wrong while loading, statement by statement.
    pub errors: Vec<(Path, Error)>,
}

impl Default for Namespace {
    fn default() -> Self {
        Self::new()
    }
}

impl Namespace {
    /// The predefined scopes and objects (ACPI 6.5, 5.3.1 and 5.7).
    pub fn new() -> Namespace {
        let mut objects = BTreeMap::new();
        objects.insert(Path::root(), Object::Scope);
        for scope in ["_GPE", "_PR", "_SB", "_SI", "_TZ"] {
            objects.insert(Path::parse(scope), Object::Scope);
        }
        objects.insert(Path::parse("_OSI"), Object::Native(Native::Osi));
        objects.insert(
            Path::parse("_OS"),
            Object::Name(Value::String("Microsoft Windows NT".into())),
        );
        objects.insert(Path::parse("_REV"), Object::Name(Value::Integer(2)));
        objects.insert(Path::parse("_GL"), Object::Mutex);
        Namespace {
            objects,
            tables: Vec::new(),
            wide: true,
            errors: Vec::new(),
        }
    }

    /// Loads a DSDT or SSDT, its header included: runs its top level.
    pub fn load(&mut self, table: &[u8], host: &mut dyn Host) -> Result<(), Error> {
        if table.len() < 36
            || !(table.starts_with(b"DSDT") || table.starts_with(b"SSDT"))
            || u32::from_le_bytes(table[4..8].try_into().unwrap()) as usize != table.len()
            || table.iter().fold(0u8, |s, &b| s.wrapping_add(b)) != 0
        {
            return Err(Error::Table);
        }
        if table.starts_with(b"DSDT") {
            self.wide = table[8] >= 2;
        }
        self.tables.push(Arc::from(table));
        let index = self.tables.len() - 1;
        Machine::new(self, host).load(index)
    }

    pub fn get(&self, path: &Path) -> Option<&Object> {
        self.objects.get(path)
    }

    /// Runs the method at `path` with `args`, or reads the object there.
    pub fn evaluate(&mut self, path: &Path, args: Vec<Value>, host: &mut dyn Host) -> Result<Value, Error> {
        Machine::new(self, host).evaluate(path, args)
    }

    /// The object at `path` if it is there: `None` for a method a device
    /// does not have, an error for one that failed.
    pub fn evaluate_if(
        &mut self,
        path: &Path,
        args: Vec<Value>,
        host: &mut dyn Host,
    ) -> Option<Result<Value, Error>> {
        self.objects
            .contains_key(path)
            .then(|| self.evaluate(path, args, host))
    }

    /// The objects one level under `path`.
    pub fn children(&self, path: &Path) -> Vec<Path> {
        self.objects
            .range(path.clone()..)
            .take_while(|(p, _)| p.starts_with(path))
            .filter(|(p, _)| p.0.len() == path.0.len() + 1)
            .map(|(p, _)| p.clone())
            .collect()
    }

    /// Every device, in namespace order.
    pub fn devices(&self) -> Vec<Path> {
        self.objects
            .iter()
            .filter(|(_, o)| matches!(o, Object::Device))
            .map(|(p, _)| p.clone())
            .collect()
    }

    /// A device's hardware ID and compatible IDs (`_HID`, `_CID`), as
    /// strings: `PNP0C0A`, `ACPI0003`, `PNP0C50`.
    pub fn ids(&mut self, device: &Path, host: &mut dyn Host) -> Vec<String> {
        let mut ids = Vec::new();
        let id = |v: &Value| match v {
            Value::Integer(i) => Some(crate::eisa_id(*i)),
            Value::String(s) => Some(s.clone()),
            _ => None,
        };
        if let Some(Ok(v)) = self.evaluate_if(&device.child(*b"_HID"), Vec::new(), host) {
            ids.extend(id(&v));
        }
        match self.evaluate_if(&device.child(*b"_CID"), Vec::new(), host) {
            Some(Ok(Value::Package(p))) => ids.extend(p.iter().filter_map(id)),
            Some(Ok(v)) => ids.extend(id(&v)),
            _ => {}
        }
        ids
    }

    /// Every device answering to `id` as its `_HID` or a `_CID`.
    pub fn find(&mut self, id: &str, host: &mut dyn Host) -> Vec<Path> {
        self.devices()
            .into_iter()
            .filter(|d| self.ids(d, host).iter().any(|i| i == id))
            .collect()
    }

    /// A device's `_STA`: present, enabled, shown, working, a battery in
    /// its bay (bits 0 to 4); 0xf where it has none.
    pub fn status(&mut self, device: &Path, host: &mut dyn Host) -> u64 {
        match self.evaluate_if(&device.child(*b"_STA"), Vec::new(), host) {
            Some(Ok(v)) => v.integer().unwrap_or(0),
            Some(Err(_)) => 0,
            None => 0xf,
        }
    }

    /// A device's current resources (`_CRS`).
    pub fn resources(&mut self, device: &Path, host: &mut dyn Host) -> Option<Vec<resource::Resource>> {
        match self.evaluate_if(&device.child(*b"_CRS"), Vec::new(), host)? {
            Ok(Value::Buffer(b)) => Some(resource::parse(&b)),
            _ => None,
        }
    }

    /// What a system does once every table is in (ACPI 6.5, 6.5.1): `_REG`
    /// for the spaces always there (memory, I/O, PCI configuration),
    /// `\_SB._INI`, then each present device's `_INI`, parents first.
    /// Errors are kept in [`Namespace::errors`], not returned: one device's
    /// firmware failing leaves the rest.
    pub fn initialize(&mut self, host: &mut dyn Host) {
        for space in [0, 1, 2] {
            self.connect(space, host);
        }
        let ini = Path::parse("_SB._INI");
        if let Some(Err(e)) = self.evaluate_if(&ini, Vec::new(), host) {
            self.errors.push((ini, e));
        }
        let mut absent: Vec<Path> = Vec::new();
        for device in self.devices() {
            if absent.iter().any(|a| device.starts_with(a)) {
                continue;
            }
            let sta = self.status(&device, host);
            if sta & 1 == 0 && sta & 8 == 0 {
                absent.push(device);
                continue;
            }
            let path = device.child(*b"_INI");
            if let Some(Err(e)) = self.evaluate_if(&path, Vec::new(), host) {
                self.errors.push((path, e));
            }
        }
    }

    /// Tells the firmware a space's handler is there: `_REG(space, 1)` on
    /// every device with a region in that space and a `_REG` (an embedded
    /// controller's methods read its space only once told).
    pub fn connect(&mut self, space: u8, host: &mut dyn Host) {
        let regs: Vec<Path> = self
            .objects
            .keys()
            .filter(|p| p.last() == Some(*b"_REG"))
            .filter(|p| {
                self.children(&p.parent()).iter().any(
                    |c| matches!(self.objects.get(c), Some(Object::Region { space: s, .. }) if *s == space),
                )
            })
            .cloned()
            .collect();
        for path in regs {
            let args = alloc::vec![Value::Integer(space.into()), Value::Integer(1)];
            if let Err(e) = self.evaluate(&path, args, host) {
                self.errors.push((path, e));
            }
        }
    }
}