Skip to content

perf(agc): compile uncached draws ahead of queue 0 - #6188

Open
mitul72 wants to merge 5 commits into
boykopovar:mainfrom
mitul72:perf/agc-draw-ahead
Open

mitul72 wants to merge 5 commits into
boykopovar:mainfrom
mitul72:perf/agc-draw-ahead

Conversation

@mitul72

@mitul72 mitul72 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What

Six commits. Draws whose register key is new (per-frame ring addresses in user data make most keys new every frame) captured and recompiled their stages on the queue-0 thread, and each draw snapshotted its small inputs through the full buffer path.

  • Read-only draw inputs of up to 4 KiB are copied into slices of a 4 MiB host-visible chunk owned by the recorder (one bump allocation and one copy), on top of main's snapshot reuse: an unchanged input in the same collect epoch rebinds its slice, larger inputs keep main's caches. Chunks are never rewound; a draw's bindings hold its chunk until its batch completes.
  • The device's graphics context is passed to draws by reference.
  • The scan publishes draw keys, parameters and prechecks ahead of queue 0.
  • Worker threads compile the stages of every such draw with a Proceed precheck, using the same request as the queue-0 miss path (DrawStageRequest, DrawStageVariant), and insert the variants into the draw cache. Queue 0 validates them as any cached variant, against current memory.
  • Graphics::PrepareDraw computes the vertex input layout, pipeline stage mask and resource content key on the worker; they are stored on the entry, tied by weak reference to the exact variants compiled. Queue 0 uses them only for a non-indirect draw whose stages refreshed no data words; otherwise it builds them as before.

Worker count: a quarter of the hardware threads, clamped to 1-4. Without a working kernel copy no workers run. Draws whose compilation consumes packet-derived inputs (mesh draws, instanced tessellation, indirect draws) are not compiled ahead.

Validation of cache hits now dominates queue 0's lookup cost, since nearly every draw hits; the last commit tests validated runs against the pending images' merged range index, takes the shadow registry's mutex once per run list, and checks a run list against queued pipelined commits under one lock (DrawPipeline::OverlapsAny, same answer as the per-run check).

Admission follows the driver's own rule: every entry compiled ahead goes on probation, in its own list bounded by the cache size, so it pushes out only other probation entries. Promotion happens only through queue 0's own sighting under main's admission rule and exclusions, in one step with queue 0's insert decision, so a key is admitted at the same execution that would admit it without compile-ahead. Worker variants record their stage capture and pure-data word positions, so they take part in stage data hits.

Speculative reads: under GuestMemory::SpeculativeReadScope, Read copies through the kernel (process_vm_readv / ReadProcessMemory) into the capture's private buffer, so a concurrent store is not a data race and an unmapped page fails the copy instead of faulting. All other guest memory access in that scope throws (SpeculativeReadRefused). The variant records the words it was compiled from; queue 0 compares them with memory after its waits and flushes. Every guest read and cache insertion of a job is pinned to its draw; queue 0 passes a draw before executing it and retires the submission when it ends.

Speculative failures never surface: any exception in the scan, resolve, decode, capture, compile or PrepareDraw only means the draw has no precomputed result. Queue 0 then performs the draw as without draw-ahead on current memory. The serial path remains authoritative and throws on genuine errors; what the speculation saw (stale, torn or unmapped memory, an unfollowable context stack) is not an error of the draw.

Tests: DrawAhead, DrawAheadRaw, DrawAheadScan, Recorder additions. They include a draw with an invalid buffer descriptor repaired before the draw, a table mapped only after the worker's read, a draw after a CONTEXT_STATE push in a skipped COND_EXEC, an indexed draw of restart indices only with a stride beyond the device limit, and a refused read of an inaccessible range.

Tested

Linux, RX 9060 XT (RADV GFX12, local Mesa). Full ctest passes except agc_driver_tessellation, which segfaults inside RADV while linking pipeline libraries on unmodified upstream main as well.

Astro Bot crash-site hub on main 4eb91ea (pipelined draws on), 3 x 10 s windows, gamescope headless, one run each, nothing else running:

fps CPU per draw packet capture recompile key/lookup/validate record phase per draw GPU busy / idle per frame
base 8.07 36.6 us 6.8 us 6.4 us 1.7 us 9.07 us 97 / 27 ms
draw-ahead 9.07 29.9 us 0.3 us 0.1 us 3.5 us 5.07 us 90 / 20 ms

Per 10 s: 196k draw records published, 196k used, 186k draws compiled ahead, 1.3k jobs dropped. With APS5_PROFILE_DRAW=1 a [draw-ahead] line reports these counts. Single runs of the base varied by about 0.3 fps.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none (test(agc): wait for the actual image in repeated untracked stores #6359 composes with it in either order)
  • Unblocks: none
  • GPUs tested: AMD Radeon RX 9060 XT (RADV GFX12, local Mesa build), Linux
  • AI-assisted: yes

🤖 Generated with Claude Code

@jotitadev jotitadev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

macOS portability note on head b779871 (static review, no full build).

Two calls in the non-Windows branches are Linux-only, so they will not compile for macOS (the port in #1 builds this driver with Apple clang):

  • Execution/src/Driver/Draw/DrawAhead.cpp:28: pthread_setname_np(pthread_self(), name); -- macOS only has the one-argument form, which names the calling thread.
  • Execution/src/GuestMemory.cpp:2014: process_vm_readv(getpid(), ...) -- not available on macOS.

Neither is used anywhere else in main today, so these would be the first ones. Checked with Apple clang 21 (clang++ -std=c++20 -arch x86_64 -c) on the two functions copied as they are:

snip6188.cpp:8:5: error: no matching function for call to 'pthread_setname_np'
snip6188.cpp:13:12: error: use of undeclared identifier 'process_vm_readv'

A drop-in for macOS that keeps the same semantics, verified on the same machine for arm64 and x86_64:

#elif defined(__APPLE__)
    pthread_setname_np(name);
#elif defined(__APPLE__)
    mach_vm_size_t copied = 0;
    return mach_vm_read_overwrite(mach_task_self(), address, destination.size(), reinterpret_cast<mach_vm_address_t>(destination.data()), &copied) == KERN_SUCCESS && copied == destination.size();

(<mach/mach.h>, <mach/mach_vm.h>). With it, the SpeculativeReadsSupported() probe succeeds, and a read of a PROT_NONE page, of an unmapped page, and of a range that straddles into a PROT_NONE page each fails cleanly instead of faulting, which is what SpeculativeReadRefused relies on. If you prefer not to add a macOS branch here, guarding both with __linux__ and letting copyThroughKernel return false elsewhere would just turn the draw-ahead workers off on macOS.

Written with AI assistance (Claude Code). I ran the checks above on my machine.

@mitul72
mitul72 force-pushed the perf/agc-draw-ahead branch from b779871 to 15647ff Compare October 15, 2026 01:32
@mitul72

mitul72 commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, applied both macOS branches as suggested (pthread_setname_np(name) and mach_vm_read_overwrite) in 15647ff. Linux builds and the draw-ahead tests pass; I can't build for macOS here, so a check on your side would be welcome.

@jotitadev jotitadev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Checked on 15647ff (Apple M2 Max, macOS 27.2, Apple clang 21): NameThread and copyThroughKernel copied verbatim from this head, with the include block, compile cleanly for arm64 and x86_64. On both, the thread gets its name, the SpeculativeReadsSupported() probe succeeds, and reads of a PROT_NONE page, an unmapped page and a range straddling into PROT_NONE return false without faulting. Not a full driver build (main doesn't link on macOS yet), but the two macOS branches look good.

Written with AI assistance (Claude Code). I ran the checks above on my machine.

@fma-rc

fma-rc commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

I measured head 15647ff against its base ab9a476 in Astro's Playroom on Linux (RTX 5080, heavy in-game scene, three alternating runs of 20 s each, APS5_PROFILE_DRAW=1). Frame rate does not move here: 7.78 / 7.64 / 7.68 FPS with the PR against 7.88 / 7.52 / 7.59 without.

The work does leave queue 0, but about as much comes back in the lookup:

us per draw packet base PR
capture 7.0-7.7 5.1-5.3
recompile 4.2 1.3-1.4
key/lookup/validate 1.4 4.2-4.3
decode 1.6-3.7 3.1-3.2
Graphics::Draw 22.1-22.3 22.6-23.8

Memo hits go from 1-3% to 42%, so the entries compiled ahead are being used; capture staying at about 5 us suggests many draws still capture on queue 0. Frame dumps from both builds show the same picture in the scene. Its draw-ahead tests, with the recorder and draw-cache tests (8 in all), pass on NVIDIA, RADV (Ryzen 7800X3D integrated Radeon) and lavapipe.

@mitul72
mitul72 force-pushed the perf/agc-draw-ahead branch from 15647ff to 0eb0d89 Compare October 15, 2026 04:49
@mitul72

mitul72 commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for measuring. 15647ff had dropped the small-snapshot arena in a rebase; it is back in 0eb0d89, and hit validation got cheaper (the pending-image check now uses the pending list's range index; key/lookup/validate 4.4 -> 3.0 us per draw in Astro Bot). With APS5_PROFILE_DRAW=1 a new [draw-ahead] line shows published, used, compiled and dropped counts. If you can rerun Playroom on the new head, that line (with [draw-cache]) would show why capture still costs ~5 us per draw there; my guess is that queue 0 reaches many draws before their worker compile commits.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 15, 2026
@fma-rc

fma-rc commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Reran Playroom on 0eb0d89 against its base d92a8da, same scene and setup, one run each: 8.37 FPS against 7.33, and the frames match where both reach the scene.

us per draw packet d92a8da 0eb0d89
capture 7.4 5.2
recompile 4.3 1.3
key/lookup/validate 1.4 3.9
decode 3.5 3.1
Graphics::Draw 22.9 19.6

Per 10 s, [draw-ahead] reads 243-245k records published, 243-244k used, 231-233k entries compiled ahead, 166-217 jobs dropped. [draw-cache] register key: 243,038 lookups, 83,313 hits, 159,468 partial (state, pixel and programs from the entry).

So queue 0 does find nearly every entry; it does not seem to arrive before the compile. About two thirds are partial hits, and those still capture. On main, nearly every register-key miss in this scene differs only in user-data words (per-frame pointers, APS5_TRACE_DRAW_CACHE), so most of the remaining capture looks like stages whose user words moved after the entry was compiled.

Update: with #5656 (8267abd) stacked on 0eb0d89, same scene, one run: 12.77 FPS, against 8.37 for 0eb0d89 alone and 7.57 for d92a8da. The frames match. Register-key hits go to 372k of 373k lookups per 10 s, and capture, recompile and decode on queue 0 drop to 0.1, 0.0 and 0.4 us per draw, so Graphics::Draw (16.2 us) is what is left. In the merge I also applied 5656's user-word mask in compileDrawAhead.

@fma-rc fma-rc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

agc_draw_snapshots fails here on NVIDIA (RTX 5080, driver 615.78.08, Linux) at 0eb0d89, and at every commit of the PR from 1aee516 on, where it is added:

AGC graphics: a draw snapshot does not hold the guest bytes of its draw

That is tests/Recorder.cpp:2711: after the CPU rewrites the element with 0x22, the snapshot still holds 0x11. agc_draw_snapshots_no_collect_memo passes, and so does --draw-snapshots-only with APS5_NO_COLLECT_MEMO=1, so the write collect memo seems to hide that CPU write from the snapshot reuse check. On RADV the case is skipped (storage buffer offset alignment 4: misaligned draw snapshots not tested), and on lavapipe too (host imports are compared, not watched: draw snapshot reuse not tested), so CI on llvmpipe would not see it. The linux job on this PR was skipped anyway.

If the test is right, a draw can read stale bytes after a CPU write on a GPU with watched host imports, the GPU my Playroom numbers above were measured on.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed — no blocking findings

The inspected draw-ahead paths show no verified blocking defect, but the review is incomplete because not all changed files were read and no checks were run.

What I ran

Reviewed head aa699de9126da33d654d20c27553138549269546 using the prepared diff and pinned repository reader. No build or tests were run.

Results

Check Result Note
Diff and targeted code review passed Inspected draw scan, speculation, cache, memory, and prepared draw paths
Build and tests not run No commands run

Findings

Blocking

None verified in the code inspected.

Non-blocking

None.

Not verified

The review folder listed 36 changed files. I read the description, commits, manifest, and portions of the diff, and inspected targeted code around draw scanning, speculative reads, cache admission, and prepared draw state. I did not read every changed file or every changed hunk. core/libs/prx/libSceAgcDriver/tests/Recorder.cpp was excluded from the review folder; I did not inspect it through the reader. Build and test results reported in the PR description were not independently verified.

To get this to a good state

Nothing is required. Optional: complete review of the remaining changed code and run the relevant build and tests before making a formal approval decision.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* build needs rebase Conflicts with main, rebase needed perf numbers missing perf pull request without a before and after summary line perf Performance change shader core/shader

Projects

None yet

Development

Successfully merging this pull request may close these issues.