fix(agc): wait for address-based writers before reading indirect draw records #17850

Merged
adam25136 merged 1 commit from upstream-pr/17850 into main 2026-11-15 20:14:22 +00:00
adam25136 commented 2026-11-09 18:05:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adam25136 on 2026-11-09T18:05:55Z.


What

The driver reads some indirect draw records and counts on the CPU. These reads now first finish the earlier batches whose address-based builds can store to guest memory, as the CPU read of DISPATCH_INDIRECT arguments has done since #6786.

An address-based store (FLAT/GLOBAL, or through a descriptor the recompiler cannot resolve to a static buffer) is not recorded as a pending write: its batch holds a lease on the registered allocations, and the flush hook does not wait for it. So these reads could see guest memory from before such a store ran:

  • the CPU path in Driver::finishDraw (Execution/src/Driver/Draw/Draw.cpp), for the draws ClassifyIndirectDraw keeps off the GPU (for example an indexed draw without INDEX_BUFFER_SIZE);
  • the empty-draw skip in Driver::draw, where a stale zero count or stale empty records skip the draw;
  • the device's fallback in prepareDraw (Graphics/src/Draw.cpp), when the GPU does not read the records.

Only leases whose build can store are waited for. CountLeaseOutcome takes !ShaderResources::BdaReadOnly(), based on the bdaReadOnly flag WriteBack already uses to decide whether an address-based build breaks proofs. It comes from a scan of each stage's SPIR-V for stores and atomics through PhysicalStorageBuffer pointers; unreadable SPIR-V counts as storing. Graphics::FinishLeaseWrites finishes the recorder up to the newest such batch. The two driver sites take GpuMutex only while LeaseWritesMayBePending() reports a storing lease counted since the last such wait, so the queue thread stays off the mutex otherwise. FinishLeaseWork and FinishLeaseWrites share their submit-and-finish step (finishLeaseBatches). LeaseStats::writing counts the leases that can store, shown in the [address-sync] profile line.

The debt entry "CPU reads behind an address-based build" is cut to the reads that still do not wait: the non-indexed copy kernel's count record (oneandonlydean showed on #13599 that it is read without the lease wait), the record recordMeshArguments reads while recording, the awaitsTitle/orderReleased checks, and the draw reads behind a draw that queue 0's draw pipeline (on by default) has queued but not yet recorded. Such a draw counts its lease only when recorded, and DrawWriteRanges gives the pipeline no range for its address-based stores. That gap is left for a separate change.

New test IndirectDrawPendingProducer.cpp (agc_driver_indirect_draw_pending_producer, its _draw_pipeline and _plan_verify variants, and _gpu_indirect_disabled with APS5_NO_GPU_INDIRECT_DRAW=1). A one-thread compute dispatch writes the draw record or count with global_store_dwordx3, then a draw of a triangle covering the target follows. Every writer case checks that the producer's lease was deferred and counted as able to store, that the store landed, that every pixel was drawn, and that the draw took the expected path once without being skipped as empty. The cases: records the GPU reads; an indexed draw without INDEX_BUFFER_SIZE; an indexed count-indirect multi-draw whose count the empty-draw skip reads; a draw behind a dispatch that only loads through an address (global_load_dword), whose lease must not be counted as able to store; and, in _gpu_indirect_disabled, a draw the device's fallback reads. A producer on a compute queue behind a label wait was tried and left out: with the two driver waits reverted it still passed in all three registrations that run it, so it does not reliably show the bug.

No title has been seen to read such memory here; the change and the test come from the debt entry.

Overlap: tools/pr_overlap.py --branch (in a full clone, 1,978 open pull requests) lists four that change lines here:

  • #13599 (MarcZX10, docs only) rewrites the same debt entry, and its current head drops the copy kernel count record that this entry keeps;
  • #12840 (EagleBearerYS) and #15845 (mehmetbayoglu) change the debt lines right after and right before it;
  • #16753 (chitters2004) changes the readStart line just before each of the three added calls.

It could not compare 75 more that conflict with main. In GitHub's patch of each, context lines included:

  • #1896 (fisherjoey, draft) adds another copy of the CPU read in finishDraw, which would need the same call;
  • #13863 and #13920 (Celegans12) change the wait inside FinishLeaseWork (FinishThroughOpened while an async lane is active); that step is now shared with FinishLeaseWrites, so whichever lands second changes it once, for both;
  • #5925 (adriadam10) changes the debt entry right after this one, and #14212 (janzezno) adds blank lines between the entries of that file;
  • #10442 (Dripl1x, draft) changes a line two below the CountLeaseOutcome call in keepRecordedDraw, and #10193, #13928 and #13929 (Celegans12) insert one three below, with unchanged lines between.

Tested

Windows 10 Pro 22H2 (19045), i9-12900KF, NVIDIA GeForce RTX 5080 (10de:2c02, driver 621.14), WinLibs GCC 15.2.0, Release, BUILD_TESTING=ON, with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1. Head c95426ff42 merged onto main 52c33518f8 unless stated.

  • The new test, ctest -R '^agc_driver_indirect_draw_pending_producer' -V: all four registrations pass, each log with Selected GPU name=NVIDIA GeForce RTX 5080.
  • With parts of the change removed (each reverted afterwards, and the test exe rebuilt each time so the libSceAgcDriver.prx staged next to it was the one just built):
Removed Fails
the three waits the records and count cases (all three registrations that run them) and _gpu_indirect_disabled
the wait in the empty-draw skip the count case
the wait in finishDraw the records case
the wait in prepareDraw _gpu_indirect_disabled
writes forced to true the read-only case
writes forced to false every writer case

These ran on this change before its rebase onto 52c33518f8; the 27 commits it moved over change no libSceAgcDriver file.

  • Reverting only Execution/src/Driver/Draw/Draw.cpp (the two driver waits) in the merge: 3 of the 4 registrations fail; _gpu_indirect_disabled, which the prepareDraw wait covers, passes. Restored, all 4 pass.
  • agc_driver_pipelined_indirect_draw, agc_driver_indirect_arguments_pending_producer, agc_driver_indexed_copy_gpu_parameters, agc_driver_queued_indirect_read_order and agc_driver_empty_indirect_skip pass.
  • Selected tests: tools/select_tests.py picks 2,685 tests for the changed files, and select_tests.py ctest build --parallel 4 --timeout 120 on the merge fails 3. Two of them, agc_driver_quad_pixel_mask (#14237) and guest_kernel_sys_paths_symlinkat_patched (a timeout), fail in main 52c33518f8's full suite on this machine too (4,824 tests; it also times out guest_kernel_sys_paths_symlinkat, which is not selected). The third, agc_driver_unregistered_label_on_gpu, passed three reruns. It fails on main too, now and then, with the same message ("the label held 0x00000000 when a later label had landed"): run alternately, 1 of 150 runs on main and 2 of 150 with this change failed (2 of 579 on main overall). From its code, it reaches none of the changed functions. The 13 tests that skip skip on main too.
  • Validation: the selected tests matching ^(agc|shader|recompiler|videoout|video_out|guest_video_out|vulkan)|gpu (1,594 on the merge, 1,597 in main's run), through ctest -V --parallel 4 with VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation (1.4.367) and VK_LOADER_LAYERS_DISABLE=~implicit~; all pass except agc_driver_quad_pixel_mask on both sides. Neither log has a VUID- line or was not found but was requested by env var VK_INSTANCE_LAYERS. Both have the same 61 Undefined-Value-ShaderOutputNotConsumed/OutputNotWritten warnings in the same 14 tests, and the four new registrations have none. A rerun of them on this head with VK_LOADER_DEBUG=layer shows Insert instance layer "VK_LAYER_KHRONOS_validation" 8 times.
  • Built again with -DANYPS5_ENABLE_SPIRV_TOOLS=ON (as the Linux CI job builds): the four registrations pass in three runs, 1.47 to 1.61 s each.
  • python tools/check_test_registration.py build and python tools/check_conventions.py --base origin/main (with this title and description) pass.
  • Rebased onto main e37e9fa3f9 before opening (head 03334ebfd3, c95426ff42 with the debt entry's last sentence reworded); none of the 48 commits since 52c33518f8 touches libSceAgcDriver or the debt file, and the four registrations pass there.
  • Planet Zoo (PPSA18026), three pairs in alternating order on main 84f4ad4f06, with an earlier head of this change whose library code differs only in names, this profile line's wording and the shared helper; APS5_PROFILE_DRAW=1 APS5_TRACE_SUMMARY_EVERY=30 APS5_TRACE_BENCH=1 APS5_LOG_TIMESTAMPS=1, 3 to 3.5 minutes of the same scene each, both sides carrying one local line, sceAjmInitialize comparing only the low 32 bits of its reserved argument as #16974 first proposed (it now drops the check; without the line this title faults in its Render thread). In every run with the change, the [address-sync] line counts 934 to 1,215 deferred leases and none by a build that stores through addresses, so the two driver sites never took the mutex. Frame times differed between runs of the same build by up to 13%, and between the two sides by less in both directions (mean 493.8 ms per present with the change, 499.3 without, after the first 60 s).

Not covered: AMD and Intel GPUs, Linux (the test's mmap allocation path is not run here), a PS5, a title whose address-based stores these waits catch, and the four reads the debt entry keeps open.

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
  • Fixes: none
  • Unblocks: none
  • GPUs tested: NVIDIA GeForce RTX 5080, driver 621.14, Windows 10 22H2 (19045)
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5228730397 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17850). Originally posted by [adam25136](https://github.com/adam25136) on 2026-11-09T18:05:55Z. --- ### What The driver reads some indirect draw records and counts on the CPU. These reads now first finish the earlier batches whose address-based builds can store to guest memory, as the CPU read of `DISPATCH_INDIRECT` arguments has done since #6786. An address-based store (FLAT/GLOBAL, or through a descriptor the recompiler cannot resolve to a static buffer) is not recorded as a pending write: its batch holds a lease on the registered allocations, and the flush hook does not wait for it. So these reads could see guest memory from before such a store ran: - the CPU path in `Driver::finishDraw` (`Execution/src/Driver/Draw/Draw.cpp`), for the draws `ClassifyIndirectDraw` keeps off the GPU (for example an indexed draw without `INDEX_BUFFER_SIZE`); - the empty-draw skip in `Driver::draw`, where a stale zero count or stale empty records skip the draw; - the device's fallback in `prepareDraw` (`Graphics/src/Draw.cpp`), when the GPU does not read the records. Only leases whose build can store are waited for. `CountLeaseOutcome` takes `!ShaderResources::BdaReadOnly()`, based on the `bdaReadOnly` flag `WriteBack` already uses to decide whether an address-based build breaks proofs. It comes from a scan of each stage's SPIR-V for stores and atomics through `PhysicalStorageBuffer` pointers; unreadable SPIR-V counts as storing. `Graphics::FinishLeaseWrites` finishes the recorder up to the newest such batch. The two driver sites take `GpuMutex` only while `LeaseWritesMayBePending()` reports a storing lease counted since the last such wait, so the queue thread stays off the mutex otherwise. `FinishLeaseWork` and `FinishLeaseWrites` share their submit-and-finish step (`finishLeaseBatches`). `LeaseStats::writing` counts the leases that can store, shown in the `[address-sync]` profile line. The debt entry "CPU reads behind an address-based build" is cut to the reads that still do not wait: the non-indexed copy kernel's count record (oneandonlydean showed on #13599 that it is read without the lease wait), the record `recordMeshArguments` reads while recording, the `awaitsTitle`/`orderReleased` checks, and the draw reads behind a draw that queue 0's draw pipeline (on by default) has queued but not yet recorded. Such a draw counts its lease only when recorded, and `DrawWriteRanges` gives the pipeline no range for its address-based stores. That gap is left for a separate change. New test `IndirectDrawPendingProducer.cpp` (`agc_driver_indirect_draw_pending_producer`, its `_draw_pipeline` and `_plan_verify` variants, and `_gpu_indirect_disabled` with `APS5_NO_GPU_INDIRECT_DRAW=1`). A one-thread compute dispatch writes the draw record or count with `global_store_dwordx3`, then a draw of a triangle covering the target follows. Every writer case checks that the producer's lease was deferred and counted as able to store, that the store landed, that every pixel was drawn, and that the draw took the expected path once without being skipped as empty. The cases: records the GPU reads; an indexed draw without `INDEX_BUFFER_SIZE`; an indexed count-indirect multi-draw whose count the empty-draw skip reads; a draw behind a dispatch that only loads through an address (`global_load_dword`), whose lease must not be counted as able to store; and, in `_gpu_indirect_disabled`, a draw the device's fallback reads. A producer on a compute queue behind a label wait was tried and left out: with the two driver waits reverted it still passed in all three registrations that run it, so it does not reliably show the bug. No title has been seen to read such memory here; the change and the test come from the debt entry. Overlap: `tools/pr_overlap.py --branch` (in a full clone, 1,978 open pull requests) lists four that change lines here: - #13599 (MarcZX10, docs only) rewrites the same debt entry, and its current head drops the copy kernel count record that this entry keeps; - #12840 (EagleBearerYS) and #15845 (mehmetbayoglu) change the debt lines right after and right before it; - #16753 (chitters2004) changes the `readStart` line just before each of the three added calls. It could not compare 75 more that conflict with `main`. In GitHub's patch of each, context lines included: - #1896 (fisherjoey, draft) adds another copy of the CPU read in `finishDraw`, which would need the same call; - #13863 and #13920 (Celegans12) change the wait inside `FinishLeaseWork` (`FinishThroughOpened` while an async lane is active); that step is now shared with `FinishLeaseWrites`, so whichever lands second changes it once, for both; - #5925 (adriadam10) changes the debt entry right after this one, and #14212 (janzezno) adds blank lines between the entries of that file; - #10442 (Dripl1x, draft) changes a line two below the `CountLeaseOutcome` call in `keepRecordedDraw`, and #10193, #13928 and #13929 (Celegans12) insert one three below, with unchanged lines between. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> Windows 10 Pro 22H2 (19045), i9-12900KF, NVIDIA GeForce RTX 5080 (`10de:2c02`, driver 621.14), WinLibs GCC 15.2.0, Release, `BUILD_TESTING=ON`, with `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1`. Head `c95426ff42` merged onto `main` `52c33518f8` unless stated. - The new test, `ctest -R '^agc_driver_indirect_draw_pending_producer' -V`: all four registrations pass, each log with `Selected GPU name=NVIDIA GeForce RTX 5080`. - With parts of the change removed (each reverted afterwards, and the test exe rebuilt each time so the `libSceAgcDriver.prx` staged next to it was the one just built): | Removed | Fails | |---|---| | the three waits | the records and count cases (all three registrations that run them) and `_gpu_indirect_disabled` | | the wait in the empty-draw skip | the count case | | the wait in `finishDraw` | the records case | | the wait in `prepareDraw` | `_gpu_indirect_disabled` | | `writes` forced to true | the read-only case | | `writes` forced to false | every writer case | These ran on this change before its rebase onto `52c33518f8`; the 27 commits it moved over change no `libSceAgcDriver` file. - Reverting only `Execution/src/Driver/Draw/Draw.cpp` (the two driver waits) in the merge: 3 of the 4 registrations fail; `_gpu_indirect_disabled`, which the `prepareDraw` wait covers, passes. Restored, all 4 pass. - `agc_driver_pipelined_indirect_draw`, `agc_driver_indirect_arguments_pending_producer`, `agc_driver_indexed_copy_gpu_parameters`, `agc_driver_queued_indirect_read_order` and `agc_driver_empty_indirect_skip` pass. - Selected tests: `tools/select_tests.py` picks 2,685 tests for the changed files, and `select_tests.py ctest build --parallel 4 --timeout 120` on the merge fails 3. Two of them, `agc_driver_quad_pixel_mask` (#14237) and `guest_kernel_sys_paths_symlinkat_patched` (a timeout), fail in `main` `52c33518f8`'s full suite on this machine too (4,824 tests; it also times out `guest_kernel_sys_paths_symlinkat`, which is not selected). The third, `agc_driver_unregistered_label_on_gpu`, passed three reruns. It fails on `main` too, now and then, with the same message ("the label held 0x00000000 when a later label had landed"): run alternately, 1 of 150 runs on `main` and 2 of 150 with this change failed (2 of 579 on `main` overall). From its code, it reaches none of the changed functions. The 13 tests that skip skip on `main` too. - Validation: the selected tests matching `^(agc|shader|recompiler|videoout|video_out|guest_video_out|vulkan)|gpu` (1,594 on the merge, 1,597 in `main`'s run), through `ctest -V --parallel 4` with `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation` (1.4.367) and `VK_LOADER_LAYERS_DISABLE=~implicit~`; all pass except `agc_driver_quad_pixel_mask` on both sides. Neither log has a `VUID-` line or `was not found but was requested by env var VK_INSTANCE_LAYERS`. Both have the same 61 `Undefined-Value-ShaderOutputNotConsumed`/`OutputNotWritten` warnings in the same 14 tests, and the four new registrations have none. A rerun of them on this head with `VK_LOADER_DEBUG=layer` shows `Insert instance layer "VK_LAYER_KHRONOS_validation"` 8 times. - Built again with `-DANYPS5_ENABLE_SPIRV_TOOLS=ON` (as the Linux CI job builds): the four registrations pass in three runs, 1.47 to 1.61 s each. - `python tools/check_test_registration.py build` and `python tools/check_conventions.py --base origin/main` (with this title and description) pass. - Rebased onto `main` `e37e9fa3f9` before opening (head `03334ebfd3`, `c95426ff42` with the debt entry's last sentence reworded); none of the 48 commits since `52c33518f8` touches `libSceAgcDriver` or the debt file, and the four registrations pass there. - Planet Zoo (PPSA18026), three pairs in alternating order on `main` `84f4ad4f06`, with an earlier head of this change whose library code differs only in names, this profile line's wording and the shared helper; `APS5_PROFILE_DRAW=1 APS5_TRACE_SUMMARY_EVERY=30 APS5_TRACE_BENCH=1 APS5_LOG_TIMESTAMPS=1`, 3 to 3.5 minutes of the same scene each, both sides carrying one local line, `sceAjmInitialize` comparing only the low 32 bits of its reserved argument as #16974 first proposed (it now drops the check; without the line this title faults in its Render thread). In every run with the change, the `[address-sync]` line counts 934 to 1,215 deferred leases and none by a build that stores through addresses, so the two driver sites never took the mutex. Frame times differed between runs of the same build by up to 13%, and between the two sides by less in both directions (mean 493.8 ms per present with the change, 499.3 without, after the first 60 s). Not covered: AMD and Intel GPUs, Linux (the test's `mmap` allocation path is not run here), a PS5, a title whose address-based stores these waits catch, and the four reads the debt entry keeps open. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: <!-- #PR, or none --> none - [x] Fixes: <!-- issue it closes as Fixes #N, or none --> none - [x] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> none - [x] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> NVIDIA GeForce RTX 5080, driver 621.14, Windows 10 22H2 (19045) - [x] AI-assisted: <!-- yes / no --> yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!17850
No description provided.