feat(gpu): a lost device dumps the pipelines its unfinished command buffers bound, each stage's shader program header, code size and SHA-256, and the first fault's code in hex, followed by the kernel's first Xid, rc and disabled-channel lines, where an Xid 13 named no shader

nouveau's "Xid:13 Graphics Exception: Shader Program Header N Error"
(upstream #262, an RTX 4060 Laptop on Meteor Lake MS-Hybrid) names the
exception and its ESR words but not the shader, and the loss's refusal
named only the entry points in flight.

The service's description of a loss now ends with a fault dump, logged as
GPU FAULT lines apart from the refusals logged once per text:

- an opening line: the command buffers the GPU was given and had not
  finished, and the pipelines they bound, render pipelines first;
- a line for each stage of each pipeline (at most 8 pipelines, 4 Vulkan
  variants each): its functions, the code's size and SHA-256, NVK's
  instruction, GPR and SLM counts, the header's GPU address, whether the
  upload queue or a CPU mapping wrote the shader, and the 32 SPH words;
- for the boot's first fault only, each stage's code in hex, 64 bytes a
  line, within 32 KiB;
- after the opening, the kernel's first 12 Xid, rc and disabled-channel
  lines of the boot (ESR, chid, exception type) and a count of all of them.

It is always on and bounded, as the loss's other reports are: nothing asks
the driver until the device is lost, and only the boot's first 3 losses
are dumped. NVK reports the header and code through
VK_KHR_pipeline_executable_properties with Mesa patch 0043, which also
changes the pipeline store's compiler key, so the first boot recompiles.
This commit is contained in:
Garvit Surana committed 2026-11-22 22:04:02 +00:00
1 parent 7f7259fb45
commit 059d63ddf2
16 files changed
+1154 -14

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
//! The kernel's lines of a GPU fault, for the Metal device's fault dump
//! (`stela_driver_gpu::metal::fault_dump`) to follow with: nouveau's
//! `Xid` lines (GSP-RM's error log, whose Xid 13 text names the exception
//! and the ESR words, such as `Graphics Exception: ESR 0x405840=...`), its
//! `rc` line (the channel GSP-RM reset, by chid and exception type) and the
//! channel it disabled. A WindowServer that faults at each start prints
//! hundreds, so the first of the boot are kept, with a count of all.
use alloc::{format, string::String, vec::Vec};
use core::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};
/// What a kernel line of a GPU fault contains.
const MARKERS: [&str; 3] = ["Xid:", " rc engn:", "errored - disabling channel"];
/// Whether `line` is a kernel line of a GPU fault.
pub fn is_fault_line(line: &str) -> bool {
MARKERS.iter().any(|marker| line.contains(marker))
}
/// The first `SLOTS` kernel lines of GPU faults of the boot, each cut to
/// `BYTES`, and how many there were. Each slot is written once; read
/// without a lock.
pub struct FaultLines<const SLOTS: usize, const BYTES: usize> {
lines: [Line<BYTES>; SLOTS],
claimed: AtomicUsize,
seen: AtomicU64,
}
struct Line<const BYTES: usize> {
ready: AtomicBool,
length: AtomicUsize,
bytes: [AtomicU8; BYTES],
}
impl<const SLOTS: usize, const BYTES: usize> Default for FaultLines<SLOTS, BYTES> {
fn default() -> Self {
Self::new()
}
}
impl<const SLOTS: usize, const BYTES: usize> FaultLines<SLOTS, BYTES> {
pub const fn new() -> Self {
Self {
lines: [const {
Line {
ready: AtomicBool::new(false),
length: AtomicUsize::new(0),
bytes: [const { AtomicU8::new(0) }; BYTES],
}
}; SLOTS],
claimed: AtomicUsize::new(0),
seen: AtomicU64::new(0),
}
}
/// Counts `line` if it is a GPU fault's and keeps it while a slot is
/// free, cut to the slot's size at a character boundary; whether it is
/// one.
pub fn observe(&self, line: &str) -> bool {
if !is_fault_line(line) {
return false;
}
self.seen.fetch_add(1, Ordering::Relaxed);
let Ok(slot) = self
.claimed
.try_update(Ordering::Relaxed, Ordering::Relaxed, |claimed| {
(claimed < SLOTS).then_some(claimed + 1)
})
else {
return true;
};
let mut end = line.len().min(BYTES);
while !line.is_char_boundary(end) {
end -= 1;
}
let slot = &self.lines[slot];
for (byte, value) in slot.bytes.iter().zip(line[..end].bytes()) {
byte.store(value, Ordering::Relaxed);
}
slot.length.store(end, Ordering::Relaxed);
slot.ready.store(true, Ordering::Release);
true
}
/// The kept lines, in the order they were printed.
pub fn kept(&self) -> Vec<String> {
self.lines
.iter()
.take_while(|slot| slot.ready.load(Ordering::Acquire))
.filter_map(|slot| {
let length = slot.length.load(Ordering::Relaxed);
let bytes = slot.bytes[..length]
.iter()
.map(|byte| byte.load(Ordering::Relaxed))
.collect();
String::from_utf8(bytes).ok()
})
.collect()
}
/// The GPU fault lines the kernel printed this boot.
pub fn seen(&self) -> u64 {
self.seen.load(Ordering::Relaxed)
}
}
/// The lines that follow fault `fault`'s opening in the log, each after
/// the log's `GPU FAULT `: the first fault gives the kept lines, and every
/// fault the count so far, which says whether each start faults alike.
pub fn kernel_lines(fault: u32, kept: &[String], seen: u64) -> Vec<String> {
let mut lines = Vec::new();
if fault == 1 {
lines.extend(kept.iter().map(|line| format!("{fault} kernel: {line}")));
}
let shown = match (fault, kept.len()) {
(_, 0) => String::new(),
(1, count) => format!(", the first {count} above"),
(_, count) => format!(", the first {count} after fault 1"),
};
lines.push(format!(
"{fault} kernel: {seen} Xid, rc and disabled-channel lines so far this boot{shown}"
));
lines
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
const XID: &str = "nouveau 0000:01:00.0: gsp: Xid:13 Graphics Exception: Shader Program \
Header 11 Error";
const ESR: &str = "nouveau 0000:01:00.0: gsp: Xid:13 Graphics Exception: ESR \
0x405840=0xa2040800 0x405844=0x0 0x405848=0x0 0x40584c=0x0";
const RC: &str = "nouveau 0000:01:00.0: gsp: rc engn:00000001 chid:22 gfid:0 level:2 \
type:13 scope:1 part:233 fault_addr:0000000000000000 fault_type:ffffffff";
const DISABLED: &str = "nouveau 0000:01:00.0: fifo:000000:0016:[stela-managed[22]] errored \
- disabling channel";
#[test]
fn the_fault_lines_are_nouveaus_xid_rc_and_disabled_channel() {
for line in [XID, ESR, RC, DISABLED] {
assert!(is_fault_line(line), "{line}");
}
for line in [
"nouveau 0000:01:00.0: gsp: mmu fault queued",
"nouveau 0000:01:00.0: stopped answering: BOOT_0 read ffffffff for 1004 ms",
"GPU REFUSED DeviceLost in operation 12",
] {
assert!(!is_fault_line(line), "{line}");
}
}
/// The first lines of the boot are kept in order, each cut at a
/// character boundary, and every one is counted.
#[test]
fn the_first_lines_are_kept_and_every_one_counted() {
let lines: FaultLines<2, 64> = FaultLines::new();
assert!(!lines.observe("nouveau 0000:01:00.0: gsp: mmu fault queued"));
assert_eq!(lines.seen(), 0);
for line in [XID, ESR, RC, DISABLED] {
assert!(lines.observe(line));
}
assert_eq!(lines.seen(), 4);
assert_eq!(lines.kept(), [&XID[..64], &ESR[..64]]);
let narrow: FaultLines<1, 5> = FaultLines::new();
narrow.observe("Xid:é13");
assert_eq!(
narrow.kept(),
["Xid:"],
"cut before a character the slot splits"
);
}
#[test]
fn the_first_fault_gives_the_kept_lines_and_each_fault_the_count() {
let kept = vec![String::from(XID), String::from(ESR)];
assert_eq!(
kernel_lines(1, &kept, 2),
[
format!("1 kernel: {XID}"),
format!("1 kernel: {ESR}"),
String::from(
"1 kernel: 2 Xid, rc and disabled-channel lines so far this boot, the first \
2 above"
),
]
);
assert_eq!(
kernel_lines(3, &kept, 240),
[
"3 kernel: 240 Xid, rc and disabled-channel lines so far this boot, the first 2 \
after fault 1"
]
);
assert_eq!(
kernel_lines(1, &[], 0),
["1 kernel: 0 Xid, rc and disabled-channel lines so far this boot"]
);
}
}
+1
View File
@@ -50,6 +50,7 @@ pub mod firmware_screen;
pub mod firmware_state;
pub mod firmware_time;
pub mod first_stop;
pub mod gpu_fault;
pub mod gpu_loss;
pub mod gpu_requests;
pub mod gpu_status;
+24 -3
View File
@@ -21,7 +21,10 @@ use core::{
ptr::{self, NonNull},
sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU64, Ordering},
};
use stela_boot_core::gpu_loss::{self, SilentLines};
use stela_boot_core::{
gpu_fault::{self, FaultLines},
gpu_loss::{self, SilentLines},
};
use stela_contracts::gate::{BundleReport, GateService, MemoryRange, window};
pub(in crate::engine) use stela_drivers::gpu::metal::deferred::Taker;
use stela_drivers::gpu::metal::{
@@ -29,6 +32,7 @@ use stela_drivers::gpu::metal::{
deferred::{busy_pause_after_slice, busy_pause_millis},
device::{lifecycle::QuiesceStatus, pass_times},
error::Error,
fault_dump,
native::{self, ExportedMemory, Loader, MemoryExporter, NativeBackend, pipeline_store},
open::{Attachment, Gpu, OpenError, PcieLink, open, reopen},
service::{
@@ -388,9 +392,21 @@ unsafe fn with_interrupts<R>(body: impl FnOnce() -> R) -> R {
result
}
/// Logs why the service refused a guest's call, once for each reason.
/// Logs why the service refused a guest's call, once for each reason. A
/// lost device's fault dump is logged as it comes, as `GPU FAULT` lines:
/// the service bounds it, and each of its lines says something new; its
/// opening is followed by the kernel's lines of the fault.
fn report(reason: &str) {
static SEEN: Seen<512> = Seen::new();
if let Some(dump) = reason.strip_prefix(fault_dump::PREFIX) {
output::arguments(format_args!("GPU FAULT {dump}\n"));
if let Some(fault) = fault_dump::opening_fault(reason) {
for line in gpu_fault::kernel_lines(fault, &FAULTS.kept(), FAULTS.seen()) {
output::arguments(format_args!("GPU FAULT {line}\n"));
}
}
return;
}
if let Some(unheld) = SEEN.first_time(reason) {
output::arguments(format_args!("GPU REFUSED {reason}{unheld}\n"));
}
@@ -408,10 +424,15 @@ static LOSS_DUE: AtomicBool = AtomicBool::new(false);
/// first, for the reason of a stop that follows.
static SILENT: SilentLines<4, 320> = SilentLines::new();
/// The kernel drivers' first lines of GPU faults (Xid, rc and the channel
/// disabled), which follow a lost device's fault dump ([`report`]).
static FAULTS: FaultLines<12, 320> = FaultLines::new();
/// A line a kernel driver printed: one that says its GPU stopped answering
/// is kept for [`watch_losses`].
/// is kept for [`watch_losses`], one of a GPU fault for the fault dump.
pub(in crate::engine) fn driver_line(line: &str) {
SILENT.observe(line);
FAULTS.observe(line);
// What the port above reads when its GPU went silent or came back.
if let Some(event) = gpu_loss::link_event(line)
&& let Some(gpu) = installed()
+1
View File
@@ -23,6 +23,7 @@ pub mod compiler;
pub mod deferred;
pub mod device;
pub mod error;
pub mod fault_dump;
pub mod hazard;
pub mod heap;
pub mod indirect;
@@ -38,6 +38,7 @@ const MARKER_MEMORY: MemoryRequest = MemoryRequest {
pub mod display;
mod execution_sets;
mod fault_dump;
#[cfg(test)]
pub(crate) mod fixture;
pub mod gpu_times;
@@ -0,0 +1,74 @@
//! A lost device's fault dump ([`crate::metal::fault_dump`]): the pipelines
//! its unfinished command buffers bound, each stage as the driver compiled
//! it.
use super::Device;
use crate::metal::{
command_buffer::BoundPipeline,
fault_dump::{
self, HEX_BUDGET, HexBudget, MAX_PIPELINES, MAX_VARIANTS, ShaderImage, more_variants,
no_shaders, released,
},
shader::Compiler,
vulkan::backend::Backend,
};
use alloc::{format, string::String, vec, vec::Vec};
/// How a dump names a pipeline: its kind and device id.
fn label(pipeline: BoundPipeline) -> String {
match pipeline {
BoundPipeline::Render(id) => format!("render {id}"),
BoundPipeline::Compute(id) => format!("compute {id}"),
}
}
impl<B: Backend, C: Compiler> Device<B, C> {
/// The lines of the boot's fault `fault` (from 1), for the log once the
/// device is lost: the command buffers it had not finished and the
/// pipelines they bound, render pipelines first (a program header the
/// GPU rejects is a graphics stage's), then a line for each stage of
/// each with its program header, and for the boot's first fault the
/// code in hex within [`HEX_BUDGET`].
pub fn fault_dump(&mut self, fault: u32) -> Vec<String> {
let (serials, mut pipelines) = self.unfinished_pipelines();
// Stable: each kind keeps the order it was bound in.
pipelines.sort_by_key(|pipeline| matches!(pipeline, BoundPipeline::Compute(_)));
let labels: Vec<String> = pipelines.iter().copied().map(label).collect();
let mut lines = vec![fault_dump::opening(fault, &serials, &labels)];
let mut stages: Vec<(&str, usize, ShaderImage)> = Vec::new();
for (&pipeline, label) in pipelines.iter().zip(&labels).take(MAX_PIPELINES) {
let (Ok(functions), Ok(vulkan)) = (
self.pipelines.entries(pipeline),
self.pipelines.vulkan_pipelines(pipeline),
) else {
lines.push(released(fault, label));
continue;
};
let functions = functions.join("+");
for (variant, &made) in vulkan.iter().enumerate().take(MAX_VARIANTS) {
let images = self.backend.shader_images(made);
if images.is_empty() {
lines.push(no_shaders(fault, label, variant, &functions));
}
for image in images {
lines.push(fault_dump::shader(
fault, label, variant, &functions, &image,
));
stages.push((label, variant, image));
}
}
if vulkan.len() > MAX_VARIANTS {
lines.push(more_variants(fault, label, vulkan.len() - MAX_VARIANTS));
}
}
let budget = if fault == 1 { HEX_BUDGET } else { 0 };
let mut hex = HexBudget::new(budget);
for (label, variant, image) in &stages {
lines.extend(hex.code(fault, label, *variant, image));
}
lines.extend(hex.end(fault, budget));
lines
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,136 @@
use super::super::{
fixture::{LIBRARY, TestDevice, device},
pipelines::{ComputePipelineRequest, LinkedFunctions},
};
use crate::metal::{
abi::{CpuCacheMode, DispatchType, HazardTrackingMode, ResourceOptions, StorageMode},
capabilities::Size,
error::Error,
fault_dump::{HEX_LINE_BYTES, ShaderImage},
};
use alloc::{format, string::String, vec, vec::Vec};
/// Commits a command buffer that dispatches a compute pipeline of the
/// function `kernel`; answers the pipeline's id and the serial.
fn dispatched(device: &mut TestDevice) -> (u64, u64) {
let kernel = device.new_function(LIBRARY, "kernel", Some(&[])).unwrap();
let pipeline = device
.new_compute_pipeline(&ComputePipelineRequest {
compute_function: kernel,
threadgroup_size_is_multiple_of_thread_execution_width: false,
max_total_threads_per_threadgroup: 0,
stage_input: None,
linked_functions: LinkedFunctions::default(),
support_indirect_command_buffers: false,
archives: Default::default(),
})
.unwrap();
let state = device.compute_pipeline_state(pipeline).unwrap().clone();
let options = ResourceOptions {
cpu_cache_mode: CpuCacheMode::DefaultCache,
storage_mode: StorageMode::Private,
hazard_tracking_mode: HazardTrackingMode::Default,
};
let buffer = device.new_buffer(4096, options).unwrap();
let buffer = device.buffer(buffer).unwrap();
let mut commands = device.new_command_buffer();
commands.begin_compute(DispatchType::Serial).unwrap();
commands.set_compute_pipeline_state(&state).unwrap();
commands.set_compute_buffer(Some(buffer), 0, 0).unwrap();
let threads = Size {
width: 64,
height: 1,
depth: 1,
};
commands
.dispatch_threadgroups(&mut device.resolver(), [1, 1, 1], threads)
.unwrap();
commands.end_encoding(&mut device.resolver()).unwrap();
let serial = device.commit(commands).unwrap();
(state.id, serial)
}
fn lose(device: &mut TestDevice) {
device.backend().semaphore_error = Some(Error::DeviceLost);
assert_eq!(device.poll(), Err(Error::DeviceLost));
}
fn kernel_image() -> ShaderImage {
ShaderImage {
stage: String::from("compute"),
code: (0..100).collect(),
statistics: vec![(String::from("Number of GPRs"), 8)],
..ShaderImage::default()
}
}
/// The first fault names the unfinished command buffer, the pipeline it
/// bound by its function, each stage the driver reports and its code in
/// hex; a later fault names the same without the hex.
#[test]
fn a_lost_device_dumps_the_pipelines_its_unfinished_work_bound() {
let mut device = device();
device.backend().shader_images = vec![kernel_image()];
let (id, serial) = dispatched(&mut device);
lose(&mut device);
let lines = device.fault_dump(1);
assert_eq!(
lines[0],
format!(
"fault dump 1/3: the device was lost running command buffer {serial}, which bound 1 \
pipeline: compute {id}"
)
);
let stage = format!("fault dump 1 compute {id} variant 0 compute (kernel): code=100 sha256=");
assert!(lines[1].starts_with(&stage), "{}", lines[1]);
assert!(lines[1].ends_with(" gprs=8 sph=none"), "{}", lines[1]);
let hex: Vec<&String> = lines[2..].iter().collect();
assert_eq!(hex.len(), 100usize.div_ceil(HEX_LINE_BYTES));
assert!(hex[0].starts_with(&format!(
"fault dump 1 compute {id} variant 0 compute code+0x0000: 000102"
)));
assert!(hex[1].starts_with(&format!(
"fault dump 1 compute {id} variant 0 compute code+0x0040: 404142"
)));
let later = device.fault_dump(2);
assert_eq!(
later.len(),
2,
"no hex past the boot's first fault: {later:?}"
);
assert!(later[1].starts_with(&format!("fault dump 2 compute {id} variant 0 compute")));
}
/// A driver that reports no shaders still has its pipelines named.
#[test]
fn a_driver_without_shader_images_still_names_the_pipelines() {
let mut device = device();
let (id, _) = dispatched(&mut device);
lose(&mut device);
assert_eq!(
device.fault_dump(1)[1..],
[format!(
"fault dump 1 compute {id} variant 0 (kernel): the driver reports no shaders"
)]
);
}
/// Work the GPU finished is not what it was running when it was lost.
#[test]
fn finished_work_is_not_named() {
let mut device = device();
device.backend().shader_images = vec![kernel_image()];
let (_, serial) = dispatched(&mut device);
let timeline = device.timeline;
device.backend().complete(timeline, serial);
assert_eq!(device.poll(), Ok(serial));
// With nothing in flight a poll asks nothing; the platform's look
// learns of the loss.
device.mark_lost();
assert_eq!(
device.fault_dump(1),
["fault dump 1/3: the device was lost with no submitted command buffer unfinished"]
);
}
@@ -173,6 +173,9 @@ pub(crate) struct MockBackend {
pub(crate) descriptors: Vec<(u32, Descriptor)>,
pub(crate) graphics: Vec<GraphicsPipelineInfo>,
pub(crate) compute: Vec<ComputePipelineInfo>,
/// What the driver reports of every pipeline's shaders, for a lost
/// device's fault dump; none when unset.
pub(crate) shader_images: Vec<crate::metal::fault_dump::ShaderImage>,
/// The pipelines each pipeline cache holds.
pub(crate) caches: BTreeMap<u64, u8>,
/// While a call may defer, the next compute pipeline creation defers
@@ -486,6 +489,9 @@ impl Backend for MockBackend {
self.graphics.push(info.clone());
Ok(Pipeline(self.id()))
}
fn shader_images(&mut self, _pipeline: Pipeline) -> Vec<crate::metal::fault_dump::ShaderImage> {
self.shader_images.clone()
}
fn create_compute_pipeline(&mut self, info: &ComputePipelineInfo) -> Result<Pipeline> {
if let Some(lock) = &self.deferring
&& info.source == PipelineSource::Compiled
@@ -357,6 +357,40 @@ impl Pipelines {
.collect()
}
/// The Vulkan pipelines `pipeline` compiled, which a command buffer
/// binding it may have run: a render pipeline's own, then its bicubic
/// and mesh variants; a compute pipeline's threadgroup shapes, then the
/// one its indirect commands set.
pub(super) fn vulkan_pipelines(&self, pipeline: BoundPipeline) -> Result<Vec<Pipeline>> {
Ok(match pipeline {
BoundPipeline::Render(id) => {
let render = self.render.get(id as u32)?;
render
.state
.pipeline
.into_iter()
.chain(render.bicubic.iter().map(|&(_, _, pipeline)| pipeline))
.chain(render.variants.iter().map(|&(_, _, pipeline)| pipeline))
.collect()
}
BoundPipeline::Compute(id) => {
let compute = self.compute.get(id as u32)?;
compute
.variants
.iter()
.map(|&(_, pipeline)| pipeline)
.chain(
compute
.state
.indirect
.as_ref()
.map(|indirect| indirect.pipeline),
)
.collect()
}
})
}
fn interface(&self, id: FunctionId) -> Result<&Interface> {
self.functions.get(id.0)?.interface()
}
@@ -1756,6 +1756,27 @@ impl<B: Backend, C: Compiler> Device<B, C> {
work
}
/// The command buffers the GPU was given and had not finished, by
/// serial, oldest first, and the pipelines they bound, each once in the
/// order first bound: what a lost device was running. Held work never
/// reached the GPU and is left out.
pub(super) fn unfinished_pipelines(&self) -> (Vec<u64>, Vec<BoundPipeline>) {
let mut serials = Vec::new();
let mut pipelines = Vec::new();
for flight in &self.queue.in_flight {
if matches!(flight.track, Track::Held | Track::Done) {
continue;
}
serials.push(flight.serial);
for &pipeline in &flight.pipelines {
if !pipelines.contains(&pipeline) {
pipelines.push(pipeline);
}
}
}
(serials, pipelines)
}
/// Submits ready held work, retires completed command buffers and
/// returns the completed serial.
pub fn poll(&mut self) -> Result<u64> {
@@ -0,0 +1,315 @@
//! What a lost device's GPU was running, for a fault such as nouveau's Xid
//! 13 ("Graphics Exception: Shader Program Header N Error"), which names no
//! shader: each pipeline that the command buffers the GPU had not finished
//! bound, by its functions, with each of its stages' shader program header
//! (SPH) as NAK wrote it and the size and SHA-256 of its machine code, as
//! NVK reports them (`VK_KHR_pipeline_executable_properties`, Mesa patch
//! 0043). The first fault of a boot also gives that code in hex, up to
//! [`HEX_BUDGET`] bytes, so the same pipeline on a GPU that runs it can be
//! compared byte for byte.
//!
//! Always on and bounded, as the other reports of a loss are: nothing is
//! asked of the driver until the device is lost, and only the first
//! [`REPORTED_FAULTS`] losses of a boot are dumped ([`Limiter`]). The lines
//! hold Metal function names, pipeline ids, driver statistics and shader
//! bytes; nothing of the user's. Each starts with [`PREFIX`], which the
//! platform logs as it is, apart from the refusals it logs once per text.
use alloc::{format, string::String, vec::Vec};
use core::{
fmt::Write,
sync::atomic::{AtomicU32, Ordering},
};
/// How each line of a fault dump starts, after which the platform's log
/// writes it whole (`GPU FAULT ...`).
pub const PREFIX: &str = "fault dump ";
/// The losses of a boot that are dumped: a WindowServer that faults at each
/// start loses the device every few seconds, and the first ones say it all.
pub const REPORTED_FAULTS: u32 = 3;
/// The pipelines a dump names, render pipelines first.
pub const MAX_PIPELINES: usize = 8;
/// The Vulkan pipelines of one Metal pipeline a dump names: its first, then
/// its bicubic and mesh variants or a compute pipeline's threadgroup shapes.
pub const MAX_VARIANTS: usize = 4;
/// The bytes of machine code the first fault's dump gives in hex.
pub const HEX_BUDGET: usize = 32 << 10;
/// The bytes of code on each hex line.
pub const HEX_LINE_BYTES: usize = 64;
/// The names of the statistics NVK reports for an executable that a
/// shader's line gives, and the word it gives each as.
const STATISTICS: [(&str, &str); 4] = [
("Instruction count", "instructions"),
("Number of GPRs", "gprs"),
("SLM size", "slm"),
("Program header address", "sph_va"),
];
/// NVK's statistic that the upload queue wrote the shader (1) rather than
/// the CPU through a mapping of the shader heap (0).
const UPLOADED_BY_QUEUE: &str = "Uploaded by queue";
/// One stage of a pipeline as the driver compiled it.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ShaderImage {
/// The driver's name for the stage's executable (`vertex`, `fragment`).
pub stage: String,
/// The shader program header, in the 32-bit words the GPU reads before
/// the code; empty for compute, which has none.
pub header: Vec<u32>,
/// A mesh shader's geometry program header, when it has one.
pub geometry_header: Vec<u32>,
/// The machine code.
pub code: Vec<u8>,
/// The driver's statistics of it, by name.
pub statistics: Vec<(String, u64)>,
}
impl ShaderImage {
/// The statistic the driver names `name`.
pub fn statistic(&self, name: &str) -> Option<u64> {
self.statistics
.iter()
.find(|(named, _)| named == name)
.map(|&(_, value)| value)
}
}
/// `bytes` as the little-endian 32-bit words a program header is read in;
/// a trailing partial word is dropped.
pub fn words(bytes: &[u8]) -> Vec<u32> {
bytes
.as_chunks::<4>()
.0
.iter()
.map(|&word| u32::from_le_bytes(word))
.collect()
}
/// The faults of a boot left to dump.
pub struct Limiter {
taken: AtomicU32,
}
impl Limiter {
pub const fn new() -> Self {
Self {
taken: AtomicU32::new(0),
}
}
/// The number, from 1, of the fault to dump now, or `None` once
/// [`REPORTED_FAULTS`] were.
pub fn take(&self) -> Option<u32> {
let taken = self
.taken
.try_update(Ordering::Relaxed, Ordering::Relaxed, |taken| {
(taken < REPORTED_FAULTS).then_some(taken + 1)
})
.ok()?;
Some(taken + 1)
}
/// The boot's limiter, which every service of the boot shares.
#[cfg(not(test))]
pub fn boot() -> &'static Self {
static BOOT: Limiter = Limiter::new();
&BOOT
}
/// A unit test's service has a limiter of its own, so tests running
/// together each see their first fault.
#[cfg(test)]
pub fn boot() -> &'static Self {
alloc::boxed::Box::leak(alloc::boxed::Box::new(Self::new()))
}
}
impl Default for Limiter {
fn default() -> Self {
Self::new()
}
}
/// The fault a dump's opening line numbers, for the platform to put the
/// kernel's lines of the fault after it.
pub fn opening_fault(line: &str) -> Option<u32> {
let (number, _) = line.strip_prefix(PREFIX)?.split_once('/')?;
number.parse().ok()
}
/// The first line of fault `fault`'s dump: the command buffers the GPU had
/// not finished, by serial, and the pipelines they bound, by label.
pub fn opening(fault: u32, serials: &[u64], pipelines: &[String]) -> String {
let mut line = format!("{PREFIX}{fault}/{REPORTED_FAULTS}: the device was lost ");
match serials {
[] => line.push_str("with no submitted command buffer unfinished"),
[only] => {
let _ = write!(line, "running command buffer {only}");
}
[first, .., last] => {
let _ = write!(
line,
"running command buffers {first} to {last} ({})",
serials.len()
);
}
}
match pipelines {
[] if !serials.is_empty() => line.push_str(", which bound no pipeline"),
[] => {}
_ => {
let _ = write!(
line,
", which bound {} pipeline{}: {}",
pipelines.len(),
if pipelines.len() == 1 { "" } else { "s" },
pipelines.join(", ")
);
if pipelines.len() > MAX_PIPELINES {
let _ = write!(line, " (the first {MAX_PIPELINES} follow)");
}
}
}
line
}
/// A pipeline whose object is gone, so its shaders cannot be named.
pub fn released(fault: u32, pipeline: &str) -> String {
format!("{PREFIX}{fault} {pipeline}: released, its shaders unknown")
}
/// A Vulkan pipeline the driver reports no shaders of: a driver without
/// `VK_KHR_pipeline_executable_properties`, or NVK without patch 0043.
pub fn no_shaders(fault: u32, pipeline: &str, variant: usize, functions: &str) -> String {
format!(
"{PREFIX}{fault} {pipeline} variant {variant} ({functions}): the driver reports no shaders"
)
}
/// The variants of a pipeline past [`MAX_VARIANTS`].
pub fn more_variants(fault: u32, pipeline: &str, more: usize) -> String {
format!("{PREFIX}{fault} {pipeline}: {more} more variants not shown")
}
/// The words of a program header in hex, or `none`.
fn header_text(header: &[u32]) -> String {
if header.is_empty() {
return String::from("none");
}
let mut text = String::with_capacity(header.len() * 9);
for (index, word) in header.iter().enumerate() {
if index > 0 {
text.push(' ');
}
let _ = write!(text, "{word:08x}");
}
text
}
/// The SHA-256 of `bytes` in hex.
fn sha256(bytes: &[u8]) -> String {
use stela_crypto::{Sha256, digest::Digest};
let mut text = String::with_capacity(64);
for byte in Sha256::digest(bytes) {
let _ = write!(text, "{byte:02x}");
}
text
}
/// One stage's line: the pipeline, its functions, the stage, its code's
/// size and hash, the statistics a fault turns on and the program header.
pub fn shader(
fault: u32,
pipeline: &str,
variant: usize,
functions: &str,
image: &ShaderImage,
) -> String {
let mut line = format!(
"{PREFIX}{fault} {pipeline} variant {variant} {} ({functions}): code={} sha256={}",
image.stage,
image.code.len(),
sha256(&image.code)
);
for (name, word) in STATISTICS {
if let Some(value) = image.statistic(name) {
if name == "Program header address" {
let _ = write!(line, " {word}={value:#x}");
} else {
let _ = write!(line, " {word}={value}");
}
}
}
if let Some(queued) = image.statistic(UPLOADED_BY_QUEUE) {
line.push_str(if queued != 0 {
" upload=queue"
} else {
" upload=mapped"
});
}
let _ = write!(line, " sph={}", header_text(&image.header));
if !image.geometry_header.is_empty() {
let _ = write!(line, " gs_sph={}", header_text(&image.geometry_header));
}
line
}
/// The bytes of code a dump has left to give in hex, and those it had to
/// leave out.
#[derive(Debug)]
pub struct HexBudget {
left: usize,
unshown: usize,
}
impl HexBudget {
/// A budget of `bytes`; none for a fault after the boot's first.
pub fn new(bytes: usize) -> Self {
Self {
left: bytes,
unshown: 0,
}
}
/// `image`'s code in hex, [`HEX_LINE_BYTES`] to a line, as far as the
/// budget goes; the rest is counted as unshown.
pub fn code(
&mut self,
fault: u32,
pipeline: &str,
variant: usize,
image: &ShaderImage,
) -> Vec<String> {
let shown = image.code.len().min(self.left);
self.left -= shown;
self.unshown += image.code.len() - shown;
image.code[..shown]
.chunks(HEX_LINE_BYTES)
.enumerate()
.map(|(index, bytes)| {
let mut line = format!(
"{PREFIX}{fault} {pipeline} variant {variant} {} code+{:#06x}: ",
image.stage,
index * HEX_LINE_BYTES
);
for byte in bytes {
let _ = write!(line, "{byte:02x}");
}
line
})
.collect()
}
/// The line that says how much code a dump with a budget left out.
pub fn end(&self, fault: u32, budget: usize) -> Option<String> {
(budget > 0 && self.unshown > 0).then(|| {
format!(
"{PREFIX}{fault} hex: {} bytes of code past the {budget}-byte budget not shown",
self.unshown
)
})
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,185 @@
use super::*;
use alloc::{string::ToString, vec};
fn vertex() -> ShaderImage {
ShaderImage {
stage: "vertex".to_string(),
header: (0..32).map(|word| 0x0006_1060 + word).collect(),
geometry_header: Vec::new(),
code: (0..=255).collect(),
statistics: vec![
("Instruction count".to_string(), 12),
("Number of GPRs".to_string(), 24),
("SLM size".to_string(), 0),
("Program header address".to_string(), 0x3_0000_0080),
("Uploaded by queue".to_string(), 1),
("Code size".to_string(), 256),
],
}
}
/// The code's hash as another SHA-256 implementation gives it, which a log
/// reader's `sha256sum` of the hex matches.
fn reference_sha256(bytes: &[u8]) -> String {
use sha2::Digest;
sha2::Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
/// Only the first [`REPORTED_FAULTS`] faults of a boot are dumped, each
/// numbered from 1, and the limiter never wraps.
#[test]
fn the_limiter_dumps_the_first_faults_of_a_boot_only() {
let limiter = Limiter::new();
let taken: Vec<_> = (0..REPORTED_FAULTS + 5).map(|_| limiter.take()).collect();
assert_eq!(taken[..3], [Some(1), Some(2), Some(3)]);
assert!(taken[3..].iter().all(Option::is_none));
// Each test's service gets a limiter of its own.
assert_eq!(Limiter::boot().take(), Some(1));
assert_eq!(Limiter::boot().take(), Some(1));
}
#[test]
fn the_opening_names_the_unfinished_work_and_its_pipelines() {
let pipelines = ["render 7".to_string(), "compute 3".to_string()];
let line = opening(1, &[812, 813, 814], &pipelines);
assert_eq!(
line,
"fault dump 1/3: the device was lost running command buffers 812 to 814 (3), which \
bound 2 pipelines: render 7, compute 3"
);
assert_eq!(opening_fault(&line), Some(1));
assert_eq!(
opening(2, &[9], &pipelines[..1]),
"fault dump 2/3: the device was lost running command buffer 9, which bound 1 pipeline: \
render 7"
);
assert_eq!(
opening(3, &[9], &[]),
"fault dump 3/3: the device was lost running command buffer 9, which bound no pipeline"
);
assert_eq!(
opening(1, &[], &[]),
"fault dump 1/3: the device was lost with no submitted command buffer unfinished"
);
let many: Vec<String> = (0..10).map(|id| format!("render {id}")).collect();
assert!(opening(1, &[1], &many).ends_with("render 9 (the first 8 follow)"));
}
/// Only an opening line names a fault for the platform, and only its own.
#[test]
fn only_an_opening_line_names_its_fault() {
assert_eq!(
opening_fault("fault dump 2/3: the device was lost"),
Some(2)
);
assert_eq!(
opening_fault(&shader(1, "render 7", 0, "f", &vertex())),
None
);
assert_eq!(opening_fault("DeviceLost in operation 9 running ..."), None);
assert_eq!(opening_fault("fault dump x/3: ..."), None);
}
#[test]
fn a_stage_line_gives_its_code_hash_statistics_and_every_header_word() {
let line = shader(1, "render 7", 0, "vertex_main+fragment_main", &vertex());
let header: Vec<String> = (0..32)
.map(|word| format!("{:08x}", 0x0006_1060 + word))
.collect();
assert_eq!(
line,
format!(
"fault dump 1 render 7 variant 0 vertex (vertex_main+fragment_main): code=256 \
sha256=40aff2e9d2d8922e47afd4648e6967497158785fbd1da870e7110266bf944880 \
instructions=12 gprs=24 slm=0 sph_va=0x300000080 upload=queue sph={}",
header.join(" ")
)
);
assert_eq!(
reference_sha256(&vertex().code),
"40aff2e9d2d8922e47afd4648e6967497158785fbd1da870e7110266bf944880"
);
// Compute has no header, and a driver may give no statistics.
let compute = ShaderImage {
stage: "compute".to_string(),
code: vec![0xde, 0xad],
..ShaderImage::default()
};
let line = shader(2, "compute 3", 1, "k", &compute);
assert_eq!(
line,
format!(
"fault dump 2 compute 3 variant 1 compute (k): code=2 sha256={} sph=none",
reference_sha256(&[0xde, 0xad])
)
);
let mapped = ShaderImage {
statistics: vec![("Uploaded by queue".to_string(), 0)],
geometry_header: vec![1, 2],
..vertex()
};
let line = shader(1, "render 8", 0, "m", &mapped);
assert!(line.contains(" upload=mapped sph="));
assert!(line.ends_with(" gs_sph=00000001 00000002"));
}
#[test]
fn header_bytes_read_as_little_endian_words() {
assert_eq!(
words(&[0x62, 0x10, 0x06, 0x00, 1, 0, 0, 0, 0xff]),
[0x0006_1062, 1]
);
}
/// The first fault's hex stops at its budget, across stages, and says how
/// much it left out; a later fault's budget gives none.
#[test]
fn hex_lines_stop_at_the_budget_and_count_the_rest() {
let image = vertex();
let mut budget = HexBudget::new(HEX_LINE_BYTES * 3 + 10);
let lines = budget.code(1, "render 7", 0, &image);
assert_eq!(lines.len(), 4, "three whole lines and part of a fourth");
assert_eq!(
lines[1],
format!(
"fault dump 1 render 7 variant 0 vertex code+0x0040: {}",
(64..128u32)
.map(|byte| format!("{byte:02x}"))
.collect::<String>()
)
);
assert_eq!(lines[3].split(": ").nth(1).unwrap().len(), 20);
assert!(budget.code(1, "render 7", 0, &image).is_empty());
assert_eq!(
budget.end(1, HEX_LINE_BYTES * 3 + 10).as_deref(),
Some("fault dump 1 hex: 310 bytes of code past the 202-byte budget not shown")
);
let mut none = HexBudget::new(0);
assert!(none.code(2, "render 7", 0, &image).is_empty());
assert_eq!(none.end(2, 0), None, "a later fault gives no hex to miss");
let mut whole = HexBudget::new(HEX_BUDGET);
assert_eq!(whole.code(1, "render 7", 0, &image).len(), 4);
assert_eq!(whole.end(1, HEX_BUDGET), None);
}
#[test]
fn every_line_starts_with_the_prefix_the_platform_logs_whole() {
let image = vertex();
let lines = [
opening(1, &[1], &["render 1".to_string()]),
released(1, "render 1"),
no_shaders(1, "render 1", 0, "f"),
more_variants(1, "render 1", 2),
shader(1, "render 1", 0, "f", &image),
HexBudget::new(64).code(1, "render 1", 0, &image).remove(0),
];
for line in lines {
assert!(line.starts_with(PREFIX), "{line}");
assert!(!line.contains('\n'), "{line}");
}
}
+137 -11
View File
@@ -34,6 +34,7 @@ use super::{
binding::{HEAP_SET, HeapLayout, NULL_DESCRIPTOR, PushConstants},
command_buffer::Segment,
error::{Error, Result, ensure},
fault_dump::{self, ShaderImage},
vulkan::{
SampleCounts,
backend::{
@@ -55,6 +56,7 @@ use alloc::{
boxed::Box,
collections::{BTreeMap, VecDeque},
format,
string::String,
sync::Arc,
vec::Vec,
};
@@ -548,6 +550,131 @@ struct Executables {
log: fn(&str),
}
/// A statistic's value as an unsigned count; 0 for a format that is none.
fn statistic_value(statistic: &vk::PipelineExecutableStatisticKHR) -> u64 {
match statistic.format {
vk::PipelineExecutableStatisticFormatKHR::UINT64 => {
// SAFETY: the format names the union's member.
unsafe { statistic.value.u64 }
}
vk::PipelineExecutableStatisticFormatKHR::INT64 => {
// SAFETY: as above.
unsafe { statistic.value.i64 }.max(0) as u64
}
_ => 0,
}
}
/// A name the driver wrote into a fixed array of C characters.
fn described(name: core::result::Result<&CStr, core::ffi::FromBytesUntilNulError>) -> String {
name.ok()
.and_then(|name| name.to_str().ok())
.unwrap_or("?")
.into()
}
impl Executables {
/// Each of `pipeline`'s stages as the driver compiled it, for a lost
/// device's fault dump: NVK's statistics, and the program header and
/// machine code its internal representations give (Mesa patch 0043).
fn images(&self, pipeline: vk::Pipeline) -> Vec<ShaderImage> {
let info = vk::PipelineInfoKHR::default().pipeline(pipeline);
// SAFETY: the pipeline is alive: the device holds the object that
// made it. The driver reads only its CPU copy of each shader.
let Ok(executables) = (unsafe { self.fns.get_pipeline_executable_properties(&info) })
else {
return Vec::new();
};
executables
.iter()
.enumerate()
.map(|(index, executable)| {
let info = vk::PipelineExecutableInfoKHR::default()
.pipeline(pipeline)
.executable_index(index as u32);
// SAFETY: the executable is one the pipeline listed.
let statistics = unsafe { self.fns.get_pipeline_executable_statistics(&info) }
.unwrap_or_default()
.iter()
.map(|statistic| {
(
described(statistic.name_as_c_str()),
statistic_value(statistic),
)
})
.collect();
let mut image = ShaderImage {
stage: described(executable.name_as_c_str()),
statistics,
..ShaderImage::default()
};
for (name, bytes) in self.representations(&info) {
match name.as_str() {
"NAK program header" => image.header = fault_dump::words(&bytes),
"NAK geometry program header" => {
image.geometry_header = fault_dump::words(&bytes)
}
"NAK binary" => image.code = bytes,
_ => {}
}
}
image
})
.collect()
}
/// The executable's internal representations, by name, with their
/// bytes: the driver says each one's size, then fills buffers of them.
fn representations(&self, info: &vk::PipelineExecutableInfoKHR<'_>) -> Vec<(String, Vec<u8>)> {
// SAFETY: the executable is one the pipeline listed; with no data
// pointers the driver writes each representation's size alone.
let Ok(sized) = (unsafe {
self.fns
.get_pipeline_executable_internal_representations(info)
}) else {
return Vec::new();
};
let mut buffers: Vec<Vec<u8>> = sized
.iter()
.map(|representation| alloc::vec![0; representation.data_size])
.collect();
let mut filled: Vec<vk::PipelineExecutableInternalRepresentationKHR<'_>> = buffers
.iter_mut()
.map(|buffer| vk::PipelineExecutableInternalRepresentationKHR {
data_size: buffer.len(),
p_data: buffer.as_mut_ptr().cast(),
..Default::default()
})
.collect();
let mut count = filled.len() as u32;
// SAFETY: each structure points at a buffer of the size it names,
// alive and not otherwise reached until the call returns.
let result = unsafe {
(self
.fns
.fp()
.get_pipeline_executable_internal_representations_khr)(
self.fns.device(),
info,
&mut count,
filled.as_mut_ptr(),
)
};
if result != vk::Result::SUCCESS {
return Vec::new();
}
filled
.iter()
.zip(buffers)
.take(count as usize)
.map(|(representation, mut bytes)| {
bytes.truncate(representation.data_size);
(described(representation.name_as_c_str()), bytes)
})
.collect()
}
}
pub struct NativeBackend {
// A failed idle query leaves the driver's code and export owner live.
_entry: ManuallyDrop<ash::Entry>,
@@ -1862,17 +1989,7 @@ impl NativeBackend {
let Ok(statistics) = (unsafe { fns.get_pipeline_executable_statistics(&info) }) else {
continue;
};
let value = |statistic: &vk::PipelineExecutableStatisticKHR| match statistic.format {
vk::PipelineExecutableStatisticFormatKHR::UINT64 => {
// SAFETY: the format names the union's member.
unsafe { statistic.value.u64 }
}
vk::PipelineExecutableStatisticFormatKHR::INT64 => {
// SAFETY: as above.
unsafe { statistic.value.i64 }.max(0) as u64
}
_ => 0,
};
let value = statistic_value;
let named = |name: &str| {
statistics
.iter()
@@ -3643,6 +3760,15 @@ impl Backend for NativeBackend {
fn take_unbound(&mut self) -> Vec<u64> {
core::mem::take(&mut self.unbound)
}
fn shader_images(&mut self, pipeline: Pipeline) -> Vec<ShaderImage> {
self.fns
.executables
.as_ref()
.map_or_else(Vec::new, |executables| {
executables.images(handle(pipeline.0))
})
}
}
/// Submits `pending` in one `vkQueueSubmit2` and empties it.
@@ -400,6 +400,9 @@ pub struct Service<B: Backend, C: Compiler> {
served: (u32, Status),
/// Whether a refusal named the work the device was lost running.
loss_described: bool,
/// The boot's faults left to dump when a loss is described
/// ([`crate::metal::fault_dump`]).
faults: &'static crate::metal::fault_dump::Limiter,
/// Whether a close reported what held work keeps.
pins_reported: bool,
/// The bytes of the call served now's library, read before its turn
@@ -448,6 +451,7 @@ impl<B: Backend, C: Compiler> Service<B, C> {
dropped: Dropped::default(),
served: (0, Status::Ok),
loss_described: false,
faults: crate::metal::fault_dump::Limiter::boot(),
pins_reported: false,
staged_library: None,
library_wanted: None,
@@ -116,6 +116,12 @@ impl<B: Backend, C: Compiler> Service<B, C> {
// What the GPU addresses near a fault held: the
// host kernel names the address and its neighbours.
book = self.device.memory_book_report();
// What it was running, shader by shader, for a
// fault that names no shader (Xid 13), the boot's
// first few losses only.
if let Some(fault) = self.faults.take() {
book.extend(self.device.fault_dump(fault));
}
format!(
"{fault} in operation {} running {}",
call.operation,
@@ -26,6 +26,7 @@ use crate::metal::{
binding::HeapArray,
command_buffer::Segment,
error::{Error, Result, ensure},
fault_dump::ShaderImage,
};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use core::{any::Any, num::NonZeroU64};
@@ -522,6 +523,14 @@ pub trait Backend {
fn take_unbound(&mut self) -> Vec<u64> {
Vec::new()
}
/// Each stage of `pipeline` as the driver compiled it: its program
/// header, machine code and statistics, for a lost device's fault dump
/// ([`crate::metal::fault_dump`]). None when the driver does not report
/// them. Only CPU copies are read, so a lost device still answers.
fn shader_images(&mut self, _pipeline: Pipeline) -> Vec<ShaderImage> {
Vec::new()
}
}
/// A Vulkan feature or extension the Metal layer needs from every device.