Skip to content

drm/asahi: g16: performance and scheduling foundation (waves 8-14) - #3042

Merged
DjDeveloperr merged 30 commits into
mainfrom
djdev/g16-perf-wave8-14
Nov 25, 2026
Merged

DjDeveloperr merged 30 commits into
mainfrom
djdev/g16-perf-wave8-14

Conversation

@DjDeveloperr

@DjDeveloperr DjDeveloperr commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What: G16 (M4) performance and scheduling foundation (waves 8 to 14), stacked on #2852: O(claims) slot accounting, CPU boost and GPU ramp for host refill, in-place compute descriptor reuse, RENDER_FEW_PRIMITIVES, CUMULATIVE_SIGNALS, cached queue graph records, TA wave pacing, cross-VM render pipelining, cross-VM compute overlap, two-pipe CDM compute, lock-free Vm::is_closed(), TVB spill avoidance, and a longer -ENODATA hold in the PMP thermal path (below the passive trip).
Tested: M4 Mac mini (J773g, G16G B0, 26B123) with the full stacked series on an earlier build, not this head: gpubench 440/440 over 4.00M GPU jobs with 0 faults and 0 recoveries, 4,670/4,670 supported CTS cases, deep sleep. Host tests pass.
Risk: two-way · M4, plus every Mac for the shared file.rs, mmu.rs and mmu/lifetime.rs changes
Not yet: known problem: compute of one VM may run beside another VM's compute here, which loses results with several clients (measured and fixed in #3087), so this PR must land together with that fix. Also: a row at the current head; a non-M4 row for the shared mmu/file changes; J713 sustained GPU load with die temperature logged for the thermal hold change; CI, which runs once the base lands and this PR targets main.

Details (original description)

Summary

Stacks onto #2852 (djdev/g16-perf-wave7) to bring the G16 native Apple M4 driver performance, multi-pipe compute, cross-VM pipelining, and stability foundation that the subsequent split-arena (wave15), ray-tracing/SCS, recovery diagnostics, and adaptive-scheduling (wave16) PRs build upon:

  • O(claims) slot & VM accounting and fast submit path: O(claims) slot VM/arena holding and mask scans; host-refill CPU boost and active-burst GPU frequency ramp; in-place clean same-VM compute WC descriptor reuse; unbound completion poll workqueue routing for pipelined d>=2 flights; deferred housekeeping off SUBMIT with adaptive repoll and unbound cluster pinning; VM-epoch span proof caching and unified CDM validation lock; lock-free Vm::is_closed() via AtomicBool.
  • Render & UAPI features: VDM root barrier USC cache invalidate admission; DRM_ASAHI_RENDER_FEW_PRIMITIVES support; DRM_ASAHI_FEATURE_CUMULATIVE_SIGNALS support; slimmed pass_scrub and selective clean render scene writes; cached firmware-owned queue graph records without WC qinfo reads; TA wave pacing (TA_WAVE_PASSES = 4, TA_WAVE_REFILL = 2, immediate doorbells, render.threshold[0] advancement, and ta_wave_wait wakeup handling); cross-job same-queue render horizon folding; TVB partial-render spill avoidance on heavy scenes.
  • Cross-VM overlap & dual-pipe CDM compute: Cross-VM compute overlap with recovery proof; per-slot render UMA descriptors and multi-active Pools; warm cross-VM render pipelining without hold[0] drains; tightened completion wakeup and housekeeping cadence; pre-gfx compute overlap; barrier-free 2-pipe CDM compute overlap (pipes 0 and 1 on events 0x74/0x75) with per-pipe lifetime tracking and out-of-order retirement.
  • Thermal stability: Hold brief -ENODATA glitches below passive trip in thermal: apple-pmp.

Testing

  • Host selftests (tools/testing/selftests/drivers/gpu/asahi-m4/): test-poll-retire.py, test-stamp-wrap.py, test-publication.py, test-resources.py, and test-abi-26b123.py all PASS.
  • Live Apple M4 (G16G B0, firmware 26B123) end-to-end validation with the full stacked series:
    • gpubench Grand Slam: 440/440 PASS across 4.00M GPU jobs (0 faults, 0 recoveries, 0 bad CRCs, 0 kernel errors), including vk-rt 98/98 (1.127×), vk-full 202/202 (1.094×), gl-native 70/70 (1.100×), gl-zink 70/70 (1.078×), 5/5 compute.long (15,467,486 ray checks, 0 wrong rays), 3/3 render.light procs d=16 (0 faults), and Deep Sleep S2R (suspend 177.7 ms, resume 346.5 ms, gpu_fw_back 644 µs, 0 errors).
    • Live CTS: 4,670/4,670 supported PASS (0 failures, 0 faults, 0 recoveries, 22,104 GPU jobs).

DjDeveloperr and others added 28 commits November 24, 2026 02:19
Previously prefix_render() unconditionally emitted a same-ring
FS(N-1)->FS(N) barrier (fs_dep) on every pipelined early render pass,
even when vdm_barrier was NONE or the render dependency had already
retired or been satisfied by TA.

Resolve the exact in-flight render wait stamp (fs_wait_render) in
prefix_render() and plan_render_barriers():
- Keep the TA(N-1)->TA(N) prev_barrier (matching G15) whenever a prior
  render is in flight and plan.ta_fs_wait does not already serialize TA
  behind prev_fs (which dominates prev_ta via own_barrier): consecutive
  pipelined renders share one parameter-buffer / UMA epoch
  (RENDER_UMA_SLOT), so TA(N) must still wait on TA(N-1) before writing
  into the shared PB.
- Emit cross-ring FS->TA (ta_fs_barrier) only when plan.ta_fs_wait
  names an in-flight FS stamp (legacy dependent renders, conservative
  early_tiling=false, or staged TA waits).
- Emit FS->FS (fs_dep) only when plan.fs_render_wait names an
  in-flight FS dependency not already dominated by plan.ta_fs_wait.
- Pre-check wait_stamp_for_with() for o2.wait_through[RENDER] in the
  multi-pass render batch fold loop so prefix_render() never defers
  after claiming a pass slot.

Independent multi-pass renders drop fs_dep (from 3 hardware barrier
records / 5 ring entries per pass to 2 barrier records / 4 ring entries)
while preserving TA->TA serialization on the shared PB epoch, exact
FS->FS coherence on dependent passes, and cross-VM / InitBM boundaries.

Expand test-publication.py to cover independent multi-pass renders,
dependent FRAGMENT_BARRIERS/STAGE_PREFIXES renders (including
TA-dominated waits and older-FS waits), legacy renders,
early_tiling=false, and cross-VM/InitBM boundaries.

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

Deep multi-pass render benchmarks (such as 11-pass render.postfx at
depth 3, 7-pass compress.bw array at depth 5, and 4-pass render.shadow
at depth 8) saturated the 32-slot pass cap (31 active + 1 displacement)
and stalled between passes waiting for the 100 us resnap timer to free
retired pass slots.

- Raise hw::sizes::RENDER_SLOTS from 32 to 48 (47 in-flight passes + 1
  displacement slot) and widen pass_busy/pass_mask/clean_mask/scrubbing
  in g16/slots.rs from u32 to u64. Both TA and FS work rings hold
  QUEUE_CAP = 256 entries (255 usable); at worst-case 4 ring entries per
  pipelined pass (MAX_RENDER_RING_ENTRIES = 4), 47 in-flight passes
  consume at most 188 entries (67 spare), bounded by compile-time
  assertion in hw.rs and clamped in params::render_flights() to
  (QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES (63), well within
  AHEAD_RECORDS = 128, RING_SLOTS = 256, FLIGHTS = 32, and firmware
  recovery snapshot_entries = 448.
- Split EXT_RENDER_TIERS in g16/resources.rs into four demand-grown
  tiers so 20-31 pass workloads do not pay for 48 slots upfront (per
  base slot = 25,184 KiB / 24.59 MiB; per ext slot = 3,680 KiB /
  3.59 MiB):
  - Base   (0..2,   2 slots):  50,368 KiB (49.19 MiB), ext       0 KiB
  - Tier 0 (2..8,  +6 ext):   +22,080 KiB (+21.56 MiB), ext  21.56 MiB
  - Tier 1 (8..18, +10 ext):  +36,800 KiB (+35.94 MiB), ext  57.50 MiB
  - Tier 2 (18..32, +14 ext): +51,520 KiB (+50.31 MiB), ext 107.81 MiB
  - Tier 3 (32..48, +16 ext): +58,880 KiB (+57.50 MiB), ext 165.31 MiB
- Add Engine::slot_wait and Firmware::blocked_on_slot_headroom() so
  poll_step() arms short_repoll (repoll_us) when pending work is
  specifically blocked on same-VM flight, pass/compute slot, or
  work-ring headroom, without arming short_repoll for cross-VM drains,
  InitBM/PB-unprimed waits, external sync fences, or CPU timestamp
  waits.

Update host selftests in test-resources.py, test-publication.py, and
test-poll-retire.py to verify 48 pass slots, all four demand-grown tier
boundaries and exact byte footprints, blocked_on_slot_headroom()
filtering, and slot_wait-gated short_repoll behavior.

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

Wrap per-queue fdinfo engine accounting in crate::usage::Lane while
keeping real per-stage firmware TA/FS/CDM timestamps, preventing
pipelined double-counting and vertex==fragment skew.

Add an rmb() between stage/queue gate checks and receipt reads in
retired_snapshot_at(), and require two consecutive unsettled polls
spanning ABORT_GRACE_NS from the first gate-passed poll before aborting
a recovery_suspect flight so innocent flights finishing > 20 ms after
recovery cannot falsely abort.

Raise the firmware DM2 (compute) progress-watchdog thresholds (~4 ms
per tick) in GLOBALS_FIXED: secondary DM2 soft-preempt watchdog 0x9c8
(26B123 0x9cc) from 40 (~0.16 s) to 750 (~3.0 s) and primary DM2
recovery watchdog 0x9cc (26B123 0x9d0) from 50 (~0.20 s) to 800
(~3.2 s) so legitimate long/contended compute dispatches (such as 1.5 s
solo workloads) complete without premature firmware recovery while real
hangs still recover strictly below the 5 s host fail-stop deadline.

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

With sibling kernel queues sharing one DRM file (such as Borealis's
per-VkQueue sibling queues across multiple flights or dual CDM pipes),
usage::Lane only deduplicated intervals per queue, allowing concurrent
sibling queues on the same DRM file to exceed 100% of wall time in
drm-engine-*.

Add Client::add_union() backed by a per-engine atomic watermark on
usage::Client (sharing union_mark() with Lane::add() and preserving
existing Client::add() and Lane::add() semantics for other backends).
Have G16 QueueState hold Arc<usage::Client> directly and charge retired
stages via Client::add_union() so overlapping intervals on the same DRM
file union cleanly to <= 100% of wall time while keeping distinct files
isolated.

Also accept end >= start (with start != 0) on 24 MHz (41.67 ns) compute
ITS and render TA/FS stage timestamps so sub-tick draws or dispatches
retire cleanly instead of remaining pending while still rejecting zero
or reversed intervals.

Signed-off-by: Diljit Singh <[email protected]>
Replace O(RENDER_SLOTS) 0..48 loops over Claims::pass_mask in Slots
(mark_dirty, note_published, hold_vm, hold_arenas, publish, retire,
quarantine, release) with bit-set iteration over set bits only.

Add O(1) per-unit helpers hold_compute_slot() and hold_render_pass()
called directly during prefix_compute() and prefix_render(), plus
verify_held() at publish_prefix_body() time so multi-pass render and
compute horizon batches no longer re-scan every slot and redundantly
clone/drop Arc VM and arena leases on every pass and again at
publication.

Add host selftest coverage for per-unit holding, verify_held() bounds
and mask validation, and bit-set cross-VM retarget accounting on high
render pass slots.

Signed-off-by: Diljit Singh <[email protected]>
Mirror G17's host-refill CPU capacity actuator on G16 and bridge short
sub-2 ms inter-flight gaps in the G16 GPU power governor:

- Add g16/feed.rs and lock-free g16/feed/detector.rs tracking monotonic
  flight [published_ns, retired_ns] intervals (independent of firmware
  microsequence timestamps). After 8 consecutive sub-2 ms back-to-back
  completions with host refill idle >= 25% of busy time, request a
  cpufreq FREQ_QOS_MIN boost on an unbound workqueue outside Shared::state
  with an 8 ms linger and uclamp wait hint. Pause, drain, and release the
  CPU floor across S2R suspend/resume and fail-stop.
- In g16/power/policy.rs, track consecutive sub-2 ms inter-flight gaps
  (BURST_GAP_NS = CLPC_IDLE_HOLD_NS, BURST_STREAK_ON = 4) and bridge
  those active-burst gaps in Governor::busy() so low-duty d=1 bursts ramp
  out of P1 without affecting 60/120 Hz paced rendering (6.8/15.2 ms gaps)
  or idle P-state decay.

Signed-off-by: Diljit Singh <[email protected]>
On clean same-VM compute reuse (compute_needs_full_work == false && before != 0), keep the already-authenticated DESCRIPTOR (0xe00..0xea0), static NOTIFIER (0xc00..0xd18), and tail (0xee0..0xf08) intact in place, writing only 0..HEAD_ACTIVE_SIZE and BODY_ACTIVE_START..SEQ_EMBEDDED+SEQ_SIZE while preserving real firmware compute timestamps.

Signed-off-by: Diljit Singh <[email protected]>
Keep single-flight (d=1) completion wakeups pinned to submitter_cpu() so
the sleeping drm_syncobj_wait thread wakes cache-hot, while routing
pipelined (active_flights >= 2) completion wakeups onto a dedicated
high-priority unbound workqueue (aurora_g16_events_unbound) so fast poll
workers do not preempt an actively encoding submitter thread:

- Add Shared::active_flights (published under Shared::state in run_poll,
  submit, try_submit_inline, and cleared on sleep_down), events_unbound,
  and UNBOUND_POLL_WORK / fast_poll_unbound in g16/mod.rs.
- Update Shared::poll_now() in g16/poll.rs to enqueue UNBOUND_POLL_WORK
  on events_unbound when active_flights >= 2 and keep per-CPU
  FAST_POLL_WORK placement on events when active_flights <= 1.
- Drain events_unbound alongside events in sleep.rs::join_workers().
- Add verbatim poll_now() placement unit tests and workqueue/sleep wiring
  assertions in test-poll-retire.py.

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

The G15 (M3 Pro/Max) and G16 (M4) VDM stream gates admit a render only
when its VDM stream starts with exactly 0x21000960. Mesa's AGX3
render-start barrier sets bit 3, the USC cache invalidate (0x21000968),
so that the USC sees memory written since the previous render; on those
GPUs it has to leave the bit out, or the render is refused with EINVAL.

Admit the root barrier with or without the invalidate in both gates.
The other backends do not check the root word, so every GPU now admits
it: report that on every GPU with DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE,
so userspace can set the bit whenever the kernel reports it and keep the
plain word on older kernels. Bit 40 is unused in both the canonical and
the G15 feature numbering.

Signed-off-by: Erik Bourget <[email protected]>
Signed-off-by: Diljit Singh <[email protected]>
Advertise DRM_ASAHI_FEATURE_FEW_PRIMITIVES in G16 GET_PARAMS, admit
DRM_ASAHI_RENDER_FEW_PRIMITIVES in both parse_stream() and
check_render(), and forward it to bit 0 of ISP register 0x15021 via
Geometry::isp_control.

This lets Mesa avoid full-tile-list overhead on tiny draws and clears on
M4 (G16G). Keep this strictly isolated from VDM_USC_INVALIDATE so
G16G hardware can be verified independently (M4 Pro T6040 previously
exhibited a hang with 0x15021 bit 0 set).

Add host selftest coverage in test-command-stream.py and
check-abi-26b123.rs for both stream admission and 0x15021 encoding.

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

Eliminate 300-648 us p95 latency bubbles and cross-cluster completion
bounces on G16:

- Never run synchronous full housekeeping (publish(), power service,
  auxiliary ring drains, hang checks) on the SUBMIT thread when the
  1 ms housekeeping period expires; keep submit_locked() on
  publish_checked() unless recovery is pending and kick poll_now() so
  run_housekeeping() executes asynchronously after completion fences
  are signalled.
- Throttle auxiliary log/ktrace/stats ring drains in run_housekeeping()
  to 10 ms while flights are active, preserving immediate drains when
  idle or recovering.
- Arm a short repoll when submit_locked() consumes an EP 0x20 event
  and retires an older flight while later flights remain active, so a
  coalesced completion does not wait a full resnap window.
- Adapt the fallback hrtimer repoll interval smoothly down to
  clamp(ewma_flight_us / 2, repoll_us, resnap_us) on sub-2*resnap_us
  bursts while respecting g16_repoll_us=0.
- Restrict aurora_g16_events_unbound to the submitter's CPU cluster
  when the cluster changes during SUBMIT so pipelined completions stay
  in the submitter's cluster instead of migrating onto E-cores.

Signed-off-by: Diljit Singh <[email protected]>
Enable DRM_ASAHI_FEATURE_CUMULATIVE_SIGNALS (bit 29) on G16, reusing
the shared g17::sync_output::SignalBundle and asahi_g17_scope chain
already compiled into aurora-y:

- Allow SYNC_CUMULATIVE output sync parsing for G16 in file.rs.
- Advertise FEATURE_CUMULATIVE_SIGNALS in g16/params.rs.
- Consume SignalBundle in g16::fence::Syncs, publishing cumulative
  scopes before scheduler enqueue so ENOMEM refuses cleanly via
  bundle.fail() without leaving an accepted job behind, and signalling
  completed job fences through asahi_g17_signal_fence() so ready scopes
  drain synchronously on the signalling CPU instead of bouncing through
  irq_work.

Signed-off-by: Diljit Singh <[email protected]>
Reuse validated page-aligned GPUVM span proofs across submits on each
G16 logical queue while the VM's mapping epoch is unchanged, and unify
compute span validation and CDM stream gating under a single
VmReadGuard hold:

- Enable `mmu::MappingEpoch` tracking for adopted M4 VMs (`m4_adopted`)
  and expose `VmReadGuard::epoch()` so locked and lockless validation
  observe the same committed page-table epoch.
- Add `g16::command::SpanProof` (128 merged equal-permission ranges,
  boxed per logical queue) mirroring `g17::validation::Proof`, skipping
  GPUVM interval-tree walks on epoch hits and invalidating immediately
  on any epoch change, mutation in progress, or validation failure.
- Move `gate::cdm_locked()` out of `check_compute()` into
  `Prepared::validate()` so render spans, compute spans, VDM root
  checks, and CDM stream walks share one `VmReadGuard` and one
  `SpanProof` cache, dropping and re-syncing the epoch only on the
  1024-record reschedule boundary.
- Extend `test-command-stream.py` and `test-stream-gate.py` to cover
  epoch reuse, partial walks, invalidation on unmap, and single-lock
  CDM gate sharing.

Signed-off-by: Diljit Singh <[email protected]>
…ompute units to 24

Address the two remaining G16 pipelining ceilings without adding knobs:

- In `g16::feed::detector`, overlapping (`d >= 2`) flights have zero
  inter-flight idle gap, which previously caused `idle_sum * 4 >=
  busy_sum` to drop the host-refill CPU boost on short CPU-recording-
  bound pipelines. Sustain boost while `overlapped && busy_sum <=
  SHORT_PIPELINE_BUSY_SUM_NS` (4.8 ms, ~8x 600 us incremental flight
  time), preserving non-boost for GPU-bound 2 ms pipelines, desktop
  60/120 Hz pacing, and the 8 ms idle linger decay.
- Raise `g16::hw::sizes::COMPUTE_UNITS` from 18 to 24 (keeping 23
  compute flights concurrent, `46 < QUEUE_CAP = 256`, UMA slots
  `1..25 <= RENDER_UMA_SLOT = 33`, and `22 * 7 = 154 <= MAX_CLIENT`).
  Tighten extension compute unit VA stride (`k >= 2`) from 64 MiB to
  40 MiB (`EXT_COMPUTE_STRIDE = 0x02800000`, 7.25 MiB guard above each
  unit's `0x20c0000` footprint) so all 24 units fit cleanly below
  `PB_HEAP` (`0x70c0000000`) with 144 MiB headroom.
- Add host tests for overlapping `d = 2` CPU-bound boost and GPU-bound
  non-boost in `detector.rs` and update `test-resources.py` to verify
  disjointness across all 48 render passes and 24 compute units.

Signed-off-by: Diljit Singh <[email protected]>
Cache::prepare() in g16/resources.rs calls vm.vm.is_closed() while
holding Cache::standby (SpinLockIrq<Standby>). Previously Vm::is_closed()
acquired VmLifetime::state (a sleeping Mutex), which triggered
"BUG: scheduling while atomic" under PREEMPT(full) whenever lifetime.state
was contended during SUBMIT, corrupting preempt_count / ref-counted
local_interrupt_disable() depth and cascading into an interrupt_rc.h:63
WARN_ON_ONCE(in_nmi()) on the subsequent Cache::release_reserved() lock.

Mirror state.closed in a lock-free AtomicBool on VmLifetime, published
with Release ordering under lifetime.state in Vm::unmap_user_ranges() and
read with Acquire ordering in Vm::is_closed(). This keeps all spinlock
callers strictly atomic and removes sleeping mutex contention on SUBMIT.

Add host selftest assertions in test-resources.py verifying Vm::is_closed()
never acquires a lock and reads lifetime.closed with Acquire ordering.

Signed-off-by: Diljit Singh <[email protected]>
Trim clean same-VM render pass preparation so steady-state reuse stops
writing dead zero spans to WC memory under and off Shared::state:

- Skip unused render `its` and preemption save areas (`pre[0..2]`) in
  `PassSlot::scrub_clean()`, retaining full zeroing on first use,
  cross-VM retarget, cancel, error, and recovery.
- Track per-slot `heap_dirty` (`0x200` for single-layer passes, `0x1000`
  for multi-layer passes), `tilemap_last`, and `tilemap_clean`. Off-lock
  `PendingScrub::run_one()` zeroes only `already..min(dirty, last)` plus
  `heap_dirty` while preserving `tilemap_dirty` high-water marks for
  cross-VM or recovery full scrubs.
- Prefer exact zero-fill clean slots in `pick_pass_in()` before falling
  back to partial-clean slots (which zero only the uncleaned delta
  `already..need`) or uncleaned slots.
- On clean same-VM `prefix_render()`, skip the 2 KiB `scratch.scene`
  memset and write only the active scene header (`0x00..0x80`), firmware
  state block (`0x80..0x300`), active prefix (`0x300..0x380`),
  `uma_submitted` (`0x500..0x508`), and internal timestamp cells
  (`0x600..0x640`).

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

Keep multi-pass render bursts from flooding TA work ahead of the tiler
while leaving single-pass pipelining (where TA completes well ahead of
FS) unthrottled:

- Add `sizes::TA_WAVE_PASSES = 3` and `Firmware::ta_pending_passes()`,
  which skips WC reads whenever active render passes are already below
  the threshold and otherwise counts active render passes whose
  `r_ta_stamp` has not yet been reached by `render.fw_stamp[0]`.
- Cap multi-pass batching in `publish_prefix_body()` and gate
  `can_queue_behind()` on `ta_pending_passes() < TA_WAVE_PASSES`.
- Flush FS+TA doorbells immediately in `publish_checked()` once a render
  wave reaches `TA_WAVE_PASSES` so the GPU begins tiling without waiting
  behind further loop iterations or alt-class compute publications.
- Record `Engine::ta_wave_wait` when a ready render job pauses solely on
  the TA wave cap, and wake `publish_checked()` in `poll_step()` via
  `ta_wave_ready()` when a `0x70` TA event advances TA without spinning
  `retry_tail` or arming `short_repoll`.

Signed-off-by: Diljit Singh <[email protected]>
…o WC reads

Keep command-pool allocations uncached (`tuning::FW_CACHED = false`),
but map firmware-owned queue graph records (`qinfo`, `qscratch`,
`job_list`) with `Class::FwCached` (`AP_RW` | `NormalWB` | `Inner` |
`PXN` | `UXN` | `AF`) while keeping `sched_ctx` uncached (`Class::Fw`)
to preserve the macOS 26B123 `t8132_queue_graph` memory contract.

In `queue_receipt()` and `queue_passed()`, read `qstate::READ` from the
existing NC `qstate` mapping instead of `qinfo::READ` so receipt/pass
tracking never reads cached `qinfo` and skips unnecessary WC `qinfo`
reads on the hot path.

Add host unit tests in `test-resources.py` and `test-stamp-wrap.py`
verifying `Class::FwCached` mapping for `qinfo`/`qscratch`/`job_list`,
uncached `Class::Fw` for `sched_ctx`, `tuning::FW_CACHED == false`, and
`queue_receipt()`/`queue_passed()` reading `qstate::READ`.

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

Extend multi-pass render batching in `publish_prefix_body()` across
consecutive ready, render-only same-queue and same-VM jobs in
`self.engine.pending` up to the remaining `TA_WAVE_PASSES` (<= 3) wave
budget, sharing one TA/FS producer advance, one UMA submitted update, and
one SubmitRecord/doorbell pair:

- Add `Job::can_fold_render_horizon_job()` verifying sequential render
  ordinals, ready inputs, healthy VM, and per-command dependency readiness
  treating earlier passes in the in-progress flight as published.
- Parameterize `prefix_render()` with explicit `resources` and `cmd_index`
  (always binding pass slots and batched PB allocator refs against the
  primary flight's `Prepared`), and update `wait_stamp_for_with()` to walk
  `flight.group` members when resolving render `r_fs_stamp` barriers.
- Commit per-job standby render reservations for both `f.job` and every
  folded member in `f.group`, handle `f.group` on `pools.retire_flight()`
  errors, and publish user timestamps for folded render `f.group` members
  in `publish_timestamps()`.
- Add host unit tests for `can_fold_render_horizon_job()`, `flight.group`
  render wait-stamp resolution, and folded render group timestamp
  publication.

Signed-off-by: Diljit Singh <[email protected]>
Allow G16 compute jobs to overlap healthy non-InitBM compute flights of
another VM without draining the engine first (while still draining across
cross-VM compute/render switches so long compute dispatches cannot starve
another client's fragment shading into a firmware DM1 timeout):

- Each compute unit already owns a private ComputeSlot, per-command ASID
  and binding generation, disjoint hardware UMA slot (1..24), full
  cross-VM scrub/work write on retarget, and queue-local barrier lookup.
  Relax needs_engine_drain() and can_queue_behind() for cross-VM
  compute-behind-compute while keeping cross-VM compute-behind-render,
  InitBM, failed-VM, and recovery drain gates intact.
- Preserve per-queue FIFO in publish_checked()'s alt-class scan by
  skipping any candidate that has an earlier pending job on the same
  queue.
- Mirror Wave 7's render FS timestamp recovery proof on compute: keep
  paired compute timestamps in prefix_compute() while gating hot-path
  ITS WC reads on compute_ts_mask, and read unit.its on the cold
  recovery_suspect path in poll.rs. Innocent cross-VM computes
  co-resident during another client's hang recovery now prove execution
  and retire Full instead of timing out as Aborted, while truly aborted
  computes (scrubbed zero ITS) still abort after the 20 ms grace period.

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

Give each G16 render PB/UMA allocator slot its own hardware UMA slot ID
and extend Pools slot selection so multiple VMs can hold simultaneously
warm PB epochs without aliasing a single firmware UMA slot:

- Pass engine::RENDER_UMA_SLOT + k (33..38, compile-time asserted within
  M4 firmware's 33..64 render UMA window and disjoint from compute UMA
  slots 1..24) in Allocator::new() and validate RENDER_UMA_SLOT + self.id
  in Allocator::prepare_in_flight().
- Add Pools::slot_inflight() and guard Pools::slot_displaced() with
  self.inflight[k] == 0 so an in-flight slot can never be treated as
  displaced.
- Update Pools::pick_slot_within() so behind=true returns any healthy
  warm reusable slot bound to vm (preferring self.active, then 0..limit)
  while still returning None for cold VMs requiring InitBM, ensuring the
  engine drains before any InitBM or slot displacement. Check all slots
  in Pools::exhausted().
- Add host tests in test-resources.py covering per-slot render UMA IDs,
  tamper rejection, multi-active warm cross-VM slot reuse, cold InitBM
  gating, and post-recovery invalidation across all slots.

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

Allow warm cross-VM renders (reusing a VM's already-primed PB/UMA slot)
to pipeline behind active non-InitBM render flights of another VM while
preserving exact cross-VM FS ordering and disallowing cross-VM
render/compute overlap in both directions (so long compute dispatches
cannot starve another client's fragment shading into a firmware DM1
timeout):

- Relax needs_engine_drain() and can_queue_behind() for warm cross-VM
  render-behind-render while draining on cold InitBM renders and on any
  cross-VM render/compute switch in either direction.
- Preserve per-VM hardware FS barriers on cross-VM render overlap while
  allowing cross-VM TA to overlap the preceding VM's FS.
- Add host regression tests covering the full cross-VM render/compute
  overlap matrix and hold[0] drain behavior.

Signed-off-by: Diljit Singh <[email protected]>
Eliminate avoidable completion wakeup delays and hot-path lock churn on
short G16 compute and render bursts:

- When submit_locked() consumes an EP 0x20 event before the oldest
  flight's wire receipt settles (and the event is not a TA-only 0x70
  stage tick), restore evented, arm a short repoll instead of resnap_us,
  and kick poll_now() so trailing completions do not stall onto 100 us.
- Recheck Shared::evented in run_poll() after signalling completed fences
  (bounded by MAX_EVENT_RECHECKS = 8) so back-to-back completions during
  fence signalling retire immediately without an extra workqueue wakeup.
- Raise the active-burst housekeeping cadence from 1 ms to 5 ms (aligned
  with power::policy::SAMPLE_NS and well below the 100 ms minimum hang
  deadline) and defer housekeeping off the hot poll_step() lock while
  flights remain active.
- Relax healthy idle hrtimer transitions via idle_resnap() to keep short
  (<= resnap_us) already-armed timers intact across sub-100 us d=1
  inter-job gaps, while keeping cancel_resnap() unconditional for system
  sleep and fail-stop paths. Lower the default g16_repoll_us from 15 us
  to 8 us and decay ewma_flight_us faster downward on burst transitions.

Signed-off-by: Diljit Singh <[email protected]>
Reduce render-wave serialization and pre-gfx compute dispatch latency:

- Raise TA_WAVE_PASSES from 3 to 8 so multi-pass render bursts can keep
  up to 8 unfinished TA passes pipelined per wave without stalling
  lightweight shadow/postfx bursts.
- Ring Channel::Compute ahead of Channel::Fs and Channel::Ta in
  flush_doorbells() so pre-gfx compute wakes immediately ahead of TA
  cross-engine barriers while preserving FS-before-TA doorbell order.
- When TA wave pacing pauses ready same-queue renders, allow a later
  independent non-query-access Command::Compute on that same queue
  (whose command dependencies are already published) to overlap onto CDM
  without violating per-queue compute FIFO or barrier ordering.

Signed-off-by: Diljit Singh <[email protected]>
Add a second independent CDM workqueue pipe (pipe 0 on event 0x74 and
pipe 1 on event 0x75) so barrier-free compute dispatches overlap across
two hardware CDM pipes while preserving exact per-pipe and cross-pipe
barriers, recovery isolation, and per-pipe UMA slot displacement:

- Track per-pipe ownership in pools::lifetime::Lifetime (publish_on,
  per-pipe FIFO retirement, and same-pipe displacement) so pipe 1 can
  retire ahead of an in-flight pipe 0 command without EINVAL and without
  falsely displacing pipe 0's retired UMA owners.
- Keep base compute units 0..BASE_COMPUTE_UNITS (0..2) on pipe 0 and
  restrict pipe 1 claims to BASE_COMPUTE_UNITS..n so a 2-unit base-only
  VM can never see both base units undisplaced across two pipes.
- Balance barrier-free dispatches across both pipes in choose_compute_pipe
  and emit cross-pipe c2c barriers only when waiting across pipes.
- Add host unit tests covering out-of-order dual-pipe retirement,
  same-pipe displacement isolation, and base-unit VM exhaustion safety.

Signed-off-by: Diljit Singh <[email protected]>
Under sustained M4 GPU load, the die hotspot runs at 90-94 C while PMP
SRAM channel validity words can transiently read != 1 during a refresh.
Previously -ENODATA was only masked below 90 C (APPLE_PMP_GATED_HOLD_MC),
so a single transient -ENODATA at >= 90 C triggered the hard sensor-fault
backstop (S1 floor for ~1.8 s until 10 good reads and gradual release).

Raise APPLE_PMP_GATED_HOLD_MC to 100 C (still 6 C below the 106 C passive
trip and 8 C below the 108 C backstop), add a 100 ms transient refresh
window (APPLE_PMP_TRANSIENT_HOLD_NS) for readings below 106 C, and share
the check via apple_pmp_hold_nodata() between g16/glue.c and
apple-pmp-thermal.c. Any -ENODATA at >= 106 C or lasting past its hold
window continues to fail closed immediately.

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

Keep the TA wave cap at 4 passes (TA_WAVE_PASSES = 4) with hysteresis refill at 2 (TA_WAVE_REFILL = 2), and keep non_terminal_only clear while ta_wave_wait is active so TA-only (0x70) interrupts wake and refill stalled TA waves without spinning once ta_wave_wait clears.

Always advance render.threshold[0] alongside render.threshold[8] to prefix.draw as u32 in publish_prefix_body(): firmware only updates notifier_page::TA_STAMP and notifier::CONTEXT when notifier.cur_count == *render.threshold[0], so holding threshold[0] at an earlier unfinished TA flight drops TA_STAMP on fast tail flights whose TA finishes before host rearm, causing a permanent Retirement::Pending -> 5 s ETIMEDOUT fail-stop (seen on render.shadow(d32f, depth_only, 2048) d=2).

Signed-off-by: Diljit Singh <[email protected]>
The G16 parameter-buffer (PB) heap window reserves 256 MiB of GPU VA per VM
(PB_HEAP_SIZE), while PoolSet maps only a 64 MiB (512-block) base backing
arena so steady 60/120 Hz single-pass desktop VMs keep a small resident
footprint. Heavy multi-pass 3D scenes can exhaust 64 MiB of TVB parameter
blocks mid-frame and trigger firmware partial-render spills.

Demand-grow up to two contiguous PB heap extension chunks inside each VM's
256 MiB PB_HEAP window paired with the existing render extension tiers:
- Tier 0: +64 MiB at PB_HEAP + 64 MiB (128 MiB / 1024 blocks total)
- Tier 1: +128 MiB at PB_HEAP + 128 MiB (256 MiB / 2048 blocks total)

Allocation is best-effort and strictly contiguous, kept mapped until VM
teardown (with live_vm_token protection) so no unmap races with in-flight
firmware parameter-buffer accesses. Record the initialized heap block count
on each PbEpoch and gate pipelined reuse in Pools so a VM whose PB heap
expanded drains once and rotates onto a displaced PB slot for a fresh
InitBM
covering the expanded block count, safely falling back to its warm epoch if
no displaced PB slot remains under quarantine.

Signed-off-by: Diljit Singh <[email protected]>
Bring in main through the updated base. Conflicts:

- usage.rs: Client keeps this series' per-file union marks next to the
  base's engine ledger, both sized by main's NUM_ENGINES. add_union()
  still charges through add(), so main's ENGINE_NS busy share counts
  it too.
- test-resources.py: keep this series' 48-slot case (slot 47, 64-bit
  mask), which already publishes its claims mutably.

Signed-off-by: Diljit Singh <[email protected]>
Bring in main through the updated base. Conflicts:

- include/uapi/drm/asahi_drm.h: this series carries its own copy of the
  VDM_USC_INVALIDATE define (bit 40). Take main's header, which also has
  ASYNC_SUBMIT (bit 39) and COMPUTE_ONLY (bit 41) around it; main's
  file.rs and g18 code use both.
- g16/params.rs: keep this series' module comment, which adds
  FEW_PRIMITIVES to the base's feature list.

Signed-off-by: Diljit Singh <[email protected]>
@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) labels Nov 24, 2026
@github-actions github-actions Bot added blast:all 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 24c6f8d3: 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 ok comment at 24c6f8d3
Conflicts ok not computed yet
PR text ok Risk: two-way · M4, plus every Mac for the shared file.rs, mmu.rs and mmu/lifetime.rs changes

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 24c6f8d3f3: FINISH, then merge. One code blocker, plus rows.

Blockers:

  1. drivers/gpu/drm/asahi/g16/engine.rs:1436-1441 (and the drain test at :1296): compute may now queue behind another VM's compute flight. With several clients that loses results without a fault. drm/asahi: g16: never run compute beside another VM's compute #3087 measured it: with six dEQP-VK processes, about one draw in 285 of dEQP-VK.glsl.texture_functions.* read back zero or a partial image, and a compute.long ray-query dispatch was reported complete with its results unwritten; one client alone never fails. Fix: move drm/asahi: g16: never run compute beside another VM's compute #3087's single commit onto this branch (it changes exactly these two conditions), or merge this PR only in the same train as drm/asahi: g16: never run compute beside another VM's compute #3087, never on its own.
  2. 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).
  3. No row for the shared code: mmu.rs (mapping epoch for handoff VMs), mmu/lifetime.rs (lock-free is_closed()) and file.rs also run on other Macs. Fix: one non-M4 row (boot plus a Vulkan smoke, 0 faults) at this head.

Checked: this PR's own 25 commits against its base, with most attention on publication and queueing, the SUBMIT/CDM validation paths and the thermal change; 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. I reformatted the PR body to What / Tested / Risk / Not yet, with the original kept folded and its attribution line removed.

Row request and row

@RyanTheTide

Copy link
Copy Markdown
Contributor

Neo (J700, T8140 / G17P B1) non-regression PASS at 24c6f8d (combined with #3043 on 7.3.0-aurora-prneo1a+, aurora.ko sha d25b133b8428537b, default cmdline, Stage 2 b17): gpubench-vk 8/8 OK (render.heavy 720p fill d1 440us/d4 261us, compute.heavy alu d1 1382us/d4 1181us, bw d1 2830us/d4 2586us), gl-smoke 32/32 + gpubench-gl 2/2 OK, dEQP-VK short CTS 30/30 PASS, s2idle 1/1 (10 s) + post-sleep GPU PASS, 0 GPU faults/timeouts, 0 failed units, Enforcing + 0 AVC, 0 new GPU/thermal kernel errors; restored to saved fleet89.

@github-actions github-actions Bot removed the needs-hw-row No hardware row at the PR head (bot) label Nov 24, 2026
@DjDeveloperr
DjDeveloperr changed the base branch from djdev/g16-perf-wave7 to main November 25, 2026 01:36
@DjDeveloperr
DjDeveloperr requested review from a team as code owners November 25, 2026 01:36
@DjDeveloperr
DjDeveloperr merged commit b6080f8 into main Nov 25, 2026
2 checks passed
@RyanTheTide
RyanTheTide deleted the djdev/g16-perf-wave8-14 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) door:two-way Revertible or not, from Merge risk (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.

3 participants