Skip to content

drm/asahi: g16: recovery timeout side attribution and fault_scan/fwlog diagnostics - #3046

Merged
DjDeveloperr merged 10 commits into
mainfrom
djdev/g16-recovery-diag
Nov 25, 2026
Merged

DjDeveloperr merged 10 commits into
mainfrom
djdev/g16-recovery-diag

Conversation

@DjDeveloperr

@DjDeveloperr DjDeveloperr commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What: G16 (M4) recovery diagnostics, stacked on #3043: a recovery timeout now says which side stalled (firmware never halted, or phase 3 never came), and recovery logs the fault-bank records and the last firmware log entries.
Tested: M4 Mac mini (J773g, G16G B0, 26B123) with the full stacked series on an earlier build, not this head: gpubench 440/440, 0 faults, 0 recoveries. Host tests pass.
Risk: two-way · M4 (J773g, J713); logging only, plus the fault-bank scan while firmware is halted for recovery
Not yet: a row at the current head; CI, which runs once the base lands and this PR targets main.

Details (original description)

Summary

Improves crash and recovery diagnostics on Apple M4 (G16G) when firmware enters recovery without an attributed stage or when recovery exceeds its timeout:

  • Recovery timeout stall classification: tracks the last recovery phase observed by the host and classifies timeout stalls (recovery::logic::Stall), printing observed vs. newest published TA/FS stamps and retained flight count while keeping the existing log prefix intact.
  • Full fault-bank decode & firmware log payload dump during recovery: extends Regs::fault_scan() to snapshot and decode all eight fault banks through log_fault() with busy/ASID flight and live-VM attribution (logging explicitly when all banks read zero), and keeps LOG_DATA attached to Channels so up to the last 32 drained firmware log payload entries are printed during recovery without altering normal non-recovery draining.

Verification

  • scripts/checkpatch.pl --strict: 0 errors, 0 warnings, 0 checks across both commits.
  • Live Apple M4 (G16G B0, 26B123) silicon:
    • Directly exercised during live fault triage (decoded unmapped L3 write fault banks with busy/ASID/flight attribution that isolated the concurrent SCS compute bug).
    • Full gpubench suite: 440/440 PASS across 4.00M GPU jobs (0 faults, 0 recoveries, 0 kernel log errors).
    • Deep Sleep S2R: suspend 177.7 ms, resume 346.5 ms, firmware back in 644 µs, 0 errors.

…and hot paths

Kernel VMAP_STACK (32 KiB with 16 KiB pages) overflowed in
g16::Firmware::start_backend (22,688 B frame) during probe.

Keep large G16 boot, backend, scrub, and command-validation structures
off the kernel stack:

- Allocate ComputeOwners, RenderOwners, Pools, ScrubQueue, GpuAdt,
  Admitted, Booted, Stats, Prof, Scratch, Firmware, and SpanProof in-
  place on the heap (KBox::init / KBox::try_init / KBox::zeroed /
  write_init).

- Retain failed Booted/Firmware sessions directly as KBox variants
  instead of unpacking Firmware back onto the stack with
  KBox::into_inner.

- Bound stack-resident ScrubBatch to 8 displaced slots per pass and
  drain ScrubQueue entries one-by-one in join_workers.

- Reuse heap-resident ValidateScratch inside SpanProof for
  Prepared::validate and SpanBatch::flush_with_proof.

- Mark probe/boot/engine phase boundaries #[inline(never)] so unrelated
  large frames do not merge.

Signed-off-by: Diljit Singh <[email protected]>
…iers

Cross-queue Vulkan binary and timeline semaphore waits on the same G16
device and VM previously fell through to drm_sched, forcing the producer
job to retire on the CPU and wake the scheduler worker before the
consumer could enter the engine.

Tag G16 queue output fences with their originating GPU, VM, queue, and
per-engine ordinals (FenceOrigin), and mark the origin enqueued once
Firmware::enqueue accepts the job. On submission, walk the input fence
tree via g17::sync_input::collect and, when every unsignalled leaf is an
already-enqueued same-GPU same-VM G16 fence (bounded to 8 waits), convert
them into job.fw_waits so try_start_inline hands the consumer straight to
the firmware engine.

Extend dependency checking, timestamp-query serialization, compute and
render stamp resolution, single-pipe compute selection, and transitive
failure doom propagation in poll.rs to cover job.fw_waits, while keeping
horizon folding disabled when cross-queue waits are present.

Signed-off-by: Diljit Singh <[email protected]>
Timeline semaphores on G16 attach each submitted JobFence into a
dma_fence_chain across participating queues. Previously, two issues
forced alternating cross-queue timeline ping-pongs permanently onto
drm_sched after the first few hops:

1. asahi_g17_collect_fences() emitted every leaf in the chain without
   skipping signalled leaves or coalescing same-context leaves, hitting
   -ENOSPC once chain depth grew past the buffer capacity.
2. FwWaits::push_unique() deduplicated only identical FenceOrigin
   allocations instead of coalescing per logical queue, overflowing
   MAX_FW_WAITS (8) by hop 9 and cascading every subsequent hop onto
   drm_sched because the bounced producer stayed !is_enqueued().

Add asahi_g17_collect_fences_coalesced() (skipping already-signalled
non-error leaves and keeping only the latest unsignalled leaf per
dma_fence context while preserving every status < 0 error leaf), record
cumulative accepted render/compute ordinals in FenceOrigin::last_ordinal
so coalescing to a queue's newest fence retains earlier unretired work
on both engines, coalesce FwWaits per logical queue, and check that a
cross-queue render wait is still unretired before clearing fragment
barriers.

Add host unit tests covering 256-hop 2-queue timeline chain coalescing,
error leaf preservation, and per-queue FwWaits ordinal merging.

Signed-off-by: Diljit Singh <[email protected]>
When multiple processes interleave compute submissions on G16, pure
round-robin compute-unit claiming rotates each VM onto another VM's
recently retired unit, forcing a full WC scrub, 160-byte WC descriptor
read-back, and 8 KiB full work write on every dispatch.

Update Slots::claim_compute_for_pipe() to prefer a displaced warm unit
already owned by the requesting VM (!scrub_full), then an unowned unit,
before falling back to round-robin over the pipe's eligible range. This
keeps concurrent multi-VM compute workloads on their own warm units
while preserving base-unit pipe-0 isolation and quarantine fallback.

Signed-off-by: Diljit Singh <[email protected]>
…ots VM-affine

Multi-process render workloads with d=4, 8, or 16 concurrent VMs
thrashed the two shared base PB/UMA allocator slots, forcing full
engine drains and InitBM epoch reinitializations on every cross-VM
handoff as well as cross-VM full pass-slot scrubs.

Expand the device-wide warm PB/UMA allocator pool to 16 slots
(WARM_PB_SLOTS = 16, hardware UMA slots 33..48) plus 4 lazy quarantine
spares (EXT_PB_SLOTS = 4, hardware UMA slots 49..52) while keeping every
VM's client VA footprint unchanged at 2 base units (local indices 0..2,
assigned rotating [home, alt] pairs) and up to 4 lazy recovery spares
(local indices 2..6). Add mask-based Pools selection that prefers a VM's
unused home slot so 16 concurrent VMs bind 16 disjoint warm slots
regardless of arrival order and pipeline with zero InitBM after warmup.

Add VM-affine render pass selection (Slots::pick_pass_in_for) and scale
bursting VMs to Tier 1 pass headroom (18 slots) when
active_render_vms >= 8 while keeping PB_HEAP_EXT_TIERS gated on
single-VM pass demand so concurrent light renders do not expand to
256 MiB PB heaps. Also trim PbEpoch::prepare WC list seeding to the
active heap_blocks prefix (plus any shrink tail on unpublished retries).

Verified with asahi-m4 (25/25) and asahi-g15 (81/81) host selftests and
checkpatch.pl (0 errors, 0 warnings).

Signed-off-by: Diljit Singh <[email protected]>
…mware PB/UMA records

After a DRM client closes, Gpu::vm_closed() drops its registry and cache
references, but device-wide slot tables (Pools::owners/owner_vms and
owner_arenas across PB_SLOTS, Slots::render across 48 pass slots, and
Slots::compute across 24 compute units) continued holding strong
Arc<VmState> and arena leases indefinitely until later traffic overwrote
every slot. Under multi-process render and compute workloads, dead VMs
stayed pinned after exit (multi-GiB Unevictable/Shmem and live TTBAT
ASIDs), starving subsequent allocations with VK_ERROR_OUT_OF_DEVICE_MEMORY.

At the same time, 26B123 RTKit firmware stores per-slot context-0
pointers in pb_mgr_table[0..15] and uma_mgr_table[1..48] that persist
across subsequent work on other slots and are walked during GPU timeout
recovery, so dropping the tiny firmware-owned metadata records before
that exact hardware slot is overwritten would leave dangling firmware
table pointers across timeout recovery.

Reclaim displaced closed-VM leases cleanly without violating hardware
displacement or firmware recovery contracts:
- Add Lifetime::is_quarantined() so quarantined slots stay pinned forever
  without keeping reclaim armed.
- Split the tiny firmware-owned metadata records (PbEpoch's pb_manager +
  counter, render Allocator's UMA descriptor + submitted, and
  ComputeSlot's kernel-lower work + counter) into VM-free FwLease objects
  allocated via Factory::fw_objects() without a Vm reference, and retain
  one FwLease per hardware slot in Pools and Slots until a later retired
  publication overwrites that exact hardware slot index.
- Add Pools::reclaim_closed() and Slots::reclaim_closed() to drop owners,
  owner VMs, and owner arenas (Deferred-backed, safe under Shared::state)
  only for displaced, idle, non-pending, non-scrubbing, non-quarantined
  slots whose VM is closed via lock-free Vm::is_closed().
- Skip closed VMs in Slots::stage_displaced_pass_scrubs(), and arm
  ScrubState::waiter if a closed VM's displaced pass slot is mid-scrub.
- Gate scanning behind Shared::closed_vm_reclaim (read-only Acquire load
  on the hot path), set in Gpu::vm_closed() and checked in idle/active
  poll_step(), submit_locked(), and run_housekeeping().
- Add host selftest coverage in test-resources.py and test-poll-retire.py.

Signed-off-by: Diljit Singh <[email protected]>
With two independent CDM pipes (COMPUTE_PIPES = 2), multi-process
compute leaves one undisplaced last-retired compute unit on pipe 0 and
one on pipe 1 (22 of 24 units reusable). Because firmware may still
reference each pipe's last-retired unit until a later retired
publication on that same pipe displaces it, those two owner leases must
remain pinned.

Previously, Ready::compute_ext backed all 22 extension compute units
(2..24) inside a single monolithic Arc<ComputeArena> (~713 MiB). Holding
a lease on one undisplaced extension unit pinned all 22 units of its
closed VM; across two CDM pipes that retained ~1.40 GiB (+1,464 MiB
Unevictable) instead of 2 x ~32.4 MiB (~65 MiB).

Split compute unit backing so each ComputeArena owns a single
self-contained ComputeSlot and introduce ComputeUnitSet (a KVec of
per-unit Arc<ComputeArena>) for Ready::{compute, compute_ext} and
Prepared::{compute, compute_ext}:
- Prepared::compute_arena(k) returns only unit k's Arc<ComputeArena>,
  keeping zero-alloc Cache::prepare() cloning intact.
- When a VM closes, Cache::close() and Slots::reclaim_closed() drop
  every unused or displaced unit immediately while each pipe's
  undisplaced (or quarantined) slot pins only its own ~32.4 MiB unit
  (~22x reduction).
- Add dual-pipe per-unit closed-VM reclamation coverage in
  test-resources.py.

Signed-off-by: Diljit Singh <[email protected]>
Commit c12278d5c9aa ("drm/asahi/g16: reclaim displaced closed-VM slot
leases and retain firmware PB/UMA records") lets Pools::reclaim_closed()
drop the owner epoch of a closed VM's PB slot as soon as a render
retires on any other slot while keeping the manager record mapped. That
epoch maps the page list of its manager in the VM's DYNAMIC client
window and its block list, and it holds the VM's TTBAT slot.

Because the firmware keeps pb_mgr_table[k] naming the manager across
work on other slots, dropping the epoch releases the page and block
lists and the VM's ASID while the firmware can still reference that
manager.

A light render workload run repeatedly with sixteen concurrent client
processes faulted with no compute or ray-query work active:

  fault bank 1: status 0x8b81ddc021 va 0x704000cb40
    (write unmapped level 0 unit 0xe0 ctx 46)
  attribution: busy=0 ctx=46 flight_matches=1 live_vm=Some(110)
    event=0xffffffff flights=1

Unit 0xe0 is gPM_SP(0), the parameter manager. Only PB page lists are
placed in the DYNAMIC window: 0x704000cb40 is entry 720 of a VM's second
page list. No TA, FS or compute slot was running for ctx 46, so the
firmware attributed the fault to no stage. The parameter manager wrote a
PB page list that ctx 46 did not map. Reclaim releases exactly such a
list, together with the VM context, while pb_mgr_table[k] still names
its manager.

Keep the owner epoch until a newer epoch retires on the same slot, as
before reclaim existed; retire_flight() already replaces it then.
Reclaim still releases the closed VM's render arena, PB heap and the
slot's VM references. A closed VM then keeps only its two 32 KiB lists,
its records and its context until its slot is reused, and each PB slot
pins at most one such VM. A slot holding nothing but that epoch no
longer keeps reclaim armed.

Add a host regression test for this sequence and update the two reclaim
tests, which expected the epoch and the VM's TTBAT slot to be released
at reclaim.

Fixes: c12278d5c9aa ("drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records")
Signed-off-by: Diljit Singh <[email protected]>
When a firmware recovery does not finish within its 1000 ms budget,
recover() only logs "M4 GPU recovery exceeded 1000 ms" and fail-stops.
On a live M4 recovery timeout after a type-4 event and its statistics
record, the log could not tell whether the firmware never halted in
phase 1 or the host acknowledged phase 1 and phase 3 never came. It also
could not tell whether tiling or fragment work was left behind; the
stats showed seven render owners still published.

Keep the last phase the host read and name the stall from it and from
whether the host had answered (recovery::logic::Stall). Also print the
observed TA and FS stamps next to the newest published ones, and the
number of flights retained. The message keeps its prefix, so existing
log matching still works.

Signed-off-by: Diljit Singh <[email protected]>
…ing recovery

When firmware announces a recovery with no attributed stage
([4, gen, 0, ffffffff]), recover() already runs fault_scan() while the
firmware is halted in phase 1, but discards the fault status, VA, bank
and unit without calling the existing log_fault() decoder, and silently
drains the nine firmware log rings without printing their payload lines.

Extend Regs::fault_scan() to snapshot all eight fault banks (restoring
the saved selector), decode every non-zero bank through log_fault() with
busy/ASID flight and live-VM attribution, and explicitly log when all
eight banks read zero.

Keep LOG_DATA attached to Channels and, whenever recovery is pending or
running, print up to the last 32 drained firmware log payload entries
before advancing the consumer (leaving the normal non-recovery drain
path untouched).

Signed-off-by: Diljit Singh <[email protected]>
@DjDeveloperr
DjDeveloperr force-pushed the djdev/g16-recovery-diag branch from 9e45cfb to a1450a2 Compare November 24, 2026 07:34
@github-actions github-actions Bot added area:gpu Area from CODEOWNERS (bot) needs-hw-row No hardware row at the PR head (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) needs-template PR body lacks Tested or Risk (bot) blast:m4 Macs affected, from Merge risk (bot) door:two-way Revertible or not, from Merge risk (bot) and removed needs-template PR body lacks Tested or Risk (bot) labels Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Merge readiness at a1450a23: 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 ok none
Hardware row at head no no line with the head SHA a1450a23, a Mac and a result in the PR body or a comment
Conflicts ok not computed yet
PR text ok Risk: two-way · M4 (J773g, J713); logging only, plus the fault-bank scan while firmware is halted for recovery

Areas: area:gpu

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

@DjDeveloperr

Copy link
Copy Markdown
Contributor Author

Verdict at a1450a23e6: FINISH, then merge. No code blockers; one row is missing.

Blockers:

  1. No hardware row at this head. The rows in this PR ran the full stack on an earlier build, not this branch as it is now. Fix: one J773g run at this head, or on a candidate that contains this head unchanged (see below).

Checked: this PR's own 2 commits against its base; the fault-bank scan stays in the path where firmware is halted for recovery, and the log drain prints only while a recovery is pending or running; no Apple material in code or commit messages; no chip or board gates; no new parameters; only bounded waits; commits carry human authors and Signed-off-by, no AI attribution; CI does not run on a stacked base and will run once this PR targets main. This branch still carries the cross-VM compute overlap from #3042, so it should merge only in the same train as #3087. I reformatted the PR body to What / Tested / Risk / Not yet, with the original kept folded and its attribution line removed.

Row

One J773g run on a candidate that contains the heads of #3087, #3057 and #3046 unchanged (boot, idle/wake, deep sleep, vk-mustpass-short, gpubench vk-full, compute.long, 0 GPU faults) counts for every non-draft PR in this stack at once.

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:m4 Macs affected, from Merge risk (bot) door:two-way Revertible or not, from Merge risk (bot) needs-hw-row No hardware row at the PR head (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.

1 participant