//! 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 { 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 { 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> = SpinLock::new(None); /// What the firmware notified, for [`watching`] to act on. static NOTIFIED: SpinLock> = SpinLock::new(Vec::new()); /// The watching task, to wake. static WATCHER: SpinLock> = 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 { 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 { 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, chargers: Vec, lids: Vec, /// 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> = 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 = 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 { 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 { 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 { 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 { 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 { 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 = { 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(f: impl FnOnce(&mut Namespace, &mut dyn Host) -> R) -> Option { 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 }