Skip to content

drm/asahi: recover from G14 firmware 27.2 command timeouts and faults per client - #3041

Merged
RyanTheTide merged 11 commits into
mainfrom
m2gpu/g14-v27-2-recovery
Nov 27, 2026
Merged

RyanTheTide merged 11 commits into
mainfrom
m2gpu/g14-v27-2-recovery

Conversation

@RyanTheTide

@RyanTheTide RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What: When a command runs past its allowance or faults, the G14 firmware 27.2 reports it on the event ring (kind 4 timeout, kind 0 fault) and stops every queue until the host answers its recovery handshake: generation +0x4bf0, phase +0x4c00 (1 -> 2 -> 3 -> 0), snapshot of the stopped work at +0x4298. Main ignores both events. One stuck command therefore stops the GPU, and after 5 s the host fails the whole runtime: every client, gnome-shell included, gets EIO until reboot, even after s2idle. This change answers the handshake and fails only the client that owns the stopped command. The other clients keep running. The 5 s host timeout still fails everything, but only when the firmware has no recovery round open, and it now logs the recovery words and the last event kinds first.

This revision merges main (#3182 pool slots, #3198 samplers, deep-sleep warm restart) and fixes Dj's two blockers:

  • Work the firmware stopped stays owned (kept for the boot), so withdraw() can no longer release its job guard.
  • A fault or timeout record whose round was already answered is consumed instead of failing all work.
  • Also: the drain waits only for the stopped command, not for the guilty client's later ones, and the recovery history resets on a warm restart.

Tested: J473 (M2 mini, firmware 27.2) rows, default cmdline, GNOME on both monitors, kernel = main 255761f + this branch:

  • J473 at fa824cfa: deliberate compute hang x3 (GL compute spinning on an atomic) pass: each time the firmware timed it out itself (<0.3 s, event 4), recovery blamed only that client by stamp, answered in 1 ms; a vkcube bystander, gnome-shell (same PID), fresh vulkaninfo/vkcube and a compute.heavy all worked after every hang; 0 fail-all; s2idle + fresh Vulkan after: pass.
  • J473 at fa824cfa: Geekbench 6 Vulkan x8 with timestamps and the full clock range pass 8/8 (0 firmware crashes, 0 timeouts), fresh clients pass after.
  • J473 at fa824cfa: gpubench compute light/heavy alu/bw, 48 runs, pass, 0 GPU errors, s2idle + fresh Vulkan pass.
  • J473 at c49b2ded (before the last two commits): 48/48 compute with a bystander + GB6 Vulkan x8 8/8 pass.

Host tests: run-host-tests.py --only g14-v27-2 pass (24 tests, 7 new), m3-runtime 1/1, m3-stamp 3/3, g16 recovery logic 11/11; asahi_core.o and clippy clean in the changed code.

Risk: two-way · only Macs running the G14 firmware 27.2 runtime (J473 today). The handshake decisions are G16's existing g16/recovery/logic.rs, included by path; no g15/g16 file is changed. With no recovery round the behaviour is main's (fail all), now with a log line saying why.

Not yet:

  • The compute.heavy stall that started this (see Evidence) is a silent firmware stall with no recovery round, so this PR does not contain it per client: it still fails all work, now with a log saying so. Fixing it needs its cause (fresh-compile only, identical program) or a host-started recovery, which neither 27.2 nor G16/M4 has today.
  • A J413 13.5 row (that runtime does not run this code).
  • Review notes still open: kind 0 is treated as a fault (as in the H1-H4 traces); a fault and a timeout record for one stop, read in two passes, would still fail all; the phase store writes back its 64-byte line; the snapshot is not cleared after a round.
Details
  • Attribution: each snapshot target is the stopped command's completion stamp, matched against the published render pair and the unretired compute commands after the retired position is refreshed. Anything ambiguous or unnamed fails all work as before. Every round is attributed; each further round needs a new generation.
  • Stopped work (Dj blocker 1): blaming reserves a slot in State::kept before anything is marked; owns() counts kept packets, so withdraw(), fail_all() and fail_publication() never release their guard. Kept work stays for the boot (at most 31 clients; then fail-all, still owned).
  • Stale reports (Dj blocker 2): RecoveryLedger counts reports read and rounds answered; a report whose round was already answered is consumed with a warning.
  • Drain: only the command the snapshot named must leave the queue; the guilty packet's later commands are failed as they retire.
  • Host timeout: with phase 1 open, the 5 s command timeout answers the round; otherwise it is a silent hang: it logs queues, recovery generation/phase/snapshot, FAULT_INFO and the last 8 event kinds, then fails all work as main does.
  • Sleep: sleep is refused while a round is open; the ledger restarts after a deep-sleep warm restart.
  • Guilty VM: its VmStatus latches; submit() refuses it and pump() fails its queued packets.
Evidence

Our own traces, traces/gpu/20261126-m2gpu-heavy/ (README) and traces/gpu/20261124-m2gpu-hang/ (H1-H5, the protocol):

  • What started this: on merged main a gpubench-vk compute.heavy timed out and every later client got EIO, even after s2idle (PEER-ROWS batch14, traces/gpu/20261126-peer-rows-batch14-j473/).
  • Not new: the same first compute.heavy fails 1/1 on m2combo19 (before drm/asahi: fix the G14 27.2 pool slot lifetime (GB6 firmware crash and pool stall) #3182 and drm/asahi: admit compute sampler heaps on G14 firmware 27.2 #3198), m2combo20 and m2combo22.
  • Trigger: a compute.heavy whose shader is compiled fresh in that process. Every failure came before the first successful run put the shader in Mesa's disk cache; with MESA_SHADER_CACHE_DISABLE=true it fails again on this branch. The compiled program is identical either way (59 instructions, 21 GPRs, no scratch).
  • With this branch's logging that stall is silent: recovery generation 0, phase 0, no snapshot, only notification events, FAULT_INFO 0. The firmware never times the job out (its watchdog caught the deliberate spin in <0.3 s), so there is no round to answer and the last resort still fails all work. The cause of the stall is open (see Not yet).

… 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 <[email protected]>
@RyanTheTide

Copy link
Copy Markdown
Contributor Author

MERGETRAIN6 source review at 8da4dbcce374. Blocking: the per-client attribution can select a healthy VM. service_locked() drains event records and calls recover() before refreshing and retiring completed compute entries. blame() then uses the first entry still in the host list. The event's slot and snapshot are logged, but neither constrains the selected packet. Completed commands can still be in that list while a later command is the one the firmware stopped. The recovery can mark the earlier VM lost and restart newer clocks without having identified the stopped packet.

Refresh completion state and correlate the stopped entry with the tracked command or packet before reporting a per-client loss. If the firmware information is ambiguous, keep the existing fail-stop behavior for that case. Please add a host fixture covering a completed entry still in the host list ahead of the stopped entry, plus a generation change while recovery drains. The earlier J473 H4 is good precursor evidence for the exercised ownership pattern.

Assisted-by: LLM (Codex)

@DjDeveloperr DjDeveloperr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formal adversarial pre-PR review bound to head 8da4dbcce37475e5a8b3db8d0e8a37492fb5d093 (stacked on #3031 / m2gpu/g14-v27-2-render ccde92779a5f0c5e52d43e6ae88547b913afea01).

Verdict: REQUEST_CHANGES

The shared g16/recovery/logic.rs reuse via #[path], commit hygiene (§4), and lack of model/board gating (§1/§2) are clean, but there are concrete correctness, memory-safety, and contract blockers in the recovery path plus missing exact-head hardware/CI evidence.


Blockers (§1 Correctness & Safety)

  1. Misattribution and false Ok(()) retirement on pipelined compute work (drivers/gpu/drm/asahi/g14_v27_2.rs:894-912, 991-994, 1020-1044, 1123-1188)

    • service_locked() drains the event ring and calls recover() before calling advance(state) and retiring already-completed entries at the front of state.inflight.
    • blame() ignores both the event's slot and every decoded SnapshotEntry { flags, event, target } (only logged / checked for stopped_tiler), and blindly marks state.inflight.first().
    • When an innocent VM's compute command has already finished on the GPU (still at inflight[0] before advance()) and a later VM's command times out/faults, blame() dooms the innocent earlier packet, doomed_retired() immediately observes retired_total >= ordinal (Ok(true)), recover() restarts started on the actually stopped command, service_locked() kills the innocent VM via fail_doomed(), and the truly stopped command—never marked doomed—can then leave the queue without a stamp and retire as packet.retired() (Ok(())).
    • Additional attribution/state-machine gaps in recover():
      • self.blame(...)'s bool return is ignored (g14_v27_2.rs:993): a halt with nothing published still answers 2 -> 3 -> 0 and stays healthy instead of correlating against a last-retired target or fail-stopping.
      • if !blamed skips blame() on rounds 1..=FURTHER_RECOVERIES, so a second recovery while draining that stops a different queued command is never marked doomed and can likewise retire as Ok(()).
      • The drain loop (g14_v27_2.rs:1020-1039) checks only recovery_phase()? == 1: it does not verify that halt_count() advanced to a new generation, does not fail-stop on unexpected phases (!= 0 && != 1), and does not check state.peer.is_crashed() during the 1 s drain wait.
    • Required fix: Refresh/retire completed work before attributing, correlate firmware snapshot (flags, event, target) / event slot / FaultStatus ASID against tracked flights (fail-stopping on ambiguity or unmatched entries as g16/engine.rs::recovery_prepare does), re-attribute on new-generation drain recoveries, and add host-test fixtures covering (a) a completed entry ahead of the stopped entry and (b) a generation change during drain.
  2. Undefined Behavior in Scene::clear_tpc (drivers/gpu/drm/asahi/buffer.rs:204-213)

    • clear_tpc(&self, bytes) creates an immutable slice let tpc = self.object.tpc.as_slice(); (&[u8] from slice::from_raw_parts, object.rs:688-691, no UnsafeCell) and then writes through tpc.as_ptr().cast_mut() with core::ptr::write_bytes. Mutating through a shared &[u8] reference is Rust UB.
    • clear_tpc is also exposed as a safe pub(crate) method on Scene::ver across all GPU generations even though self.object.tpc is a shared Arc<GpuArray<u8>> cached in BufferInner::tpc (buffer.rs:700-717) and relies on an unchecked caller precondition that no concurrent reader/writer exists.
    • Required fix: Zero through a raw pointer method on GpuArray<u8> (without fabricating &[u8]) and document/enforce the exclusivity precondition cleanly.
  3. Guilty VM is not actually banned from admission (drivers/gpu/drm/asahi/g14_v27_2.rs:577-589, 676-712, 880-889, m3_submit.rs:288-359)

    • The PR claims "the guilty VM is latched" and "only that packet and its VM fail", but fail_doomed() only withdraws the single doomed packet from state.pending and records the error in VmStatus.
    • Neither m3_submit::Queue::submit(), mmu::Vm::retain_job(), Runtime::submit(), nor Runtime::pump() checks vm.status().get() != 0 (compare g16/engine.rs:695).
    • Consequently, other packets already queued in state.pending or the scheduler from the same guilty VM still publish and run after recovery, and a client that submits again without checking VM_STATUS continues executing on the GPU. (status.note_recovery_guilty() is also never called.)
    • Required fix: Reject new submissions and fail/withdraw queued state.pending packets belonging to any VM whose VmStatus is non-zero (and call status.note_recovery_guilty() when blaming a guilty VM).
  4. Fallback render recovery in retire_render() strands state.rendering (drivers/gpu/drm/asahi/g14_v27_2.rs:864-869)

    • When retire_render() hits COMMAND_TIMEOUT_MS and finds recovery_phase()? == 1 && doomed.is_none(), it executes return self.recover(state, ETIMEDOUT, -1);.
    • recover() drains TA and FS to completion and returns Ok(()), after which retire_render() returns Ok(()) without taking state.rendering or calling fail_doomed(). service_locked() then calls pump(state), which immediately returns because state.rendering.is_some(). With TA/FS already retired, no further EP 0x20 interrupt arrives, leaving the doomed fence unsignaled and starving all other clients' state.pending work until the 10 s DRM scheduler timeout fires wake().
    • Required fix: Re-run the retirement check (or loop, as the compute fallback at g14_v27_2.rs:1174-1180 does) after recover() returns Ok(()) so state.rendering is taken, slots are retired, and fail_doomed() runs immediately.
  5. DMA / resource retirement witness on aborted commands (drivers/gpu/drm/asahi/g14_v27_2.rs:832-863, 880-889, 1155-1168 vs g16/recovery/logic.rs:51-53)

    • On an aborted (doomed) command, no completion stamp is written; render_retired() / advance() only proves queue cursor progress. Yet retire_render() and service_locked() immediately drop RenderFlight/Inflight (releasing VmBind, scene/aux_fb/scene27/tvb_*, preempt), call packet.release_guard() (allowing immediate user BO unmap/free), and clear state.busy (allowing pool slot reuse once registered(slot) reads 0).
    • Contrast with the invariant in g16/recovery/logic.rs:51-53 (imported by this PR) and g16/poll.rs:519-524: "A passed abort proves queue progress only and never permits reuse." Either establish and document the exact G14 27.2 firmware/hardware quiescence guarantee proving that retired-cursor advance after phase 3 -> 0 guarantees zero further DMA to client BOs, VmBind, scene buffers, and pool slots, or quarantine aborted slots/guards/owners instead of releasing them.

Non-blocking hardening notes

  • drivers/gpu/drm/asahi/gpu/v27_2.rs:745-761: control_snapshot() slices self.control.as_slice()[from..] and runs clean_invalidate_poc(at, out.len() * 4) before bounds-checking from + out.len() * 4 <= self.control.len(). Current internal callers are in-bounds, but as a pub(crate) fallible helper it should validate the full byte range before slicing/cache-cleaning (likewise control_store()).
  • drivers/gpu/drm/asahi/g14_v27_2.rs:962-1044: Up to 1 + FURTHER_RECOVERIES (5) rounds × (50 ms + 1000 ms + 1000 ms) holds self.state mutex for up to ~10.25 s, exceeding the 10 s scheduler timeout and blocking submit()/withdraw()/sleep_prepare()/stop(). Consider bounding total recovery wall time under the lock.

Checklist Status (§2–§6)

  • §2 Scope & No Hacks: PASS — no chip/board/firmware-version gates, no new cmdline/module params, clean #[path] reuse of g16/recovery/logic.rs (compiles without CONFIG_DRM_ASAHI_G16), no cross-SoC regressions beyond buffer.rs::clear_tpc (B2).
  • §3 Docs & PR Body: Needs update once B1/B3 are fixed so "the guilty VM is latched" and per-client isolation match implementation.
  • §4 Commit Hygiene: PASS — single commit 8da4dbcce37475e5a8b3db8d0e8a37492fb5d093 has human author/committer (Ryan Murray <[email protected]>), human Signed-off-by:, and zero AI trailers in commits.
  • §5 Hardware Evidence: Missing (blocker before merge) — as noted in "Still to run", exact-head J473 (27.2, without lab encoder-params edits; covering render + compute fault/timeout recovery, innocent context survival, pipelined compute attribution, and repeated fault stress) and J413 (13.5 regression tuple) are still required.
  • §6 Build & CI: 0 CI checks ran on 8da4dbcce37475e5a8b3db8d0e8a37492fb5d093 (host-tests.yml skips stacked base m2gpu/g14-v27-2-render; sep-source.yml path filters do not match drivers/gpu/drm/asahi/** or tools/asahi/**). Locally verified rustc --test on g14_v27_2_abi.rs (6/6 pass) and g16/recovery/logic.rs (9/9 pass); arm64 kernel rust-build and KUnit (asahi_g14_fw_queues) have not yet run on this head.

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 <[email protected]>
@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, that's a real bug. Fixed in 52166ad, a new commit on top; no force push.

  • A snapshot entry's target is the completion stamp the stopped command would have written. On the J473, compute had written 0x7900 when its entry was {0x7, 0x7a00}; the tiler had written 0x2156500 when its entry was {0x1f, 0x2156600}. Recovery now refreshes the retired position, then matches every valid entry against the published render pair's stamps and the unretired compute commands' stamps. It blames only when all entries of a round name the same tracked command. A stopped tiler can only be the render pair. An entry that is unnamed, mixed or matches both kinds of work keeps the fail-stop.
  • Every round is now attributed, not just the first. A further round while the work drains must carry a new generation; a repeated generation fails with EPROTO.
  • Host fixtures in g14_v27_2_abi.rs (run by tools/asahi/g14-v27-2-abi-tests.rs, 10/10 pass):
    • a completed entry still in the host list ahead of the stopped one;
    • render pair entries, and a tiler entry that matches no published pair;
    • untracked, mixed and colliding snapshots;
    • generation changes while draining.
  • Full arm64 build at 52166ad is OK with 0 warnings in the changed files.

The H3/H4 snapshots each had one entry naming the stopped command's next stamp, so the earlier rows should attribute the same way. A J473 row at this head is still needed.

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Re-review of 52166ad98c80. The stale-front selection is addressed. An already-retired compute entry is excluded from attribution, every valid entry must name the same tracked work, and repeated round generations fail closed. I re-ran the ABI unit tests on this head and all 10 passed.

The other open review findings remain in the code. Queue retirement still releases aborted-command state without a separate quiescence witness. The guilty VM still needs admission and pending-queue enforcement, the render timeout fallback still needs to retire and signal the render flight after recovery, and the shared TPC clear still needs a valid exclusive write path. Keep recovery separate from base render qualification while these are addressed.

Assisted-by: LLM (Codex)

@DjDeveloperr DjDeveloperr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Focused §1–§6 re-review at exact head 52166ad98c80677784ee2cd77dcb69cf5bf8e1eb (stacked on 8da4dbcce37475e5a8b3db8d0e8a37492fb5d093, no force push). Posting as COMMENT so the existing CHANGES_REQUESTED hold remains active while the remaining code blockers and hardware evidence are still open.

Verification of 52166ad98c80 (Snapshot Attribution & Round Generation Fix)

Resolved: Blocker #1 (stale-front selection / snapshot attribution) is cleanly addressed with no new regressions introduced:

  • Already-retired compute entries: recover() now refreshes state.retired_total via self.advance(state)? before scanning the snapshot and excludes retired entries via f.ordinal > retired (drivers/gpu/drm/asahi/g14_v27_2.rs:988-1003). An already-completed innocent command sitting at state.inflight[0] is no longer blamed and retires normally in service_locked().
  • Render pair & stopped-tiler rules: Attribution::add() matches [TILER, FRAGMENT] completion stamps to Stopped::Render, blocks stopped_tiler(flags) (flags & 9 == 9) from attributing compute, and fails closed (ambiguous = true -> None -> Err(EIO) fail-stop) on empty (0 entries), unnamed, mixed, or dual-match snapshots (drivers/gpu/drm/asahi/g14_v27_2_abi.rs:106-138).
  • Per-round attribution & generation check: Every drain recovery round is now attributed and enforces new_round(previous, generation) (generation != p, failing with EPROTO on repeat; g14_v27_2.rs:981-986, g14_v27_2_abi.rs:142-147).
  • Locking & ordering: Runs exclusively under self.state mutex; recovery_phase(), halt_count(), progress(), and recovery_entry() each perform clean_invalidate_poc + poc_barrier() + Acquire loads while firmware is halted at phase 1 before answer_recovery(2) (Release + clean_poc + poc_barrier()).
  • Host tests: Re-ran rustc --test drivers/gpu/drm/asahi/g14_v27_2_abi.rs at 52166ad98c80 — 10/10 pass.

Remaining Open Blockers (Verified Unchanged at 52166ad98c80)

  1. Shared TPC clear UB / exclusivity (drivers/gpu/drm/asahi/buffer.rs:204-213): Scene::clear_tpc(&self, bytes) still fabricates an immutable &[u8] slice (self.object.tpc.as_slice()) and writes through tpc.as_ptr().cast_mut() via write_bytes on a shared Arc<GpuArray<u8>> exposed as a safe pub(crate) method.
  2. Guilty VM admission & pending-queue enforcement (drivers/gpu/drm/asahi/g14_v27_2.rs:578-590, 677-713, 881-890): submit() and pump() still do not reject VMs with non-zero VmStatus, fail_doomed() still only removes the single doomed packet from state.pending (leaving other queued packets from the same guilty VM to publish), and status.note_recovery_guilty() is still not called.
  3. Render timeout fallback strands state.rendering (drivers/gpu/drm/asahi/g14_v27_2.rs:865-870): Returning self.recover(state, ETIMEDOUT, -1) directly leaves state.rendering populated after recover() drains TA/FS, blocking pump() and leaving the doomed fence unsignaled until a later wakeup/scheduler timeout.
  4. Queue retirement without a separate quiescence witness on aborted commands (drivers/gpu/drm/asahi/g14_v27_2.rs:833-864, 881-890, 1178-1192 vs g16/recovery/logic.rs:51-53): Aborted commands still immediately drop RenderFlight/Inflight, release packet guards, and clear state.busy on retired-cursor advance alone without either an established G14 27.2 firmware/hardware quiescence guarantee or quarantine.

Additional Pre-existing Recovery Note (Worth Fixing Alongside the 4 Blockers)

  • Unconsumed EVENT_RING record after multi-round or fallback recovery (drivers/gpu/drm/asahi/g14_v27_2.rs:965-1068, 1146-1157): state.root.drain() (gpu/v27_2.rs:818-834) drains telemetry rings only, not EVENT_RING. If a further recovery round during drain (rounds >= 1), a fallback timeout recovery, or a racing fault+timeout pair leaves an already-answered Timeout/Fault record in EVENT_RING, the next service_locked() pass consumes it, calls recover(), waits PHASE1_WAIT_MS (50 ms) while firmware is already back at phase 0, and triggers fail_all(ETIMEDOUT) across healthy clients. (Also, the drain loop at g14_v27_2.rs:1043-1062 still does not fast-fail on unexpected phases != 0 && != 1 or state.peer.is_crashed().)

Checklist Status (§1–§6 at 52166ad98c80)

  • §1 No model gating: PASS — no chip, SoC, board, or firmware-version gates.
  • §2 Production-ready, no hacks: PASS — default kernel cmdline, no sleeps/retries over races, clean shared g16/recovery/logic.rs.
  • §3 Safety: OPEN — 4 code blockers above still open.
  • §4 Clean-room & attribution: PASS — both commits (8da4dbcce374, 52166ad98c80) carry human author/committer (Ryan Murray <[email protected]>), human Signed-off-by:, zero AI trailers in commit messages, and no force push.
  • §5 Hardware evidence: OPEN — exact-head J473 (27.2, without lab encoder-params edits) and J413 (13.5 regression tuple) runs are still required before merge.
  • §6 Naming & CI: Naming PASS (Borealis / Aurora conventions). 0 CI check runs / 0 commit statuses ran on 52166ad98c80 (stacked base m2gpu/g14-v27-2-render); locally verified g14_v27_2_abi.rs unit tests (10/10 pass).

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<u8> 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 <[email protected]>
@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. Everything is addressed at f55ae32 (two new commits on top; no force push):

  1. Attribution (52166ad): each snapshot target is the stopped command's completion stamp. It is matched against the render pair and the unretired compute stamps after the retired position is refreshed. Ambiguous or unmatched entries keep the fail-stop. Every round is attributed, and each further round needs a new generation. Host fixtures cover both cases you named. The drain loop now fails on a crashed coprocessor or on a phase the protocol does not allow; a new phase 1 starts the next round.
  2. TPC UB: Scene::clear_tpc is now an unsafe fn on the G14 27.2 scene only (no longer on Scene::ver). It zeroes through the new GpuArray<u8>::zero_prefix, a raw-pointer write with no &[u8], and both functions state the exclusivity precondition. The call site's SAFETY comment gives the reason: firmware in phase 1 with every queue stopped, no CPU reader, one render flight under the state lock.
  3. Guilty VM admission: blaming latches the VM (note_recovery_guilty + record) before the work drains. submit() refuses packets of a VM whose status is set, and pump() fails queued ones instead of publishing them (G16 enqueue parity).
  4. Render fallback: after recover() returns Ok, retire_render() runs again, so the flight is taken, its slots retired and its fence failed at once.
  5. DMA witness: there is no stronger G14 witness than queue progress, so the G16 Retirement::Aborted rule now applies. The doomed packet's guard is not released; finish(Err) quarantines it. The stopped flight (packet, VmBind, scene) is kept for the rest of the boot, as stop() does. Pool slots are still reused only after the firmware unregisters them (free_slots -> registered()).

Hardening notes: control-object reads and writes check their byte range before slicing or cache maintenance. Rounds start only within a 5 s budget, so the lock is held for at most about 7 s, inside the 10 s job timeout.

Full arm64 build at f55ae32 is OK with 0 warnings in the changed files. ABI host tests pass 10/10. A J473 row at this exact head is next (kit 7.3.0-aurora-m2h3). The J413 row and CI are still open.

@RyanTheTide
RyanTheTide changed the base branch from m2gpu/g14-v27-2-render to integration/aurora November 24, 2026 07:28
@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Independent source review of f55ae32f692706ff409508610b3a39e969f3f508. I re-ran the exact G14 ABI tests (10/10) and the shared recovery logic tests (9/9). The guilty-VM admission and render fallback changes address the reviewed paths.

One resource lifetime issue remains. quarantine() in g14_v27_2.rs forgets each stopped flight for the rest of the boot. That retains the packet, VM binding, residency, and the render scene where applicable. The recovery-storm check limits admissions per time window. It resets its count when the window rolls over, so it supplies no lifetime bound on the retained resources. Those flights also cannot be reclaimed by a later verified device stop once the references have been forgotten.

Please track retained resources under the runtime and bound their cumulative retention. If that limit is reached, use the existing fail-stop path while preserving the DMA guard until a proven quiescent state. Please keep #3041 separate from the fleet cut. The J473 and J413 hardware rows at this head remain separate.

Assisted-by: LLM (Codex)

@DjDeveloperr DjDeveloperr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Focused §1–§6 exact-head re-review at f55ae32f692706ff409508610b3a39e969f3f508 (now rebased/retargeted onto integration/aurora after #3031 merged; 3 human-signed commits, no force push).

Verdict: REQUEST_CHANGES

All 4 code blockers from the 52166ad98c80 review and the prior hardening notes are cleanly addressed, and the base branch is now integration/aurora. However, 3 concrete code issues remain in the recovery/quarantine path (including the unconsumed EVENT_RING note and two quarantine-tracking issues), alongside pending CI runs and exact-head §5 J473/J413 hardware evidence.


Cleared Since 52166ad98c80

  1. Scene::clear_tpc UB / exclusivity (object.rs:722-732, buffer.rs:305-308, g14_v27_2_render.rs:86-89, g14_v27_2.rs:1070-1080): Resolved. Moved off generic impl Scene::ver onto #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl SceneG14V13_5 as unsafe fn, zeroing directly through GpuArray<u8>::zero_prefix (self.raw pointer without fabricating &[u8]) with documented # Safety preconditions satisfied under self.state during firmware phase 1 halt. (Tiny non-blocking nit: duplicate summary doc line at g14_v27_2_render.rs:80-81.)
  2. Guilty VM admission & pending-queue enforcement (g14_v27_2.rs:415-426, 610, 712-716, 943, 955): Resolved. blame() calls latch_guilty() (status.note_recovery_guilty() + status.record(error)) before drain; submit() rejects failed VMs with Err(EIO); pump() fails already-queued packets from failed VMs via state.fail_publication(&packet, EIO) instead of publishing them.
  3. Render timeout fallback stranding state.rendering (g14_v27_2.rs:901-907): Resolved. retire_render() now re-invokes self.retire_render(state) immediately after self.recover(state, ETIMEDOUT, -1)? succeeds (bounded depth 1 since doomed is set), taking state.rendering, retiring slots, signaling the error fence, and unblocking pump().
  4. Aborted-command guard/flight quarantine (g14_v27_2.rs:431-433, 891-893, 925-933, 1247-1249): Primary retirement path resolved (fail_doomed() no longer calls packet.release_guard(); Packet::finish(Err(err)) quarantines the VmJobGuard and quarantine(flight) retains the flight/binding/scene; pool slots reuse only after CommandPool::registered(slot) reads 0), subject to the two quarantine-lifetime blockers below.
  5. Hardening notes: Resolved. RootV27_2::control_range() validates byte bounds and 4-byte alignment before slicing/cache maintenance (gpu/v27_2.rs:745-771), RECOVERY_BUDGET_MS (5 s) bounds lock hold time within the 10 s scheduler timeout (g14_v27_2.rs:81, 1018-1021), and the drain loop fast-fails on state.peer.is_crashed() or unexpected phases via recovery_logic::action() (g14_v27_2.rs:1110-1121).
  6. Base branch: Retargeted to integration/aurora.

Remaining Code Blockers (§3 Safety & Correctness)

  1. Runtime::withdraw() can release a quarantined VmJobGuard (drivers/gpu/drm/asahi/g14_v27_2.rs:621-634, m3_submit.rs:180-188):
    • quarantine(flight) removes the doomed flight from state.rendering / state.inflight and calls core::mem::forget(flight), so state.owns(packet) becomes false even though packet.vm_job still holds the quarantined VmJobGuard.
    • If a racing DRM scheduler Job::timed_out() subsequently sees !runtime.healthy() (e.g., on a later failure or during Runtime::stop() between self.healthy.store(false) at g14_v27_2.rs:1346 and guard.take() at line 1359) and calls runtime.withdraw(&job.packet), withdraw() sees !state.owns(packet) and calls packet.release_guard(), dropping the quarantined VmJobGuard and allowing drain_mappings() to unmap the quarantined VM's user pages.
  2. Unbounded core::mem::forget quarantine retention (aligning with #7125073939, drivers/gpu/drm/asahi/g14_v27_2.rs:431-433, 893, 1249):
    • Because recovery_logic::admit() resets its counter every 10 s window, slow faults can retain VmBind context slots, buffer slots, and scenes indefinitely via core::mem::forget(flight) with no cumulative cap.
    • Combined fix for #1 and #2: Track quarantined flights inside State up to a bounded cumulative cap (failing closed via fail_all() when exhausted while keeping guards quarantined), and include quarantined flights in state.owns(packet) (and/or guard Packet::release_guard() against releasing a quarantined guard).
  3. Unconsumed EVENT_RING record after multi-round (rounds >= 1) or fallback timeout recovery (drivers/gpu/drm/asahi/g14_v27_2.rs:905, 1010-1134, 1212-1223, 1266, gpu/v27_2.rs:827-844):
    • Still open at f55ae32f6927. state.root.drain() drains telemetry rings only, not EVENT_RING.
    • When a second recovery round occurs during drain (rounds >= 1) or when a fallback timeout recovery runs from retire_render() / compute timeout after process_events(), firmware's Timeout/Fault record for that already-answered recovery remains unread in EVENT_RING. On the next service_locked() wakeup, process_events() consumes that stale record and calls recover(), which waits PHASE1_WAIT_MS (50 ms) against phase 0 and triggers fail_all(ETIMEDOUT) across every innocent client.
    • Fix: Drain/consume stale Timeout/Fault records belonging to the handled recovery (without dropping Grow or ChannelError records) or verify recovery phase/generation before escalating a stale event record to fail_all(ETIMEDOUT).

Checklist Status (§1–§6 at f55ae32f6927)

  • §1 No model gating: PASS — no chip, SoC, board, or firmware-version gates.
  • §2 Production-ready, no hacks: PASS — default kernel cmdline, clean shared g16/recovery/logic.rs.
  • §3 Safety: OPEN — 3 code blockers above (withdraw() guard release on quarantined packet, bounded quarantine tracking in State, and unconsumed EVENT_RING record).
  • §4 Clean-room & attribution: PASS — all 3 commits (8da4dbcce374, 52166ad98c80, f55ae32f6927) carry human author/committer (Ryan Murray <[email protected]>), human Signed-off-by:, 0 AI commit trailers, no force pushes.
  • §5 Hardware evidence: OPEN — exact-head J473 (27.2, default cmdline, without lab encoder-params edits) and J413 (13.5 regression tuple: 0 SELinux denials, 0 failed units, 0 new kernel errors) runs are still pending.
  • §6 Naming & CI: Naming PASS (Borealis / Aurora conventions; zero forbidden naming in diff/PR body). Base is now integration/aurora, but 0 CI check runs / 0 commit statuses have executed on f55ae32f6927 yet. Locally verified rustc --test drivers/gpu/drm/asahi/g14_v27_2_abi.rs (10/10 pass) and rustc --test drivers/gpu/drm/asahi/g16/recovery/logic.rs (9/9 pass).

@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

J473 row at the exact head f55ae32 passes. Our own traces; default cmdline; GNOME on both monitors with a bystander glxgears; same repro as H4 but no lab changes.

  • Render: the firmware timed out piglit shader-mem-barrier's TA. Snapshot {0x1f, 0x2782400} was blamed by stamp, the TPC was cleared, recovery was answered in 2 ms and the work drained in 1 ms. The client's next submission was refused with EIO (the guilty-VM latch), so its queued computes never ran. H4 needed two more recoveries for them.
  • Compute: the firmware timed out GB6 Vulkan Background Blur. Snapshot {0x7, 0x5f700} was blamed as stopped compute 0x5f700 of geekbench_aarch, answered in 3 ms, drained in 1 ms.
  • gnome-shell kept the same PID. glxgears drew at 67-82 fps throughout. Fresh vkcube and vulkaninfo passed (rc=0) before, between and after. 0 Oops. Production was restored and verified.

A first attempt ran the runner's default three s2idle cycles on the lab Stage 2 and reset during the second, before the repro, so it gave no recovery result. That Stage 2 has no #2953 fix.

Still open: the J413 regression row, and CI on the integration base.

@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Proposal for the remaining retention finding at f55ae32f (cumulative quarantine is unbounded across storm windows; #3041 (comment)).

recovery_logic::admit() limits the rate (32 recoveries per 10 s), but quarantine() keeps every stopped flight for the rest of the boot. A slow trickle of stopped work, one every 11 s, never trips the storm limit. Each kept flight pins a VmBind, and with it one of the 63 user UAT contexts (mmu.rs UAT_USER_CTX), plus a scene and its buffer slots for render. Once enough of these leak, innocent clients can no longer bind, and that failure is a hang rather than a clean error.

Smallest bound I can see: a per-boot count of doomed flights, checked in blame() before anything is marked, so the check runs before answer_recovery(2). When the budget is spent, blame() returns Err(EIO) and recover() takes the existing fail-all path: the GPU goes unhealthy, published work stays owned and no guard is released. That is the same fail-closed state as before this PR. It needs no new teardown path and does not touch the DMA guards.

  • Count flights, not recoveries. One compute recovery dooms every queued command of the guilty packet. Count only flights whose doomed was None (compute uses get_or_insert, and a later round may name the same packet again).
  • Count at doom time, not in quarantine(). The budget then also covers doomed flights that have not drained yet, so the total kept stays within the limit.
  • Use a count, not bytes. The scarce resources are counted ones (UAT contexts, buffer-manager slots), and each flight's memory is already capped by its own allocation. A count bounds both without walking VmBind or scene sizes.
  • Tie the limit to the resource it protects. Use UAT_USER_CTX / 2 (31) behind a compile-time assert, so innocent clients always keep at least half of the contexts. This adds no new chip, board or firmware gate.
Sketch
// g14_v27_2_abi.rs (host-tested with the other ABI rules)
/// Stopped commands one boot may keep (`quarantine`): each pins a VM binding (a user UAT
/// context) and, for render, a scene. Half the user contexts, so innocent clients keep the rest.
pub(crate) const QUARANTINE_LIMIT: u32 = 31;

/// Whether `more` newly stopped commands still fit next to the `kept` ones.
pub(crate) const fn quarantine_fits(kept: u32, more: u32) -> bool {
    match kept.checked_add(more) { Some(total) => total <= QUARANTINE_LIMIT, None => false }
}

#[test]
fn quarantine_is_bounded_per_boot() {
    assert!(quarantine_fits(0, 1));
    assert!(quarantine_fits(QUARANTINE_LIMIT - 1, 1));
    assert!(!quarantine_fits(QUARANTINE_LIMIT, 1));
    assert!(!quarantine_fits(QUARANTINE_LIMIT - 1, 2));
    assert!(!quarantine_fits(u32::MAX, 1));
    assert!(quarantine_fits(QUARANTINE_LIMIT, 0)); // a re-named, already doomed packet
}
// g14_v27_2.rs
const _: () = assert!(g14_v27_2_abi::QUARANTINE_LIMIT as usize <= mmu::UAT_USER_CTX / 2);
// (mmu::UAT_USER_CTX becomes pub(crate))

struct State {
    // ...
    /// Commands doomed by a recovery this boot; each is kept until shutdown (`quarantine`).
    quarantined: u32,
}

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); };
            let more = u32::from(flight.doomed.is_none());
            if !g14_v27_2_abi::quarantine_fits(state.quarantined, more) {
                return self.quarantine_spent(state);
            }
            state.quarantined += more;
            flight.doomed = Some(error);
            // ... unchanged
        }
        Stopped::Compute(stamp) => {
            let Some(packet) = /* unchanged */ else { return Err(EIO); };
            let more = state.inflight.iter()
                .filter(|f| Arc::ptr_eq(&f.packet, &packet) && f.doomed.is_none())
                .count() as u32;
            if !g14_v27_2_abi::quarantine_fits(state.quarantined, more) {
                return self.quarantine_spent(state);
            }
            state.quarantined += more;
            // ... unchanged: mark doomed, latch_guilty, log
        }
    }
    Ok(())
}

/// Recovery would keep more stopped work than one boot may: fail all work instead (the
/// caller's fail-all path keeps published work owned, as before recovery existed).
fn quarantine_spent(&self, state: &State) -> Result {
    dev_err!(self.dev, "GPU: {} stopped commands kept this boot; not recovering more\n",
             state.quarantined);
    Err(EIO)
}

Hardware check: the existing H5 repro, run 32 times in one boot (spaced more than 10 s apart, so the storm limit never trips). The first 31 recover per client. The next one fails all work with the new message and 0 Oops, and the host stays up.

This does not address the separate withdraw() item from the 07:34 review (quarantined packets are not in state.owns()). That needs its own fix; the counter only adds a place to hang it.

Assisted-by: LLM (Claude:Opus 5.5 via Antigravity)

@github-actions github-actions Bot added area:gpu Area from CODEOWNERS (bot) changes-requested A reviewer requested changes (bot) door:two-way Revertible or not, from Merge risk (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) labels Nov 24, 2026
@github-actions

Copy link
Copy Markdown

Merge readiness at f55ae32f: not ready yet

Check Detail
CI at head ok no CI for this change (the hardware row is the gate)
Review no needs one approving review from Core or Omarchy Mac (not the author)
Requested changes no requested by DjDeveloperr
Hardware row at head ok in the PR body at f55ae32f
Conflicts ok none
PR text ok Risk: two-way · only Macs running the G14 firmware 27.2 runtime (J473 today). The handshake decisions are G16's existing g16/recovery/logic.rs, included by path; no g15/g16 file is changed.

Areas: area:gpu

Updated by pr-readiness on every push, edit and review, and every 30 minutes. Rules: merge policy · labels.

1 similar comment
@github-actions

Copy link
Copy Markdown

Merge readiness at f55ae32f: not ready yet

Check Detail
CI at head ok no CI for this change (the hardware row is the gate)
Review no needs one approving review from Core or Omarchy Mac (not the author)
Requested changes no requested by DjDeveloperr
Hardware row at head ok in the PR body at f55ae32f
Conflicts ok none
PR text ok Risk: two-way · only Macs running the G14 firmware 27.2 runtime (J473 today). The handshake decisions are G16's existing g16/recovery/logic.rs, included by path; no g15/g16 file is changed.

Areas: area:gpu

Updated by pr-readiness on every push, edit and review, and every 30 minutes. Rules: merge policy · labels.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Merge readiness at fa824cfa: not ready yet

Check Detail
CI at head no failing: pr-text / pr-text
Review ok approved by DjDeveloperr
Requested changes ok none
Hardware row at head ok in the PR body at fa824cfa
Conflicts ok none
PR text ok Risk: two-way · only Macs running the G14 firmware 27.2 runtime (J473 today). The handshake decisions are G16's existing g16/recovery/logic.rs, included by path; no g15/g16 file is changed. With no recovery round the behaviour is main's (fail all), now with a log line saying why.

Areas: area:gpu

Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels.

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Code review of head f55ae32f692706 (drivers/gpu/drm/asahi/g14_v27_2.rs) found two blocking bugs:

1. Unread Fault/Timeout records left in EVENT_RING brick the GPU on the next notification (Critical)

  • Locations: process_events() (:453-461), service_locked() (:469-475, 506-513), retire_render() (:211-217), recover() drain loop (:408-438).
  • Scenario:
    • recover() drains telemetry/log/trace rings via state.root.drain() (:419), which does not drain EVENT_RING.
    • If a second command faults/times out during recover()'s drain loop (round 2+ at :425), or if recovery was entered via the fallback recovery_phase() == 1 check in retire_render() (:215) or compute timeout (:508) before EVENT_RING was popped, the firmware's EventKind::Fault/Timeout record(s) stay unread in EVENT_RING.
    • After recover() succeeds and firmware returns to phase 0, the next service_locked() runs process_events(), pops the stale Fault/Timeout record, sets state.firmware_error, and re-enters recover().
    • wait_recovery() then waits 50 ms for recovery_phase() == 1, which never arrives because that halt was already recovered. recover() returns Err(ETIMEDOUT), and service_locked() calls self.fail_all(state, ETIMEDOUT) — permanently killing the GPU for the rest of the boot.
  • Suggested fix: Drain/discard stale Fault/Timeout records from EVENT_RING at the end of recover() once firmware has returned to phase 0 (and/or only trigger recover() when recovery_phase() == 1 or when halt_count has advanced past the last recovered halt).

2. Permanent quarantine() retention leaks UAT and buffer-manager slots into a permanent kernel self-deadlock (Critical)

  • Locations: quarantine() (:84-86, 202, 492) + blocking Uat::bind() (:693, 733) held under Runtime.state mutex (:557, 851).
  • Scenario:
    • Every quarantined Inflight/RenderFlight retains its VmBind (permanently consuming 1 of 63 user UAT context slots, or the single slot under asahi.robust_isolation=1) and, for renders, retains SceneG14V13_5 (permanently consuming 1 of 127 BufferInner.active_slot entries and keeping active_scenes >= 1).
    • A slow trickle of 1 faulty VM every 11 s bypasses the 32-per-10 s storm window. After 63 quarantined VMs (~11 min), all user UAT slots are permanently pinned.
    • The 64th healthy client calls Runtime::submit() -> acquires self.state.lock() -> calls blocking Uat::bind() -> sleeps forever in slots.get(). Because Runtime::service() also requires self.state.lock(), the entire GPU runtime self-deadlocks permanently.
  • Suggested fix: Combine non-blocking Uat::try_bind() under Runtime.state, a hard cap on total quarantined entries/slots (fail-stopping cleanly before UAT slot exhaustion), and releasing quarantined objects once a clean reset/halt proves firmware no longer references them.

@github-actions github-actions Bot added merge-conflict Conflicts with the base branch (bot) and removed merge-conflict Conflicts with the base branch (bot) labels Nov 24, 2026
@github-actions github-actions Bot added merge-conflict Conflicts with the base branch (bot) and removed merge-conflict Conflicts with the base branch (bot) labels Nov 25, 2026
Brings the G14 firmware 27.2 recovery up to main 255761f (the source of
the m2combo22 kit): pool slot double buffers with the publish-only flip
and cursor re-advance (#3182), compute sampler heaps (#3198), the pool
stall report and the deep-sleep warm restart.

Conflicts were additive: State keeps both the recovery fields and
hardware_unreachable/commit_stop, the ABI file keeps both the recovery
records and the Globals/compute/pool helpers with both test sets, and
run-host-tests.py runs both g14-v27-2-abi-tests.rs and pmp-alloc-tests.rs.
Stopped commands keep #3182's slot rule: their slot is retired the normal
way, and its next command goes to the slot's other buffer, so the stopped
command stays intact until the firmware unlinks the slot again.

Signed-off-by: Ryan Murray <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
… 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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
@RyanTheTide
RyanTheTide requested review from a team as code owners November 26, 2026 14:47
@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Both blockers from the 11-25 review are addressed at fa824cfa (main merged in with a merge commit, no force push):

  1. Stopped work stays owned: d39ba214 keeps every stopped packet in State::kept (reserved before anything is marked), and owns() counts it, so withdraw(), fail_all() and fail_publication() can no longer release its job guard; c49b2ded never drops a flight if keeping it fails. Host test a_withdrawn_stopped_packet_keeps_its_guard.
  2. Stale Fault/Timeout records: 5d3c9dc9 consumes a report whose round was already answered instead of failing all work. Host tests for a report read before, during and after its round.

Also from an independent review of the merge: the drain now waits only for the command the firmware stopped (2213f981), and the recovery history restarts after a deep-sleep warm restart (fa824cfa).

J473 rows at fa824cfa are in the description: deliberate compute hang x3 recovered per client (bystander, gnome-shell and fresh clients unaffected), GB6 Vulkan x8 8/8, compute 48/48. One limit, listed under Not yet: the compute.heavy stall that started this is a silent firmware stall (no event, phase 0), so it still fails all work.

@github-actions github-actions Bot added blast:all Macs affected, from Merge risk (bot) ci-failing A check failed at the PR head (bot) and removed merge-conflict Conflicts with the base branch (bot) labels Nov 26, 2026

@DjDeveloperr DjDeveloperr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: approve at fa824cfae022. Both blockers from my earlier review are fixed, so I'm dismissing it.

Blocker 1 (a stopped flight could lose its VM job guard): fixed in d39ba214 and c49b2ded.

  • blame() now calls reserve_kept() before it marks anything. The packet goes into State::kept, which is allocated with QUARANTINE_LIMIT places at start, so keeping it never allocates.
  • owns() counts kept packets, so withdraw(), fail_all() and fail_publication() can no longer release a stopped packet's guard.
  • fail_publication() checks guard_releasable(false, kept). The stopped flight itself goes to kept_compute/kept_renders. If that push can't allocate, the flight is leaked with mem::forget, so it is never dropped.
  • At the limit, reserve_kept() returns EIO and the caller fails all work, with published work still owned.
  • The host test a_withdrawn_stopped_packet_keeps_its_guard covers it.

Blocker 2 (unread Fault/Timeout records brick the GPU): fixed in 5d3c9dc9.

  • RecoveryLedger counts one report per process_events() pass and records each answered generation.
  • recover() starts from the last round already answered and returns Ok(false) when no round opens. A report whose round was already answered is then consumed with a warning instead of failing all work.
  • A missing later round inside a recovery is still EPROTO.
  • The command-timeout path retires the render only when a round actually happened.
  • Host tests cover a report read before, during and after its round.

Also checked

  • 2213f981: the drain now waits only for the stopped command.
  • fa824cfa: the ledger and window are reset across a warm restart.
  • Shared drm/asahi files: the only changes there are new helpers, Scene::clear_tpc in buffer.rs and the zero-prefix helper in object.rs. Only the G14 27.2 runtime calls them, so other generations don't change and no second-generation row is needed.
  • J473 rows at this head:
    • 3 deliberate compute hangs, each recovered per client, with the bystander, gnome-shell and fresh clients unaffected;
    • GB6 Vulkan 8/8 and compute 48/48;
    • s2idle followed by fresh Vulkan.
  • CI and commits: CI is green at this head, main was merged in with a merge commit (no force-push), and every commit is signed off.

Not blocking: as the PR body says, the silent compute.heavy stall (no event, phase 0) still fails all work.

Merging is left to the PR Merge Lane.

@DjDeveloperr
DjDeveloperr dismissed their stale review November 26, 2026 23:25

Superseded by the review at fa824cf

@github-actions github-actions Bot removed changes-requested A reviewer requested changes (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) labels Nov 26, 2026
@RyanTheTide
RyanTheTide merged commit 66fbacc into main Nov 27, 2026
21 of 23 checks passed
@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Correction to the Evidence and Not yet sections: the trigger is not a fresh shader compile.

  • The cold cache only changed timing. The same cold payload has since passed (12/12) and stalled on other boots, and s2idle before the run turned out to be a timing effect too.
  • The stall comes 15-21 identical heavy dispatches into the burst, not on the first job.
  • A log-only state dump (lab build, not part of this PR) at the silent hang shows the firmware had just raised the GPU to its top performance state (operating point 3 -> 8).
  • With the published ceiling capped at state 5 (lab build only), the exact condition that stalled 6/6 rows uncapped passed 24/24 runs on 2 boots.

So it is the clock-raise class from #3075, still open for a max-ALU ramp after #3162. Not yet item 1 is unchanged in effect: the stall posts no recovery round, so this PR still cannot contain it per client. The fix belongs in the 27.2 power/perf init and is tracked outside this PR.

@RyanTheTide
RyanTheTide deleted the m2gpu/g14-v27-2-recovery branch November 27, 2026 13:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:gpu Area from CODEOWNERS (bot) blast:all Macs affected, from Merge risk (bot) ci-failing A check failed at the PR head (bot) door:two-way Revertible or not, from Merge risk (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants