diff --git a/crates/stela-boot-core/src/lib.rs b/crates/stela-boot-core/src/lib.rs index 8d1f5bed9a..202370df64 100644 --- a/crates/stela-boot-core/src/lib.rs +++ b/crates/stela-boot-core/src/lib.rs @@ -72,6 +72,7 @@ pub mod install_progress; pub mod interrupt_image; pub mod ioapic; pub mod irq_context; +pub mod lid_panel; pub mod linux_pump; pub mod load_lines; pub mod loader_lines; diff --git a/crates/stela-boot-core/src/lid_panel.rs b/crates/stela-boot-core/src/lid_panel.rs new file mode 100644 index 0000000000..42a803828a --- /dev/null +++ b/crates/stela-boot-core/src/lid_panel.rs @@ -0,0 +1,29 @@ +//! A built-in panel's power while the host's lid is shut. The guest's +//! display sleep turns its display's outputs off and on; a closed lid +//! turns them off as well where they are all built-in panels, and an open +//! lid gives the guest its say back. An external monitor that shows the +//! display too keeps it lit: the display's outputs go dark together. + +/// Whether the guest's display is lit: while the guest's display is on, +/// unless the lid is closed and each of its outputs is a built-in panel. +pub fn lit(guest_on: bool, lid_closed: bool, panels_only: bool) -> bool { + guest_on && !(lid_closed && panels_only) +} + +#[cfg(test)] +mod tests { + use super::lit; + + #[test] + fn a_closed_lid_darkens_only_a_display_on_built_in_panels_alone() { + // The lid open: the guest's display sleep decides. + assert!(lit(true, false, true)); + assert!(!lit(false, false, true)); + // Closed, on the panel alone: dark, however the guest's display is. + assert!(!lit(true, true, true)); + assert!(!lit(false, true, true)); + // Closed, with an external monitor showing it too: the guest decides. + assert!(lit(true, true, false)); + assert!(!lit(false, true, false)); + } +} diff --git a/crates/stela-boot/src/engine.rs b/crates/stela-boot/src/engine.rs index 36d5db82a9..0bfc78b37a 100644 --- a/crates/stela-boot/src/engine.rs +++ b/crates/stela-boot/src/engine.rs @@ -33,6 +33,7 @@ mod install_progress; pub(crate) mod interrupts; mod kernel_work; mod large_blocks; +mod lid; pub(crate) use kernel_work::FirmwareContext; mod network; pub(crate) mod nor; diff --git a/crates/stela-boot/src/engine/aml.rs b/crates/stela-boot/src/engine/aml.rs index 8d13833e9b..54fb1b190e 100644 --- a/crates/stela-boot/src/engine/aml.rs +++ b/crates/stela-boot/src/engine/aml.rs @@ -1117,6 +1117,15 @@ unsafe extern "C" fn fatal(_: *mut c_void, status: Status) -> ! { )) } +/// Publish the lid's state `open` for the scanout ([`super::lid`]), with a +/// line saying it, `when` qualifying it. +fn lid_changed(lid: &stela_drivers::platform::lid::Lid<'_>, open: bool, when: &str) { + super::lid::set(open); + let path = lid.path().unwrap_or_else(|_| String::from("PNP0C0D")); + let state = if open { "open" } else { "closed" }; + output::arguments(format_args!("HOST ACPI lid {path}: {state}{when}\n")); +} + /// The firmware's ACPI namespace, for the host's power transitions. /// One namespace serves the whole program: [`HostAcpi::start`] leaks it, and /// the host drivers and power transitions borrow it for `'static`. @@ -1520,6 +1529,12 @@ impl HostAcpi { provider.reach(physical, bytes).and_then(NonNull::new) } pub(super) fn retain_power(&self, power: stela_drivers::probe::Power) { + // The state the lid starts in counts, as Linux reports it. + if let Some(lid) = &power.lid + && let Some(open) = lid.open() + { + lid_changed(lid, open, " at start"); + } *self.power.borrow_mut() = power; } pub(super) fn hardware_active(&self) -> bool { @@ -1655,10 +1670,14 @@ impl HostAcpi { { output::arguments(format_args!("HOST ACPI AC refresh failed: {error:?}\n")); } - if let Some(lid) = &mut power.lid - && let Err(error) = lid.refresh() - { - output::arguments(format_args!("HOST ACPI lid refresh failed: {error:?}\n")); + if let Some(lid) = &mut power.lid { + match lid.change() { + Ok(Some(open)) => lid_changed(lid, open, ""), + Ok(None) => {} + Err(error) => { + output::arguments(format_args!("HOST ACPI lid refresh failed: {error:?}\n")) + } + } } } self.service_ucsi(); diff --git a/crates/stela-boot/src/engine/gpu/display.rs b/crates/stela-boot/src/engine/gpu/display.rs index f76c57db25..2bd7a05e60 100644 --- a/crates/stela-boot/src/engine/gpu/display.rs +++ b/crates/stela-boot/src/engine/gpu/display.rs @@ -106,6 +106,10 @@ struct KmsScanout { vblank_tsc: Option, /// The display's frames its GPU composes. composition: composition::Composition, + /// The power the guest's display last asked of the outputs. + guest_on: bool, + /// The lid state the display last followed ([`Self::follow_lid`]). + lid_closed: bool, } impl Scanout for KmsScanout { @@ -224,7 +228,8 @@ impl Scanout for KmsScanout { fn queued(&self) -> bool { let looking = self.display.is_some() || !self.waiting.is_empty(); - (looking && host::rdtsc() >= self.next_look) + let lid = self.display.is_some() && crate::engine::lid::closed() != self.lid_closed; + lid || (looking && host::rdtsc() >= self.next_look) || self .display .as_ref() @@ -238,6 +243,7 @@ impl Scanout for KmsScanout { let flushed = display.flush(); finish_present(display, flushed)?; } + self.follow_lid(); self.look(); Ok(()) } @@ -249,21 +255,68 @@ impl Scanout for KmsScanout { self.blank } + /// A closed lid keeps a display on built-in panels alone dark through + /// a wake ([`Self::follow_lid`]). fn set_power(&mut self, on: bool) -> Result<()> { + self.guest_on = on; let Some((_, display)) = &mut self.display else { return Ok(()); }; - display.set_power(on).map_err(|error| { + // A sleeping display may have passed no flush since the lid moved. + self.lid_closed = crate::engine::lid::closed(); + let lit = stela_boot_core::lid_panel::lit(on, self.lid_closed, panels_only(display)); + display.set_power(lit).map_err(|error| { refuse!( "the GPU's display refused to turn its outputs {state}: {error}", - state = if on { "on" } else { "off" }, + state = if lit { "on" } else { "off" }, error = format!("{error:?}") ) }) } } +/// Whether every output showing `display` is a built-in panel. +fn panels_only(display: &Display) -> bool { + display.ports().all(|port| port.panel()) +} + impl KmsScanout { + /// Follow a change of the host's lid ([`crate::engine::lid`]) on the + /// display taken, as the guest's display sleep's power is applied: a + /// closed lid darkens a display shown on built-in panels alone, and an + /// open one lights it again unless the guest's display sleeps. A + /// display taken later follows the lid at its first flush. + fn follow_lid(&mut self) { + let Some((name, display)) = &mut self.display else { + return; + }; + let closed = crate::engine::lid::closed(); + if closed == self.lid_closed { + return; + } + self.lid_closed = closed; + let state = if closed { "closed" } else { "open" }; + if !panels_only(display) { + output::arguments(format_args!( + "GPU {name}: lid {state}: the display shows on an external monitor too, so it \ + stays as the guest's display sleep has it\n" + )); + return; + } + let lit = stela_boot_core::lid_panel::lit(self.guest_on, closed, true); + let what = match (closed, lit) { + (true, _) => "built-in panel off", + (false, true) => "built-in panel on", + (false, false) => "built-in panel stays off while the guest's display sleeps", + }; + match display.set_power(lit) { + Ok(()) => output::arguments(format_args!("GPU {name}: lid {state}: {what}\n")), + Err(error) => output::arguments(format_args!( + "GPU {name}: lid {state}: the display refused to turn its outputs {}: {error:?}\n", + if lit { "on" } else { "off" } + )), + } + } fn new( mode: ScanoutMode, refresh_millihertz: u32, @@ -286,6 +339,8 @@ impl KmsScanout { reported: false, vblank_tsc: None, composition: composition::Composition::default(), + guest_on: true, + lid_closed: false, } } diff --git a/crates/stela-boot/src/engine/lid.rs b/crates/stela-boot/src/engine/lid.rs new file mode 100644 index 0000000000..a60c8c760e --- /dev/null +++ b/crates/stela-boot/src/engine/lid.rs @@ -0,0 +1,17 @@ +//! The host's lid as ACPI last read it (`aml`), for the scanout: while it +//! is closed, a guest display shown on built-in panels alone stays dark +//! (`gpu::display`, [`stela_boot_core::lid_panel`]). +use core::sync::atomic::{AtomicBool, Ordering}; + +static CLOSED: AtomicBool = AtomicBool::new(false); + +/// The lid was read open, or closed. +pub(in crate::engine) fn set(open: bool) { + CLOSED.store(!open, Ordering::Release); +} + +/// Whether the lid was last read closed; open until a reading says not. +#[cfg_attr(not(feature = "nvk"), allow(dead_code))] +pub(in crate::engine) fn closed() -> bool { + CLOSED.load(Ordering::Acquire) +} diff --git a/crates/stela-driver-base/src/platform/lid.rs b/crates/stela-driver-base/src/platform/lid.rs index dd33ff80b0..8a73f76555 100644 --- a/crates/stela-driver-base/src/platform/lid.rs +++ b/crates/stela-driver-base/src/platform/lid.rs @@ -33,6 +33,22 @@ impl<'a> Lid<'a> { pub fn open(&self) -> Option { self.open } + + /// [`Self::refresh`], and what it read where that differs from the + /// state known before: Linux's `acpi_lid_notify_state` reports the lid + /// switch at every notification, and its input layer passes a change + /// on alone. The first reading is one, as Linux reports the state the + /// lid starts in (`lid_init_state=method`, its default). + pub fn change(&mut self) -> Result, acpi::Error> { + let before = self.open; + let open = self.refresh()?; + Ok((before != Some(open)).then_some(open)) + } + + /// The lid device's absolute path. + pub fn path(&self) -> Result { + self.handle.path() + } } /// `_LID`'s answer: nonzero is open. @@ -45,7 +61,18 @@ fn state(value: Option>) -> Result { #[cfg(test)] mod tests { + extern crate std; use super::*; + use crate::platform::acpi::{ + Argument, Mode, Session, + test_support::{self, TEST_SERIAL, aml}, + }; + use alloc::vec::Vec; + use core::sync::atomic::{AtomicU32, Ordering}; + + unsafe extern "C" { + fn acpi_os_wait_events_complete(); + } #[test] fn nonzero_lid_state_is_open_and_others_are_malformed() { @@ -54,4 +81,83 @@ mod tests { assert_eq!(state(Some(Value::String(alloc::vec![b'1']))), Err(TYPE)); assert_eq!(state(None), Err(TYPE)); } + + /// A lid whose `_LID` answers what `SETL` stored, open at first. + fn namespace() -> Vec { + aml::scope( + "\\_SB_", + &aml::device( + "LID0", + &[ + aml::named("_HID", &aml::string("PNP0C0D")), + aml::named("LSTA", &aml::integer(1)), + aml::method("_LID", 0, &aml::ret(&aml::name("LSTA"))), + aml::method("SETL", 1, &aml::store(&[aml::ARG0], &aml::name("LSTA"))), + ] + .concat(), + ), + ) + } + + #[test] + fn a_change_is_reported_once_and_the_first_reading_is_one() { + let _serial = TEST_SERIAL.lock().unwrap(); + // SAFETY: the fixture owns every ACPICA service; serialized singleton. + let session = unsafe { + Session::start( + test_support::dsdt_fixture(&namespace()), + Mode::InterpreterOnly, + ) + } + .unwrap(); + let handle = session.devices("PNP0C0D").unwrap().remove(0); + let mut lid = Lid::attach(handle).unwrap(); + assert_eq!(lid.path().unwrap(), "\\_SB_.LID0"); + let set = |open: u64| { + handle + .invoke(Some("SETL"), &[Argument::Integer(open)]) + .unwrap() + }; + assert_eq!(lid.change(), Ok(Some(true))); + assert_eq!(lid.change(), Ok(None)); + set(0); + assert_eq!(lid.change(), Ok(Some(false))); + assert_eq!(lid.change(), Ok(None)); + assert_eq!(lid.open(), Some(false)); + set(1); + assert_eq!(lid.change(), Ok(Some(true))); + session.shutdown().unwrap(); + } + + /// `STELA_TEST_DSDT` names the ASUS TUF A16 FA608PP's DSDT; skipped + /// without one. Its EC query `_Q2F` notifies `\_SB.LID0` with 0x80, + /// whose `_LID` reads open while the EC reports nothing (ECOK clear). + #[test] + fn the_fa608pps_ec_query_notifies_its_lid() { + static NOTIFIED: AtomicU32 = AtomicU32::new(0); + let Some(services) = test_support::named_dsdt_fixture() else { + return; + }; + let _serial = TEST_SERIAL.lock().unwrap(); + // SAFETY: the fixture owns every ACPICA service; serialized singleton. + let session = unsafe { Session::start(services, Mode::InterpreterOnly) }.unwrap(); + let handles = session.devices("PNP0C0D").unwrap(); + assert_eq!(handles.len(), 1); + let mut lid = Lid::attach(handles[0]).unwrap(); + assert_eq!(lid.path().unwrap(), "\\_SB_.LID0"); + let notification = handles[0] + .notify(|value| NOTIFIED.store(value, Ordering::Release)) + .unwrap(); + session + .handle("\\_SB.PCI0.SBRG.EC0._Q2F") + .unwrap() + .invoke(None, &[]) + .unwrap(); + // SAFETY: serialized test process context outside an AML frame. + unsafe { acpi_os_wait_events_complete() }; + assert_eq!(NOTIFIED.load(Ordering::Acquire), 0x80); + assert_eq!(lid.change(), Ok(Some(true))); + drop(notification); + session.shutdown().unwrap(); + } }