Time a fault that later failing encoders follow as Metal's GPU reaches them

The steps this packet landed as, in order:
- Stop a running predicated loop at the GPU's recovery from a fault or a hang
- Resolve multisampled extended-range targets by Metal's measured rules
- Run the emulation's indirect mesh draws with an object function

Content: the tree of `development` at 60cf488339, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:07 +02:00
1 parent b8fb5f48c2
commit b0b61ac179
51 files changed
+3577 -461

No files matched your search

@@ -35,6 +35,26 @@
//! encoder; the queue's command buffers committed meanwhile join its list, read `Scheduled`
//! early ([`holding`]), and run.
//!
//! Metal's GPU that faulted at an encoder goes on, once it recovered, to the later encoders that
//! fail too ([`Later`]): an indexed draw of type 9 then a direct one of 3 vertices, or another
//! indexed one. Measured on the M3 Max (macOS 27.0.1, 88 such command buffers, each pass its own
//! encoder, fresh processes and warm ones): the command buffer failed with the first fault's
//! error (`PageFault`, 88 of 88), every event signal firing. It read `Scheduled` 14.3 to 21.0 ms
//! after its commit, where one that faulted once read it 8.4 to 9.4 ms after and completed 6.1 to
//! 9.0 ms after that: once the GPU recovered from the fault. It completed 25.8 to 29.1 ms after
//! that where a hang followed the fault (56), 6.05 to 9.67 ms after it where a fault did (17), 12.7
//! to 16.5 ms where two did (5), and 31.65 to 34.97 ms where a fault then a hang did (5); past a
//! hang the GPU reached nothing (a fault after it added nothing, 27.0 to 27.2 ms, 5). The queue's
//! command buffer committed right after it ran nothing where a hang followed the fault (6 of 6),
//! and in 1 of 2 where a fault did. The encoders between the fault and the later failure ran in
//! that shape, as the ones after a single fault there did. A command buffer whose GPU hangs first
//! fails as a hang alone does (30 of 30: `GpuHang`, 27.0 to 28.1 ms after `Scheduled`, the fault
//! after the hang never reached). The runtime answers: `Scheduled` [`FAULT_FROM_REACHED`] after
//! the GPU reached the fault, its wait going [`FAULT_FROM_REACHED`] after that for each later
//! fault, then [`FROM_REACHED`] for a hang ([`Held::after_recovered`]); the queue's command
//! buffers committed meanwhile run nothing where a hang follows, as during a hang, and run where
//! faults alone do; and from the fault on nothing runs, as after a single fault.
//!
//! - **The hold.** The hanging encoder's end signals an event of the hang's own to 1 after the
//! encoder, and adds the runtime's own wait ([`Batches::hold`]) for 2 after that, so what
//! follows it in the command buffer (its later event signals, its completion) waits; its commit
@@ -75,6 +95,10 @@
//! whose waits are not met by then, and every one after it, read `Scheduled` with their last
//! batch, after the hang's, as does every one where the hang's own came with its last batch, and
//! one with a switch of storage forms riding on its commit.
//! - **The device's recovery.** As its wait goes, the hold raises the device's recovery from
//! what it holds for: a hang's, and a fault's that a hang follows, from a hang; else from a
//! fault. A fault's that later failures follow raised the fault's already, as it read
//! `Scheduled`. A predicated loop running meanwhile ends there (`recovery.rs`).
//!
//! [`Batches::hold`]: super::batches::Batches::hold
@@ -82,6 +106,7 @@ use super::super::event::{EventShared, SharedEvent};
use super::super::exit_guard;
use super::super::gpu_time;
use super::super::{CommandQueue, Device, Error};
use super::recovery::Recovery;
use super::{lock, CommandBufferShared, CommitFailure, FailedEncoders, Item, State};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
@@ -167,9 +192,9 @@ impl Verdict {
impl QueueHangs {
/// The count of holds in flight of `held`'s kind.
fn counter(&self, held: Held) -> &AtomicUsize {
match held {
Held::Hang => &self.in_flight,
Held::Fault => &self.holding,
match held.discards() {
true => &self.in_flight,
false => &self.holding,
}
}
@@ -235,16 +260,33 @@ pub(super) enum Held {
/// Metal's GPU hangs at its encoder (`CommandBufferError::GpuHang`).
Hang,
/// Metal's GPU faults at its encoder, or fails it as a victim of its recovery
/// (`CommandBufferError::PageFault`, `GpuRecoveryVictim`).
Fault,
/// (`CommandBufferError::PageFault`, `GpuRecoveryVictim`), then at the later encoders
/// [`Later`] counts, which it reaches once it recovered.
Fault(Later),
}
/// The ended encoders after a faulting one that Metal's GPU fails too, which it reaches once it
/// recovered from the fault (the module docs): the faults (victims too) before the first hang,
/// and whether a hang follows them, past which it reaches none.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Later {
faults: u32,
hang: bool,
}
impl Held {
/// Whether the queue's command buffers committed meanwhile run nothing, as during a hang (a
/// hang's hold, and a fault's that a hang follows), or run (a fault's alone, or followed by
/// faults alone) (the module docs).
fn discards(self) -> bool {
matches!(self, Held::Hang | Held::Fault(Later { hang: true, .. }))
}
/// When after its commit the command buffer reads `Scheduled` at the earliest.
fn scheduled(self) -> Duration {
match self {
Held::Hang => SCHEDULED,
Held::Fault => Duration::ZERO,
Held::Fault(_) => Duration::ZERO,
}
}
@@ -252,7 +294,32 @@ impl Held {
fn after_reached(self) -> Duration {
match self {
Held::Hang => FROM_REACHED,
Held::Fault => FAULT_FROM_REACHED,
Held::Fault(_) => FAULT_FROM_REACHED,
}
}
/// What the GPU recovers from as the wait goes: a hang's, and a fault's that a hang follows,
/// from a hang; else from a fault (`recovery.rs`).
fn recovery(self) -> Recovery {
match self.discards() {
true => Recovery::Hang,
false => Recovery::Fault,
}
}
/// A fault's that later failures follow: how long after it read `Scheduled`, once the GPU
/// recovered from the fault, its wait goes: [`FAULT_FROM_REACHED`] for each later fault, then
/// [`FROM_REACHED`] for a hang. `None` for a hang's, and a fault's alone.
fn after_recovered(self) -> Option<Duration> {
match self {
Held::Fault(Later { faults, hang }) if faults > 0 || hang => {
let hang = match hang {
true => FROM_REACHED,
false => Duration::ZERO,
};
Some(FAULT_FROM_REACHED * faults + hang)
}
_ => None,
}
}
}
@@ -306,6 +373,20 @@ impl Hang {
self.encoder
}
/// Metal's GPU fails a later ended encoder too, hanging there where `hangs`, else faulting:
/// a fault's hold counts it, the GPU reaching it once it recovered, unless a hang came before
/// it, past which the GPU reaches nothing (the module docs).
pub(super) fn fails_later(&mut self, hangs: bool) {
let Held::Fault(later) = &mut self.held else {
return;
};
match (later.hang, hangs) {
(true, _) => {}
(false, true) => later.hang = true,
(false, false) => later.faults += 1,
}
}
/// The event of its signals and its wait.
pub(super) fn event(&self) -> &SharedEvent {
&self.event
@@ -317,15 +398,18 @@ impl Hang {
}
/// The command buffer `buffer`, of state `state`, committed at `committed`, runs its hold:
/// its queue counts it until its work signalled [`Hang::DONE`] (a hang's among those that
/// discard the queue's others, a fault's among those that do not); it reads `Scheduled`
/// [`SCHEDULED`] after the commit (a hang's) or at once (a fault's), or later once the batch
/// before its wait was taken ([`Scheduling::Hang`]), and the queue's command buffers committed
/// meanwhile follow ([`QueueHangs::schedule_early`]); its wait goes [`FROM_REACHED`] (a
/// hang's) or [`FAULT_FROM_REACHED`] (a fault's) after it read `Scheduled` and the GPU reached
/// the encoder. One with a switch of storage forms riding on its commit, which settles by its
/// last batch's submission, reads `Scheduled` with that batch, as do the queue's others. Where
/// no thread can be made for that, the wait goes at once, the queue not counting it.
/// its queue counts it until its work signalled [`Hang::DONE`] (a hang's, and a fault's that
/// a hang follows, among those that discard the queue's others; another fault's among those
/// that do not); it reads `Scheduled` [`SCHEDULED`] after the commit (a hang's) or at once (a
/// fault's), or later once the batch before its wait was taken ([`Scheduling::Hang`]), and the
/// queue's command buffers committed meanwhile follow ([`QueueHangs::schedule_early`]); its
/// wait goes [`FROM_REACHED`] (a hang's) or [`FAULT_FROM_REACHED`] (a fault's) after it read
/// `Scheduled` and the GPU reached the encoder. A fault's that later failures follow reads
/// `Scheduled` [`FAULT_FROM_REACHED`] after the GPU reached the encoder, and its wait goes
/// [`Held::after_recovered`] after that. One with a switch of storage forms riding on its
/// commit, which settles by its last batch's submission, reads `Scheduled` with that batch,
/// as do the queue's others. Where no thread can be made for that, the wait goes at once, the
/// queue not counting it.
pub(super) fn start(
self,
buffer: &Arc<CommandBufferShared>,
@@ -335,6 +419,7 @@ impl Hang {
let queue = &buffer.queue;
let hangs = Arc::clone(queue.hangs());
let trails = Arc::clone(&queue.device().shared().trails);
let recoveries = Arc::clone(&queue.device().shared().recoveries);
let held = self.held;
hangs.counter(held).fetch_add(1, Ordering::SeqCst);
let hang = {
@@ -353,17 +438,30 @@ impl Hang {
let builder = std::thread::Builder::new().name("metal2vulkan-hang".to_owned());
let ended = crate::exit_guard::spawn(builder, move || {
sleep_until(committed + held.scheduled());
let scheduled = hang_scheduled(weak);
event.wait_until_signaled_value(Hang::REACHED, SIGNAL_BOUND);
let release = Instant::now() + held.after_reached();
let (scheduled, release) = match held.after_recovered() {
// A fault that later failures follow reads `Scheduled` once the GPU recovered
// from it, and its wait goes once the GPU recovered from them too.
Some(after) => {
event.wait_until_signaled_value(Hang::REACHED, SIGNAL_BOUND);
std::thread::sleep(FAULT_FROM_REACHED);
recoveries.raise(Recovery::Fault);
(hang_scheduled(weak), Instant::now() + after)
}
None => {
let scheduled = hang_scheduled(weak);
event.wait_until_signaled_value(Hang::REACHED, SIGNAL_BOUND);
(scheduled, Instant::now() + held.after_reached())
}
};
match scheduled {
true => hangs.schedule_early(hang, release),
false => sleep_until(release),
}
let trail = trails.open();
if held == Held::Hang {
if held.discards() {
hangs.decide();
}
recoveries.raise(held.recovery());
event.set_signaled_value(Hang::RELEASED);
event.wait_until_signaled_value(Hang::DONE, SIGNAL_BOUND);
lock(&hangs.early).joined.clear();
@@ -374,7 +472,7 @@ impl Hang {
});
if ended.is_err() {
state.hang_scheduling = None;
if held == Held::Hang {
if held.discards() {
queue.hangs().decide();
}
lock(&queue.hangs().early).joined.clear();
@@ -41,6 +41,7 @@ pub(super) mod kept_barriers;
pub(super) mod own;
mod protection;
pub(super) mod rebound_use;
pub(super) mod recovery;
mod reencode;
pub(super) mod rerun;
pub(super) mod revocation;
@@ -106,7 +107,7 @@ use checks::{Checks, SubmissionCheck};
use completion::Submitted;
use first_submission::{Listing, Live};
use gate::{Gate, Hold};
use hang::{Hang, Held};
use hang::{Hang, Held, Later};
use metal2vulkan::bind::{
ExecutionStatus, IndexBoundsPass, ReplayFaults, ResidentRange, ResidentSet, RootTable,
StatusReport,
@@ -1223,6 +1224,8 @@ impl State {
/// it on (`faulted`, `Failure::with_faults`); where nothing failed it from an earlier encoder
/// and no earlier encoder faulted, the work before the encoder signals the fault's hold and
/// what follows waits for it (`hang.rs`), so the command buffer completes when Metal's does.
/// Where an earlier encoder faulted, the GPU reaches this one once it recovered: the earlier
/// fault's hold counts it (`Hang::fails_later`).
pub(super) fn fault(
&mut self,
encoder: usize,
@@ -1230,7 +1233,11 @@ impl State {
device: &Device,
) -> Result<(), Error> {
if self.fails_from.is_none() && self.hang.is_none() {
self.hold(device, encoder, Held::Fault)?;
self.hold(device, encoder, Held::Fault(Later::default()))?;
} else if !self.faulted.contains_key(&encoder) {
if let Some(hang) = &mut self.hang {
hang.fails_later(false);
}
}
self.faulted.entry(encoder).or_insert(error);
Ok(())
@@ -1240,9 +1247,13 @@ impl State {
/// (`hang.rs`): the command buffer fails from it on with `CommandBufferError::GpuHang`, and,
/// where nothing failed it from an earlier encoder, the work before the encoder signals the
/// hang's event and what follows waits for the hang's hold. Where an earlier encoder faulted,
/// the GPU never reaches it: it fails from the fault (`State::fault`).
/// it fails from the fault with the fault's error (`State::fault`), and the GPU reaches it
/// once it recovered: the fault's hold counts it (`Hang::fails_later`).
pub(super) fn hang_from(&mut self, encoder: usize, device: &Device) -> Result<(), Error> {
if !self.faulted.is_empty() {
if let Some(hang) = &mut self.hang {
hang.fails_later(true);
}
return Ok(());
}
if self.fails_from.is_none() && self.hang.is_none() {
@@ -0,0 +1,107 @@
//! The recoveries of a device's GPU from a fault or a hang, as Metal's GPU makes them, and what
//! they do to a predicated loop that runs again meanwhile (`rerun.rs`).
//!
//! Metal's GPU recovers from a page fault or a hang device-wide: a predicated loop running on the
//! device when it does stops there. Measured on the M3 Max (macOS 27.0.1): a `While` loop of
//! 160,000 passes, its unit's encoder followed by a mark and a blit, committed on a queue; 50 ms on,
//! two command buffers drawing primitive type 9 committed on that queue or another one.
//! - A fault (an indexed draw, `PageFault`; 6 runs, committed 50 ms on or at once) failed the
//! loop's command buffer as a victim (`MTLCommandBufferErrorInternal`,
//! `CommandBufferError::GpuRecoveryVictim`) 0.0 to 0.02 ms before the faulting one completed,
//! 3,463 to 39,098 passes in. The loop ran on through the fault's 8 ms hold, and nothing after
//! its encoder ran.
//! - A hang (a direct draw, `GpuHang`; 2 runs) ended the loop with no error 0.05 to 0.08 ms
//! before the hanging one failed, about 53,450 passes in. Its command buffer completed cleanly
//! and nothing after the loop's encoder ran.
//! - A loop committed behind faults that recovered before it started ran all its passes.
//!
//! The runtime answers so: each hold (`hang.rs`) raises the device's recovery from what it holds
//! for as its wait goes, the GPU's recovery ([`Recoveries::raise`]). A fault's hold that later
//! failures follow raises the fault's once it read `Scheduled`, and the later ones' as its wait
//! goes. Before each run again a loop asks for the first recovery since its command buffer's
//! first submission ([`Recoveries::since`]):
//! - after a fault's, it fails as a victim;
//! - after a hang's, it stops with no error ([`cut`]): from the check's part on, nothing of the
//! command buffer runs, and it completes cleanly. Whether its later event signals fire is not
//! measured; they fire.
//!
//! A fault committed on the loop's own queue behind the loop waits for the loop to end in the
//! runtime, as every batch of a queue does, where Metal's GPU runs it during the loop
//! (`docs/FAST-PATHS.md`, known gaps).
use super::super::gpu_time;
use super::rerun::LoopCheck;
use super::{lock, CommandBufferShared, State};
use crate::deferred::Deferred;
use crate::encoder::Recorded;
use std::sync::atomic::{AtomicU64, Ordering};
/// A device's GPU recoveries (the module docs): when the last from a fault and the last from a
/// hang came, in host nanoseconds (`gpu_time::host_nanos`); 0 for none.
#[derive(Default)]
pub(crate) struct Recoveries {
fault: AtomicU64,
hang: AtomicU64,
}
/// What the GPU recovered from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Recovery {
/// A page fault, or a draw it fails as a victim of its recovery
/// (`CommandBufferError::PageFault`, `GpuRecoveryVictim`).
Fault,
/// A hang (`CommandBufferError::GpuHang`).
Hang,
}
impl Recoveries {
/// The GPU recovered from `recovery`, now.
pub(super) fn raise(&self, recovery: Recovery) {
let at = match recovery {
Recovery::Fault => &self.fault,
Recovery::Hang => &self.hang,
};
at.fetch_max(gpu_time::host_nanos(), Ordering::AcqRel);
}
/// The GPU's first recovery after host time `since` (nanoseconds), of each kind's last:
/// `None` where none came since.
pub(super) fn since(&self, since: u64) -> Option<Recovery> {
let after = |at: &AtomicU64| Some(at.load(Ordering::Acquire)).filter(|&at| at > since);
match (after(&self.fault), after(&self.hang)) {
(Some(fault), Some(hang)) if hang < fault => Some(Recovery::Hang),
(Some(_), _) => Some(Recovery::Fault),
(None, Some(_)) => Some(Recovery::Hang),
(None, None) => None,
}
}
}
/// The first recovery of `buffer`'s device since its first submission (the module docs).
pub(super) fn recovered(buffer: &CommandBufferShared) -> Option<Recovery> {
let since = buffer.kernel.start();
buffer.device.shared().recoveries.since(since)
}
/// The loop of `check` stopped at a hang's recovery (the module docs): every part of `buffer`
/// from the one holding the check on runs nothing, each keeping its place among the batches with
/// its fences' waits and updates alone (`State::fail_part`), and the command buffer completes
/// with no error.
pub(super) fn cut(buffer: &CommandBufferShared, check: &LoopCheck) {
let mut state = lock(&buffer.state);
let State {
recorded, retained, ..
} = &mut *state;
let holds_check = |part: &Recorded| {
part.segments.iter().any(|segment| match &segment.work {
Deferred::Loop(held) => std::ptr::eq(&**held, check),
_ => false,
})
};
let Some(from) = recorded.iter().position(holds_check) else {
return;
};
for part in &mut recorded[from..] {
State::fail_part(part, retained);
}
}
@@ -39,13 +39,15 @@
//! once the check ends: they read what the laying leaves.
//! - **Ends.** As Metal's GPU runs a loop without bound on after the program let go of every
//! handle of its queue and its device, so does the thread, which holds the command buffer, and
//! through it the queue and the device. It stops only at a lost device, a failed submission,
//! wait or recording (each failing the command buffer as its submission or host step would),
//! or the process's exit, which it never holds up: it waits in slices of [`WAIT_SLICE`], each
//! inside a section of the exit guard, and does nothing more once the guard closes. Each run
//! again is counted (`WorkCounts::predicated_loop_runs_again`).
//! through it the queue and the device. It stops only at a lost device, the GPU's recovery
//! from a fault or a hang anywhere on the device, as Metal's loop does (`recovery.rs`), a
//! failed submission, wait or recording (each failing the command buffer as its submission or
//! host step would), or the process's exit, which it never holds up: it waits in slices of
//! [`WAIT_SLICE`], each inside a section of the exit guard, and does nothing more once the
//! guard closes. Each run again is counted (`WorkCounts::predicated_loop_runs_again`).
use super::gate::Hold;
use super::recovery::{self, Recovery};
use super::{
command_pool, recording_error, step_error, submission_error, CommandBuffer, CommandBufferShared,
};
@@ -177,6 +179,8 @@ enum Round {
Ended,
/// The command buffer fails so.
Failed(CommandBufferError),
/// The loop stopped with no error, and nothing after it runs (`recovery.rs`).
Cut,
/// The process is exiting: the thread does nothing more.
Exiting,
}
@@ -482,12 +486,17 @@ fn nothing() -> RecordedSegment {
}
/// The loop's decision before each run again: `None` where it runs again; else how it ends
/// without running. It stops once its device is lost (the module docs).
/// without running. It stops once its device is lost (the module docs), and at the GPU's
/// recovery from a fault (as a victim) or a hang (cut) since its command buffer's first
/// submission (`recovery.rs`).
fn before_round(buffer: &CommandBufferShared) -> Option<Round> {
if buffer.device.is_lost() {
return Some(Round::Failed(CommandBufferError::DeviceLost));
}
None
match recovery::recovered(buffer)? {
Recovery::Fault => Some(Round::Failed(CommandBufferError::GpuRecoveryVictim)),
Recovery::Hang => Some(Round::Cut),
}
}
/// The check's thread (the module docs): run the laying again until the loop ends, or the check
@@ -515,6 +524,10 @@ fn run_again(check: &LoopCheck, buffer: Hold<CommandBufferShared>) {
Round::Ended => break (None, true),
// A recording it left unended leaves the pool to be reset.
Round::Failed(error) => break (Some(error), false),
Round::Cut => {
recovery::cut(&buffer, check);
break (None, true);
}
// What it holds stays held to the process's end, as the scheduler's does.
Round::Exiting => {
std::mem::forget(arenas);