From 50fac65aba19811c5f0f68a989b1896d07e12129 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:04:08 +0000 Subject: [PATCH 1/3] feat(gpu): read the port above a GPU through the fabric's owner of its page, with its DPC state, and turn the link's ASPM and L1 PM Substates off at both ends at the claim with --gpu-aspm off, where every GPU's port was refused with ResourceConflict and a link the firmware left in L1 stayed so A port that forwards to its GPU keeps its configuration page with the containment fabric's owner of it (forward_cold_bridge), beside which no other mapping may open, so port_above's read-only mapping was refused with ResourceConflict on every GPU (native_mmio/shared.rs:738). The port is now read through that owner (read_forwarding_bridge), and the old mapping is kept only for a port that does not forward. The link lines at the claim and the port's line at a loss or return now carry the port's link, slot, AER and, new in the link report, its Downstream Port Containment control, status and error source. As the port now reads, the L1 PM Substates are set as Linux leaves them where they were skipped. --gpu-aspm off|firmware, default firmware, is hand-written, so the options revision stays 13. With off, each GPU's claim turns every L1 PM Substate off at both ends, the GPU's first, then ASPM L0s and L1 at the GPU and then at its port, as Linux's pcie_aspm.policy=performance does, through the fabric that owns the port, read back, before the claim's reset; one line says what each end had. Without a port, only the GPU's end, which still keeps the link out of L1. The register work is disable_link_power, beside disable_aspm_link, which now shares its link-control and L1SS helpers. For a Yoga Slim 7 16ACH6 whose RTX 3050 drops off the bus after minutes with the firmware's ASPM L1 on (stambha issue #1). --- crates/stela-boot-core/src/options.rs | 51 ++++++ crates/stela-boot-core/src/options/error.rs | 4 + crates/stela-boot-core/src/options/parse.rs | 6 + crates/stela-boot-core/src/options/tests.rs | 27 +++ crates/stela-boot/src/engine/gpu.rs | 2 +- crates/stela-boot/src/engine/gpu/link.rs | 161 ++++++++++++++++-- crates/stela-boot/src/engine/start.rs | 1 + .../shared/config_space/containment.rs | 2 +- .../config_space/containment/bus_reset.rs | 49 +++++- crates/stela-driver-base/src/bus/pci.rs | 4 +- crates/stela-driver-base/src/bus/pci/aspm.rs | 134 +++++++++++++-- .../src/bus/pci/aspm/tests.rs | 72 ++++++++ .../src/bus/pci/link_report.rs | 37 +++- crates/stela-loader/src/mount_interface.rs | 2 + 14 files changed, 519 insertions(+), 33 deletions(-) diff --git a/crates/stela-boot-core/src/options.rs b/crates/stela-boot-core/src/options.rs index 5cfc60b6ad..c87a16d462 100644 --- a/crates/stela-boot-core/src/options.rs +++ b/crates/stela-boot-core/src/options.rs @@ -325,6 +325,46 @@ impl AsusMode { } } +/// The power management of each GPU's PCI Express link +/// (`--gpu-aspm off|firmware`): `off` turns ASPM L0s and L1 and every L1 PM +/// Substate off at both ends of the link at the GPU's claim, as Linux's +/// `pcie_aspm.policy=performance` does, a test for GPUs that drop off the +/// bus while the firmware left L1 on. A hand-written opt-in setup never +/// writes, so the options revision stays 13; without it the link keeps +/// what the firmware set. +pub const GPU_ASPM: &str = "--gpu-aspm"; + +/// `--gpu-aspm`'s value. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum GpuAspm { + /// The default: the link's ASPM as the firmware left it, its L1 PM + /// Substates set as Linux leaves them. + #[default] + Firmware, + /// ASPM and the L1 PM Substates off at both ends. + Off, +} + +impl GpuAspm { + const NAMES: [(&'static str, Self); 2] = [("firmware", Self::Firmware), ("off", Self::Off)]; + + pub fn parse(value: &str) -> Result { + Self::NAMES + .iter() + .find(|(name, _)| *name == value) + .map(|(_, aspm)| *aspm) + .ok_or(Error::GpuAspm) + } + + pub fn name(self) -> &'static str { + Self::NAMES + .iter() + .find(|(_, aspm)| *aspm == self) + .map(|(name, _)| *name) + .unwrap_or_default() + } +} + /// Runs the host's ACPI in hardware mode (`--acpi-hardware`): the SCI, /// fixed events and GPEs, the embedded controller's queries and the /// notifications they send ([`crate::acpi_hardware`]). A hand-written @@ -668,6 +708,9 @@ pub struct System { /// The ASUS thermal policy set before macOS starts ([`ASUS_MODE`]); /// [`AsusMode::Performance`] unless given ([`Self::asus_mode`]). pub asus_mode: Option, + /// The GPU links' power management ([`GPU_ASPM`]); + /// [`GpuAspm::Firmware`] unless given ([`Self::gpu_aspm`]). + pub gpu_aspm: Option, /// [`AMX_NATIVE`]'s value, unset where the line has none /// ([`Self::amx_model`]). pub amx_native: Option, @@ -798,6 +841,7 @@ impl Default for System { acpi_hardware: false, laptop: None, asus_mode: None, + gpu_aspm: None, amx_native: None, ecid: None, network_check: None, @@ -972,6 +1016,12 @@ impl System { self.asus_mode.unwrap_or_default() } + /// The GPU links' power management: `--gpu-aspm`, else + /// [`GpuAspm::Firmware`]. + pub fn gpu_aspm(&self) -> GpuAspm { + self.gpu_aspm.unwrap_or_default() + } + /// The trackpad this boot cables: `--trackpad`, on the hub `--input` /// cables, so none without host input. The hub's disk-port count and /// the cabling both read this, so they agree. @@ -1337,6 +1387,7 @@ impl fmt::Display for System { line.flag(ACPI_HARDWARE, self.acpi_hardware)?; line.value(LAPTOP, self.laptop.map(Laptop::name))?; line.value(ASUS_MODE, self.asus_mode.map(AsusMode::name))?; + line.value(GPU_ASPM, self.gpu_aspm.map(GpuAspm::name))?; line.value(AMX_NATIVE, self.amx_native)?; line.flag("--monitor-trace", self.monitor_trace)?; line.flag("--display-trace", self.display_trace)?; diff --git a/crates/stela-boot-core/src/options/error.rs b/crates/stela-boot-core/src/options/error.rs index 1ff4f3228e..060ddbb3e1 100644 --- a/crates/stela-boot-core/src/options/error.rs +++ b/crates/stela-boot-core/src/options/error.rs @@ -84,6 +84,8 @@ pub enum Error { DuplicateLaptop, AsusMode, DuplicateAsusMode, + GpuAspm, + DuplicateGpuAspm, DuplicateAudioHpet, DuplicateNativePciIoapic, MissingAudioMode, @@ -233,6 +235,8 @@ impl Error { Self::DuplicateLaptop => "duplicate --laptop", Self::AsusMode => "--asus-mode takes performance, turbo, silent or off", Self::DuplicateAsusMode => "duplicate --asus-mode", + Self::GpuAspm => "--gpu-aspm takes off or firmware", + Self::DuplicateGpuAspm => "duplicate --gpu-aspm", Self::DuplicateAudioHpet => "duplicate audio HPET handoff", Self::DuplicateNativePciIoapic => "duplicate native PCI IOAPIC handoff", Self::MissingAudioMode => "missing audio check mode", diff --git a/crates/stela-boot-core/src/options/parse.rs b/crates/stela-boot-core/src/options/parse.rs index e758d427aa..7354c80ea8 100644 --- a/crates/stela-boot-core/src/options/parse.rs +++ b/crates/stela-boot-core/src/options/parse.rs @@ -57,6 +57,12 @@ impl ParseState<'_> { return Err(Error::DuplicateAsusMode); } } + GPU_ASPM => { + let aspm = GpuAspm::parse(value().ok_or(Error::GpuAspm)?)?; + if options.gpu_aspm.replace(aspm).is_some() { + return Err(Error::DuplicateGpuAspm); + } + } AMX_NATIVE => { let model = value().and_then(AmxModel::parse).ok_or(Error::AmxNative)?; if options.amx_native.replace(model).is_some() { diff --git a/crates/stela-boot-core/src/options/tests.rs b/crates/stela-boot-core/src/options/tests.rs index 95708b00e7..4071e53245 100644 --- a/crates/stela-boot-core/src/options/tests.rs +++ b/crates/stela-boot-core/src/options/tests.rs @@ -93,6 +93,33 @@ fn an_asus_laptop_runs_in_performance_unless_asus_mode_says_otherwise() { } } +#[test] +fn a_gpu_link_keeps_the_firmwares_aspm_unless_gpu_aspm_turns_it_off() { + let plain = System::parse("--system").unwrap(); + assert_eq!(plain.gpu_aspm(), GpuAspm::Firmware); + assert_eq!(plain.gpu_aspm, None); + assert_eq!(plain.to_string(), "--system"); + for (text, aspm) in [ + ("--system --gpu-aspm off", GpuAspm::Off), + ("--system --gpu-aspm firmware", GpuAspm::Firmware), + ("--system --acpi-hardware --gpu-aspm off", GpuAspm::Off), + ] { + let options = System::parse(text).unwrap(); + assert_eq!(options.gpu_aspm(), aspm); + assert_eq!(options.to_string(), text); + } + for (text, error) in [ + ("--system --gpu-aspm", Error::GpuAspm), + ("--system --gpu-aspm on", Error::GpuAspm), + ( + "--system --gpu-aspm off --gpu-aspm off", + Error::DuplicateGpuAspm, + ), + ] { + assert_eq!(System::parse(text).err(), Some(error), "{text}"); + } +} + #[test] fn audio_hpet_handoff_requires_an_audio_diagnostic() { assert_eq!( diff --git a/crates/stela-boot/src/engine/gpu.rs b/crates/stela-boot/src/engine/gpu.rs index c3fc6805b3..4a3a771365 100644 --- a/crates/stela-boot/src/engine/gpu.rs +++ b/crates/stela-boot/src/engine/gpu.rs @@ -1255,7 +1255,7 @@ fn claim( // SAFETY: the cold owner of `address` its fabric promoted, in D0 since // `enable_decode`, Bus Master sealed by its preparation; the fabric // keeps every other configuration writer out. - unsafe { link::set_substates(address, function, port.as_ref()) }; + unsafe { link::set_link_power(address, function, port.as_ref()) }; let config = function .config() .retain_epoch() diff --git a/crates/stela-boot/src/engine/gpu/link.rs b/crates/stela-boot/src/engine/gpu/link.rs index 9c39b50c53..51397f6b4a 100644 --- a/crates/stela-boot/src/engine/gpu/link.rs +++ b/crates/stela-boot/src/engine/gpu/link.rs @@ -4,43 +4,118 @@ //! Substates as the firmware left them and after the claim's reset, and the //! port's view when the GPU stops answering or answers again, which tells a //! link that went down from a port that lost power with it, with the -//! recovery the port still allows. The port is read through a read-only -//! mapping of its configuration kept for the boot; only the substates are -//! written, through the fabric that owns the port. +//! recovery the port still allows. A port that forwards to the GPU, as +//! every GPU's does, keeps its own configuration page with the fabric's +//! owner of it, beside which no other mapping may open, so it is read +//! through that owner; another port through a read-only mapping kept for +//! the boot. Only the substates, or with `--gpu-aspm off` the link's power +//! management, are written, through the fabric that owns the port. use crate::{native_mmio, output}; use alloc::{format, string::String}; +use core::sync::atomic::{AtomicBool, Ordering}; +use stela_boot_core::options::GpuAspm; use stela_drivers::bus::pci::{ - Address, ConfigSpace, Function, link_report, owned::ObservedConfig, owned::OwnedConfig, + Address, ConfigError, ConfigFailure, ConfigSpace, Function, link_report, owned::ObservedConfig, + owned::OwnedConfig, }; -/// The PCI Express port directly above a GPU, kept read-only, and the -/// fabric that owns it. +/// The PCI Express port directly above a GPU, read only, and the fabric +/// that owns it. pub(in crate::engine) struct Port { address: Address, #[cfg_attr(not(feature = "nvk"), allow(dead_code, reason = "asked at a loss"))] gpu: Address, - config: ObservedConfig, + view: View, source: &'static native_mmio::Source, } +/// How a port's configuration is read. +enum View { + /// Through the fabric's owner of a port whose forwarding it restored. + Held, + /// Through a read-only mapping of its page kept for the boot. + Observed(ObservedConfig), +} + +/// A forwarding port's configuration, read through the fabric's owner of +/// it ([`native_mmio::Source::read_forwarding_bridge`]); never written. +struct Held<'a> { + source: &'a native_mmio::Source, + address: Address, +} + +impl Held<'_> { + fn read(&self, offset: u16, width: u16) -> Result { + match self + .source + .read_forwarding_bridge(self.address, offset, width) + { + Some(Ok(value)) => Ok(value), + Some(Err(error)) => Err(ConfigError::before_effect(ConfigFailure::Mapping(error))), + // The fabric no longer holds it open. + None => Err(ConfigError::before_effect(ConfigFailure::ForeignGrant)), + } + } +} + +impl ConfigSpace for Held<'_> { + fn read8(&self, offset: u16) -> Result { + self.read(offset, 1).map(|value| value as u8) + } + fn read16(&self, offset: u16) -> Result { + self.read(offset, 2).map(|value| value as u16) + } + fn read32(&self, offset: u16) -> Result { + self.read(offset, 4) + } + fn write8(&mut self, _: u16, _: u8) -> Result<(), ConfigError> { + Err(ConfigError::before_effect(ConfigFailure::Protection)) + } + fn write16(&mut self, _: u16, _: u16) -> Result<(), ConfigError> { + Err(ConfigError::before_effect(ConfigFailure::Protection)) + } + fn write32(&mut self, _: u16, _: u32) -> Result<(), ConfigError> { + Err(ConfigError::before_effect(ConfigFailure::Protection)) + } +} + impl Port { + /// What the port reports now. + fn read(&self) -> Result { + match &self.view { + View::Held => link_report::read(&Held { + source: self.source, + address: self.address, + }), + View::Observed(config) => link_report::read(config), + } + } + /// `port
`, or why it could not be read. fn report(&self) -> String { - match link_report::read(&self.config) { + match self.read() { Ok(end) => format!("port {} {end}", self.address), Err(error) => format!("port {} unreadable: {error:?}", self.address), } } } -/// The port above the GPU at `address`, mapped read-only for the boot; -/// `None` for one on a root bus, and, said in a line, for one whose port -/// cannot be mapped. +/// The port above the GPU at `address`, read through the fabric's owner of +/// it when it forwards, else mapped read-only for the boot; `None` for one +/// on a root bus, and, said in a line, for one that cannot be read. pub(in crate::engine) fn port_above( mmio: &'static native_mmio::Source, address: Address, ) -> Option { let bridge = mmio.parent_bridge(address)?; + if mmio.read_forwarding_bridge(bridge, 0, 4).is_some() { + return Some(Port { + address: bridge, + gpu: address, + view: View::Held, + source: mmio, + }); + } let refused = |why: &dyn core::fmt::Debug| { output::arguments(format_args!( "GPU {address}: its port {bridge} is not read for the link lines: {why:?}\n" @@ -60,7 +135,7 @@ pub(in crate::engine) fn port_above( Ok(config) => Some(Port { address: bridge, gpu: address, - config, + view: View::Observed(config), source: mmio, }), Err((error, mut mapping)) => { @@ -114,6 +189,66 @@ pub(in crate::engine) unsafe fn set_substates( output::arguments(format_args!("GPU {address} L1 PM Substates: {done}\n")); } +/// Whether the GPUs' links go without power management (`--gpu-aspm off`). +static ASPM_OFF: AtomicBool = AtomicBool::new(false); + +/// What [`set_link_power`] does at each GPU's claim from here: the boot's +/// `--gpu-aspm`, chosen before the GPUs are claimed. +pub(in crate::engine) fn choose(aspm: GpuAspm) { + ASPM_OFF.store(aspm == GpuAspm::Off, Ordering::Relaxed); +} + +/// `GPU
link power: `: with +/// `--gpu-aspm off`, the link above the GPU `function` at `address`, in D0, +/// with ASPM L0s and L1 and every L1 PM Substate off at both ends +/// ([`stela_drivers::bus::pci::disable_link_power`]), before the claim's +/// reset, which saves and restores the GPU's side as set here. Without a +/// port that can be written, only the GPU's end, which still keeps the +/// link out of L1. Otherwise the substates as [`set_substates`] sets them. +/// +/// # Safety +/// As [`set_substates`]. +pub(in crate::engine) unsafe fn set_link_power( + address: Address, + function: &mut Function, + port: Option<&Port>, +) { + if !ASPM_OFF.load(Ordering::Relaxed) { + // SAFETY: forwarded. + unsafe { set_substates(address, function, port) }; + return; + } + let done = match port { + // SAFETY: forwarded; the fabric owns the port. + Some(port) => unsafe { port.source.disable_link_power(address, function) } + .map(|found| (found, Some(port.address))), + None => { + stela_drivers::bus::pci::disable_link_power::(function.config(), None) + .map(|found| (found, None)) + .map_err(|error| format!("{error:?}")) + } + }; + let line = match done { + Ok((found, Some(at))) => { + let port = found + .port + .map_or_else(|| String::from("unread"), |end| format!("{end}")); + format!( + "off at both ends by --gpu-aspm off: the GPU was {}, its port {at} {port}; \ + both read back off", + found.device + ) + } + Ok((found, None)) => format!( + "off at the GPU's end only by --gpu-aspm off (no port above it is read), which \ + keeps the link out of L1: the GPU was {}; read back off", + found.device + ), + Err(why) => format!("--gpu-aspm off failed, the link may be left as it was: {why}"), + }; + output::arguments(format_args!("GPU {address} link power: {line}\n")); +} + /// `GPU ; port
`: what the port above /// a GPU whose driver said `event` of it reads now, which tells whether the /// port and its link are still up, and, when it stopped answering, which @@ -138,7 +273,7 @@ impl Port { /// make one, else why not. fn recovery(&self) -> stela_boot_core::gpu_loss::Recovery { use stela_boot_core::gpu_loss::Recovery; - let end = match link_report::read(&self.config) { + let end = match self.read() { Ok(end) => end, Err(_) => return Recovery::Unknown, }; diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index 731e44aef6..712e5e4925 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -3472,6 +3472,7 @@ fn start_devices( crate::status::warn(&stela_boot_core::work_status::gpu_without_work(reason)); } }); + gpu::link::choose(options.gpu_aspm()); if options.boots_macos() && let Ok(work) = work && open_gpus( diff --git a/crates/stela-boot/src/native_mmio/shared/config_space/containment.rs b/crates/stela-boot/src/native_mmio/shared/config_space/containment.rs index ba7cae29f2..66b154328f 100644 --- a/crates/stela-boot/src/native_mmio/shared/config_space/containment.rs +++ b/crates/stela-boot/src/native_mmio/shared/config_space/containment.rs @@ -1375,7 +1375,7 @@ impl Source { /// One register of a bridge whose forwarding is restored, read through /// the configuration owner that keeps its page, beside which no other /// map may open; `None` for any other function. - pub(in crate::native_mmio) fn read_forwarding_bridge( + pub(crate) fn read_forwarding_bridge( &self, address: Address, offset: u16, diff --git a/crates/stela-boot/src/native_mmio/shared/config_space/containment/bus_reset.rs b/crates/stela-boot/src/native_mmio/shared/config_space/containment/bus_reset.rs index 381795b280..91ec627bf6 100644 --- a/crates/stela-boot/src/native_mmio/shared/config_space/containment/bus_reset.rs +++ b/crates/stela-boot/src/native_mmio/shared/config_space/containment/bus_reset.rs @@ -4,7 +4,9 @@ use super::*; use stela_drivers::{ block::BlockError, - bus::pci::{ConfigSpace, Function, bus_reset, capability, power::Timer, substates}, + bus::pci::{ + self as pci, ConfigSpace, Function, bus_reset, capability, power::Timer, substates, + }, }; /// PCI Express device/port types whose link carries a single device: a @@ -236,6 +238,51 @@ impl Source { .map_err(|error| alloc::format!("{error:?}")) } + /// Turn the power management of the link above the cold requester at + /// `address` off at both ends ([`pci::disable_link_power`]): its L1 PM + /// Substates, then ASPM L0s and L1, the device's end first. Only the + /// bridge directly above is written, and only its Link Control and L1 + /// PM Substates Control 1, as [`Self::configure_link_substates`] writes. + /// + /// # Safety + /// As [`Self::configure_link_substates`]. + pub(crate) unsafe fn disable_link_power( + &self, + address: Address, + function: &mut Function, + ) -> Result { + use alloc::string::ToString; + if function.address != address || function.config().address() != address { + return Err("the PCI function's owner does not match".to_string()); + } + let mut cohort = self + .pci_slots + .0 + .try_borrow_mut() + .map_err(|_| "the PCI fabric is busy".to_string())?; + let Cohort::Parked(fabric) = &mut *cohort else { + return Err("the PCI fabric is not contained".to_string()); + }; + let slot_of = |fabric: &Fabric, address: Address| { + fabric + .slots + .binary_search_by_key(&address, |slot| slot.address) + .ok() + }; + let at = slot_of(fabric, address) + .ok_or_else(|| "the PCI function is outside the contained fabric".to_string())?; + let topology::Parent::Bridge(bridge) = fabric.slots[at].route else { + return Err("the PCI function sits on a root bus, with no link above it".to_string()); + }; + let parent = slot_of(fabric, bridge) + .ok_or_else(|| "the bridge above is outside the contained fabric".to_string())?; + let Some(Forwarding::Open { config, .. }) = &mut fabric.slots[parent].forwarding else { + return Err("the bridge above the PCI function does not forward".to_string()); + }; + pci::disable_link_power(function.config(), Some(config)) + .map_err(|error| alloc::format!("{error:?}")) + } + /// Reset the bus of the cold requester at `address` by Secondary Bus /// Reset on the forwarding bridge above it, as Linux /// `pci_parent_bus_reset` ([`bus_reset::reset_secondary_bus`]). Linux diff --git a/crates/stela-driver-base/src/bus/pci.rs b/crates/stela-driver-base/src/bus/pci.rs index 1bc9049947..4408126cda 100644 --- a/crates/stela-driver-base/src/bus/pci.rs +++ b/crates/stela-driver-base/src/bus/pci.rs @@ -34,8 +34,8 @@ pub mod regs; pub mod requester; pub mod substates; pub use aspm::{ - aspm_control, disable_aspm_l1_2_link, disable_aspm_link, link_control_word, link_speed, - native as native_aspm, + EndPower, LinkPowerOff, aspm_control, disable_aspm_l1_2_link, disable_aspm_link, + disable_link_power, link_control_word, link_speed, native as native_aspm, }; pub use capability::{ Capabilities, Capability, CapabilityError, ExtendedCapabilities, ExtendedCapability, Layout, diff --git a/crates/stela-driver-base/src/bus/pci/aspm.rs b/crates/stela-driver-base/src/bus/pci/aspm.rs index d781d4e88b..ed4817a1b7 100644 --- a/crates/stela-driver-base/src/bus/pci/aspm.rs +++ b/crates/stela-driver-base/src/bus/pci/aspm.rs @@ -16,6 +16,7 @@ pub mod native; use super::{ConfigSpace, EcamWindow, Function}; use crate::{Handoff, block::BlockError}; use alloc::vec::Vec; +use core::fmt; const CAPABILITY_PCIE: u8 = 0x10; const PCIE_FLAGS: u16 = 0x02; @@ -65,15 +66,19 @@ pub unsafe fn disable_aspm_l1_2_link( } fn l1ss_control(function: &Function) -> Result, BlockError> { + l1ss_control_of(&function.config) +} + +fn l1ss_control_of(config: &C) -> Result, BlockError> { // Validate a real conventional PCIe function before accessing its extended // configuration space. Keep malformed chains distinct from absent L1SS. - link_control(function)?; - let first = function.config.read32(0x100)?; + link_control_of(config)?; + let first = config.read32(0x100)?; if first == u32::MAX { return Err(BlockError::Device { status: first }); } let mut found = None; - for entry in function.config.extended_capabilities() { + for entry in super::capability::extended_capabilities(config) { let entry = entry?; if entry.id != EXT_CAPABILITY_L1SS { continue; @@ -83,8 +88,8 @@ fn l1ss_control(function: &Function) -> Result(function: &Function) -> Result( function: &mut Function, snapshot: (u16, u32), +) -> Result<(), BlockError> { + clear_l1ss(&mut function.config, snapshot, ASPM_L1_2) +} + +/// Clear `bits` of L1 PM Substates Control 1 from its `snapshot`, read back. +fn clear_l1ss( + config: &mut C, + snapshot: (u16, u32), + bits: u32, ) -> Result<(), BlockError> { let (offset, original) = snapshot; - let wanted = original & !ASPM_L1_2; + let wanted = original & !bits; if original != wanted { // Linux notes some devices require DWORD access to L1SS. CTL1 is a // full control register, unlike Link Control's adjacent W1C status. - function.config.write32(offset, wanted)?; + config.write32(offset, wanted)?; } - let observed = function.config.read32(offset)?; + let observed = config.read32(offset)?; if observed != wanted { return Err(BlockError::Device { status: observed }); } @@ -215,9 +229,15 @@ fn segment_windows( fn link_control_optional( function: &Function, +) -> Result, BlockError> { + link_control_optional_of(&function.config) +} + +fn link_control_optional_of( + config: &C, ) -> Result, BlockError> { let mut express = None; - for entry in function.config.capabilities() { + for entry in super::capability::capabilities(config) { let entry = entry?; if entry.id == CAPABILITY_PCIE && express.replace(entry.offset).is_some() { return Err(BlockError::Unsupported("multiple PCIe capabilities")); @@ -231,7 +251,7 @@ fn link_control_optional( "PCIe link control outside capability space", )); } - let flags = function.config.read16(capability + PCIE_FLAGS)?; + let flags = config.read16(capability + PCIE_FLAGS)?; let port_type = (flags >> 4) & 15; if matches!(port_type, 9 | 10) { return Ok(None); @@ -242,7 +262,10 @@ fn link_control_optional( Ok(Some(capability + PCIE_LINK_CONTROL)) } fn link_control(function: &Function) -> Result { - link_control_optional(function)? + link_control_of(&function.config) +} +fn link_control_of(config: &C) -> Result { + link_control_optional_of(config)? .ok_or(BlockError::Unsupported("ASPM requires a PCIe capability")) } pub fn aspm_control(function: &Function) -> Result { @@ -295,13 +318,17 @@ fn upstream( } fn clear_aspm(function: &mut Function, control: u16) -> Result<(), BlockError> { - let value = function.config.read16(control)?; + clear_aspm_of(&mut function.config, control) +} + +fn clear_aspm_of(config: &mut C, control: u16) -> Result<(), BlockError> { + let value = config.read16(control)?; if value & PCIE_ASPM != 0 { // Narrow access is essential: Link Status shares this DWORD and // includes W1C fields that must not be acknowledged by this write. - function.config.write16(control, value & !PCIE_ASPM)?; + config.write16(control, value & !PCIE_ASPM)?; } - let status = function.config.read16(control)?; + let status = config.read16(control)?; if status & PCIE_ASPM != 0 { return Err(BlockError::Device { status: u32::from(status), @@ -310,6 +337,85 @@ fn clear_aspm(function: &mut Function, control: u16) -> Resul Ok(()) } +/// L1 PM Substates Control 1's four enables: ASPM L1.1 and L1.2, PCI-PM +/// L1.1 and L1.2 (Linux `PCI_L1SS_CTL1_L1SS_MASK`). +const L1SS_ENABLES: u32 = 0xf; + +/// One end of a link as [`disable_link_power`] found it: Link Control's +/// ASPM field (bit 0 L0s, bit 1 L1) and L1 PM Substates Control 1's four +/// enables, `None` where that end has no L1 PM Substates capability. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct EndPower { + pub aspm: u16, + pub substates: Option, +} + +impl fmt::Display for EndPower { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(["off", "L0s", "L1", "L0s+L1"][usize::from(self.aspm & PCIE_ASPM)])?; + match self.substates { + None => f.write_str(" with no L1SS"), + Some(0) => f.write_str(" with L1SS none"), + Some(enables) => write!(f, " with L1SS enables {enables:x}"), + } + } +} + +/// What [`disable_link_power`] found at the device's end and at the port's +/// before it turned their power management off; `port` is `None` where +/// only the device's end was given. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct LinkPowerOff { + pub device: EndPower, + pub port: Option, +} + +/// Turn a link's power management off as Linux's ASPM core does when its +/// policy is `performance` (`pcie_config_aspm_link(link, 0)`): every L1 PM +/// Substate off at both ends, the device's first, then ASPM L0s and L1 off +/// in Link Control at the device and then at the port, which is the order +/// PCIe asks for disabling L1. `port` is the bridge directly above +/// `device`; without it only the device's end changes, which still stops +/// L1 entry, as L1 needs both ends to enable it. Both ends' capabilities +/// are validated before the first write and every write is read back. An +/// error may leave the device's end off; nothing is turned back on. +pub fn disable_link_power( + device: &mut C, + port: Option<&mut P>, +) -> Result { + let mut port = port; + let device_control = link_control_of(device)?; + let device_l1ss = l1ss_control_of(device)?; + let port_controls = match port.as_deref() { + Some(port) => Some((link_control_of(port)?, l1ss_control_of(port)?)), + None => None, + }; + let found = LinkPowerOff { + device: EndPower { + aspm: device.read16(device_control)? & PCIE_ASPM, + substates: device_l1ss.map(|(_, enables)| enables & L1SS_ENABLES), + }, + port: match (port.as_deref(), port_controls) { + (Some(port), Some((control, l1ss))) => Some(EndPower { + aspm: port.read16(control)? & PCIE_ASPM, + substates: l1ss.map(|(_, enables)| enables & L1SS_ENABLES), + }), + _ => None, + }, + }; + if let Some(snapshot) = device_l1ss { + clear_l1ss(device, snapshot, L1SS_ENABLES)?; + } + if let (Some(port), Some((_, Some(snapshot)))) = (port.as_deref_mut(), port_controls) { + clear_l1ss(port, snapshot, L1SS_ENABLES)?; + } + clear_aspm_of(device, device_control)?; + if let (Some(port), Some((control, _))) = (port, port_controls) { + clear_aspm_of(port, control)?; + } + Ok(found) +} + fn disable_aspm_with( function: &mut Function, functions: &mut [Function], diff --git a/crates/stela-driver-base/src/bus/pci/aspm/tests.rs b/crates/stela-driver-base/src/bus/pci/aspm/tests.rs index 6049e2e2d6..91f38523d1 100644 --- a/crates/stela-driver-base/src/bus/pci/aspm/tests.rs +++ b/crates/stela-driver-base/src/bus/pci/aspm/tests.rs @@ -410,3 +410,75 @@ fn extended_headers_cannot_alias_l1ss_bodies_in_either_traversal_direction() { } } } + +#[test] +fn link_power_goes_off_substates_first_then_aspm_device_before_port() { + let writes = Writes::default(); + let mut endpoint = device(address(0, 1, 0), None, &writes); + let mut port = device(address(0, 0, 1), Some((1, 1)), &writes); + add_l1ss(&mut endpoint, 0x180, 0x5abca50f); + add_l1ss(&mut port, 0x240, 0xabcdff0a); + let (endpoint_address, port_address) = (endpoint.address, port.address); + let found = disable_link_power(&mut endpoint.config, Some(&mut port.config)).unwrap(); + assert_eq!( + found, + LinkPowerOff { + device: EndPower { + aspm: 3, + substates: Some(0xf) + }, + port: Some(EndPower { + aspm: 3, + substates: Some(0xa) + }), + } + ); + assert_eq!( + *writes.borrow(), + [ + (endpoint_address, 0x188, 0x5abca500), + (port_address, 0x248, 0xabcdff00), + (endpoint_address, 0x50, 0xa5a0), + (port_address, 0x50, 0xa5a0), + ] + ); + assert_eq!(endpoint.config.words[20], 0xc000_a5a0); + assert_eq!(port.config.words[20], 0xc000_a5a0); + assert_eq!( + alloc::format!("{}; {}", found.device, found.port.unwrap()), + "L0s+L1 with L1SS enables f; L0s+L1 with L1SS enables a" + ); + writes.borrow_mut().clear(); + // Already off: read back, nothing written. + let again = disable_link_power(&mut endpoint.config, Some(&mut port.config)).unwrap(); + assert!(writes.borrow().is_empty()); + assert_eq!(alloc::format!("{}", again.device), "off with L1SS none"); +} + +#[test] +fn link_power_without_a_port_turns_only_the_device_end_off() { + let writes = Writes::default(); + let mut endpoint = device(address(0, 1, 0), None, &writes); + let found = disable_link_power::(&mut endpoint.config, None).unwrap(); + assert_eq!(found.port, None); + assert_eq!(alloc::format!("{}", found.device), "L0s+L1 with no L1SS"); + assert_eq!(*writes.borrow(), [(endpoint.address, 0x50, 0xa5a0)]); +} + +#[test] +fn link_power_checks_both_ends_before_writing_and_reports_a_refusal() { + let writes = Writes::default(); + let mut endpoint = device(address(0, 1, 0), None, &writes); + let mut port = device(address(0, 0, 1), Some((1, 1)), &writes); + port.config.words[16] = 0; // no PCIe capability + assert!(disable_link_power(&mut endpoint.config, Some(&mut port.config)).is_err()); + assert!(writes.borrow().is_empty()); + let mut port = device(address(0, 0, 1), Some((1, 1)), &writes); + port.config.refuses_aspm = true; + assert!(matches!( + disable_link_power(&mut endpoint.config, Some(&mut port.config)), + Err(BlockError::Device { .. }) + )); + // The device's end went off before the port refused. + assert_eq!(endpoint.config.words[20], 0xc000_a5a0); +} diff --git a/crates/stela-driver-base/src/bus/pci/link_report.rs b/crates/stela-driver-base/src/bus/pci/link_report.rs index 40d1a3cb22..fd2dfbdc66 100644 --- a/crates/stela-driver-base/src/bus/pci/link_report.rs +++ b/crates/stela-driver-base/src/bus/pci/link_report.rs @@ -11,8 +11,10 @@ use super::{ }; use core::fmt; -/// Extended capability IDs: Advanced Error Reporting, LTR, L1 PM Substates. +/// Extended capability IDs: Advanced Error Reporting, LTR, L1 PM Substates +/// and Downstream Port Containment. const EXTENDED_AER: u16 = 0x01; +const EXTENDED_DPC: u16 = 0x1d; const EXTENDED_LTR: u16 = 0x18; const EXTENDED_L1SS: u16 = 0x1e; @@ -59,6 +61,10 @@ pub struct LinkEnd { /// AER Uncorrectable and Correctable Error Status, and Root Error Status /// on a root port. pub aer: Option<[u32; 3]>, + /// DPC Control, Status and Error Source ID (PCIe r6.0 7.9.14), on a + /// port with Downstream Port Containment: Status bit 0 says the port + /// contained its link, and bits 2:1 why. + pub dpc: Option<[u16; 3]>, } impl LinkEnd { @@ -134,6 +140,13 @@ pub fn read(config: &C) -> Result }; end.aer = Some([config.read32(at + 4)?, config.read32(at + 0x10)?, root]); } + EXTENDED_DPC if end.dpc.is_none() => { + end.dpc = Some([ + config.read16(at + 6)?, + config.read16(at + 8)?, + config.read16(at + 0xa)?, + ]); + } _ => {} } } @@ -246,6 +259,12 @@ impl fmt::Display for LinkEnd { write!(f, " root {root:08x}")?; } } + if let Some([control, status, source]) = self.dpc { + write!( + f, + "; DPC control {control:04x} status {status:04x} source {source:04x}" + )?; + } Ok(()) } } @@ -309,6 +328,22 @@ mod tests { Words(words) } + #[test] + fn a_port_that_contained_its_link_says_so() { + let mut port = root_port(); + // L1SS points on to a DPC capability whose status says triggered. + port.0[0x150 / 4] = 0x1801_001e; + port.0[0x180 / 4] = 0x0001_001d; + port.0[0x184 / 4] = 0x0001_0000; + port.0[0x188 / 4] = 0x0100_0003; + let end = read(&port).unwrap(); + assert_eq!(end.dpc, Some([0x0001, 0x0003, 0x0100])); + assert!( + alloc::format!("{end}").ends_with("; DPC control 0001 status 0003 source 0100"), + "{end}" + ); + } + #[test] fn a_root_port_reports_its_link_power_and_error_status() { let end = read(&root_port()).unwrap(); diff --git a/crates/stela-loader/src/mount_interface.rs b/crates/stela-loader/src/mount_interface.rs index ad58cb12a7..5a7982678a 100644 --- a/crates/stela-loader/src/mount_interface.rs +++ b/crates/stela-loader/src/mount_interface.rs @@ -55,6 +55,8 @@ pub const MARKER_BYTES: usize = MAGIC.len() + 4 * FIELDS; /// So does the fork's `--asus-mode performance|turbo|silent|off`, as /// hand-written: an ASUS laptop's firmware thermal policy is set to /// performance unasked, and no line setup writes holds the option. +/// So does the fork's `--gpu-aspm off|firmware`, a hand-written opt-in that +/// turns the GPU links' ASPM off at the claim: no line setup writes holds it. pub const OPTIONS_REVISION: u32 = 13; /// The startup choices, beside `stela.cfg` on the ESP. From dfda54be15b2be036fd6fd64b443231c85c3e630 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:04:09 +0000 Subject: [PATCH 2/3] fix(nouveau): a GPU that stopped answering for good is no longer read or written, and every timer wait ends at once on it or on a timer that reads all ones (patch 0222), where a teardown of a GPU off the bus spun 30 s through VMM flush waits until the step watchdog stopped the boot On the tester's boot 3 the GPU was gone at 531.7 s; from 609.8 s, after NVK's device loss, a job ran tu102_vmm_flush() over and over, each a stalled PTIMER, a "timeout" and a WARN at vmmtu102.c:51, until the step watchdog stopped it at 640.6 s. Its rip, image+0x1f2653e, sits on an lfence before a return (code 0faee85dc3), as after an MMIO read; the 0.5.0 image's symbols are not at hand to name the function. Patch 0222 makes the nvkm_rd*()/nvkm_wr*() accessors give all ones and drop writes once nvkm_device_gone() holds, ends nvkm_nsec() waits with -ENODEV before their condition runs, ends a wait whose PTIMER reads all ones at once (feeding nvkm_device_gone()), and warns for neither, so the boot reaches the GPU-lost stop. --- .../patches/linux/0222-a-gpu-that.patch | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 third_party/patches/linux/0222-a-gpu-that.patch diff --git a/third_party/patches/linux/0222-a-gpu-that.patch b/third_party/patches/linux/0222-a-gpu-that.patch new file mode 100644 index 0000000000..e21f707bc8 --- /dev/null +++ b/third_party/patches/linux/0222-a-gpu-that.patch @@ -0,0 +1,130 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> +Date: Mon, 23 Nov 2026 10:18:11 +0000 +Subject: [PATCH] fix(nouveau): a GPU that stopped answering for good is no + longer read or written, and every timer wait ends at once on it or on a timer + that reads all ones, where a teardown of a GPU off the bus spun 30 s through + VMM flush waits until the step watchdog stopped the boot + +Once nvkm_device_gone() has found BOOT_0 all ones for a second, the +nvkm_rd*() accessors give all ones and the nvkm_wr*() ones drop the +write without reaching the bus: on a link that is down each access +waits out the root port's completion timeout. nvkm_nsec() and its +usec/msec forms end at once with -ENODEV on such a device, before +their condition runs, and nvkm_timer_wait_test() ends a wait whose +PTIMER reads all ones with -ENODEV instead of after 16 stalled reads, +feeding nvkm_device_gone(); neither warns, as the loss is said once +where it is found. On a Ryzen 5800H + RTX 3050 laptop, the channel +teardown after the loss ran tu102_vmm_flush() thousands of times, each +a stalled timer, a "timeout" warning and a backtrace, for 30 s. +--- + .../drm/nouveau/include/nvkm/core/device.h | 36 +++++++++++++++---- + .../drm/nouveau/include/nvkm/subdev/timer.h | 16 ++++++--- + .../gpu/drm/nouveau/nvkm/subdev/timer/base.c | 12 +++++++ + 3 files changed, 53 insertions(+), 11 deletions(-) + +diff --git a/drivers/gpu/drm/nouveau/include/nvkm/core/device.h b/drivers/gpu/drm/nouveau/include/nvkm/core/device.h +index db6961b4a9e1bc4e412afe7db62039df00655bf6..f577337a81643978dcdae4ce7df646a9bc062131 100644 +--- a/drivers/gpu/drm/nouveau/include/nvkm/core/device.h ++++ b/drivers/gpu/drm/nouveau/include/nvkm/core/device.h +@@ -134,13 +134,35 @@ struct nvkm_device_chip { + + struct nvkm_device *nvkm_device_find(u64 name); + +-/* privileged register interface accessor macros */ +-#define nvkm_rd08(d,a) ioread8((d)->pri + (a)) +-#define nvkm_rd16(d,a) ioread16_native((d)->pri + (a)) +-#define nvkm_rd32(d,a) ioread32_native((d)->pri + (a)) +-#define nvkm_wr08(d,a,v) iowrite8((v), (d)->pri + (a)) +-#define nvkm_wr16(d,a,v) iowrite16_native((v), (d)->pri + (a)) +-#define nvkm_wr32(d,a,v) iowrite32_native((v), (d)->pri + (a)) ++/* ++ * privileged register interface accessor macros ++ * ++ * Once the device stopped answering for good (nvkm_device_gone()), a read ++ * gives all ones, as the bus would, and a write is dropped, without either ++ * reaching the bus: on a link that is down, each access waits out the root ++ * port's completion timeout, and a teardown's thousands of them held one ++ * task for the whole step watchdog. ++ */ ++static inline u8 nvkm_gone_rd08(void) { return 0xff; } ++static inline u16 nvkm_gone_rd16(void) { return 0xffff; } ++static inline u32 nvkm_gone_rd32(void) { return 0xffffffff; } ++#define nvkm_rd08(d,a) (unlikely(READ_ONCE((d)->gone)) ? nvkm_gone_rd08() : ioread8((d)->pri + (a))) ++#define nvkm_rd16(d,a) \ ++ (unlikely(READ_ONCE((d)->gone)) ? nvkm_gone_rd16() : ioread16_native((d)->pri + (a))) ++#define nvkm_rd32(d,a) \ ++ (unlikely(READ_ONCE((d)->gone)) ? nvkm_gone_rd32() : ioread32_native((d)->pri + (a))) ++#define nvkm_wr08(d,a,v) ({ \ ++ if (likely(!READ_ONCE((d)->gone))) \ ++ iowrite8((v), (d)->pri + (a)); \ ++}) ++#define nvkm_wr16(d,a,v) ({ \ ++ if (likely(!READ_ONCE((d)->gone))) \ ++ iowrite16_native((v), (d)->pri + (a)); \ ++}) ++#define nvkm_wr32(d,a,v) ({ \ ++ if (likely(!READ_ONCE((d)->gone))) \ ++ iowrite32_native((v), (d)->pri + (a)); \ ++}) + #define nvkm_mask(d,a,m,v) ({ \ + struct nvkm_device *_device = (d); \ + u32 _addr = (a), _temp = nvkm_rd32(_device, _addr); \ +diff --git a/drivers/gpu/drm/nouveau/include/nvkm/subdev/timer.h b/drivers/gpu/drm/nouveau/include/nvkm/subdev/timer.h +index 439a3f72b0d7d4ba79f8b671cb35469b1b9a5cd3..ef7702a2b32a82ed2fed7438bba78283301bdeaf 100644 +--- a/drivers/gpu/drm/nouveau/include/nvkm/subdev/timer.h ++++ b/drivers/gpu/drm/nouveau/include/nvkm/subdev/timer.h +@@ -47,6 +47,11 @@ s64 nvkm_timer_wait_test(struct nvkm_timer_wait *); + * + * NVKM_DELAY can be passed for 'cond' to disable the timeout warning, + * which is useful for unconditional delay loops. ++ * ++ * A device that stopped answering (nvkm_device_gone()) ends the wait at ++ * once with -ENODEV, before 'cond' runs, and so does a wait whose timer ++ * reads all ones (nvkm_timer_wait_test()); neither warns, as the device's ++ * loss is said once where it is found. + */ + #define NVKM_DELAY _warn = false; + #define nvkm_nsec(d,n,cond...) ({ \ +@@ -55,11 +60,14 @@ s64 nvkm_timer_wait_test(struct nvkm_timer_wait *); + s64 _taken = 0; \ + \ + nvkm_timer_wait_init((d), (n), &_wait); \ +- do { \ +- cond \ +- } while ((_taken = nvkm_timer_wait_test(&_wait)) >= 0); \ ++ if (unlikely(READ_ONCE((d)->gone))) \ ++ _taken = -ENODEV; \ ++ else \ ++ do { \ ++ cond \ ++ } while ((_taken = nvkm_timer_wait_test(&_wait)) >= 0); \ + \ +- if (_warn && _taken < 0) \ ++ if (_warn && _taken < 0 && _taken != -ENODEV) \ + dev_WARN(_wait.tmr->subdev.device->dev, "timeout\n"); \ + _taken; \ + }) +diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/timer/base.c b/drivers/gpu/drm/nouveau/nvkm/subdev/timer/base.c +index e971b6643483cb38c45d6820cb711dfbddbe8548..681defebfec1a5c3db4f99db0ab046975d45fd96 100644 +--- a/drivers/gpu/drm/nouveau/nvkm/subdev/timer/base.c ++++ b/drivers/gpu/drm/nouveau/nvkm/subdev/timer/base.c +@@ -29,6 +29,18 @@ nvkm_timer_wait_test(struct nvkm_timer_wait *wait) + struct nvkm_subdev *subdev = &wait->tmr->subdev; + u64 time = nvkm_timer_read(wait->tmr); + ++ /* ++ * A timer that reads all ones is a device that does not answer: end ++ * the wait at once, without the 16 reads of a stalled timer, each of ++ * which waits out a completion timeout on a link that is down. The ++ * look counts towards nvkm_device_gone(), which says once that the ++ * device went silent and, after a second of it, that it is gone. ++ */ ++ if (unlikely(time == ~0ULL)) { ++ nvkm_device_gone(subdev->device); ++ return -ENODEV; ++ } ++ + if (wait->reads == 0) { + wait->time0 = time; + wait->time1 = time; From 71ff51765d8593013660e7f920d17f1378e5cd63 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:04:09 +0000 Subject: [PATCH 3/3] feat(gpu): log the GPU's temperature every beat as GPU THERMAL, from the sensor nouveau now reads each second beside GSP-RM's P-state (patch 0223), where nothing read the GPU's temperature and a GPU that dropped off the bus under load could not show whether it ran hot Each perf round reads NV_THERM_I2CS_SENSOR_00 as gp100_temp_get() does; nvkm_perf gains the register as last read, the temperature and the beat's highest. "GPU THERMAL temp=52C max=55C power=unread" follows the GPU PERF line every beat with a reading; a sensor that gives none (a GSP-RM priv error or all ones) is said once with its register. Whether GSP-RM leaves the sensor readable to the CPU is untested. Power is not read: GSP-RM 570.144's headers hold no power monitor control. --- crates/stela-boot/src/engine/gpu.rs | 15 ++- crates/stela-driver-gpu/src/gsp_perf.rs | 69 +++++++++++++ crates/stela-driver-gpu/src/gsp_perf/tests.rs | 66 ++++++++++++- .../patches/linux/0223-read-the-gpus.patch | 98 +++++++++++++++++++ 4 files changed, 241 insertions(+), 7 deletions(-) create mode 100644 third_party/patches/linux/0223-read-the-gpus.patch diff --git a/crates/stela-boot/src/engine/gpu.rs b/crates/stela-boot/src/engine/gpu.rs index 4a3a771365..5d10771663 100644 --- a/crates/stela-boot/src/engine/gpu.rs +++ b/crates/stela-boot/src/engine/gpu.rs @@ -3470,7 +3470,9 @@ fn nvkm_report() -> String { /// `\nGPU PERF pstate=… seen=… pcie=… rounds=…`: the GPU's P-state as GSP-RM /// reported it and its PCIe link since the last report /// (`stela_drivers::gpu::gsp_perf`), at the first report after GSP starts and -/// then when they changed. Empty otherwise. +/// then when they changed; then `\nGPU THERMAL temp=… max=… power=unread` +/// every report whose rounds read the GPU's temperature, or once for a +/// sensor that gives none. Empty otherwise. #[cfg(feature = "nvk")] fn perf_report() -> String { use stela_drivers::gpu::gsp_perf::{Report, Reported}; @@ -3482,11 +3484,14 @@ fn perf_report() -> String { static REPORTED: Reported = Reported::new(); // SAFETY: nouveau's static report, which it only updates atomically. let report = unsafe { &nvkm_perf }; - report - .take() - .and_then(|taken| REPORTED.line(&taken)) + let Some(taken) = report.take() else { + return String::new(); + }; + [REPORTED.line(&taken), REPORTED.thermal_line(&taken)] + .into_iter() + .flatten() .map(|line| format!("\n{line}")) - .unwrap_or_default() + .collect() } /// The function of the timer-list timer due first when Linux last looked, diff --git a/crates/stela-driver-gpu/src/gsp_perf.rs b/crates/stela-driver-gpu/src/gsp_perf.rs index 56736a5350..9481079040 100644 --- a/crates/stela-driver-gpu/src/gsp_perf.rs +++ b/crates/stela-driver-gpu/src/gsp_perf.rs @@ -8,6 +8,13 @@ //! P-state, so the line shows whether the link follows load too. Clocks are //! not read: GSP-RM 570.144's headers define no clock control, and RM refused //! the 615.78.08 one. +//! +//! `GPU THERMAL`: each round also reads the GPU's internal temperature +//! sensor, and every beat with a reading says the last and the highest +//! since the beat before, so a GPU that runs hot before it is lost shows it. +//! A sensor that gives no reading is said once, with its register, and +//! again when that changes. Power is not read: GSP-RM 570.144's headers hold +//! no power monitor control. use alloc::{format, string::String}; use core::{ fmt, @@ -27,6 +34,9 @@ pub struct Report { link_control: AtomicU32, link_speeds: AtomicU32, link_cap: AtomicU32, + tsensor: AtomicU32, + temp: AtomicI32, + temp_max: AtomicU32, } impl Report { @@ -42,6 +52,9 @@ impl Report { link_control: AtomicU32::new(0), link_speeds: AtomicU32::new(0), link_cap: AtomicU32::new(0), + tsensor: AtomicU32::new(0), + temp: AtomicI32::new(-1), + temp_max: AtomicU32::new(0), } } @@ -54,6 +67,7 @@ impl Report { let rounds = self.rounds.swap(0, Ordering::Relaxed); let pstates = self.pstates.swap(0, Ordering::Relaxed); let link_speeds = self.link_speeds.swap(0, Ordering::Relaxed); + let temp_max = self.temp_max.swap(0, Ordering::Relaxed); (rounds != 0).then(|| Taken { rounds, pstate: self.pstate.load(Ordering::Relaxed), @@ -65,6 +79,11 @@ impl Report { speeds: link_speeds, cap: self.link_cap.load(Ordering::Relaxed) as u16, }, + thermal: Thermal { + sensor: self.tsensor.load(Ordering::Relaxed), + temp: self.temp.load(Ordering::Relaxed), + max: temp_max, + }, }) } } @@ -89,6 +108,43 @@ pub struct Taken { pub status: i32, /// The GPU's PCIe link. pub link: Link, + /// The GPU's temperature sensor. + pub thermal: Thermal, +} + +/// The GPU's internal temperature sensor as the beat's rounds read it. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct Thermal { + /// NV_THERM_I2CS_SENSOR_00 as last read, zero before any read. + pub sensor: u32, + /// The last reading in degrees C, negative for none. + pub temp: i32, + /// The highest reading of the beat in degrees C, zero for none. + pub max: u32, +} + +impl Thermal { + fn read(&self) -> bool { + self.temp >= 0 + } +} + +/// `temp=52C max=55C power=unread`, or `temp=unread sensor=badf1100 +/// power=unread` for a sensor that gave no reading. +impl fmt::Display for Thermal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.read() { + write!( + f, + "temp={}C max={}C", + self.temp, + self.max.max(self.temp as u32) + )?; + } else { + write!(f, "temp=unread sensor={:08x}", self.sensor)?; + } + f.write_str(" power=unread") + } } impl Taken { @@ -219,15 +275,28 @@ impl fmt::Display for Taken { /// The state the last line reported. pub struct Reported { last: spin_cell::Cell, + sensor: spin_cell::Cell, } impl Reported { pub const fn new() -> Self { Self { last: spin_cell::Cell::new(), + sensor: spin_cell::Cell::new(), } } + /// `GPU THERMAL …` for `taken`: every beat with a reading, else when + /// the sensor's register is new, so a sensor that gives none is said + /// once. + pub fn thermal_line(&self, taken: &Taken) -> Option { + let thermal = &taken.thermal; + let state = [u64::from(thermal.read()), u64::from(thermal.sensor)]; + let last = self.sensor.replace(state); + (thermal.read() || last.is_none_or(|last| last != state)) + .then(|| format!("GPU THERMAL {thermal}")) + } + /// `GPU PERF …` for `taken` when it is the first or its state changed /// since the last line. pub fn line(&self, taken: &Taken) -> Option { diff --git a/crates/stela-driver-gpu/src/gsp_perf/tests.rs b/crates/stela-driver-gpu/src/gsp_perf/tests.rs index d4f874b891..950a57b7fb 100644 --- a/crates/stela-driver-gpu/src/gsp_perf/tests.rs +++ b/crates/stela-driver-gpu/src/gsp_perf/tests.rs @@ -39,8 +39,11 @@ const fn lane(speed: u16, width: u16) -> u16 { #[test] fn the_layout_is_nouveaus() { - // `struct nvkm_perf_report`: nine 32-bit words. - assert_eq!(core::mem::size_of::(), 36); + // `struct nvkm_perf_report`: twelve 32-bit words. + assert_eq!(core::mem::size_of::(), 48); + assert_eq!(core::mem::offset_of!(Report, tsensor), 36); + assert_eq!(core::mem::offset_of!(Report, temp), 40); + assert_eq!(core::mem::offset_of!(Report, temp_max), 44); assert_eq!(core::mem::offset_of!(Report, pstate_status), 16); assert_eq!(core::mem::offset_of!(Report, link_status), 20); assert_eq!(core::mem::offset_of!(Report, link_control), 24); @@ -68,6 +71,11 @@ fn a_take_clears_the_counts_and_keeps_the_current_pstate() { pstates: P5 | P8, status: 0, link: Link::default(), + thermal: Thermal { + sensor: 0, + temp: -1, + max: 0 + }, } ); assert_eq!( @@ -147,3 +155,57 @@ fn a_link_change_alone_gives_a_line() { ) ); } + +/// A report whose last round read the sensor as `sensor`, giving `temp`, +/// with `max` the beat's highest. +fn sensed(report: Report, sensor: u32, temp: i32, max: u32) -> Report { + report.tsensor.store(sensor, Ordering::Relaxed); + report.temp.store(temp, Ordering::Relaxed); + report.temp_max.store(max, Ordering::Relaxed); + report +} + +#[test] +fn a_reading_is_said_every_beat_with_the_beats_highest() { + let reported = Reported::new(); + let report = sensed(sampled(10, P0, 0), 0x2000_3400, 52, 55); + let taken = report.take().unwrap(); + assert_eq!( + reported.thermal_line(&taken).as_deref(), + Some("GPU THERMAL temp=52C max=55C power=unread") + ); + // The same reading again is still said, and the highest starts again. + report.rounds.store(10, Ordering::Relaxed); + let again = report.take().unwrap(); + assert_eq!(again.thermal.max, 0); + assert_eq!( + reported.thermal_line(&again).as_deref(), + Some("GPU THERMAL temp=52C max=52C power=unread") + ); + // The P-state line does not move with the temperature. + assert!(reported.line(&taken).is_some()); + let warmer = sensed(sampled(10, P0, 0), 0x2000_3c00, 60, 60) + .take() + .unwrap(); + assert_eq!(reported.line(&warmer), None); +} + +#[test] +fn a_sensor_without_a_reading_is_said_once_with_its_register() { + let reported = Reported::new(); + let guarded = sensed(sampled(10, P0, 0), 0xbadf_1100, -1, 0) + .take() + .unwrap(); + assert_eq!( + reported.thermal_line(&guarded).as_deref(), + Some("GPU THERMAL temp=unread sensor=badf1100 power=unread") + ); + assert_eq!(reported.thermal_line(&guarded), None); + let gone = sensed(sampled(1, P0, 0), 0xffff_ffff, -1, 0) + .take() + .unwrap(); + assert_eq!( + reported.thermal_line(&gone).as_deref(), + Some("GPU THERMAL temp=unread sensor=ffffffff power=unread") + ); +} diff --git a/third_party/patches/linux/0223-read-the-gpus.patch b/third_party/patches/linux/0223-read-the-gpus.patch new file mode 100644 index 0000000000..32be328ff7 --- /dev/null +++ b/third_party/patches/linux/0223-read-the-gpus.patch @@ -0,0 +1,98 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> +Date: Mon, 23 Nov 2026 10:18:57 +0000 +Subject: [PATCH] feat(nouveau): read the GPU's internal temperature sensor + each second beside GSP-RM's P-state, with the highest reading since the host + last took it, where nothing read the GPU's temperature and a laptop whose GPU + dropped off the bus under load could not show whether it ran hot + +Each perf round reads NV_THERM_I2CS_SENSOR_00 (0x020460) as +gp100_temp_get() reads it: degrees C in bits 16:8, valid with bit 29. +nvkm_perf keeps the register as last read, the temperature or -1, and +the highest temperature since the host took it. A 0xbadXXXXX priv error +or an all-ones read counts as no reading; whether GSP-RM leaves the +sensor readable to the CPU is untested. GSP-RM 570.144's headers hold no +power monitor control, so power is not read. +--- + .../drm/nouveau/include/nvkm/core/counts.h | 9 +++++ + .../nouveau/nvkm/subdev/gsp/rm/r535/perf.c | 33 +++++++++++++++++++ + 2 files changed, 42 insertions(+) + +diff --git a/drivers/gpu/drm/nouveau/include/nvkm/core/counts.h b/drivers/gpu/drm/nouveau/include/nvkm/core/counts.h +index 2bfd1f058e25244f6b0287d41a2055239c935a4e..f3037b1617e19572fe0b8b1909e888ad52a98f0a 100644 +--- a/drivers/gpu/drm/nouveau/include/nvkm/core/counts.h ++++ b/drivers/gpu/drm/nouveau/include/nvkm/core/counts.h +@@ -39,6 +39,12 @@ extern u64 nvkm_counts[NVKM_COUNTS][3]; + * Capabilities' low word, all zero for a function with no PCIe capability or + * a read that failed. A host takes the counts and the speeds seen with atomic + * swaps and reads the rest. ++ * ++ * Each round also reads the GPU's internal temperature sensor ++ * (NV_THERM_I2CS_SENSOR_00, as gp100_temp_get() reads it): the register as ++ * last read, the temperature it gave in degrees C or -1 where it gave none, ++ * and the highest temperature since the host last took it, 0 for none, ++ * which the host takes with an atomic swap. + */ + struct nvkm_perf_report { + u32 started; +@@ -50,6 +56,9 @@ struct nvkm_perf_report { + u32 link_control; + u32 link_speeds; + u32 link_cap; ++ u32 tsensor; ++ s32 temp; ++ u32 temp_max; + }; + + extern struct nvkm_perf_report nvkm_perf; +diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/perf.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/perf.c +index 8722a6587a516678e1952628e85956d2f94f4fe3..750dbcfc889082bc133573ed8ece2d083edaf506 100644 +--- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/perf.c ++++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/perf.c +@@ -120,6 +120,38 @@ r535_gsp_perf_link(struct nvkm_gsp *gsp) + __ATOMIC_RELAXED); + } + ++/* ++ * The GPU's internal temperature, as gp100_temp_get() reads it from ++ * NV_THERM_I2CS_SENSOR_00: bits 16:8 are degrees C, bit 29 says the reading ++ * is valid. GSP-RM owns the thermal unit, and whether it leaves the sensor ++ * readable to the CPU is untested: a register it guards answers a ++ * 0xbadXXXXX priv error, which counts as no reading, as does a device that ++ * answers all ones, and the raw register is kept for the host's line. ++ * GSP-RM 570.144's headers hold no power monitor control, so power is not ++ * read. ++ */ ++static void ++r535_gsp_perf_temp(struct nvkm_gsp *gsp) ++{ ++ struct nvkm_device *device = gsp->subdev.device; ++ u32 tsensor = nvkm_rd32(device, 0x020460); ++ s32 temp = -1; ++ u32 max; ++ ++ if (tsensor != 0xffffffff && (tsensor & 0xfff00000) != 0xbad00000 && ++ (tsensor & 0x20000000)) ++ temp = (tsensor & 0x0001fff8) >> 8; ++ __atomic_store_n(&nvkm_perf.tsensor, tsensor, __ATOMIC_RELAXED); ++ __atomic_store_n(&nvkm_perf.temp, temp, __ATOMIC_RELAXED); ++ if (temp < 0) ++ return; ++ max = __atomic_load_n(&nvkm_perf.temp_max, __ATOMIC_RELAXED); ++ while ((u32)temp > max && ++ !__atomic_compare_exchange_n(&nvkm_perf.temp_max, &max, temp, true, ++ __ATOMIC_RELAXED, __ATOMIC_RELAXED)) ++ ; ++} ++ + static void + r535_gsp_perf_work(struct work_struct *work) + { +@@ -130,6 +162,7 @@ r535_gsp_perf_work(struct work_struct *work) + return; + + r535_gsp_perf_link(gsp); ++ r535_gsp_perf_temp(gsp); + if (!gsp->perf.pstate_off) + r535_gsp_perf_pstate(gsp); + __atomic_fetch_add(&nvkm_perf.rounds, 1, __ATOMIC_RELAXED);