Skip to content

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

Open
RyanTheTide wants to merge 3 commits into
mainfrom
m2gpu/g14-v27-2-recovery
Open

RyanTheTide wants to merge 3 commits into
mainfrom
m2gpu/g14-v27-2-recovery

Conversation

@RyanTheTide

@RyanTheTide RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown

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. The 27.2 runtime ignored both events. One stuck client therefore stalled the GPU until the host timeout failed every client, taking gnome-shell down with it. This change answers the handshake and fails only the client that owns the stopped command.

Tested: J473 (M2 mini, firmware 27.2) at f55ae32f (row H5), default cmdline, GNOME on both monitors with a bystander glxgears:

  • A render hang (piglit) and a compute hang (Geekbench 6 Background Blur) were each recovered in 2-3 ms and blamed by stamp.
  • Only those two clients lost their device; the guilty client's next submission was refused.
  • gnome-shell kept its PID, glxgears drew throughout, and fresh vkcube and vulkaninfo returned 0 before, between and after.
  • No Oops; production was restored and verified.

The host tests pass 10/10.

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.

Not yet:

Details
  • Attribution: each snapshot target is the stopped command's completion stamp. It is 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 recovery round is attributed, and each further round needs a new generation.
  • Aborted work follows the G16 Retirement::Aborted rule: its VM job guard stays quarantined, and its flight (packet, binding, scene) is kept for the rest of the boot. Pool slots are reused only after the firmware unregisters them.
  • Guilty VM: blaming latches its VmStatus (guilty + error). submit() refuses it, and pump() fails its queued packets.
  • TPC clear: for a stopped tiler, the TPC is cleared through a raw-pointer GpuArray<u8>::zero_prefix (unsafe, precondition stated) before the host answers 2.
  • Bounds: rounds start within a 5 s budget, so the state lock is held for at most about 7 s; the drain checks for a crashed coprocessor and for illegal phases; control reads and writes check their range.
  • Review: MERGETRAIN6 (attribution) and Dj (5 blockers + hardening) are addressed in 52166ad9 and f55ae32f.
Evidence

Our own traces, traces/gpu/20261124-m2gpu-hang/:

  • H1: event 4 + halt found.
  • H2: the 13.5-style halted/resume answer is never consumed.
  • H3/H4: the phase protocol recovers render and compute.
  • H5 (20261124-190100-j473-h5): exact head, as above.

… 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 <ryan@aurorasilicon.org>
@RyanTheTide

Copy link
Copy Markdown
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

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 <ryan@aurorasilicon.org>), 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.

Assisted-by: LLM (Gemini 4 Neon)

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 <ryan@aurorasilicon.org>
@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
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
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

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 <ryan@aurorasilicon.org>), 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).

Assisted-by: LLM (Gemini 4 Neon)

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 <ryan@aurorasilicon.org>
@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
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
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

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 <ryan@aurorasilicon.org>), 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).

Assisted-by: LLM (Gemini 4 Neon)

@RyanTheTide

RyanTheTide commented Nov 24, 2026 •

Copy link
Copy Markdown
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
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 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 no merge conflicts with main: merge it in (no force push)
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.

@RyanTheTide

Copy link
Copy Markdown
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 the merge-conflict Conflicts with the base branch (bot) label Nov 24, 2026
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) changes-requested A reviewer requested changes (bot) door:two-way Revertible or not, from Merge risk (bot) merge-conflict Conflicts with the base branch (bot) needs-review No approving review from Core or Omarchy Mac yet (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants