From 8da4dbcce37475e5a8b3db8d0e8a37492fb5d093 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 14:42:25 +1100 Subject: [PATCH 01/10] drm/asahi: recover from G14 firmware 27.2 command timeouts and faults per client When a command runs past its execution allowance or faults, the G14 firmware 27.2 reports it on the event ring (kind 4 timeout with the named slot at +0xc, kind 0 fault) and stops every queue in a recovery handshake: it publishes phase 1 at control +0x4c00, advances the u64 generation at +0x4bf0 and records the stopped work at +0x4298 as {flags, target} pairs. It runs nothing until the host answers 2 and, at its phase 3, 0. This is the order G16 and M3 answer in their firmware data. The runtime decoded neither event. A stuck command stopped the whole GPU until the host's own timeout failed every client, so a single test client took the compositor down with it. Decode both events and answer the handshake. Mark the stopped work: the published render pair (a render is always published alone) or the oldest unretired compute command and the rest of its packet. Clear the TPC storage of a stopped tiler (snapshot flags 0x9) before answering 2, as G16 does. Then wait for phase 3 with an unchanged generation, answer 0, and wait for the stopped work to leave its queue. Its stamp is not written, so its position is what counts. It fails only its own packet and VM, so the client sees a lost context. Work queued behind it has its clocks restarted and retires normally. Further recoveries while the work drains are answered up to four times. If the firmware does not enter recovery, reach phase 3 or drain, all work fails as before. A host timeout that finds phase 1 without a seen event takes the same path. A doomed packet records the error in its VM status even if a racing scheduler timeout claimed its fence first. The handshake decisions are G16's: which phase the host may answer, how a snapshot entry decodes and the recovery-storm window (32 in 10 s) come from its pure, host-tested g16/recovery/logic.rs, included by path rather than copied. The G14 27.2 record kinds, recovery offsets and the stopped-tiler rule move to g14_v27_2_abi.rs with host tests (tools/asahi/g14-v27-2-abi-tests.rs, registered in run-host-tests.py). Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/buffer.rs | 14 ++ drivers/gpu/drm/asahi/g14_v27_2.rs | 269 ++++++++++++++++++++-- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 77 +++++++ drivers/gpu/drm/asahi/g14_v27_2_render.rs | 5 + drivers/gpu/drm/asahi/gpu/v27_2.rs | 77 ++++++- tools/asahi/g14-v27-2-abi-tests.rs | 5 + tools/asahi/run-host-tests.py | 2 + 7 files changed, 429 insertions(+), 20 deletions(-) create mode 100644 tools/asahi/g14-v27-2-abi-tests.rs diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index 1680fd05d035..cd79a762cb3e 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -198,6 +198,20 @@ impl Scene::ver { self.object.tpc.gpu_pointer() } + /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after + /// a firmware recovery stopped its tiler finds no tiles. + #[allow(dead_code)] + pub(crate) fn clear_tpc(&self, bytes: usize) -> Result { + let tpc = self.object.tpc.as_slice(); + if bytes > tpc.len() { return Err(ERANGE); } + // SAFETY: the TPC belongs to this scene, whose tiler was stopped by the firmware and is + // halted; nothing else writes it until the scene's fragment pass runs or is dropped. + unsafe { core::ptr::write_bytes(tpc.as_ptr().cast_mut(), 0, bytes) }; + crate::pgtable::clean_poc(tpc.as_ptr(), bytes); + crate::pgtable::poc_barrier(); + Ok(()) + } + /// Returns the GPU pointer to the first preemption scratch buffer. pub(crate) fn preempt_buf_1_pointer(&self) -> GpuPointer<'_, &'_ [u8]> { self.object.preempt_buf.gpu_pointer() diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index e9edc12813ab..a6c9056771ab 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -40,6 +40,14 @@ use crate::{ m3::m3_submit::{Command, Packet}, }; +/// The recovery handshake is the one G16 answers: share its decisions (which phase the host may +/// answer, how a snapshot entry decodes, the recovery-storm window) instead of restating them. +/// Its FirmwareData offsets are G16's own and unused here. +#[path = "g16/recovery/logic.rs"] +#[allow(dead_code)] +mod recovery_logic; +use recovery_logic::{RecoveryAction, SnapshotEntry}; + /// RTKit endpoints of the GPU firmware. const EP_FIRMWARE: u8 = 0x20; const EP_DOORBELL: u8 = 0x21; @@ -58,6 +66,14 @@ const RETIRE_WAIT_US: i64 = 2000; const RESOURCE_RETRY_MS: u32 = 10; /// Work item for the poll. Ordinary firmware notifications can still queue immediate work. const RETRY_WORK: u64 = 1; +/// The firmware's recovery handshake (the G16/M3 order and limits): phase 1 follows the error +/// event within 50 ms; the whole handshake within 1 s; then the stopped work leaves its queue. +const PHASE1_WAIT_MS: i64 = 50; +const HANDSHAKE_MS: i64 = 1000; +const RECOVERY_DRAIN_MS: i64 = 1000; +/// Further recoveries answered while the stopped work drains (work behind it can time out in +/// turn) before the runtime gives up. +const FURTHER_RECOVERIES: u32 = 4; struct FirmwareWait { since: Instant, @@ -399,6 +415,8 @@ struct Inflight { /// Queue publications up to and including this command, counted from take-over. ordinal: u64, started: Instant, + /// Set when the firmware stopped this command: it fails its packet when it leaves the queue. + doomed: Option, _bind: mmu::VmBind, } @@ -411,6 +429,7 @@ struct RenderFlight { stamps: [event::EventValue; 2], targets: [u32; 2], started: Instant, + doomed: Option, } struct State { @@ -447,6 +466,12 @@ struct State { accepting: bool, submitted: u64, retired: u64, + /// A fault or timeout the firmware reported (error, named slot), answered by `recover`. + firmware_error: Option<(Error, i32)>, + recoveries: u64, + /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. + recovery_window: u64, + recovery_count: u32, } impl State { @@ -706,7 +731,8 @@ impl Runtime { let ordinal = state.published + 1; // Commit ownership before the firmware can see the new work. state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + publication_error: None, started: Instant::now(), doomed: None, _bind: bind }, + GFP_KERNEL)?; packet.mark_published(); submission.publish(); state.last = stamp; @@ -762,7 +788,7 @@ impl Runtime { let fs_post = state.root.stage_render(FRAGMENT, &fs_work)?; state.rendering = Some(RenderFlight { packet: packet.clone(), last, bind, scene, slots, stamps, - targets: [ta_post.target(), fs_post.target()], started: Instant::now(), + targets: [ta_post.target(), fs_post.target()], started: Instant::now(), doomed: None, }); queue.published(); packet.mark_published(); @@ -801,19 +827,26 @@ impl Runtime { fn retire_render(&self, state: &mut State) -> Result { let Some(flight) = state.rendering.as_ref() else { return Ok(()); }; - let mut ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; - let mut fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + let (targets, stamps, doomed, started) = + (flight.targets, flight.stamps, flight.doomed, flight.started); + let done = |root: &RootV27_2, dm: usize| -> Result { + // A command the firmware stopped leaves its queue without reaching its stamp. + if doomed.is_some() { root.render_retired(dm, targets[dm]) } + else { root.render_done(dm, targets[dm], stamps[dm]) } + }; + let mut ta_done = done(&state.root, TILER)?; + let mut fs_done = done(&state.root, FRAGMENT)?; if !(ta_done && fs_done) - && state.root.render_queue(TILER).1 >= flight.stamps[TILER] - && state.root.render_queue(FRAGMENT).1 >= flight.stamps[FRAGMENT] + && state.root.render_queue(TILER).1 >= stamps[TILER] + && state.root.render_queue(FRAGMENT).1 >= stamps[FRAGMENT] { // As on the compute queue, the final stamp precedes the retired cursor and // there may be no separate notification when the cursor changes. let start = Instant::::now(); while !(ta_done && fs_done) && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { fsleep(Delta::from_micros(20)); - ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; - fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + ta_done = done(&state.root, TILER)?; + fs_done = done(&state.root, FRAGMENT)?; } } if ta_done && fs_done { @@ -821,13 +854,19 @@ impl Runtime { for slot in flight.slots { self.retire_slot(state, slot); } - if flight.last { + if let Some(err) = flight.doomed { + self.fail_doomed(state, &flight.packet, err); + } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { flight.packet.release_guard(); } - } else if flight.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); + if state.root.recovery_phase()? == 1 && doomed.is_none() { + // The firmware stopped it and halted, but its event was not seen. + return self.recover(state, ETIMEDOUT, -1); + } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); return Err(ETIMEDOUT); @@ -835,6 +874,176 @@ impl Runtime { Ok(()) } + /// Fails a packet the firmware stopped, once none of its commands is in a queue: its + /// unpublished commands are withdrawn, and its VM records the error (the client sees a + /// lost context). Other clients' work is not touched. + fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { + if state.owns(packet) { return; } + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + packet.release_guard(); + // Record it even if a racing scheduler timeout already claimed the fence (as fail_all). + if let Some(status) = packet.vm.status() { status.record(err); } + packet.finish(Err(err)); + } + + /// Marks the work the firmware stopped: the render pair if one is published (a render is + /// published alone), else the oldest unretired compute command and the rest of its packet. + /// Returns whether anything was published. + fn blame(&self, state: &mut State, error: Error, slot: i32) -> bool { + if let Some(flight) = state.rendering.as_mut() { + flight.doomed = Some(error); + let owner = &flight.packet.owner; + dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", + owner.process(), owner.pid, slot, error); + return true; + } + let Some(packet) = state.inflight.first().map(|f| f.packet.clone()) else { + dev_err!(self.dev, "GPU: firmware stopped with nothing published (slot {})\n", slot); + return false; + }; + for flight in state.inflight.iter_mut().filter(|f| Arc::ptr_eq(&f.packet, &packet)) { + flight.doomed = Some(error); + } + dev_err!(self.dev, "GPU: stopped compute of {}[{}] (slot {}, {:?})\n", + packet.owner.process(), packet.owner.pid, slot, error); + true + } + + /// Whether every command marked by `blame` has left its queue. + fn doomed_retired(&self, state: &mut State) -> Result { + if let Some(flight) = state.rendering.as_ref() { + if flight.doomed.is_some() { + return Ok(state.root.render_retired(TILER, flight.targets[TILER])? + && state.root.render_retired(FRAGMENT, flight.targets[FRAGMENT])?); + } + } + let Some(ordinal) = + state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal) + else { return Ok(true); }; + self.advance(state)?; + Ok(state.retired_total >= ordinal) + } + + /// Waits up to `ms` for the firmware's next recovery phase: 1 before the host answered, + /// 3 with the same `generation` after it answered 2. Ok(None) on timeout; Err(EPROTO) on + /// any phase the protocol does not allow (`recovery_logic::action`). + fn wait_recovery(&self, state: &mut State, answered: bool, generation: u64, ms: i64) + -> Result> { + let start = Instant::::now(); + loop { + let phase = state.root.recovery_phase()?; + let same = !answered || state.root.halt_count()? == generation; + match recovery_logic::action(phase, answered, same) { + RecoveryAction::Wait => {} + RecoveryAction::ProtocolError => { + dev_err!(self.dev, "GPU: recovery phase {} (answered {}, same generation {})\n", + phase, answered, same); + return Err(EPROTO); + } + found => return Ok(Some(found)), + } + if start.elapsed() > Delta::from_millis(ms) { return Ok(None); } + if state.peer.is_crashed() { return Err(EIO); } + let _ = state.root.drain(); + fsleep(Delta::from_millis(1)); + } + } + + /// The firmware recovery handshake after a fault or command timeout (the G16/M3 protocol). + /// The firmware stops every queue and publishes phase 1 with a generation and a snapshot of + /// the stopped work; the host marks that work (`blame`), clears the tiler storage of a + /// stopped tiler, answers 2, waits for 3 with the same generation and answers 0. The stopped + /// work then leaves its queue and fails only its own packet and VM; the next recoveries + /// while it drains are answered the same way, a bounded number of times. Errors here fail + /// all work (the runtime is not trusted). + fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { + state.root.log_timeout(&self.dev); + let mut rounds = 0; + let mut blamed = false; + loop { + if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { + dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", + error, slot); + return Err(ETIMEDOUT); + } + let now = ::ktime_get() as u64; + if !recovery_logic::admit(now, &mut state.recovery_window, &mut state.recovery_count) { + dev_err!(self.dev, "GPU: {} recoveries in {} s; not answering more\n", + recovery_logic::WINDOW_LIMIT, recovery_logic::WINDOW_NS / 1_000_000_000); + return Err(EIO); + } + let generation = state.root.halt_count()?; + let mut entries = 0; + let mut stopped_tiler = false; + for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { + let (flags, target) = state.root.recovery_entry(i)?; + let Some(entry) = SnapshotEntry::decode(flags, target) else { break; }; + entries += 1; + stopped_tiler |= gpu::stopped_tiler(entry.flags); + if entries <= 8 { + dev_err!(self.dev, + "GPU: recovery {} entry {}: flags {:#x} (event {:#x}) target {:#x}\n", + generation, i, entry.flags, entry.event, entry.target); + } + } + if !blamed { + blamed = true; + self.blame(state, error, slot); + } + if stopped_tiler { + if let Some(flight) = state.rendering.as_ref() { + let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; + if !ta_left { + flight.scene.clear_tpc()?; + dev_err!(self.dev, "GPU: cleared the stopped tiler's TPC storage\n"); + } + } + } + let start = Instant::::now(); + state.root.answer_recovery(2)?; + let mut reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + if reached.is_none() { + dev_warn!(self.dev, "GPU: no recovery phase 3 in {} ms; ringing the device-control doorbell\n", + HANDSHAKE_MS / 2); + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK); + reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + } + if reached != Some(RecoveryAction::Resume) { + return Err(ETIMEDOUT); + } + state.root.answer_recovery(0)?; + dev_err!(self.dev, "GPU: recovery {} answered in {} ms ({} snapshot entries)\n", + generation, start.elapsed().as_millis(), entries); + let start = Instant::::now(); + loop { + let _ = state.root.drain(); + if self.doomed_retired(state)? { + state.recoveries += 1; + // Work behind the stopped command waited out the recovery: restart its clocks. + let now = Instant::now(); + for flight in state.inflight.iter_mut() { flight.started = now; } + dev_err!(self.dev, + "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", + state.recoveries, start.elapsed().as_millis()); + return Ok(()); + } + if state.root.recovery_phase()? == 1 { break; } + if start.elapsed() > Delta::from_millis(RECOVERY_DRAIN_MS) { + dev_err!(self.dev, "GPU: stopped work did not leave the queue\n"); + state.root.log_timeout(&self.dev); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + rounds += 1; + dev_err!(self.dev, "GPU: firmware entered recovery again while the stopped work drained ({})\n", + rounds); + if rounds > FURTHER_RECOVERIES { return Err(EIO); } + } + } + /// Reads the queue's retired position into `retired_total`. fn advance(&self, state: &mut State) -> Result { let (_, raw) = state.root.progress()?; @@ -885,6 +1094,15 @@ impl Runtime { state.root.consume_event(cursor)?; return Err(EIO); } + FirmwareEvent::Timeout { slot } => { + dev_err!(self.dev, "GPU firmware timed out a command (slot {})\n", slot); + state.firmware_error.get_or_insert((ETIMEDOUT, slot)); + } + FirmwareEvent::Fault => { + dev_err!(self.dev, "GPU firmware reported a GPU fault\n"); + state.fault.log(&self.dev); + state.firmware_error.get_or_insert((EIO, -1)); + } FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} } state.waiting_control = None; @@ -907,6 +1125,13 @@ impl Runtime { self.fail_all(state, err); return; } + if let Some((error, slot)) = state.firmware_error.take() { + if let Err(err) = self.recover(state, error, slot) { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } + } if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } // The completion stamp is written before the firmware's post-processing advances the @@ -925,10 +1150,14 @@ impl Runtime { } while !state.inflight.is_empty() { let front = &state.inflight[0]; - if state.retired_total >= front.ordinal { + let (ordinal, started, unblamed, expected) = + (front.ordinal, front.started, front.doomed.is_none(), front.stamp.raw()); + if state.retired_total >= ordinal { if let Ok(done) = state.inflight.remove(0) { self.retire_slot(state, done.slot); - if let Some(err) = done.publication_error { + if let Some(err) = done.doomed { + self.fail_doomed(state, &done.packet, err); + } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); } else if done.last { @@ -939,9 +1168,17 @@ impl Runtime { } continue; } - if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", - state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); + state.queue_stamp(), expected, state.submitted, state.retired); + if unblamed && state.root.recovery_phase().unwrap_or(0) == 1 { + // The firmware stopped it and halted, but its event was not seen. + if let Err(err) = self.recover(state, ETIMEDOUT, -1) { + self.fail_all(state, err); + return; + } + continue; + } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); self.fail_all(state, ETIMEDOUT); @@ -1146,6 +1383,10 @@ impl Backend { accepting: true, submitted: 0, retired: 0, + firmware_error: None, + recoveries: 0, + recovery_window: 0, + recovery_count: 0, }); // From here the firmware's messages run the service; one run consumes anything it // published before. diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 535313f91126..501be19bdd1a 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -71,6 +71,52 @@ impl GrowRequest { } } +/// Control-object recovery words (the recovery block G16 and M3 answer in their FirmwareData): +/// the u64 recovery generation, which growth requests also carry; 0x10 on, the recovery phase +/// (firmware 1 -> host 2 -> firmware 3 -> host 0); the snapshot of the work the firmware +/// stopped, {flags u32, target u32} pairs, at the same offset as in the M3 object, up to the +/// next recovery field. Seen on the J473: a stopped tiler {0x1f, its next stamp}, a stopped +/// compute {0x7, its next stamp}. +pub(crate) const RECOVERY_GENERATION: usize = 0x4bf0; +pub(crate) const RECOVERY_PHASE: usize = 0x4c00; +pub(crate) const RECOVERY_SNAPSHOT: usize = 0x4298; +const RECOVERY_SNAPSHOT_END: usize = 0x4b20; +pub(crate) const RECOVERY_SNAPSHOT_ENTRIES: usize = (RECOVERY_SNAPSHOT_END - RECOVERY_SNAPSHOT) / 8; + +/// A snapshot entry of a stopped tiler (valid + tiler bits): its TPC storage must be cleared +/// before the host answers phase 2, as G16 does. +pub(crate) const fn stopped_tiler(flags: u32) -> bool { + flags & 9 == 9 +} + +/// Event ring record kinds. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum EventKind { + /// 0: the firmware stopped on a GPU fault and entered recovery. + Fault, + /// 4: the firmware timed out a command (slot at `TIMEOUT_SLOT_OFFSET`) and entered recovery. + Timeout, + /// 6: a buffer growth request. + Grow, + /// 7: the firmware rejected a channel record. + ChannelError, + /// Anything else (stage flags, statistics): nothing for the host to answer. + Notification, +} + +/// Byte offset of the slot a timeout record names. +pub(crate) const TIMEOUT_SLOT_OFFSET: usize = 0x0c; + +pub(crate) const fn event_kind(kind: u32) -> EventKind { + match kind { + 0 => EventKind::Fault, + 4 => EventKind::Timeout, + 6 => EventKind::Grow, + 7 => EventKind::ChannelError, + _ => EventKind::Notification, + } +} + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { @@ -148,4 +194,35 @@ mod tests { ] ); } + + #[test] + fn recovery_events_are_decoded_and_others_stay_notifications() { + assert_eq!(event_kind(0), EventKind::Fault); + assert_eq!(event_kind(4), EventKind::Timeout); + assert_eq!(event_kind(6), EventKind::Grow); + assert_eq!(event_kind(7), EventKind::ChannelError); + for kind in [1, 2, 3, 5, 8, u32::MAX] { + assert_eq!(event_kind(kind), EventKind::Notification); + } + // The H1 record [4, 0, 0, 1, ...]: slot in the fourth word. + assert_eq!(TIMEOUT_SLOT_OFFSET / 4, 3); + } + + #[test] + fn recovery_block_geometry_matches_the_g16_order() { + // Phase 0x10 above the u64 generation, as in the G16/M3 FirmwareData. + assert_eq!(RECOVERY_PHASE - RECOVERY_GENERATION, 0x10); + assert_eq!(RECOVERY_SNAPSHOT_ENTRIES, 273); + assert!(RECOVERY_SNAPSHOT + 8 * RECOVERY_SNAPSHOT_ENTRIES <= RECOVERY_SNAPSHOT_END); + assert!(RECOVERY_SNAPSHOT_END <= RECOVERY_GENERATION); + } + + #[test] + fn only_a_valid_tiler_entry_clears_tiler_storage() { + // J473 snapshots: stopped tiler {0x1f, ..}, stopped compute {0x7, ..}. + assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x7)); + assert!(!stopped_tiler(0x8)); + assert!(stopped_tiler(0x9 | (0x70 << 4))); + } } diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index 10ce122708db..c81b3b469974 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -76,6 +76,11 @@ impl Prep { pub(crate) fn slot(&self) -> u32 { self.scene.slot() } + + /// Clears the tiler's TPC storage after a firmware recovery stopped the tiler. + pub(crate) fn clear_tpc(&self) -> Result { + self.scene.clear_tpc(self.tile.tpc_size) + } } fn to_cmdbuf(r: &UapiRenderCommand) -> kernel::uapi::drm_asahi_cmd_render { diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index c3b3dd9b9952..9e23697fcec5 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -10,7 +10,7 @@ use super::*; use kernel::device; -use crate::g14_v27_2_abi::{self, GrowRequest, QueueError}; +use crate::g14_v27_2_abi::{self, EventKind, GrowRequest, QueueError}; use crate::g17::fw::m5::initdata as abi; use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; use crate::m3::m3_init_26 as directory26; @@ -40,6 +40,11 @@ const STATISTICS_RING: usize = 16; /// Ring geometries: the trace ring has 512 records of 0x48 bytes, the others 256. const TRACE_RECORDS: u32 = 512; const RING_RECORDS: u32 = 256; +use crate::g14_v27_2_abi::{ + RECOVERY_GENERATION as CONTROL_RECOVERY_GENERATION, RECOVERY_PHASE as CONTROL_RECOVERY_PHASE, + RECOVERY_SNAPSHOT as CONTROL_RECOVERY_SNAPSHOT, +}; +pub(crate) use crate::g14_v27_2_abi::{stopped_tiler, RECOVERY_SNAPSHOT_ENTRIES}; /// Queue capacity at position block +0x50 (16 x the 0x50 channels). const QUEUE_CAPACITY: u32 = 0x500; /// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. @@ -473,6 +478,11 @@ impl CommandPool { } pub(crate) enum FirmwareEvent { + /// Kind 0: the firmware stopped on a GPU fault and halted for recovery. + Fault, + /// Kind 4: the firmware timed out a command (the slot it names at +0xc) and halted for + /// recovery. + Timeout { slot: i32 }, Grow(GrowRequest), ChannelError, Notification, @@ -559,6 +569,15 @@ impl RootV27_2 { (queue.info(self.render_states[dm]), queue.event.current_noncoherent()) } + /// Whether the render queue's retired position reached `target`, stamp or not: a command + /// the firmware stopped for recovery leaves the queue without writing its stamp. + pub(crate) fn render_retired(&self, dm: usize, target: u32) -> Result { + let queue = &self.render_queues[dm]; + crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok(Self::word(&queue.positions, 0)? == target) + } + pub(crate) fn render_done(&self, dm: usize, target: u32, stamp: event::EventValue) -> Result { let queue = &self.render_queues[dm]; crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); @@ -708,16 +727,39 @@ impl RootV27_2 { crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); crate::pgtable::poc_barrier(); let word = |offset| Self::word(ring, at + offset); - let event = match word(0)? { - 6 => FirmwareEvent::Grow(GrowRequest::decode([ + let event = match g14_v27_2_abi::event_kind(word(0)?) { + EventKind::Grow => FirmwareEvent::Grow(GrowRequest::decode([ word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, ])), - 7 => FirmwareEvent::ChannelError, - _ => FirmwareEvent::Notification, + EventKind::Fault => FirmwareEvent::Fault, + EventKind::Timeout => FirmwareEvent::Timeout { + slot: word(g14_v27_2_abi::TIMEOUT_SLOT_OFFSET)? as i32, + }, + EventKind::ChannelError => FirmwareEvent::ChannelError, + EventKind::Notification => FirmwareEvent::Notification, }; Ok(Some((read, event))) } + /// Reads control words from `from` into `out`. + pub(crate) fn control_snapshot(&self, from: usize, out: &mut [u32]) -> Result { + let at = self.control.as_slice()[from..].as_ptr(); + crate::pgtable::clean_invalidate_poc(at, out.len() * 4); + crate::pgtable::poc_barrier(); + for (i, w) in out.iter_mut().enumerate() { + *w = Self::word(&self.control, from + 4 * i)?; + } + Ok(()) + } + + /// Writes one control word and makes it visible to the firmware. + pub(crate) fn control_store(&self, at: usize, value: u32) -> Result { + self.control.shared_index(at)?.store(value, Ordering::Release); + crate::pgtable::clean_poc(self.control.as_slice()[at..].as_ptr(), 4); + crate::pgtable::poc_barrier(); + Ok(()) + } + pub(crate) fn consume_event(&self, cursor: u32) -> Result { let state = &self.channels[2 * EVENT_RING]; state.shared_index(0)?.store((cursor + 1) % RING_RECORDS, Ordering::Release); @@ -726,8 +768,31 @@ impl RootV27_2 { Ok(()) } + /// The recovery phase. The firmware publishes 1 after it reported a fault or a command + /// timeout and stopped every queue; it runs nothing until the host's answers. + pub(crate) fn recovery_phase(&self) -> Result { + let mut word = [0u32]; + self.control_snapshot(CONTROL_RECOVERY_PHASE, &mut word)?; + Ok(word[0]) + } + + /// Answers a recovery phase (2 at phase 1, 0 at phase 3). + pub(crate) fn answer_recovery(&self, phase: u32) -> Result { + self.control_store(CONTROL_RECOVERY_PHASE, phase) + } + + /// Snapshot entry `i` of the stopped work: (flags, target). Bit 0 of flags marks a valid + /// entry; the first invalid one ends the snapshot. + pub(crate) fn recovery_entry(&self, i: usize) -> Result<(u32, u32)> { + if i >= RECOVERY_SNAPSHOT_ENTRIES { return Err(EINVAL); } + let mut words = [0u32; 2]; + self.control_snapshot(CONTROL_RECOVERY_SNAPSHOT + 8 * i, &mut words)?; + Ok((words[0], words[1])) + } + + /// The recovery generation (u64). Growth requests carry the value current when sent. pub(crate) fn halt_count(&self) -> Result { - const OFFSET: usize = 0x4bf0; + const OFFSET: usize = CONTROL_RECOVERY_GENERATION; crate::pgtable::clean_invalidate_poc(self.control.as_slice()[OFFSET..].as_ptr(), 8); crate::pgtable::poc_barrier(); Ok(u64::from(Self::word(&self.control, OFFSET)?) diff --git a/tools/asahi/g14-v27-2-abi-tests.rs b/tools/asahi/g14-v27-2-abi-tests.rs new file mode 100644 index 000000000000..04ae20680f7c --- /dev/null +++ b/tools/asahi/g14-v27-2-abi-tests.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Host tests of the production G14 firmware 27.2 queue, event and recovery records. +#![allow(dead_code)] +#[path = "../../drivers/gpu/drm/asahi/g14_v27_2_abi.rs"] +mod g14_v27_2_abi; diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f929..310a3c8a0fb1 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -322,6 +322,8 @@ def mutations(flag, names, base, expect=KILL): # Production G17 decoder vectors also build directly with rustc --test. ASAHI_RUST += ['g17-telemetry-tests.rs', 'legacy-frequency-tests.rs'] ASAHI_RUST.append('m3-firmware-tests.rs') +# G14 firmware 27.2 queue, event and recovery records (its KUnit suite, run on the host). +ASAHI_RUST.append('g14-v27-2-abi-tests.rs') # Python that runs on the host but imports its neighbours, so it keeps the # script directory on sys.path (-E -s instead of -I). From 52166ad98c80677784ee2cd77dcb69cf5bf8e1eb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 17:05:19 +1100 Subject: [PATCH 02/10] drm/asahi: attribute G14 27.2 recoveries by the stopped command's stamp The recovery blamed the first command still in the host's compute list. That list can hold a command the firmware already completed but the host has not yet retired, ahead of the one the firmware stopped, so a healthy client could lose its context while the guilty one carried on. Each recovery snapshot entry's target is the completion stamp the stopped command would have written (on the J473: compute stamp 0x7900 written, entry {0x7, 0x7a00}; tiler stamp 0x2156500 written, entry {0x1f, 0x2156600}). Refresh the retired position, then match every valid entry against the published render pair's stamps and the unretired compute commands' stamps. Blame only when all entries of a round name the same tracked command. A stopped tiler can only be the render pair. Anything unnamed, mixed or colliding keeps the fail-stop. Attribute every round, not just the first: work queued behind the first stopped command can time out while it drains. A further round must carry a new recovery generation. The attribution and round rules live in g14_v27_2_abi.rs, with host tests for a completed entry ahead of the stopped one, render pairs, ambiguous snapshots and generation changes while draining. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 73 ++++++++++++------ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 102 +++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index a6c9056771ab..571c320dd2d6 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -47,6 +47,7 @@ use crate::{ #[allow(dead_code)] mod recovery_logic; use recovery_logic::{RecoveryAction, SnapshotEntry}; +use crate::g14_v27_2_abi::{self, Stopped}; /// RTKit endpoints of the GPU firmware. const EP_FIRMWARE: u8 = 0x20; @@ -888,27 +889,30 @@ impl Runtime { packet.finish(Err(err)); } - /// Marks the work the firmware stopped: the render pair if one is published (a render is - /// published alone), else the oldest unretired compute command and the rest of its packet. - /// Returns whether anything was published. - fn blame(&self, state: &mut State, error: Error, slot: i32) -> bool { - if let Some(flight) = state.rendering.as_mut() { - flight.doomed = Some(error); - let owner = &flight.packet.owner; - dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", - owner.process(), owner.pid, slot, error); - return true; - } - let Some(packet) = state.inflight.first().map(|f| f.packet.clone()) else { - dev_err!(self.dev, "GPU: firmware stopped with nothing published (slot {})\n", slot); - return false; - }; - for flight in state.inflight.iter_mut().filter(|f| Arc::ptr_eq(&f.packet, &packet)) { - flight.doomed = Some(error); + /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the + /// published render pair, or the compute command with that completion stamp and the rest of + /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. + fn blame(&self, state: &mut State, error: Error, slot: i32, work: Stopped) -> Result { + match work { + Stopped::Render => { + let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; + flight.doomed = Some(error); + let owner = &flight.packet.owner; + dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", + owner.process(), owner.pid, slot, error); + } + Stopped::Compute(stamp) => { + let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) + .map(|f| f.packet.clone()) else { return Err(EIO); }; + let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); + for flight in state.inflight.iter_mut().filter(owned) { + flight.doomed.get_or_insert(error); + } + dev_err!(self.dev, "GPU: stopped compute {:#x} of {}[{}] (slot {}, {:?})\n", + stamp, packet.owner.process(), packet.owner.pid, slot, error); + } } - dev_err!(self.dev, "GPU: stopped compute of {}[{}] (slot {}, {:?})\n", - packet.owner.process(), packet.owner.pid, slot, error); - true + Ok(()) } /// Whether every command marked by `blame` has left its queue. @@ -961,7 +965,7 @@ impl Runtime { fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { state.root.log_timeout(&self.dev); let mut rounds = 0; - let mut blamed = false; + let mut previous = None; loop { if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", @@ -975,6 +979,16 @@ impl Runtime { return Err(EIO); } let generation = state.root.halt_count()?; + if !g14_v27_2_abi::new_round(previous, generation) { + dev_err!(self.dev, "GPU: recovery generation {} repeated\n", generation); + return Err(EPROTO); + } + previous = Some(generation); + // Retired work must not be blamed: refresh the retired position first. + self.advance(state)?; + let render = state.rendering.as_ref() + .map(|f| [f.stamps[TILER].raw(), f.stamps[FRAGMENT].raw()]); + let mut attribution = g14_v27_2_abi::Attribution::default(); let mut entries = 0; let mut stopped_tiler = false; for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { @@ -982,16 +996,25 @@ impl Runtime { let Some(entry) = SnapshotEntry::decode(flags, target) else { break; }; entries += 1; stopped_tiler |= gpu::stopped_tiler(entry.flags); + let retired = state.retired_total; + let inflight = &state.inflight; + attribution.add(entry.flags, entry.target, render, |stamp| { + inflight.iter().any(|f| f.stamp.raw() == stamp && f.ordinal > retired) + }); if entries <= 8 { dev_err!(self.dev, "GPU: recovery {} entry {}: flags {:#x} (event {:#x}) target {:#x}\n", generation, i, entry.flags, entry.event, entry.target); } } - if !blamed { - blamed = true; - self.blame(state, error, slot); - } + // Every round is attributed: work behind the first stopped command can time out in + // turn. Unnamed or ambiguous stopped work keeps the fail-stop. + let Some(work) = attribution.result() else { + dev_err!(self.dev, "GPU: recovery {} names no single tracked command ({} entries)\n", + generation, entries); + return Err(EIO); + }; + self.blame(state, error, slot, work)?; if stopped_tiler { if let Some(flight) = state.rendering.as_ref() { let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 501be19bdd1a..74488ed60be9 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -89,6 +89,63 @@ pub(crate) const fn stopped_tiler(flags: u32) -> bool { flags & 9 == 9 } +/// The tracked work a recovery snapshot names. A snapshot entry's target is the completion +/// stamp the stopped command would have written (J473: compute stamp 0x7900 written, entry +/// {0x7, 0x7a00}; tiler stamp 0x2156500 written, entry {0x1f, 0x2156600}). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Stopped { + /// The published render pair (either of its completion stamps). + Render, + /// The published compute command with this completion stamp. + Compute(u32), +} + +/// Attribution of one recovery round: every valid snapshot entry must name the same tracked, +/// unretired work, else the round is ambiguous and the caller fails all work (fail-stop). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct Attribution { + work: Option, + ambiguous: bool, +} + +impl Attribution { + /// Adds a valid entry. `render` holds the published render pair's completion stamps; + /// `compute(stamp)` says whether an unretired compute command carries that stamp. + pub(crate) fn add(&mut self, flags: u32, target: u32, render: Option<[u32; 2]>, + compute: impl Fn(u32) -> bool) { + let as_render = render.is_some_and(|stamps| stamps.contains(&target)); + // A stopped tiler can only be the render pair. + let as_compute = !stopped_tiler(flags) && compute(target); + let work = match (as_render, as_compute) { + (true, false) => Stopped::Render, + (false, true) => Stopped::Compute(target), + _ => { + self.ambiguous = true; + return; + } + }; + match self.work { + None => self.work = Some(work), + Some(seen) if seen == work => {} + Some(_) => self.ambiguous = true, + } + } + + /// The stopped work, if the round named exactly one tracked command. + pub(crate) fn result(self) -> Option { + if self.ambiguous { None } else { self.work } + } +} + +/// A further recovery round while stopped work drains must carry a new generation; the same +/// generation again means the host misread the handshake. +pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { + match previous { + None => true, + Some(p) => generation != p, + } +} + /// Event ring record kinds. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum EventKind { @@ -225,4 +282,49 @@ mod tests { assert!(!stopped_tiler(0x8)); assert!(stopped_tiler(0x9 | (0x70 << 4))); } + + #[test] + fn a_completed_front_entry_is_not_blamed_for_a_later_stop() { + // Host list: 0x7900 completed but not yet retired by the host, 0x7a00 stopped. + let unretired = [0x7900u32, 0x7a00, 0x7b00]; + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| unretired.contains(&s)); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + } + + #[test] + fn render_entries_name_the_published_pair() { + let pair = Some([0x2156600, 0x3156600]); + let mut a = Attribution::default(); + a.add(0x1f, 0x2156600, pair, |_| false); + a.add(0x7, 0x3156600, pair, |_| false); + assert_eq!(a.result(), Some(Stopped::Render)); + // A stopped tiler that matches no published pair is not pinned on compute. + let mut a = Attribution::default(); + a.add(0x1f, 0x7a00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + } + + #[test] + fn untracked_mixed_or_colliding_entries_fail_stop() { + let mut a = Attribution::default(); + assert_eq!(a.result(), None); + a.add(0x7, 0x7c00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| s == 0x7a00 || s == 0x7b00); + a.add(0x7, 0x7b00, None, |s| s == 0x7a00 || s == 0x7b00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x3156600, Some([0x2156600, 0x3156600]), |s| s == 0x3156600); + assert_eq!(a.result(), None); + } + + #[test] + fn recovery_rounds_while_draining_need_a_new_generation() { + assert!(new_round(None, 1)); + assert!(new_round(Some(1), 2)); + assert!(!new_round(Some(2), 2)); + assert!(new_round(Some(u64::MAX), 0)); + } } From f55ae32f692706ff409508610b3a39e969f3f508 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 17:52:31 +1100 Subject: [PATCH 03/10] drm/asahi: keep the G14 27.2 recovery's isolation contract Review of the G14 27.2 per-client recovery found these gaps: - A stopped command leaves its queue without a completion stamp. That proves queue progress, not that the GPU no longer reaches its memory, which is the G16 Retirement::Aborted rule. The runtime still released the command's VM job guard, binding and scene. Now the error completion quarantines the guard, and the stopped command's flight (packet, binding, scene) is kept for the rest of the boot, as stop() does for everything. Pool slots are still reused only after the firmware unregisters them. - The guilty VM was not barred from running more work. Blaming now latches its VmStatus (note_recovery_guilty + record) before the work drains. submit() refuses packets of a failed VM, and pump() fails the ones already queued instead of publishing them, as G16 does. - A render timeout that found the firmware in recovery recovered but left the render flight in place. Nothing then signalled its fence or published the queue behind it until the scheduler timeout. Retire it right after the recovery. - Scene::clear_tpc wrote through a shared slice and was available to every GPU generation. It is now an unsafe fn of the G14 27.2 scene only, and zeroes through a raw-pointer GpuArray helper with its exclusivity precondition stated. - While stopped work drains, a crashed coprocessor or a phase the protocol does not allow now fails the recovery. The whole recovery starts no round after 5 s, so the state lock is released inside the scheduler's job timeout. Control-object reads and writes validate their byte range first. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/buffer.rs | 26 ++++---- drivers/gpu/drm/asahi/g14_v27_2.rs | 77 +++++++++++++++++++++-- drivers/gpu/drm/asahi/g14_v27_2_render.rs | 10 ++- drivers/gpu/drm/asahi/gpu/v27_2.rs | 10 +++ drivers/gpu/drm/asahi/object.rs | 18 ++++++ 5 files changed, 120 insertions(+), 21 deletions(-) diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index cd79a762cb3e..7a19153a9096 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -198,20 +198,6 @@ impl Scene::ver { self.object.tpc.gpu_pointer() } - /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after - /// a firmware recovery stopped its tiler finds no tiles. - #[allow(dead_code)] - pub(crate) fn clear_tpc(&self, bytes: usize) -> Result { - let tpc = self.object.tpc.as_slice(); - if bytes > tpc.len() { return Err(ERANGE); } - // SAFETY: the TPC belongs to this scene, whose tiler was stopped by the firmware and is - // halted; nothing else writes it until the scene's fragment pass runs or is dropped. - unsafe { core::ptr::write_bytes(tpc.as_ptr().cast_mut(), 0, bytes) }; - crate::pgtable::clean_poc(tpc.as_ptr(), bytes); - crate::pgtable::poc_barrier(); - Ok(()) - } - /// Returns the GPU pointer to the first preemption scratch buffer. pub(crate) fn preempt_buf_1_pointer(&self) -> GpuPointer<'_, &'_ [u8]> { self.object.preempt_buf.gpu_pointer() @@ -308,6 +294,18 @@ impl SceneG14V13_5 { pub(crate) fn render_addresses(&self) -> (u64, u64) { self.object.with(|raw, _| (raw.user_buffer.or(0).into(), raw.stats.into())) } + + /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after + /// a firmware recovery stopped its tiler finds no tiles. + /// + /// # Safety + /// + /// The GPU must not access the TPC during the call (its tiler is stopped and no other + /// render using this buffer is in flight), and no CPU reference into it may be live. + pub(crate) unsafe fn clear_tpc(&self, bytes: usize) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.object.tpc.zero_prefix(bytes) } + } } /// Host-owned parameter-buffer inputs that persist across firmware submissions. diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 571c320dd2d6..561673b82155 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -75,6 +75,10 @@ const RECOVERY_DRAIN_MS: i64 = 1000; /// Further recoveries answered while the stopped work drains (work behind it can time out in /// turn) before the runtime gives up. const FURTHER_RECOVERIES: u32 = 4; +/// Rounds start only within this budget; one round takes at most PHASE1_WAIT_MS + +/// HANDSHAKE_MS + RECOVERY_DRAIN_MS, so the lock is released well within the 10 s scheduler +/// job timeout. +const RECOVERY_BUDGET_MS: i64 = 5000; struct FirmwareWait { since: Instant, @@ -407,6 +411,27 @@ pub(crate) fn start<'a>( Ok(Started { backend, drm, binding, resources }) } +/// Whether the packet's VM has failed (`VmStatus` latched): its work is no longer admitted. +fn vm_failed(packet: &Packet) -> bool { + packet.vm.status().is_some_and(|status| status.get() != 0) +} + +/// Latches the VM of work a recovery stopped as guilty, before the work drains: from here on +/// `submit` refuses it and `pump` publishes none of its queued packets. +fn latch_guilty(packet: &Packet, error: Error) { + if let Some(status) = packet.vm.status() { + status.note_recovery_guilty(); + status.record(error); + } +} + +/// Keeps a command the firmware stopped, and everything it owns (packet and VM job guard, VM +/// binding, scene), for the rest of the boot: see `Runtime::fail_doomed`. Bounded by the +/// recovery-storm window; the same as `stop` does for everything at shutdown. +fn quarantine(flight: T) { + core::mem::forget(flight); +} + struct Inflight { packet: Arc, last: bool, @@ -580,6 +605,9 @@ impl Runtime { if packet.commands.is_empty() { return Err(ENOTSUPP); } + // A VM that lost its context (a recovery found it guilty, or its work failed) runs + // nothing more on the GPU. + if vm_failed(&packet) { return Err(EIO); } let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; if !self.healthy() { return Err(EIO); } @@ -681,6 +709,11 @@ impl Runtime { } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); + if vm_failed(&packet) { + // Queued before its VM failed: none of it is published from now on. + state.fail_publication(&packet, EIO); + continue; + } let command = packet.commands[index]; let paired = matches!(command, Command::Render { .. }); if paired && state.running() { return; } @@ -857,6 +890,7 @@ impl Runtime { } if let Some(err) = flight.doomed { self.fail_doomed(state, &flight.packet, err); + quarantine(flight); } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { @@ -865,8 +899,11 @@ impl Runtime { } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); if state.root.recovery_phase()? == 1 && doomed.is_none() { - // The firmware stopped it and halted, but its event was not seen. - return self.recover(state, ETIMEDOUT, -1); + // The firmware stopped it and halted, but its event was not seen. Recovery + // marks it and waits until it left both queues: retire it now, so its fence + // is signalled and the queue behind it runs without waiting for another message. + self.recover(state, ETIMEDOUT, -1)?; + return self.retire_render(state); } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); @@ -878,12 +915,18 @@ impl Runtime { /// Fails a packet the firmware stopped, once none of its commands is in a queue: its /// unpublished commands are withdrawn, and its VM records the error (the client sees a /// lost context). Other clients' work is not touched. + /// + /// A stopped command left its queue without a completion stamp: that proves queue progress, + /// not that the GPU no longer reaches its memory (the G16 rule, `Retirement::Aborted`). So + /// its VM job guard is not released: the error completion quarantines it (no mapping + /// changes), and the caller keeps the flight that owns the packet, its VM binding and + /// scene for the rest of the boot (`quarantine`). Pool slots are reused only after the + /// firmware unregisters them (`free_slots`). fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { if state.owns(packet) { return; } if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { let _ = state.pending.remove(i); } - packet.release_guard(); // Record it even if a racing scheduler timeout already claimed the fence (as fail_all). if let Some(status) = packet.vm.status() { status.record(err); } packet.finish(Err(err)); @@ -897,6 +940,7 @@ impl Runtime { Stopped::Render => { let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; flight.doomed = Some(error); + latch_guilty(&flight.packet, error); let owner = &flight.packet.owner; dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", owner.process(), owner.pid, slot, error); @@ -908,6 +952,7 @@ impl Runtime { for flight in state.inflight.iter_mut().filter(owned) { flight.doomed.get_or_insert(error); } + latch_guilty(&packet, error); dev_err!(self.dev, "GPU: stopped compute {:#x} of {}[{}] (slot {}, {:?})\n", stamp, packet.owner.process(), packet.owner.pid, slot, error); } @@ -966,7 +1011,14 @@ impl Runtime { state.root.log_timeout(&self.dev); let mut rounds = 0; let mut previous = None; + let began = Instant::::now(); loop { + // The state lock is held throughout: keep the whole recovery, including a last round + // started at the budget, inside the DRM scheduler's job timeout. + if began.elapsed() > Delta::from_millis(RECOVERY_BUDGET_MS) { + dev_err!(self.dev, "GPU: recovery took more than {} ms\n", RECOVERY_BUDGET_MS); + return Err(ETIMEDOUT); + } if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", error, slot); @@ -1019,7 +1071,10 @@ impl Runtime { if let Some(flight) = state.rendering.as_ref() { let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; if !ta_left { - flight.scene.clear_tpc()?; + // SAFETY: the firmware is in recovery phase 1 with every queue stopped, + // so the GPU does not access the stopped tiler's TPC; the CPU reads it + // nowhere, and the state lock (held) serializes every render flight. + unsafe { flight.scene.clear_tpc()? }; dev_err!(self.dev, "GPU: cleared the stopped tiler's TPC storage\n"); } } @@ -1052,7 +1107,18 @@ impl Runtime { state.recoveries, start.elapsed().as_millis()); return Ok(()); } - if state.root.recovery_phase()? == 1 { break; } + if state.peer.is_crashed() { return Err(EIO); } + // Phase 0 = still draining; 1 = a new recovery (a new generation is checked + // at the next round); the host's own phases mean the handshake was misread. + match recovery_logic::action(state.root.recovery_phase()?, false, true) { + RecoveryAction::Wait => {} + RecoveryAction::MarkAndAcknowledge => break, + _ => { + dev_err!(self.dev, "GPU: recovery phase {} while the stopped work drained\n", + state.root.recovery_phase()?); + return Err(EPROTO); + } + } if start.elapsed() > Delta::from_millis(RECOVERY_DRAIN_MS) { dev_err!(self.dev, "GPU: stopped work did not leave the queue\n"); state.root.log_timeout(&self.dev); @@ -1180,6 +1246,7 @@ impl Runtime { self.retire_slot(state, done.slot); if let Some(err) = done.doomed { self.fail_doomed(state, &done.packet, err); + quarantine(done); } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index c81b3b469974..02b2b3be55ed 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -78,8 +78,14 @@ impl Prep { } /// Clears the tiler's TPC storage after a firmware recovery stopped the tiler. - pub(crate) fn clear_tpc(&self) -> Result { - self.scene.clear_tpc(self.tile.tpc_size) + /// Zeroes the scene's TPC after a firmware recovery stopped its tiler. + /// + /// # Safety + /// + /// As [`crate::buffer::Scene::clear_tpc`]. + pub(crate) unsafe fn clear_tpc(&self) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.scene.clear_tpc(self.tile.tpc_size) } } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 9e23697fcec5..d34991feb3b9 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -741,8 +741,17 @@ impl RootV27_2 { Ok(Some((read, event))) } + /// Validates a byte range of the control object before it is sliced or cache-maintained. + fn control_range(control: &fw::types::GpuArray, from: usize, bytes: usize) -> Result { + match from.checked_add(bytes) { + Some(end) if end <= control.as_slice().len() && from % 4 == 0 => Ok(()), + _ => Err(EINVAL), + } + } + /// Reads control words from `from` into `out`. pub(crate) fn control_snapshot(&self, from: usize, out: &mut [u32]) -> Result { + Self::control_range(&self.control, from, out.len() * 4)?; let at = self.control.as_slice()[from..].as_ptr(); crate::pgtable::clean_invalidate_poc(at, out.len() * 4); crate::pgtable::poc_barrier(); @@ -754,6 +763,7 @@ impl RootV27_2 { /// Writes one control word and makes it visible to the firmware. pub(crate) fn control_store(&self, at: usize, value: u32) -> Result { + Self::control_range(&self.control, at, 4)?; self.control.shared_index(at)?.store(value, Ordering::Release); crate::pgtable::clean_poc(self.control.as_slice()[at..].as_ptr(), 4); crate::pgtable::poc_barrier(); diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index ef7027ff1a63..90e492a2b1b9 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -712,6 +712,24 @@ impl> GpuArray { // this word only in aligned 32-bit transactions while the ring is live. Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) } + + /// Zeroes the first `bytes` through the raw CPU mapping, without creating a Rust reference + /// to the payload, and cleans them to the point of coherency for the GPU. + /// + /// # Safety + /// + /// No CPU reference into the range may be live, and no device may access it during the call. + pub(crate) unsafe fn zero_prefix(&self, bytes: usize) -> Result { + if bytes > self.len { + return Err(ERANGE); + } + // SAFETY: `raw` is valid for `len` bytes (type invariant) and `bytes <= len`; the caller + // guarantees that nothing else accesses the range meanwhile. + unsafe { core::ptr::write_bytes(self.raw, 0, bytes) }; + crate::pgtable::clean_poc(self.raw.cast_const(), bytes); + crate::pgtable::poc_barrier(); + Ok(()) + } } impl> Deref for GpuArray { From d39ba2143dfff4ea677d017a8422155294c2cfe6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:06:25 +1100 Subject: [PATCH 04/10] drm/asahi: keep stopped G14 27.2 work owned until shutdown A command the firmware stopped in a recovery left its queue without a completion stamp. That proves queue progress, not that the GPU no longer reaches its memory, so its VM job guard must not be released. But quarantine() took the flight off rendering/inflight and forgot it. The packet then no longer counted as owned, and a later withdraw() from the scheduler's timeout or cancel path, or fail_all(), could release its guard and let the client's mappings change under the firmware. Track kept work in the runtime instead. blame() adds the packet to State::kept before anything is marked, and the stopped flights, with their VM binding and scene, go to State::kept_flights when they leave the queue. owns() now covers kept packets, so withdraw(), fail_all() and fail_publication() leave the guard alone. fail_doomed() asks only whether a queue still holds the packet. stop() already keeps the whole state for the boot. kept has QUARANTINE_LIMIT (31) places, allocated at start, so keeping a packet never allocates. Each kept packet pins its VM's user UAT context, so the limit is half of the 63 user contexts. Once it is reached, blame() fails and the recovery takes the fail-all path, which keeps all published work owned. The storm window limits the rate of recoveries but not the total, so a slow trickle of stopped work could otherwise use up every context. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 87 ++++++++++++++++++++------ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 41 ++++++++++++ 2 files changed, 110 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 82916164955a..97aa78aa0846 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -533,13 +533,6 @@ fn latch_guilty(packet: &Packet, error: Error) { } } -/// Keeps a command the firmware stopped, and everything it owns (packet and VM job guard, VM -/// binding, scene), for the rest of the boot: see `Runtime::fail_doomed`. Bounded by the -/// recovery-storm window; the same as `stop` does for everything at shutdown. -fn quarantine(flight: T) { - core::mem::forget(flight); -} - struct Inflight { packet: Arc, last: bool, @@ -566,6 +559,14 @@ struct RenderFlight { doomed: Option, } +/// A command the firmware stopped, kept with everything it owns (VM binding, scene) after it +/// left its queue: see `Runtime::fail_doomed` and `Runtime::keep`. Held, never read. +#[allow(dead_code)] +enum Kept { + Compute(Inflight), + Render(RenderFlight), +} + struct State { peer: Peer, root: crate::fw::types::GpuObject, @@ -606,6 +607,12 @@ struct State { /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. recovery_window: u64, recovery_count: u32, + /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept + /// for the rest of the boot: the firmware may still reach that memory. Allocated with + /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. + kept: KVec>, + /// The stopped commands of those packets, once they left their queue. + kept_flights: KVec, /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so /// teardown skips live-hardware MMIO and RTKit operations. hardware_unreachable: bool, @@ -622,7 +629,9 @@ impl State { { last.publication_error = Some(err); } else { - packet.release_guard(); + if g14_v27_2_abi::guard_releasable(false, self.kept(packet)) { + packet.release_guard(); + } packet.finish(Err(err)); } } @@ -631,11 +640,22 @@ impl State { !self.inflight.is_empty() || self.rendering.is_some() } - fn owns(&self, packet: &Arc) -> bool { + /// Whether a queue holds any of the packet's commands. + fn live(&self, packet: &Arc) -> bool { self.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, packet)) || self.rendering.as_ref().is_some_and(|flight| Arc::ptr_eq(&flight.packet, packet)) } + /// Whether a recovery stopped a command of the packet: it stays owned for the boot. + fn kept(&self, packet: &Arc) -> bool { + self.kept.iter().any(|kept| Arc::ptr_eq(kept, packet)) + } + + /// Whether the runtime owns the packet's VM job guard (`g14_v27_2_abi::guard_releasable`). + fn owns(&self, packet: &Arc) -> bool { + !g14_v27_2_abi::guard_releasable(self.live(packet), self.kept(packet)) + } + fn pending(&self, packet: &Arc) -> bool { self.pending.iter().any(|(current, _)| Arc::ptr_eq(current, packet)) } @@ -1029,7 +1049,7 @@ impl Runtime { } if let Some(err) = flight.doomed { self.fail_doomed(state, &flight.packet, err); - quarantine(flight); + self.keep(state, Kept::Render(flight)); } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { @@ -1058,11 +1078,12 @@ impl Runtime { /// A stopped command left its queue without a completion stamp: that proves queue progress, /// not that the GPU no longer reaches its memory (the G16 rule, `Retirement::Aborted`). So /// its VM job guard is not released: the error completion quarantines it (no mapping - /// changes), and the caller keeps the flight that owns the packet, its VM binding and - /// scene for the rest of the boot (`quarantine`). Pool slots are reused only after the - /// firmware unregisters them (`free_slots`). + /// changes), the packet stays in `State::kept` (`blame`), and the caller keeps the flight + /// with its VM binding and scene (`keep`), all for the rest of the boot. Pool slots follow + /// the normal rule: reused only after the firmware unregisters them (`free_slots`), and + /// then in the slot's other buffer, so the stopped command stays intact. fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { - if state.owns(packet) { return; } + if state.live(packet) { return; } if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { let _ = state.pending.remove(i); } @@ -1071,12 +1092,38 @@ impl Runtime { packet.finish(Err(err)); } + /// Keeps a stopped command that left its queue, with its VM binding and scene, for the rest + /// of the boot. Its packet is already in `State::kept`, so ownership does not depend on + /// this allocation; if it fails, the flight is leaked instead, which keeps it as well. + fn keep(&self, state: &mut State, flight: Kept) { + if let Err(err) = state.kept_flights.push(flight, GFP_KERNEL) { + dev_warn!(self.dev, "GPU: no memory to track a stopped command ({:?}); leaking it\n", err); + } + } + + /// Adds the packet of stopped work to `State::kept` before anything is marked, so it stays + /// owned from here on. Err(EIO) once `g14_v27_2_abi::QUARANTINE_LIMIT` packets are kept: + /// the caller then fails all work, and published work stays owned. + fn reserve_kept(&self, state: &mut State, packet: &Arc) -> Result { + if state.kept(packet) { return Ok(()); } + if !g14_v27_2_abi::quarantine_fits(state.kept.len()) { + dev_err!(self.dev, "GPU: {} clients' stopped work kept this boot; not recovering more\n", + state.kept.len()); + return Err(EIO); + } + // Within the capacity allocated at start: never allocates. + state.kept.push_within_capacity(packet.clone()).map_err(|_| EIO) + } + /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the /// published render pair, or the compute command with that completion stamp and the rest of /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. fn blame(&self, state: &mut State, error: Error, slot: i32, work: Stopped) -> Result { match work { Stopped::Render => { + let Some(packet) = state.rendering.as_ref().map(|f| f.packet.clone()) + else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; flight.doomed = Some(error); latch_guilty(&flight.packet, error); @@ -1087,6 +1134,7 @@ impl Runtime { Stopped::Compute(stamp) => { let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) .map(|f| f.packet.clone()) else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); for flight in state.inflight.iter_mut().filter(owned) { flight.doomed.get_or_insert(error); @@ -1385,7 +1433,7 @@ impl Runtime { self.retire_slot(state, done.slot); if let Some(err) = done.doomed { self.fail_doomed(state, &done.packet, err); - quarantine(done); + self.keep(state, Kept::Compute(done)); } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); @@ -1804,12 +1852,13 @@ impl Backend { } }; let (queue, last) = root.queue(); - let checked = (|| -> Result<(u32, u32)> { + let checked = (|| -> Result<(u32, u32, KVec>)> { let (head, retired) = root.progress()?; if head != retired { return Err(EBUSY); } - Ok((head, root.capacity()?)) + let kept = KVec::with_capacity(g14_v27_2_abi::QUARANTINE_LIMIT, GFP_KERNEL)?; + Ok((head, root.capacity()?, kept)) })(); - let (head, capacity) = match checked { + let (head, capacity, kept) = match checked { Ok(v) => v, Err(e) => { halt_unowned(dev, peer, root, asc, true); @@ -1843,6 +1892,8 @@ impl Backend { recoveries: 0, recovery_window: 0, recovery_count: 0, + kept, + kept_flights: KVec::new(), hardware_unreachable: false, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: None, diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index ed044dd77880..e6afbaee74ce 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -146,6 +146,25 @@ pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { } } +/// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, +/// and with it one user UAT context, and a render one also pins its scene. The limit is half +/// the user contexts, so innocent clients keep the rest. +pub(crate) const QUARANTINE_LIMIT: usize = 31; + +/// Whether one more packet with stopped work fits next to the `kept` ones. When it does not, +/// the caller fails all work, and everything published stays owned. +pub(crate) const fn quarantine_fits(kept: usize) -> bool { + kept < QUARANTINE_LIMIT +} + +/// Whether a packet's VM job guard may be released, so its mappings may change. That needs +/// none of its commands in a queue (`live`) and no stopped command of it kept (`kept`). The +/// firmware may still reach a stopped command's memory, so a kept packet stays owned for the +/// rest of the boot, whoever asks: retirement, `withdraw` or `fail_all`. +pub(crate) const fn guard_releasable(live: bool, kept: bool) -> bool { + !live && !kept +} + /// Event ring record kinds. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum EventKind { @@ -472,6 +491,28 @@ mod tests { assert!(new_round(Some(u64::MAX), 0)); } + #[test] + fn a_withdrawn_stopped_packet_keeps_its_guard() { + // The scheduler withdraws a packet whose stopped command left the queue: it is no + // longer live, but it is kept, so its guard stays. + assert!(!guard_releasable(false, true)); + // Still in a queue, kept or not. + assert!(!guard_releasable(true, false)); + assert!(!guard_releasable(true, true)); + // Retired innocent work. + assert!(guard_releasable(false, false)); + } + + #[test] + fn kept_packets_are_bounded_per_boot() { + assert!(quarantine_fits(0)); + assert!(quarantine_fits(QUARANTINE_LIMIT - 1)); + assert!(!quarantine_fits(QUARANTINE_LIMIT)); + assert!(!quarantine_fits(usize::MAX)); + // Innocent clients keep at least half of the 63 user UAT contexts. + assert!(2 * QUARANTINE_LIMIT <= 63); + } + #[test] fn progress_words_fit_the_globals_and_leave_power_words_alone() { let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; From 5d3c9dc95779e0b57d903f6d019f845f8f265c46 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:09:55 +1100 Subject: [PATCH 05/10] drm/asahi: consume G14 27.2 recovery reports of rounds already answered The firmware posts a fault or timeout record on the event ring and then opens its recovery round (phase 1). The host can answer a round before it reads that record: a further round opened while stopped work drained, or a round the command timeout found at phase 1. The record then stays in the ring. The next service pass read it, waited 50 ms for a phase 1 that never came, and failed all work. One recovered fault could so take down every client a moment later. Keep a ledger of reports read and rounds answered (g14_v27_2_abi::RecoveryLedger). recover() returns Ok(false) when no round opens. The service then consumes a report whose round was already answered, with a warning, and keeps the fail-all only for a report that has no round. Records read in one pass count as one report, so a fault and a timeout for the same stop do not look like two. recover() also starts from the last generation answered, so a round the host already answered is never answered again. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 63 +++++++++++++------ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 85 ++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 17 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 97aa78aa0846..0b1b82976ebc 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -607,6 +607,8 @@ struct State { /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. recovery_window: u64, recovery_count: u32, + /// Reports read and rounds answered: tells a stale report from a new one. + ledger: g14_v27_2_abi::RecoveryLedger, /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept /// for the rest of the boot: the firmware may still reach that memory. Allocated with /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. @@ -1061,8 +1063,9 @@ impl Runtime { // The firmware stopped it and halted, but its event was not seen. Recovery // marks it and waits until it left both queues: retire it now, so its fence // is signalled and the queue behind it runs without waiting for another message. - self.recover(state, ETIMEDOUT, -1)?; - return self.retire_render(state); + if self.recover(state, ETIMEDOUT, -1)? { + return self.retire_render(state); + } } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); @@ -1193,11 +1196,13 @@ impl Runtime { /// stopped tiler, answers 2, waits for 3 with the same generation and answers 0. The stopped /// work then leaves its queue and fails only its own packet and VM; the next recoveries /// while it drains are answered the same way, a bounded number of times. Errors here fail - /// all work (the runtime is not trusted). - fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { + /// all work (the runtime is not trusted). Ok(false) if the firmware opened no round within + /// PHASE1_WAIT_MS: the caller decides whether its report was stale. + fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { state.root.log_timeout(&self.dev); let mut rounds = 0; - let mut previous = None; + // A round the host already answered must not be answered again. + let mut previous = state.ledger.last(); let began = Instant::::now(); loop { // The state lock is held throughout: keep the whole recovery, including a last round @@ -1207,9 +1212,9 @@ impl Runtime { return Err(ETIMEDOUT); } if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { - dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", - error, slot); - return Err(ETIMEDOUT); + // A further round starts at a phase 1 the drain saw: it cannot go missing. + if rounds > 0 { return Err(EPROTO); } + return Ok(false); } let now = ::ktime_get() as u64; if !recovery_logic::admit(now, &mut state.recovery_window, &mut state.recovery_count) { @@ -1279,6 +1284,7 @@ impl Runtime { return Err(ETIMEDOUT); } state.root.answer_recovery(0)?; + state.ledger.answered(generation); dev_err!(self.dev, "GPU: recovery {} answered in {} ms ({} snapshot entries)\n", generation, start.elapsed().as_millis(), entries); let start = Instant::::now(); @@ -1292,7 +1298,7 @@ impl Runtime { dev_err!(self.dev, "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", state.recoveries, start.elapsed().as_millis()); - return Ok(()); + return Ok(true); } if state.peer.is_crashed() { return Err(EIO); } // Phase 0 = still draining; 1 = a new recovery (a new generation is checked @@ -1342,6 +1348,8 @@ impl Runtime { } fn process_events(&self, state: &mut State) -> Result { + // A fault and a timeout read in one pass are one report (`RecoveryLedger`). + let mut reported = false; // Limit one pass to the ring capacity. Further arrivals notify the worker again. for _ in 0..256 { let Some((cursor, event)) = state.root.peek_event()? else { break; }; @@ -1373,11 +1381,13 @@ impl Runtime { FirmwareEvent::Timeout { slot } => { dev_err!(self.dev, "GPU firmware timed out a command (slot {})\n", slot); state.firmware_error.get_or_insert((ETIMEDOUT, slot)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } } FirmwareEvent::Fault => { dev_err!(self.dev, "GPU firmware reported a GPU fault\n"); state.fault.log(&self.dev); state.firmware_error.get_or_insert((EIO, -1)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } } FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} } @@ -1402,10 +1412,25 @@ impl Runtime { return; } if let Some((error, slot)) = state.firmware_error.take() { - if let Err(err) = self.recover(state, error, slot) { - dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); - self.fail_all(state, err); - return; + match self.recover(state, error, slot) { + Ok(true) => {} + // The host answered this report's round before it read the report (a round + // opened while stopped work drained, or found at a command timeout). + Ok(false) if state.ledger.report_answered() => { + dev_warn!(self.dev, "GPU: firmware report {:?} (slot {}) is for recovery {:?}, already answered\n", + error, slot, state.ledger.last()); + } + Ok(false) => { + dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", + error, slot); + self.fail_all(state, ETIMEDOUT); + return; + } + Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } } } if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } @@ -1450,11 +1475,14 @@ impl Runtime { state.queue_stamp(), expected, state.submitted, state.retired); if unblamed && state.root.recovery_phase().unwrap_or(0) == 1 { // The firmware stopped it and halted, but its event was not seen. - if let Err(err) = self.recover(state, ETIMEDOUT, -1) { - self.fail_all(state, err); - return; + match self.recover(state, ETIMEDOUT, -1) { + Ok(true) => continue, + Ok(false) => {} + Err(err) => { + self.fail_all(state, err); + return; + } } - continue; } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); @@ -1892,6 +1920,7 @@ impl Backend { recoveries: 0, recovery_window: 0, recovery_count: 0, + ledger: g14_v27_2_abi::RecoveryLedger::default(), kept, kept_flights: KVec::new(), hardware_unreachable: false, diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index e6afbaee74ce..662f4fb13744 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -146,6 +146,51 @@ pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { } } +/// Tells a fault or timeout report on the event ring that needs a recovery from one whose round +/// the host already answered. +/// +/// The firmware posts the report, then opens the round (phase 1). The host can answer a round +/// before it reads its report: a further round opened while stopped work drains, or a round +/// found at a command timeout. That report is then still in the ring, and the next service pass +/// reads it after the firmware is back at phase 0. It must be consumed, not answered with a +/// wait for a phase 1 that never comes, which would fail all work. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct RecoveryLedger { + /// Service passes that read fault or timeout records. One pass counts once, so a fault and + /// a timeout posted for the same stop are one report. + reports: u64, + /// Rounds the host answered. + answered: u64, + /// Generation of the last round answered. + last: Option, +} + +impl RecoveryLedger { + /// A service pass read fault or timeout records. + pub(crate) fn report(&mut self) { + self.reports = self.reports.saturating_add(1); + } + + /// The host answered round `generation` (wrote phase 0). + pub(crate) fn answered(&mut self, generation: u64) { + self.answered = self.answered.saturating_add(1); + self.last = Some(generation); + } + + /// Generation of the last round answered: a round at phase 1 must carry another one + /// (`new_round`). + pub(crate) const fn last(&self) -> Option { + self.last + } + + /// With no new round open after a report: whether every report read so far has a round the + /// host already answered. Then the report is stale and is consumed. Otherwise the firmware + /// reported a stop without entering recovery. + pub(crate) const fn report_answered(&self) -> bool { + self.reports <= self.answered + } +} + /// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, /// and with it one user UAT context, and a render one also pins its scene. The limit is half /// the user contexts, so innocent clients keep the rest. @@ -491,6 +536,46 @@ mod tests { assert!(new_round(Some(u64::MAX), 0)); } + #[test] + fn a_report_read_before_its_round_is_answered_once() { + // Report, then its round: balanced, nothing left over. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + assert!(ledger.report_answered()); + assert_eq!(ledger.last(), Some(7)); + // A later report with no round open is a stop without recovery: not consumed. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_drain_round_is_consumed() { + // Round 7 from its report; round 8 opened while 7's work drained, answered before its + // report was read. Round 8's report then comes on the next pass, at phase 0. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + ledger.answered(8); + ledger.report(); + assert!(ledger.report_answered()); + // Round 8 is answered: phase 1 with generation 8 again is not a new round. + assert!(!new_round(ledger.last(), 8)); + assert!(new_round(ledger.last(), 9)); + // Its credit is spent: a further report without a round is not stale. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_timeout_round_is_consumed() { + // The command timeout found phase 1 and answered round 3 before the event was read. + let mut ledger = RecoveryLedger::default(); + ledger.answered(3); + ledger.report(); + assert!(ledger.report_answered()); + } + #[test] fn a_withdrawn_stopped_packet_keeps_its_guard() { // The scheduler withdraws a packet whose stopped command left the queue: it is no From a0b2c2e774b723bbe1583045fa139014b055af87 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:12:39 +1100 Subject: [PATCH 06/10] drm/asahi: log each G14 27.2 recovery round on one line A J473 row has to tell a firmware-reported stop from a silent hang. Up to now a round logged up to eight snapshot lines and a separate blame line, and the command timeout log had no recovery words at all. Each round now logs one warning with the error, the slot the event named, the last event ring kinds, the snapshot ({flags, target} in hex, the first four entries and the count), and the blamed client with its stamps (compute: the stopped command's stamp and the queue's current stamp; render: the tiler and fragment stamps). log_timeout() also prints the recovery generation, phase and snapshot, so every command timeout and recovery failure shows the control words at that moment. peek_event() now returns the raw kind word for the event history. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 72 +++++++++++++++++++++--------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 29 ++++++++++-- 2 files changed, 78 insertions(+), 23 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 0b1b82976ebc..6ca2d2f4be94 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -128,6 +128,8 @@ const RECOVERY_DRAIN_MS: i64 = 1000; /// Further recoveries answered while the stopped work drains (work behind it can time out in /// turn) before the runtime gives up. const FURTHER_RECOVERIES: u32 = 4; +/// Event ring record kinds kept for the logs of a timeout or a recovery. +const EVENT_HISTORY: usize = 8; /// Rounds start only within this budget; one round takes at most PHASE1_WAIT_MS + /// HANDSHAKE_MS + RECOVERY_DRAIN_MS, so the lock is released well within the 10 s scheduler /// job timeout. @@ -567,6 +569,13 @@ enum Kept { Render(RenderFlight), } +/// Who a recovery round blamed, for its log line: the client, and the stopped work's stamps +/// (render: tiler and fragment; compute: the stopped command's and the queue's current one). +struct Blamed { + owner: crate::m3::m3_submit::Owner, + stamps: [u32; 2], +} + struct State { peer: Peer, root: crate::fw::types::GpuObject, @@ -609,6 +618,9 @@ struct State { recovery_count: u32, /// Reports read and rounds answered: tells a stale report from a new one. ledger: g14_v27_2_abi::RecoveryLedger, + /// Kind words of the last event ring records read, and how many were read in all. + events: [u32; EVENT_HISTORY], + events_read: u64, /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept /// for the rest of the boot: the firmware may still reach that memory. Allocated with /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. @@ -638,6 +650,17 @@ impl State { } } + /// The kinds of the last event ring records read, oldest first, for a log line. + fn recent_events(&self) -> ([u32; EVENT_HISTORY], usize) { + let count = self.events_read.min(EVENT_HISTORY as u64) as usize; + let mut out = [0; EVENT_HISTORY]; + for (i, kind) in out.iter_mut().take(count).enumerate() { + let at = (self.events_read - count as u64 + i as u64) % EVENT_HISTORY as u64; + *kind = self.events[at as usize]; + } + (out, count) + } + fn running(&self) -> bool { !self.inflight.is_empty() || self.rendering.is_some() } @@ -1121,8 +1144,8 @@ impl Runtime { /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the /// published render pair, or the compute command with that completion stamp and the rest of /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. - fn blame(&self, state: &mut State, error: Error, slot: i32, work: Stopped) -> Result { - match work { + fn blame(&self, state: &mut State, error: Error, work: Stopped) -> Result { + let blamed = match work { Stopped::Render => { let Some(packet) = state.rendering.as_ref().map(|f| f.packet.clone()) else { return Err(EIO); }; @@ -1130,9 +1153,8 @@ impl Runtime { let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; flight.doomed = Some(error); latch_guilty(&flight.packet, error); - let owner = &flight.packet.owner; - dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", - owner.process(), owner.pid, slot, error); + Blamed { owner: flight.packet.owner, + stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()] } } Stopped::Compute(stamp) => { let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) @@ -1143,11 +1165,10 @@ impl Runtime { flight.doomed.get_or_insert(error); } latch_guilty(&packet, error); - dev_err!(self.dev, "GPU: stopped compute {:#x} of {}[{}] (slot {}, {:?})\n", - stamp, packet.owner.process(), packet.owner.pid, slot, error); + Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()] } } - } - Ok(()) + }; + Ok(blamed) } /// Whether every command marked by `blame` has left its queue. @@ -1234,6 +1255,7 @@ impl Runtime { .map(|f| [f.stamps[TILER].raw(), f.stamps[FRAGMENT].raw()]); let mut attribution = g14_v27_2_abi::Attribution::default(); let mut entries = 0; + let mut first = [(0u32, 0u32); 4]; let mut stopped_tiler = false; for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { let (flags, target) = state.root.recovery_entry(i)?; @@ -1245,20 +1267,26 @@ impl Runtime { attribution.add(entry.flags, entry.target, render, |stamp| { inflight.iter().any(|f| f.stamp.raw() == stamp && f.ordinal > retired) }); - if entries <= 8 { - dev_err!(self.dev, - "GPU: recovery {} entry {}: flags {:#x} (event {:#x}) target {:#x}\n", - generation, i, entry.flags, entry.event, entry.target); - } + if let Some(at) = first.get_mut(i) { *at = (entry.flags, entry.target); } } + let shown = &first[..entries.min(first.len())]; + let (events, seen) = state.recent_events(); // Every round is attributed: work behind the first stopped command can time out in // turn. Unnamed or ambiguous stopped work keeps the fail-stop. let Some(work) = attribution.result() else { - dev_err!(self.dev, "GPU: recovery {} names no single tracked command ({} entries)\n", - generation, entries); + dev_err!(self.dev, "GPU: recovery {} ({:?}, slot {}) names no single tracked command: snapshot ({} entries) {:x?}, events {:?}\n", + generation, error, slot, entries, shown, &events[..seen]); return Err(EIO); }; - self.blame(state, error, slot, work)?; + let blamed = self.blame(state, error, work)?; + let (what, second) = match work { + Stopped::Render => ("render, tiler", "fragment"), + Stopped::Compute(_) => ("compute", "queue at"), + }; + dev_warn!(self.dev, "GPU: recovery {} ({:?}, slot {}, events {:?}): snapshot ({} entries) {:x?}; stopped {} {:#x} ({} {:#x}) of {}[{}]\n", + generation, error, slot, &events[..seen], entries, shown, what, + blamed.stamps[0], second, blamed.stamps[1], + blamed.owner.process(), blamed.owner.pid); if stopped_tiler { if let Some(flight) = state.rendering.as_ref() { let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; @@ -1285,8 +1313,8 @@ impl Runtime { } state.root.answer_recovery(0)?; state.ledger.answered(generation); - dev_err!(self.dev, "GPU: recovery {} answered in {} ms ({} snapshot entries)\n", - generation, start.elapsed().as_millis(), entries); + dev_info!(self.dev, "GPU: recovery {} answered in {} ms\n", + generation, start.elapsed().as_millis()); let start = Instant::::now(); loop { let _ = state.root.drain(); @@ -1352,7 +1380,9 @@ impl Runtime { let mut reported = false; // Limit one pass to the ring capacity. Further arrivals notify the worker again. for _ in 0..256 { - let Some((cursor, event)) = state.root.peek_event()? else { break; }; + let Some((cursor, kind, event)) = state.root.peek_event()? else { break; }; + state.events[(state.events_read % EVENT_HISTORY as u64) as usize] = kind; + state.events_read += 1; match event { FirmwareEvent::Grow(request) if request.halt_count == state.root.halt_count()? => { let Some(reply) = state.root.reserve_control_reply()? else { @@ -1921,6 +1951,8 @@ impl Backend { recovery_window: 0, recovery_count: 0, ledger: g14_v27_2_abi::RecoveryLedger::default(), + events: [0; EVENT_HISTORY], + events_read: 0, kept, kept_flights: KVec::new(), hardware_unreachable: false, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 1b48e8cf6618..78046f9abb07 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -738,6 +738,27 @@ impl RootV27_2 { for (name, queue) in ["tiler", "fragment"].into_iter().zip(&self.render_queues) { Self::log_queue(dev, name, &queue.positions, &queue.queue, &queue.event); } + let (generation, phase) = (self.halt_count(), self.recovery_phase()); + let (snapshot, entries) = self.recovery_snapshot(); + dev_err!(dev, "GPU: recovery generation={:?} phase={:?} snapshot ({} entries) {:x?}\n", + generation, phase, entries, &snapshot[..entries.min(snapshot.len())]); + } + + /// The first valid recovery snapshot entries, {flags, target} in hex, and how many valid + /// entries there are in all (the first invalid entry ends the snapshot). Logging only. + pub(crate) fn recovery_snapshot(&self) -> ([(u32, u32); 4], usize) { + let mut first = [(0, 0); 4]; + let mut entries = 0; + for i in 0..RECOVERY_SNAPSHOT_ENTRIES { + match self.recovery_entry(i) { + Ok((flags, target)) if flags & 1 != 0 => { + if let Some(slot) = first.get_mut(entries) { *slot = (flags, target); } + entries += 1; + } + _ => break, + } + } + (first, entries) } pub(crate) fn render_kick(dm: usize) -> u64 { @@ -850,7 +871,8 @@ impl RootV27_2 { && job.event.current_noncoherent().raw() == job.expected_stamp) } - pub(crate) fn peek_event(&self) -> Result> { + /// The record at the head of the event ring: its cursor, its raw kind word and its decoding. + pub(crate) fn peek_event(&self) -> Result> { use crate::m3::m3_channel_format::RECEIVE_BYTES; let state = &self.channels[2 * EVENT_RING]; let ring = &self.channels[2 * EVENT_RING + 1]; @@ -863,7 +885,8 @@ impl RootV27_2 { crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); crate::pgtable::poc_barrier(); let word = |offset| Self::word(ring, at + offset); - let event = match g14_v27_2_abi::event_kind(word(0)?) { + let kind = word(0)?; + let event = match g14_v27_2_abi::event_kind(kind) { EventKind::Grow => FirmwareEvent::Grow(GrowRequest::decode([ word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, ])), @@ -874,7 +897,7 @@ impl RootV27_2 { EventKind::ChannelError => FirmwareEvent::ChannelError, EventKind::Notification => FirmwareEvent::Notification, }; - Ok(Some((read, event))) + Ok(Some((read, kind, event))) } /// Validates a byte range of the control object before it is sliced or cache-maintained. From 9303dd812506365e6495af0320be259ab031db70 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:16:00 +1100 Subject: [PATCH 07/10] drm/asahi: fail all G14 27.2 work on a command timeout only without a round The driver's 5 s command timeout is a backstop for the firmware's own recovery, but it still acted alone. The compute path answered a round open at phase 1 only when the front command was not blamed yet, and the render path only when the render was not stopped. Recovery also restarted the clocks of queued compute work but not of the render in flight. So a render that waited out a round for another client could reach the timeout and fail every client. Ask the firmware first, in both paths (g14_v27_2_abi:: command_timeout_action). With a round open, recover: the snapshot names the stopped command by stamp (stopped_compute(), which never names a retired command), only that client fails, and the others' work resumes after phase 0 with its clock restarted. Only with no round open, a silent hang, does the timeout still fail all work. It then logs the queue positions, the recovery generation, phase and snapshot, the MMU fault status, the last event ring kinds and the report and round counts, so a row tells a silent hang from a missed report. sleep_prepare() also refuses while the firmware has a round open, so no round crosses a system sleep. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 60 +++++++++++++++----- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 77 ++++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 6ca2d2f4be94..b87e308af54f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1082,16 +1082,18 @@ impl Runtime { } } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); - if state.root.recovery_phase()? == 1 && doomed.is_none() { - // The firmware stopped it and halted, but its event was not seen. Recovery - // marks it and waits until it left both queues: retire it now, so its fence - // is signalled and the queue behind it runs without waiting for another message. + if g14_v27_2_abi::command_timeout_action(state.root.recovery_phase()?) + == g14_v27_2_abi::TimeoutAction::Recover + { + // The firmware has a round open whose event was not seen. Recovery blames the + // work it stopped and waits until that left its queue. Then retire again, so a + // stopped render's fence is signalled and the queue behind it runs without + // waiting for another message; an innocent render got its clock restarted. if self.recover(state, ETIMEDOUT, -1)? { return self.retire_render(state); } } - state.root.log_timeout(&self.dev); - state.fault.log(&self.dev); + self.log_silent_hang(state, "render"); return Err(ETIMEDOUT); } Ok(()) @@ -1157,8 +1159,9 @@ impl Runtime { stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()] } } Stopped::Compute(stamp) => { - let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) - .map(|f| f.packet.clone()) else { return Err(EIO); }; + let flights = state.inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + let Some(packet) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) + .map(|i| state.inflight[i].packet.clone()) else { return Err(EIO); }; self.reserve_kept(state, &packet)?; let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); for flight in state.inflight.iter_mut().filter(owned) { @@ -1171,6 +1174,19 @@ impl Runtime { Ok(blamed) } + /// The last resort of a command timeout: the firmware has no recovery round open, so it + /// reported nothing the host can answer. Logs what a row needs to tell a silent hang from a + /// missed report: queue positions and recovery words (`log_timeout`), the MMU fault status, + /// and the last event ring kinds with the report and round counts. + fn log_silent_hang(&self, state: &State, work: &str) { + state.root.log_timeout(&self.dev); + state.fault.log(&self.dev); + let (events, seen) = state.recent_events(); + let (reports, answered) = state.ledger.counts(); + dev_err!(self.dev, "GPU: {} timed out with no recovery round open: last events {:?} ({} read), {} reports, {} rounds answered (last {:?}); failing all work\n", + work, &events[..seen], state.events_read, reports, answered, state.ledger.last()); + } + /// Whether every command marked by `blame` has left its queue. fn doomed_retired(&self, state: &mut State) -> Result { if let Some(flight) = state.rendering.as_ref() { @@ -1265,7 +1281,8 @@ impl Runtime { let retired = state.retired_total; let inflight = &state.inflight; attribution.add(entry.flags, entry.target, render, |stamp| { - inflight.iter().any(|f| f.stamp.raw() == stamp && f.ordinal > retired) + let flights = inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + g14_v27_2_abi::stopped_compute(flights, retired, stamp).is_some() }); if let Some(at) = first.get_mut(i) { *at = (entry.flags, entry.target); } } @@ -1323,6 +1340,7 @@ impl Runtime { // Work behind the stopped command waited out the recovery: restart its clocks. let now = Instant::now(); for flight in state.inflight.iter_mut() { flight.started = now; } + if let Some(flight) = state.rendering.as_mut() { flight.started = now; } dev_err!(self.dev, "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", state.recoveries, start.elapsed().as_millis()); @@ -1481,8 +1499,7 @@ impl Runtime { } while !state.inflight.is_empty() { let front = &state.inflight[0]; - let (ordinal, started, unblamed, expected) = - (front.ordinal, front.started, front.doomed.is_none(), front.stamp.raw()); + let (ordinal, started, expected) = (front.ordinal, front.started, front.stamp.raw()); if state.retired_total >= ordinal { if let Ok(done) = state.inflight.remove(0) { self.retire_slot(state, done.slot); @@ -1503,19 +1520,22 @@ impl Runtime { if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", state.queue_stamp(), expected, state.submitted, state.retired); - if unblamed && state.root.recovery_phase().unwrap_or(0) == 1 { - // The firmware stopped it and halted, but its event was not seen. + let phase = state.root.recovery_phase().unwrap_or(0); + if g14_v27_2_abi::command_timeout_action(phase) == g14_v27_2_abi::TimeoutAction::Recover { + // The firmware has a round open whose event was not seen. Recovery blames + // the command it names by stamp, which need not be this front one, and + // fails only that client; the others' work resumes after phase 0. match self.recover(state, ETIMEDOUT, -1) { Ok(true) => continue, Ok(false) => {} Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); self.fail_all(state, err); return; } } } - state.root.log_timeout(&self.dev); - state.fault.log(&self.dev); + self.log_silent_hang(state, "compute"); self.fail_all(state, ETIMEDOUT); return; } @@ -1573,6 +1593,16 @@ impl Runtime { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } if !state.running() { + // No recovery round crosses a sleep: a round open now (the firmware stopped + // without anything of ours running) is answered by the service first. + let phase = state.root.recovery_phase().unwrap_or(0); + if phase != 0 { + dev_err!(self.dev, "GPU: sleep refused, firmware recovery phase {}\n", phase); + self.asleep.store(false, Ordering::Release); + self.pump(state); + self.notify.wake(); + return Err(EBUSY); + } break; } if remaining == 0 { diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 662f4fb13744..96d4992845d6 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -137,6 +137,39 @@ impl Attribution { } } +/// The published compute command a snapshot target names: the one, among commands the queue +/// has not retired (`ordinal > retired`), whose completion stamp is `stamp`. `flights` yields +/// each published command's (completion stamp, ordinal) in publication order. A command that +/// already retired is never blamed, even before the host has taken it off its list. +pub(crate) fn stopped_compute( + flights: impl IntoIterator, + retired: u64, + stamp: u32, +) -> Option { + flights.into_iter().position(|(s, ordinal)| s == stamp && ordinal > retired) +} + +/// What the host does when a command ran past the driver's command timeout. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TimeoutAction { + /// The firmware has a recovery round open (phase 1): answer it, which blames the work it + /// stopped by stamp and fails only that client. + Recover, + /// No round open: the firmware reported nothing and stopped nothing that the host can + /// answer (a silent hang), or the handshake is in a state the host does not own. Failing + /// all work is the last resort. + FailAll, +} + +/// The driver's command timeout is only a backstop for the firmware's own recovery: it fails +/// every client only when the firmware has no round open. +pub(crate) const fn command_timeout_action(phase: u32) -> TimeoutAction { + match phase { + 1 => TimeoutAction::Recover, + _ => TimeoutAction::FailAll, + } +} + /// A further recovery round while stopped work drains must carry a new generation; the same /// generation again means the host misread the handshake. pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { @@ -189,6 +222,11 @@ impl RecoveryLedger { pub(crate) const fn report_answered(&self) -> bool { self.reports <= self.answered } + + /// Reports read and rounds answered so far, for a log line. + pub(crate) const fn counts(&self) -> (u64, u64) { + (self.reports, self.answered) + } } /// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, @@ -576,6 +614,45 @@ mod tests { assert!(ledger.report_answered()); } + #[test] + fn a_timed_out_compute_is_blamed_by_stamp_and_spares_its_neighbours() { + // Compute list in publication order: (owner, completion stamp, ordinal). Client A's + // command completed and retired, but the host has not taken it off its list yet; B's + // command is the one the firmware timed out (event 4); C's command was published after + // it and waits behind it. + let flights = [('A', 0x7900u32, 1u64), ('B', 0x7a00, 2), ('C', 0x7b00, 3)]; + let retired = 1; + let unretired = |stamp| stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, stamp) + .is_some(); + // The J473 compute snapshot: one entry {0x7, next stamp of the stopped command}. + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, unretired); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + let stopped = stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7a00); + assert_eq!(stopped, Some(1)); + // blame() dooms every listed command of the stopped command's packet, and only those. + let guilty = flights[stopped.unwrap()].0; + let doomed: [bool; 3] = core::array::from_fn(|i| flights[i].0 == guilty); + assert_eq!(doomed, [false, true, false]); + // A target naming the retired front is not blamed on it. + assert_eq!(stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7900), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7900, None, unretired); + assert_eq!(a.result(), None); + } + + #[test] + fn the_command_timeout_fails_all_only_without_a_recovery_round() { + assert_eq!(command_timeout_action(1), TimeoutAction::Recover); + // Silent hang: no round open. + assert_eq!(command_timeout_action(0), TimeoutAction::FailAll); + // The host's own phases or anything else: the handshake is not the firmware's to + // continue, so the host does not answer it from a timeout. + for phase in [2, 3, 4, u32::MAX] { + assert_eq!(command_timeout_action(phase), TimeoutAction::FailAll); + } + } + #[test] fn a_withdrawn_stopped_packet_keeps_its_guard() { // The scheduler withdraws a packet whose stopped command left the queue: it is no From c49b2ded3a4ba6c90b149025b08bcdf614de732b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:21:22 +1100 Subject: [PATCH 08/10] drm/asahi: never drop a stopped G14 27.2 flight when keeping it fails Keeping a stopped flight used KVec::push(), which drops the value when the allocation fails. That would release the flight's VM binding and scene while the firmware may still reach them. Reserve the place first and leak the flight if that fails. Its packet is kept either way, so the client's guard stays. Keep compute and render flights in two lists instead of one enum. A RenderFlight is much larger than an Inflight, so the enum would have made every kept compute flight as large as a render one. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 37 +++++++++++++++--------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index b87e308af54f..ac78695a87d7 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -561,14 +561,6 @@ struct RenderFlight { doomed: Option, } -/// A command the firmware stopped, kept with everything it owns (VM binding, scene) after it -/// left its queue: see `Runtime::fail_doomed` and `Runtime::keep`. Held, never read. -#[allow(dead_code)] -enum Kept { - Compute(Inflight), - Render(RenderFlight), -} - /// Who a recovery round blamed, for its log line: the client, and the stopped work's stamps /// (render: tiler and fragment; compute: the stopped command's and the queue's current one). struct Blamed { @@ -625,8 +617,10 @@ struct State { /// for the rest of the boot: the firmware may still reach that memory. Allocated with /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. kept: KVec>, - /// The stopped commands of those packets, once they left their queue. - kept_flights: KVec, + /// The stopped commands of those packets, with their VM binding and scene, once they left + /// their queue (`Runtime::keep`). Held, never read. + kept_compute: KVec, + kept_renders: KVec, /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so /// teardown skips live-hardware MMIO and RTKit operations. hardware_unreachable: bool, @@ -1074,7 +1068,7 @@ impl Runtime { } if let Some(err) = flight.doomed { self.fail_doomed(state, &flight.packet, err); - self.keep(state, Kept::Render(flight)); + self.keep(&mut state.kept_renders, flight); } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { @@ -1121,11 +1115,17 @@ impl Runtime { } /// Keeps a stopped command that left its queue, with its VM binding and scene, for the rest - /// of the boot. Its packet is already in `State::kept`, so ownership does not depend on - /// this allocation; if it fails, the flight is leaked instead, which keeps it as well. - fn keep(&self, state: &mut State, flight: Kept) { - if let Err(err) = state.kept_flights.push(flight, GFP_KERNEL) { - dev_warn!(self.dev, "GPU: no memory to track a stopped command ({:?}); leaking it\n", err); + /// of the boot (`State::kept_compute`, `kept_renders`). Its packet is already in + /// `State::kept`, so ownership does not depend on this allocation. If it fails, the flight + /// is leaked, which keeps it as well; it is never dropped. + fn keep(&self, list: &mut KVec, flight: T) { + if list.reserve(1, GFP_KERNEL).is_err() { + dev_warn!(self.dev, "GPU: no memory to track a stopped command; leaking it\n"); + core::mem::forget(flight); + return; + } + if let Err(kernel::alloc::kvec::PushError(flight)) = list.push_within_capacity(flight) { + core::mem::forget(flight); } } @@ -1505,7 +1505,7 @@ impl Runtime { self.retire_slot(state, done.slot); if let Some(err) = done.doomed { self.fail_doomed(state, &done.packet, err); - self.keep(state, Kept::Compute(done)); + self.keep(&mut state.kept_compute, done); } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); @@ -1984,7 +1984,8 @@ impl Backend { events: [0; EVENT_HISTORY], events_read: 0, kept, - kept_flights: KVec::new(), + kept_compute: KVec::new(), + kept_renders: KVec::new(), hardware_unreachable: false, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: None, From 2213f9815e3143a31323ba6deec9029cb003bc7f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 00:04:52 +1100 Subject: [PATCH 09/10] drm/asahi: drain only the G14 27.2 command the firmware stopped After a recovery round, the host waited for every command of the guilty packet to leave the queue within RECOVERY_DRAIN_MS. Only the command the snapshot named was stopped: the packet's later commands run normally. A hung client usually has several dispatches queued, and if one of them also runs past the drain budget, the round ended in "stopped work did not leave the queue" and failed every client, which is what the recovery is there to avoid. Wait for the stopped command only. The packet's later commands are already marked and are failed as they retire; if one of them hangs too, the firmware stops it in a round of its own. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index ac78695a87d7..0b9f120cc7de 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -566,6 +566,9 @@ struct RenderFlight { struct Blamed { owner: crate::m3::m3_submit::Owner, stamps: [u32; 2], + /// The stopped compute command's queue ordinal: the drain waits for this command only. The + /// packet's later commands were not stopped and retire (failed) through the normal path. + stopped: Option, } struct State { @@ -1156,19 +1159,22 @@ impl Runtime { flight.doomed = Some(error); latch_guilty(&flight.packet, error); Blamed { owner: flight.packet.owner, - stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()] } + stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()], + stopped: None } } Stopped::Compute(stamp) => { let flights = state.inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); - let Some(packet) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) - .map(|i| state.inflight[i].packet.clone()) else { return Err(EIO); }; + let Some((packet, stopped)) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) + .map(|i| (state.inflight[i].packet.clone(), state.inflight[i].ordinal)) + else { return Err(EIO); }; self.reserve_kept(state, &packet)?; let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); for flight in state.inflight.iter_mut().filter(owned) { flight.doomed.get_or_insert(error); } latch_guilty(&packet, error); - Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()] } + Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()], + stopped: Some(stopped) } } }; Ok(blamed) @@ -1187,16 +1193,17 @@ impl Runtime { work, &events[..seen], state.events_read, reports, answered, state.ledger.last()); } - /// Whether every command marked by `blame` has left its queue. - fn doomed_retired(&self, state: &mut State) -> Result { + /// Whether the stopped work has left its queue: the render pair, or the compute command at + /// `stopped` (its packet's later commands run normally and are failed as they retire). + fn doomed_retired(&self, state: &mut State, stopped: Option) -> Result { if let Some(flight) = state.rendering.as_ref() { if flight.doomed.is_some() { return Ok(state.root.render_retired(TILER, flight.targets[TILER])? && state.root.render_retired(FRAGMENT, flight.targets[FRAGMENT])?); } } - let Some(ordinal) = - state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal) + let Some(ordinal) = stopped.or_else(|| + state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal)) else { return Ok(true); }; self.advance(state)?; Ok(state.retired_total >= ordinal) @@ -1335,7 +1342,7 @@ impl Runtime { let start = Instant::::now(); loop { let _ = state.root.drain(); - if self.doomed_retired(state)? { + if self.doomed_retired(state, blamed.stopped)? { state.recoveries += 1; // Work behind the stopped command waited out the recovery: restart its clocks. let now = Instant::now(); From fa824cfae0227f17d33e2ae151f0674f664f6d75 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 00:04:52 +1100 Subject: [PATCH 10/10] drm/asahi: forget G14 27.2 recovery rounds across a warm restart The recovery ledger keeps the last answered generation and refuses a round that repeats it. After a deep-sleep warm restart the firmware may count generations from its start again, so the first real round after wake could be refused with EPROTO and fail all work. No round can cross a sleep (sleep_prepare refuses while one is open), so start the ledger afresh once the firmware is back. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 0b9f120cc7de..24a1b9c66e23 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1796,6 +1796,9 @@ impl Runtime { state.waiting_control = None; match restart { Ok(()) => { + // No round crosses a sleep (sleep_prepare refuses one), and the restarted + // firmware may count generations again from its start: forget old rounds. + state.ledger = g14_v27_2_abi::RecoveryLedger::default(); dev_info!(self.dev, "GPU firmware 27.2 back in {} us (commit idle={} {} us, pending={})\n", started.elapsed().as_micros_ceil(), commit.idle_ret, commit.idle_us, state.pending.len());