git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T13:51:12Z
feat(kernel): a laptop's battery, charger and lid from its firmware The DSDT and SSDTs are loaded at boot and run (_REG, _INI); the embedded controller is found from AML (PNP0C09: ports from _CRS, GPE from _GPE) and drives AML's EmbeddedControl regions. GPEs are turned on for what answers them (the EC, \_GPE._Lxx/_Exx) and their methods run in a kernel task, never in the SCI. The battery (_BIX/_BIF, _BST), charger (_PSR) and lid (_LID) are asked live by a new system call, power (71, reserved at the hub), as key=value lines; rt::power parses them. A lid or charger change, or a battery's Notify, reaches the display server as an input event (InputEvent::POWER). cargo xtask laptop and pc on mac-2: QEMU's DSDT loads with 0 statements failed; the test SSDT's battery reads 55 %, discharging.
abi/src/lib.rs | 20 ++
kernel/Cargo.toml | 1 +
kernel/src/main.rs | 6 +
kernel/src/syscall.rs | 13 ++
kernel/src/x86_64/acpi.rs | 150 +++++++++++-
kernel/src/x86_64/power.rs | 569 +++++++++++++++++++++++++++++++++++++++++++++
rt/src/lib.rs | 61 +++++
7 files changed, 818 insertions(+), 2 deletions(-)
diff --git a/abi/src/lib.rs b/abi/src/lib.rs
index ac3e478..0cdb431 100644
--- a/abi/src/lib.rs
+++ b/abi/src/lib.rs
@@ -296,6 +296,14 @@ pub mod call {
/// serial port, its last 64 KiB, oldest first; returns the length
/// written. Not for confined or sealed programs.
pub const LOG: u64 = 70;
+ /// `power(buf, len)`: the battery, the charger and the lid as the
+ /// firmware says now, `key=value` lines into `buf`: `ac=1` (plugged
+ /// in), `lid=open` or `closed`, and a line a battery,
+ /// `battery=<n>|state=<charging, discharging, full or absent>|percent=…|minutes=…|remaining=…|full=…|design=…|unit=<mWh or mAh>|cycles=…|model=…|maker=…`
+ /// (a field the firmware does not know left out). Returns the length;
+ /// 0 on a machine with none of them. Not for confined or sealed
+ /// programs.
+ pub const POWER: u64 = 71;
}
/// Where the network is, as [`NET_SWITCH`](call::NET_SWITCH) answers.
@@ -435,6 +443,18 @@ impl InputEvent {
/// The screen's size changed to `x` × `y` (QEMU's window resized, a
/// monitor plugged in): from the kernel to the display server only.
pub const SCREEN: u16 = 4;
+ /// Something of the machine's power changed, from the kernel to the
+ /// display server only: `code` says what ([`LID`](Self::LID),
+ /// [`CHARGER`](Self::CHARGER), [`BATTERY`](Self::BATTERY)), `value` is
+ /// 1 for open or plugged in, 0 for closed or out. The rest is asked by
+ /// [`POWER`](call::POWER).
+ pub const POWER: u16 = 5;
+ /// A laptop's lid opened (1) or closed (0).
+ pub const LID: u16 = 0;
+ /// The charger plugged in (1) or out (0).
+ pub const CHARGER: u16 = 1;
+ /// The battery's status changed (its level, charging or not).
+ pub const BATTERY: u16 = 2;
/// The bit of `kind` on the wire that is [`InputEvent::synthetic`].
pub const SYNTHETIC: u16 = 0x8000;
diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml
index 68d3812..6f88653 100644
--- a/kernel/Cargo.toml
+++ b/kernel/Cargo.toml
@@ -21,6 +21,7 @@ bench = false
[dependencies]
pinnacle-crypto = { path = "../crypto" }
pinnacle-abi = { path = "../abi" }
+pinnacle-aml = { path = "../aml" }
pinnacle-disk = { path = "../disk" }
pinnacle-fs = { path = "../pfs" }
pinnacle-net = { path = "../net" }
diff --git a/kernel/src/main.rs b/kernel/src/main.rs
index 8eee881..09ffb47 100644
--- a/kernel/src/main.rs
+++ b/kernel/src/main.rs
@@ -52,6 +52,9 @@ mod mm;
mod mmu;
mod object;
mod pci;
+#[cfg(target_arch = "x86_64")]
+#[path = "x86_64/power.rs"]
+mod power;
mod process;
#[cfg(target_arch = "aarch64")]
mod profile;
@@ -167,6 +170,8 @@ extern "C" fn kmain(start_info: usize, magic: u32) -> ! {
if acpi::init_power(boot.rsdp).is_none() {
println!("acpi: no FADT: off and the power button by QEMU's means only");
}
+ // The firmware's AML: the embedded controller, battery, charger, lid.
+ power::init(boot.rsdp);
// USB before the disks: a stick is one of them.
// Not inside println!: the driver prints as it goes, and the console's
// lock is held while println!'s arguments are worked out.
@@ -255,6 +260,7 @@ extern "C" fn kmain(start_info: usize, magic: u32) -> ! {
board::power_off(0)
}
drivers::usb::watch();
+ power::watch();
let inputs = drivers::input::init();
println!("input: {inputs} devices");
drivers::screen_log::stop();
diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs
index 73ddf7c..b2c9f19 100644
--- a/kernel/src/syscall.rs
+++ b/kernel/src/syscall.rs
@@ -315,6 +315,19 @@ fn handle_call(frame: *mut Frame) -> *mut Frame {
FAILED
}
}
+ call::POWER if confined() => FAILED,
+ call::POWER => {
+ #[cfg(target_arch = "x86_64")]
+ let text = crate::power::status();
+ #[cfg(not(target_arch = "x86_64"))]
+ let text = alloc::string::String::new();
+ let len = text.len().min(a[1] as usize);
+ if write_user(a[0] as usize, &text.as_bytes()[..len]) {
+ (len as u64, 0, 0)
+ } else {
+ FAILED
+ }
+ }
call::PROCESSES | call::KILL_ID | call::LOG if confined() => FAILED,
call::PROCESSES => processes(a[0], a[1] as usize, a[2] as usize),
call::KILL_ID => kill_id(a[0]),
diff --git a/kernel/src/x86_64/acpi.rs b/kernel/src/x86_64/acpi.rs
index 794190e..5522261 100644
--- a/kernel/src/x86_64/acpi.rs
+++ b/kernel/src/x86_64/acpi.rs
@@ -80,6 +80,46 @@ fn find(rsdp_given: u64, signature: &[u8; 4]) -> Option<&'static [u8]> {
.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)> {
@@ -199,8 +239,12 @@ pub struct Power {
event_len: u8,
control: [Option<Register>; 2],
/// The general-purpose event blocks (status, then enable, each half of
- /// its length): turned off, as nothing here answers them yet.
+ /// 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,
@@ -261,6 +305,7 @@ pub fn power(rsdp_given: u64) -> Option<Power> {
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,
@@ -421,13 +466,114 @@ pub fn init_power(rsdp_given: u64) -> Option<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.
+/// 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) {
diff --git a/kernel/src/x86_64/power.rs b/kernel/src/x86_64/power.rs
new file mode 100644
index 0000000..21bf40c
--- /dev/null
+++ b/kernel/src/x86_64/power.rs
@@ -0,0 +1,569 @@
+//! A laptop's power as its firmware describes it: the DSDT and SSDTs run
+//! by `pinnacle_aml`, the embedded controller they read through (ACPI
+//! 6.5, chapter 12), and what the system is told from them: the battery
+//! (`PNP0C0A`), the charger (`ACPI0003`) and the lid (`PNP0C0D`).
+//!
+//! The firmware's methods run in a kernel task of their own
+//! ([`watching`]), never in an interrupt: the SCI only notes which GPE
+//! fired and wakes it. A lid opened or closed, a charger plugged in or
+//! out, reach the display server as input events
+//! ([`InputEvent::POWER`]); the battery's level is asked by system call
+//! ([`status`]), each time live from the firmware.
+
+use crate::sync::{Mutex, SpinLock};
+use alloc::string::String;
+use alloc::vec::Vec;
+use core::fmt::Write as _;
+use pinnacle_abi::InputEvent;
+use pinnacle_aml::battery::{Info, Status};
+use pinnacle_aml::resource::Resource;
+use pinnacle_aml::{Host, Namespace, Path, Space, Value};
+
+/// The embedded controller's two ports: data, then command and status.
+#[derive(Clone, Copy)]
+struct Ec {
+ data: u16,
+ command: u16,
+}
+
+const EC_OBF: u8 = 1;
+const EC_IBF: u8 = 1 << 1;
+const EC_SCI_EVT: u8 = 1 << 5;
+const EC_READ: u8 = 0x80;
+const EC_WRITE: u8 = 0x81;
+const EC_QUERY: u8 = 0x84;
+
+impl Ec {
+ /// Waits for `ready` of the status byte, at most 50 ms: an EC that
+ /// does not answer leaves AML reading 0, not the kernel stuck.
+ fn wait(&self, ready: impl Fn(u8) -> bool) -> bool {
+ let deadline = crate::timer::now_ms() + 50;
+ loop {
+ if ready(crate::arch::in8(self.command)) {
+ return true;
+ }
+ if crate::timer::now_ms() > deadline {
+ return false;
+ }
+ core::hint::spin_loop();
+ }
+ }
+
+ fn send(&self, port: u16, byte: u8) -> bool {
+ self.wait(|s| s & EC_IBF == 0) && {
+ crate::arch::out8(port, byte);
+ true
+ }
+ }
+
+ fn receive(&self) -> Option<u8> {
+ self.wait(|s| s & EC_OBF != 0)
+ .then(|| crate::arch::in8(self.data))
+ }
+
+ fn read(&self, address: u8) -> u8 {
+ let _one = EC_LOCK.lock();
+ if self.send(self.command, EC_READ) && self.send(self.data, address) {
+ self.receive().unwrap_or(0)
+ } else {
+ 0
+ }
+ }
+
+ fn write(&self, address: u8, value: u8) {
+ let _one = EC_LOCK.lock();
+ let _ =
+ self.send(self.command, EC_WRITE) && self.send(self.data, address) && self.send(self.data, value);
+ }
+
+ /// The next event the EC has queued for its `_Qxx` method; None when
+ /// it has none (0).
+ fn query(&self) -> Option<u8> {
+ let _one = EC_LOCK.lock();
+ if crate::arch::in8(self.command) & EC_SCI_EVT == 0 && !self.send(self.command, EC_QUERY) {
+ return None;
+ }
+ if crate::arch::in8(self.command) & EC_SCI_EVT != 0 && !self.send(self.command, EC_QUERY) {
+ return None;
+ }
+ self.receive().filter(|&q| q != 0)
+ }
+}
+
+/// One EC transaction at a time (a spin lock: AML's reads are short and
+/// may come from any task).
+static EC_LOCK: SpinLock<()> = SpinLock::new(());
+static EC: SpinLock<Option<Ec>> = SpinLock::new(None);
+/// What the firmware notified, for [`watching`] to act on.
+static NOTIFIED: SpinLock<Vec<(Path, u64)>> = SpinLock::new(Vec::new());
+/// The watching task, to wake.
+static WATCHER: SpinLock<Option<usize>> = SpinLock::new(None);
+
+/// The machine, as AML reaches it.
+struct Machine {
+ /// Each PCI segment's configuration space: base, first and last bus.
+ ecam: Vec<(u64, u8, u8)>,
+}
+
+impl Host for Machine {
+ fn read(&mut self, space: Space, address: u64, bits: u8) -> u64 {
+ match space {
+ Space::Memory => memory(address, bits, None),
+ Space::Io => match bits {
+ 8 => u64::from(crate::arch::in8(address as u16)),
+ 16 => u64::from(crate::arch::in16(address as u16)),
+ _ => u64::from(crate::arch::in32(address as u16)),
+ },
+ Space::PciConfig => self.config(address).map_or(u64::MAX, |a| memory(a, bits, None)),
+ Space::EmbeddedControl => match *EC.lock() {
+ Some(ec) => (0..u64::from(bits / 8))
+ .fold(0, |v, i| v | u64::from(ec.read((address + i) as u8)) << (8 * i)),
+ None => 0,
+ },
+ Space::Cmos => {
+ crate::arch::out8(0x70, address as u8 & 0x7f);
+ u64::from(crate::arch::in8(0x71))
+ }
+ _ => 0,
+ }
+ }
+
+ fn write(&mut self, space: Space, address: u64, bits: u8, value: u64) {
+ match space {
+ Space::Memory => {
+ memory(address, bits, Some(value));
+ }
+ Space::Io => match bits {
+ 8 => crate::arch::out8(address as u16, value as u8),
+ 16 => crate::arch::out16(address as u16, value as u16),
+ _ => crate::arch::out32(address as u16, value as u32),
+ },
+ Space::PciConfig => {
+ if let Some(a) = self.config(address) {
+ memory(a, bits, Some(value));
+ }
+ }
+ Space::EmbeddedControl => {
+ if let Some(ec) = *EC.lock() {
+ for i in 0..u64::from(bits / 8) {
+ ec.write((address + i) as u8, (value >> (8 * i)) as u8);
+ }
+ }
+ }
+ Space::Cmos => {
+ crate::arch::out8(0x70, address as u8 & 0x7f);
+ crate::arch::out8(0x71, value as u8);
+ }
+ _ => {}
+ }
+ }
+
+ fn sleep(&mut self, ms: u64) {
+ self.stall(ms * 1000);
+ }
+
+ fn stall(&mut self, us: u64) {
+ crate::apic::wait_us(us.min(1_000_000));
+ }
+
+ fn timer(&mut self) -> u64 {
+ let hz = crate::timer::frequency().max(1);
+ (u128::from(crate::arch::tsc()) * 10_000_000 / u128::from(hz)) as u64
+ }
+
+ fn notify(&mut self, object: &Path, value: u64) {
+ NOTIFIED.lock().push((object.clone(), value));
+ if let Some(id) = *WATCHER.lock() {
+ crate::sched::wake(id);
+ }
+ }
+}
+
+impl Machine {
+ /// AML's PCI address (segment, bus, device, function, offset) in the
+ /// direct map.
+ fn config(&self, address: u64) -> Option<u64> {
+ let bus = (address >> 20 & 0xff) as u8;
+ let (base, _, _) = self
+ .ecam
+ .iter()
+ .find(|&&(_, first, last)| (first..=last).contains(&bus))?;
+ Some(base + (address & 0x0fff_ffff))
+ }
+}
+
+/// Reads, or writes with `value`, `bits` at physical `address` (in the
+/// direct map: uncached where it is not RAM).
+fn memory(address: u64, bits: u8, value: Option<u64>) -> u64 {
+ let at = crate::mmu::virt(address as usize);
+ // SAFETY: an address the firmware's own tables name for its device
+ // registers; a stray one reads what is there, as on any OS that runs
+ // AML.
+ unsafe {
+ match (bits, value) {
+ (8, None) => u64::from((at as *const u8).read_volatile()),
+ (16, None) => u64::from((at as *const u16).read_volatile()),
+ (32, None) => u64::from((at as *const u32).read_volatile()),
+ (_, None) => (at as *const u64).read_volatile(),
+ (8, Some(v)) => {
+ (at as *mut u8).write_volatile(v as u8);
+ 0
+ }
+ (16, Some(v)) => {
+ (at as *mut u16).write_volatile(v as u16);
+ 0
+ }
+ (32, Some(v)) => {
+ (at as *mut u32).write_volatile(v as u32);
+ 0
+ }
+ (_, Some(v)) => {
+ (at as *mut u64).write_volatile(v);
+ 0
+ }
+ }
+ }
+}
+
+/// What the firmware describes, once loaded.
+struct Firmware {
+ ns: Namespace,
+ host: Machine,
+ batteries: Vec<Path>,
+ chargers: Vec<Path>,
+ lids: Vec<Path>,
+ /// The EC's device and its GPE.
+ ec: Option<(Path, u32)>,
+ /// GPEs with a method of the firmware's (`\_GPE._Lxx`, `_Exx`): its
+ /// number, and whether it is level-triggered.
+ gpes: Vec<(u32, bool)>,
+}
+
+static FIRMWARE: Mutex<Option<Firmware>> = Mutex::new(None);
+
+/// Loads the firmware's AML, finds the embedded controller and the power
+/// devices. Says on the boot log what it found.
+pub fn init(rsdp: u64) {
+ let mut host = Machine {
+ ecam: crate::acpi::mcfg(rsdp),
+ };
+ let mut ns = Namespace::new();
+ let tables = crate::acpi::aml_tables(rsdp);
+ let mut failed = 0;
+ for t in &tables {
+ if ns.load(t, &mut host).is_err() {
+ failed += 1;
+ }
+ }
+ crate::println!(
+ "aml: {} tables, {} objects, {} statements failed{}",
+ tables.len(),
+ ns.devices().len(),
+ ns.errors.len() + failed,
+ match ns.errors.first() {
+ Some((path, e)) => alloc::format!(" (first: {path}: {e})"),
+ None => String::new(),
+ }
+ );
+ ns.initialize(&mut host);
+
+ // The embedded controller: its ports from _CRS (data, then command),
+ // its GPE from _GPE; told to the firmware by _REG.
+ let mut ec = None;
+ for device in ns.find("PNP0C09", &mut host) {
+ if ns.status(&device, &mut host) & 1 == 0 {
+ continue;
+ }
+ let ports: Vec<u16> = ns
+ .resources(&device, &mut host)
+ .unwrap_or_default()
+ .iter()
+ .filter_map(|r| match r {
+ Resource::Io { min, .. } => Some(*min),
+ Resource::FixedIo { base, .. } => Some(*base),
+ _ => None,
+ })
+ .collect();
+ let gpe = match ns.evaluate_if(&device.child(*b"_GPE"), Vec::new(), &mut host) {
+ Some(Ok(v)) => v.integer(),
+ _ => None,
+ };
+ if let ([data, command, ..], Some(gpe)) = (ports.as_slice(), gpe) {
+ *EC.lock() = Some(Ec {
+ data: *data,
+ command: *command,
+ });
+ crate::println!("aml: embedded controller {device}, ports {data:#x}/{command:#x}, GPE {gpe:#x}");
+ ec = Some((device, gpe as u32));
+ ns.connect(3, &mut host);
+ break;
+ }
+ }
+
+ let present = |ns: &mut Namespace, host: &mut Machine, id: &str| -> Vec<Path> {
+ ns.find(id, host)
+ .into_iter()
+ .filter(|d| ns.status(d, host) & 1 != 0)
+ .collect()
+ };
+ let batteries = present(&mut ns, &mut host, "PNP0C0A");
+ let chargers = present(&mut ns, &mut host, "ACPI0003");
+ let lids = present(&mut ns, &mut host, "PNP0C0D");
+ let gpes = firmware_gpes(&ns);
+
+ let mut firmware = Firmware {
+ ns,
+ host,
+ batteries,
+ chargers,
+ lids,
+ ec,
+ gpes,
+ };
+ for line in firmware.describe() {
+ crate::println!("power: {line}");
+ }
+ *FIRMWARE.lock() = Some(firmware);
+}
+
+/// The GPEs the firmware handles itself, from `\_GPE`'s method names.
+fn firmware_gpes(ns: &Namespace) -> Vec<(u32, bool)> {
+ ns.children(&Path::parse("_GPE"))
+ .iter()
+ .filter_map(|p| {
+ let [b'_', kind @ (b'L' | b'E'), hi, lo] = p.last()? else {
+ return None;
+ };
+ let digit = |c: u8| char::from(c).to_digit(16);
+ Some((digit(hi)? << 4 | digit(lo)?, kind == b'L'))
+ })
+ .collect()
+}
+
+impl Firmware {
+ fn eval(&mut self, device: &Path, method: &[u8; 4]) -> Option<Value> {
+ match self
+ .ns
+ .evaluate_if(&device.child(*method), Vec::new(), &mut self.host)?
+ {
+ Ok(v) => Some(v),
+ Err(e) => {
+ crate::println!("aml: {device}.{}: {e}", String::from_utf8_lossy(method));
+ None
+ }
+ }
+ }
+
+ fn battery(&mut self, device: &Path) -> Option<(Info, Status)> {
+ if self.ns.status(device, &mut self.host) & 0x10 == 0 {
+ return None;
+ }
+ let info = match self.eval(device, b"_BIX").and_then(|v| Info::from_bix(&v)) {
+ Some(info) => info,
+ None => Info::from_bif(&self.eval(device, b"_BIF")?)?,
+ };
+ let status = Status::from_bst(&self.eval(device, b"_BST")?)?;
+ Some((info, status))
+ }
+
+ fn charging_power(&mut self) -> Option<bool> {
+ let chargers = self.chargers.clone();
+ let mut any = None;
+ for c in chargers {
+ let on = self.eval(&c, b"_PSR").and_then(|v| v.integer())? != 0;
+ any = Some(any.unwrap_or(false) || on);
+ }
+ any
+ }
+
+ fn lid_open(&mut self) -> Option<bool> {
+ let lid = self.lids.first()?.clone();
+ Some(self.eval(&lid, b"_LID")?.integer()? != 0)
+ }
+
+ /// What [`status`] answers: `key=value` lines.
+ fn describe(&mut self) -> Vec<String> {
+ let mut lines = Vec::new();
+ if let Some(on) = self.charging_power() {
+ lines.push(alloc::format!("ac={}", u8::from(on)));
+ }
+ if let Some(open) = self.lid_open() {
+ lines.push(alloc::format!("lid={}", if open { "open" } else { "closed" }));
+ }
+ for (n, device) in self.batteries.clone().iter().enumerate() {
+ let mut line = alloc::format!("battery={n}");
+ match self.battery(device) {
+ Some((info, status)) => {
+ let unit = if info.milliwatts { "mWh" } else { "mAh" };
+ let state = match () {
+ _ if status.charging => "charging",
+ _ if status.discharging => "discharging",
+ _ => "full",
+ };
+ let _ = write!(line, "|state={state}");
+ if let Some(p) = status.percent(&info) {
+ let _ = write!(line, "|percent={p}");
+ }
+ if let Some(m) = status.minutes(&info) {
+ let _ = write!(line, "|minutes={m}");
+ }
+ let _ = write!(
+ line,
+ "|remaining={}|full={}|design={}|unit={unit}",
+ status.remaining, info.full_capacity, info.design_capacity
+ );
+ if info.cycles != pinnacle_aml::battery::UNKNOWN {
+ let _ = write!(line, "|cycles={}", info.cycles);
+ }
+ let clean =
+ |s: &str| -> String { s.chars().filter(|c| !matches!(c, '|' | '\n')).collect() };
+ let _ = write!(line, "|model={}|maker={}", clean(&info.model), clean(&info.maker));
+ }
+ None => line.push_str("|state=absent"),
+ }
+ lines.push(line);
+ }
+ lines
+ }
+
+ /// A GPE fired: the EC's queries run (`_Qxx`), or the firmware's own
+ /// method; then it is cleared and turned on again.
+ fn gpe(&mut self, n: u32) {
+ if let Some((device, gpe)) = self.ec.clone()
+ && gpe == n
+ {
+ let ec = *EC.lock();
+ // At most a few events at a time: an EC stuck answering keeps
+ // the system no longer.
+ for _ in 0..8 {
+ let Some(q) = ec.and_then(|ec| ec.query()) else {
+ break;
+ };
+ let method = alloc::format!("_Q{q:02X}");
+ let path = device.child(method.as_bytes().try_into().unwrap());
+ if let Some(Err(e)) = self.ns.evaluate_if(&path, Vec::new(), &mut self.host) {
+ crate::println!("aml: {path}: {e}");
+ }
+ }
+ crate::acpi::gpe_clear(n);
+ crate::acpi::gpe_enable(n, true);
+ return;
+ }
+ if let Some(&(_, level)) = self.gpes.iter().find(|g| g.0 == n) {
+ if !level {
+ crate::acpi::gpe_clear(n);
+ }
+ let kind = if level { 'L' } else { 'E' };
+ let name = alloc::format!("_{kind}{n:02X}");
+ let path = Path::parse("_GPE").child(name.as_bytes().try_into().unwrap());
+ if let Err(e) = self.ns.evaluate(&path, Vec::new(), &mut self.host) {
+ crate::println!("aml: {path}: {e}");
+ }
+ if level {
+ crate::acpi::gpe_clear(n);
+ }
+ crate::acpi::gpe_enable(n, true);
+ }
+ }
+}
+
+/// Turns on the GPEs something answers and starts [`watching`]. After the
+/// scheduler runs.
+pub fn watch() {
+ let gpes: Vec<u32> = {
+ let fw = FIRMWARE.lock();
+ let Some(fw) = fw.as_ref() else { return };
+ // A GPE that only wakes the machine (named by a device's _PRW) is
+ // left off, as Linux leaves it: some fire for ever while awake.
+ fw.ec
+ .iter()
+ .map(|e| e.1)
+ .chain(fw.gpes.iter().map(|g| g.0))
+ .collect()
+ };
+ let id = crate::sched::spawn(watching);
+ *WATCHER.lock() = Some(id);
+ *crate::acpi::GPE_HANDLER.lock() = Some(|| {
+ if let Some(id) = *WATCHER.lock() {
+ crate::sched::wake(id);
+ }
+ });
+ let on = gpes
+ .iter()
+ .filter(|&&n| n < crate::acpi::gpe_count() && crate::acpi::gpe_enable(n, true))
+ .count();
+ crate::println!("power: {on} GPEs on");
+}
+
+/// The kernel task the firmware's events run in: a fired GPE's method,
+/// then what the firmware notified, as input events.
+fn watching() {
+ let mut last = (None, None);
+ loop {
+ let fired = crate::acpi::gpe_take_fired();
+ let notified = core::mem::take(&mut *NOTIFIED.lock());
+ let mut events = Vec::new();
+ {
+ let mut fw = FIRMWARE.lock();
+ let Some(fw) = fw.as_mut() else { return };
+ for n in fired {
+ fw.gpe(n);
+ }
+ if !notified.is_empty() || last == (None, None) {
+ let now = (fw.lid_open(), fw.charging_power());
+ if now.0 != last.0
+ && let Some(open) = now.0
+ {
+ events.push(event(InputEvent::LID, open));
+ }
+ if now.1 != last.1
+ && let Some(on) = now.1
+ {
+ events.push(event(InputEvent::CHARGER, on));
+ }
+ if notified.iter().any(|(p, _)| fw.batteries.contains(p)) {
+ events.push(event(InputEvent::BATTERY, true));
+ }
+ last = now;
+ }
+ }
+ crate::drivers::input::deliver(events);
+ if NOTIFIED.lock().is_empty() {
+ crate::sched::sleep();
+ }
+ }
+}
+
+fn event(code: u16, value: bool) -> InputEvent {
+ InputEvent {
+ kind: InputEvent::POWER,
+ code,
+ value: i32::from(value),
+ ..InputEvent::default()
+ }
+}
+
+/// Runs `f` with the firmware's namespace and the machine AML reaches
+/// it through, for a driver that needs what only AML says (a touchpad's
+/// I²C address and its HID descriptor's register). None before [`init`].
+pub fn with_namespace<R>(f: impl FnOnce(&mut Namespace, &mut dyn Host) -> R) -> Option<R> {
+ let mut fw = FIRMWARE.lock();
+ let fw = fw.as_mut()?;
+ Some(f(&mut fw.ns, &mut fw.host))
+}
+
+/// The battery, charger and lid as `key=value` lines (`ac=1`,
+/// `lid=open`, `battery=0|state=discharging|percent=50|…`), each time
+/// asked of the firmware; empty with none.
+pub fn status() -> String {
+ let mut fw = FIRMWARE.lock();
+ let Some(fw) = fw.as_mut() else {
+ return String::new();
+ };
+ let mut text = String::new();
+ for line in fw.describe() {
+ text.push_str(&line);
+ text.push('\n');
+ }
+ text
+}
diff --git a/rt/src/lib.rs b/rt/src/lib.rs
index f1aca05..3b499f1 100644
--- a/rt/src/lib.rs
+++ b/rt/src/lib.rs
@@ -505,6 +505,67 @@ pub fn log() -> String {
String::from_utf8_lossy(&buffer).into_owned()
}
+/// A battery, as [`power`] reads it.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Battery {
+ /// `charging`, `discharging`, `full` or `absent`.
+ pub state: String,
+ pub percent: Option<u8>,
+ /// To empty, discharging; to full, charging.
+ pub minutes: Option<u32>,
+ /// The rest, as the kernel wrote it (`remaining`, `full`, `design`,
+ /// `unit`, `cycles`, `model`, `maker`).
+ pub fields: Vec<(String, String)>,
+}
+
+/// The machine's power: none of it on a machine without a battery,
+/// charger or lid, or for a confined program.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Power {
+ /// The charger plugged in.
+ pub ac: Option<bool>,
+ pub lid_open: Option<bool>,
+ pub batteries: Vec<Battery>,
+}
+
+/// The battery, charger and lid, asked of the firmware now.
+pub fn power() -> Power {
+ let mut buffer = alloc::vec![0u8; 4096];
+ let len = sys::call2(call::POWER, buffer.as_mut_ptr() as u64, buffer.len() as u64);
+ if len == ERROR {
+ return Power::default();
+ }
+ buffer.truncate(len as usize);
+ parse_power(&String::from_utf8_lossy(&buffer))
+}
+
+/// What [`power`] reads, from the kernel's lines.
+pub fn parse_power(text: &str) -> Power {
+ let mut power = Power::default();
+ for line in text.lines() {
+ if let Some(v) = line.strip_prefix("ac=") {
+ power.ac = Some(v == "1");
+ } else if let Some(v) = line.strip_prefix("lid=") {
+ power.lid_open = Some(v == "open");
+ } else if line.starts_with("battery=") {
+ let mut b = Battery::default();
+ for part in line.split('|').skip(1) {
+ let Some((k, v)) = part.split_once('=') else {
+ continue;
+ };
+ match k {
+ "state" => b.state = v.into(),
+ "percent" => b.percent = v.parse().ok(),
+ "minutes" => b.minutes = v.parse().ok(),
+ _ => b.fields.push((k.into(), v.into())),
+ }
+ }
+ power.batteries.push(b);
+ }
+ }
+ power
+}
+
/// Cores running, bytes of RAM, bytes free.
pub fn info() -> (u64, u64, u64) {
sys::call_result(call::INFO, [0; 7])