perf(agc): find a range's newest writer through a granule index instead of scanning the ring #12264

Merged
Tehshortbus merged 2 commits from upstream-pr/12264 into main 2026-10-29 20:19:11 +00:00
Tehshortbus commented 2026-10-28 05:56:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Tehshortbus on 2026-10-28T05:56:32Z.


What

Driver::newestWriterLocked (used by classifyPendingWrite when a capture reads memory with pending GPU writes, and by write evidence) walked the 4096-entry written-buffer ring from the newest entry on every lookup, so a range without a recorded writer cost a full walk. In GTA V cutscenes it was the hottest function on the packet thread not touched by an open pull request.

The ring is now a WrittenBufferIndex (Execution/include/Driver/Memory/WrittenBufferIndex.hpp). It keeps the same deque, capacity and eviction order, and also files each entry's position under the 64 KiB granules it covers; entries wider than 16 granules (1 MiB) go on a short list of their own so a large buffer does not make a push expensive. Newest(begin, end) walks only the query's granules and that list, newest first, applies the same overlap test as before and returns the newest match, so it returns the same entry as the walk (an empty entry is filed under the granule of its address, since the old test also matches it). Queries wider than 16 granules, and empty queries, still walk the ring. WrittenBuffer and WrittenBufferRing move into the new header unchanged; the three push sites call Push, and describeWriters iterates Entries().

Memory. The entries stay in the same 4096-entry deque as before (64 bytes each, 0.25 MiB). On top of that, the index keeps one unordered_map node with a std::deque<std::uint64_t> for each distinct 64 KiB granule that a non-wide entry covers. With its first 512-byte chunk, that is about 700 bytes per granule on libstdc++. A granule's 65th and later sequences cost 8 bytes each. A non-wide entry covers at most 16 granules, so the index files at most 4096 × 16 = 65,536 granules. Wider entries cost 8 bytes each on their own list. Measured with a counting operator new around the class (GCC 16.2.1, libstdc++), as the peak live heap of the class including its entries while pushing three times the ring capacity:

Last 4096 recorded writes Peak
one 4 KiB buffer, rewritten 0.30 MiB
4096 distinct 4 KiB buffers (1 granule each) 3.0 MiB
4096 distinct 256 KiB buffers (5 granules each) 14.0 MiB
4096 distinct buffers spanning 16 granules each (about 1 MiB, the widest that is indexed) 44.4 MiB
4096 distinct 2 MiB buffers (all on the wide list) 0.30 MiB

So the upper bound is about 44 MiB, against 0.25 MiB for the ring on main. It is reached only when the last 4096 recorded writes went to 4096 different buffers of about 1 MiB that share no granules. In GTA V (PPSA04264 01.011.001) the index stays far below that. I ran a 307 s session from the title through the save load, the first Story cutscene and 136 s of the second, with temporary counters sampled each second. The sample estimate counts the same allocations as the table and reads within 3 % of it, slightly high, for each row. The ring filled to 4096 entries within 66 s of the first recorded write. The peak was 2,360 granules and 639 wide entries, about 1.9 MiB, while the save loaded. During cutscene 1 the index held 25 to 65 granules (about 0.4 MiB), and during cutscene 2 at most 322 granules (about 0.5 MiB).

Tested

CachyOS Linux (kernel 7.3.0-4-cachyos), GCC 16.2.1, Release, NVIDIA GeForce RTX 4070 SUPER (615.78.08).

  • agc_written_buffer_index (new): pushes 20,000 random entries (empty, small, medium and wider than 1 MiB) into a 64-entry index, so it evicts constantly, and after each push compares 8 random queries (also empty and wider than 16 granules) against the linear walk over Entries(); plus explicit newest-wins and eviction cases. With the wide-entry list left out of Newest, it fails on the first differing query.

  • Focused tests, main 0cd07dc4ab and this change on it, with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation ctest --test-dir build-tests -V -R '^(agc_driver_copied_writer_copy|agc_driver_copied_writer_label_order|agc_driver_pending_exact_surface|agc_driver_indirect_arguments_pending_producer|agc_driver_gated_dispatch_capture|agc_space_pending_writes|agc_pending_write_snapshot|agc_written_buffer_index)$': main 7/7 pass, this change 8/8 pass; no VUID- line and no missing-layer message in either log. Under gdb, WrittenBufferIndex::Push is reached 65 times in agc_driver_gated_dispatch_capture and 85 times in agc_driver_indirect_arguments_pending_producer, and Newest 4 times in the latter; the other tests do not reach the ring, so the lookup's equivalence rests mainly on the new test.

  • GTA V (PPSA04264 01.011.001), perf record -F 499 -e cpu-clock:u --call-graph dwarf over the first 20 s of the first two Story cutscenes, one run per build, both on main 86fb985abb + #11580 (which the title needs, #11425) + #12244, the second with this change cherry-picked; same machine, warm shader cache. Share of all samples:

    cutscene 1: base → this cutscene 2: base → this
    newestWriterLocked (with callees) 0.65 % → 0.21 % 0.39 % → 0.04 %
    classifyPendingWrite (with callees) 0.60 % → 0.27 % 0.44 % → 0.07 %
    WrittenBufferIndex::Push + evictOldest – → 0.02 % – → 0.02 %
    queue worker 0 busy (user time) 56.8 % → 57.5 % 64.2 % → 64.2 %

    The saving is about 1 % of the packet thread, below the run-to-run variation of whole-thread and frame-time numbers, so I am not claiming a frame-rate change.

  • Performance captures (details, alignment and trace_digest.py output in the comment below; traces attached there): aps5-summary.jsonl lines of the 75–105 s window, base 9f2d365268 then this PR e98000093a:

    {"commit":"9f2d365268de","dirty":false,"env":{"APS5_TRACE_DIR":"<path>","APS5_TRACE_EVENTS":"4194304","APS5_TRACE_SECONDS":"75:30","APS5_TRACE_SUMMARY_EVERY":"10"},"gpu":"NVIDIA GeForce RTX 4070 SUPER","driver":"NVIDIA 615.78.08","os":"Linux 7.3.0-4-cachyos","cpu":"AMD Ryzen 7 5800X 8-Core Processor","cpu_threads":16,"memory_mib":64203,"title_id":"PPSA04264","title":"Grand Theft Auto V","content_version":"01.011.001","resolution":"3840x2160","window":{"spec":"seconds 75:30","first_present":2444,"ms":30014.412},"presents":403,"frame_ms":{"p50":73.748,"p90":79.862,"p99":110.775,"max":138.755},"gpu_busy_ms_per_present":36.963,"worker_busy_pct":{"queue worker 0x0":97.973},"top_phases_ms_per_frame":{"Driver.Packet":69.797,"Graphics.Draw":41.297,"Driver.Packet.draw":37.758,"Driver.Draw":37.408,"Graphics.Draw.draw_and_resource_release":35.681,"Driver.Packet.dispatch":24.439,"Driver.Draw.shader_compile_and_link":24.424,"Shader.DrawStage":18.971},"trace_dropped":false,"trace":"aps5-trace-9f2d365268de-1333741.json.gz"}
    {"commit":"e98000093a1a","dirty":false,"env":{"APS5_TRACE_DIR":"<path>","APS5_TRACE_EVENTS":"4194304","APS5_TRACE_SECONDS":"75:30","APS5_TRACE_SUMMARY_EVERY":"10"},"gpu":"NVIDIA GeForce RTX 4070 SUPER","driver":"NVIDIA 615.78.08","os":"Linux 7.3.0-4-cachyos","cpu":"AMD Ryzen 7 5800X 8-Core Processor","cpu_threads":16,"memory_mib":64203,"title_id":"PPSA04264","title":"Grand Theft Auto V","content_version":"01.011.001","resolution":"3840x2160","window":{"spec":"seconds 75:30","first_present":2741,"ms":30014.360},"presents":451,"frame_ms":{"p50":68.988,"p90":76.357,"p99":108.921,"max":588.045},"gpu_busy_ms_per_present":33.496,"worker_busy_pct":{"queue worker 0x0":93.744},"top_phases_ms_per_frame":{"Driver.Packet":59.260,"Graphics.Draw":33.805,"Graphics.Draw.draw_and_resource_release":29.403,"Driver.Packet.draw":29.328,"Driver.Draw":29.035,"Driver.Packet.dispatch":20.850,"Driver.Draw.shader_compile_and_link":18.695,"Recorder.Sync":16.659},"trace_dropped":false,"trace":"aps5-trace-e98000093a1a-1327440.json.gz"}
    
  • python3 tools/check_conventions.py --base origin/main passes.

Overlap: tools/pr_overlap.py reports #11439, which changes the program argument of the writtenBuffers.push_back call in BufferCopy.cpp (L131) that this PR turns into writtenBuffers.Push. Whichever merges second keeps #11439's argument inside the other call; no behaviour overlaps. The 66 pull requests it lists as not compared (they conflict with main) share CMakeLists.txt or Driver.hpp; I checked their diffs (#5021 by its file list and its CMakeLists.txt patch, since its full diff is too large to fetch): none adds, removes or edits the writtenBuffers member, WrittenBuffer, WrittenBufferRing or newestWriterLocked.

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 4070 SUPER, driver 615.78.08, CachyOS Linux (kernel 7.3.0-4-cachyos)
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5045933057 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12264). Originally posted by [Tehshortbus](https://github.com/Tehshortbus) on 2026-10-28T05:56:32Z. --- ### What `Driver::newestWriterLocked` (used by `classifyPendingWrite` when a capture reads memory with pending GPU writes, and by write evidence) walked the 4096-entry written-buffer ring from the newest entry on every lookup, so a range without a recorded writer cost a full walk. In GTA V cutscenes it was the hottest function on the packet thread not touched by an open pull request. The ring is now a `WrittenBufferIndex` (`Execution/include/Driver/Memory/WrittenBufferIndex.hpp`). It keeps the same deque, capacity and eviction order, and also files each entry's position under the 64 KiB granules it covers; entries wider than 16 granules (1 MiB) go on a short list of their own so a large buffer does not make a push expensive. `Newest(begin, end)` walks only the query's granules and that list, newest first, applies the same overlap test as before and returns the newest match, so it returns the same entry as the walk (an empty entry is filed under the granule of its address, since the old test also matches it). Queries wider than 16 granules, and empty queries, still walk the ring. `WrittenBuffer` and `WrittenBufferRing` move into the new header unchanged; the three push sites call `Push`, and `describeWriters` iterates `Entries()`. **Memory.** The entries stay in the same 4096-entry deque as before (64 bytes each, 0.25 MiB). On top of that, the index keeps one `unordered_map` node with a `std::deque<std::uint64_t>` for each distinct 64 KiB granule that a non-wide entry covers. With its first 512-byte chunk, that is about 700 bytes per granule on libstdc++. A granule's 65th and later sequences cost 8 bytes each. A non-wide entry covers at most 16 granules, so the index files at most 4096 × 16 = 65,536 granules. Wider entries cost 8 bytes each on their own list. Measured with a counting `operator new` around the class (GCC 16.2.1, libstdc++), as the peak live heap of the class including its entries while pushing three times the ring capacity: | Last 4096 recorded writes | Peak | |---|---| | one 4 KiB buffer, rewritten | 0.30 MiB | | 4096 distinct 4 KiB buffers (1 granule each) | 3.0 MiB | | 4096 distinct 256 KiB buffers (5 granules each) | 14.0 MiB | | 4096 distinct buffers spanning 16 granules each (about 1 MiB, the widest that is indexed) | 44.4 MiB | | 4096 distinct 2 MiB buffers (all on the wide list) | 0.30 MiB | So the upper bound is about 44 MiB, against 0.25 MiB for the ring on `main`. It is reached only when the last 4096 recorded writes went to 4096 different buffers of about 1 MiB that share no granules. In GTA V (PPSA04264 01.011.001) the index stays far below that. I ran a 307 s session from the title through the save load, the first Story cutscene and 136 s of the second, with temporary counters sampled each second. The sample estimate counts the same allocations as the table and reads within 3 % of it, slightly high, for each row. The ring filled to 4096 entries within 66 s of the first recorded write. The peak was 2,360 granules and 639 wide entries, about 1.9 MiB, while the save loaded. During cutscene 1 the index held 25 to 65 granules (about 0.4 MiB), and during cutscene 2 at most 322 granules (about 0.5 MiB). ### 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. --> CachyOS Linux (kernel 7.3.0-4-cachyos), GCC 16.2.1, Release, NVIDIA GeForce RTX 4070 SUPER (615.78.08). - **`agc_written_buffer_index` (new):** pushes 20,000 random entries (empty, small, medium and wider than 1 MiB) into a 64-entry index, so it evicts constantly, and after each push compares 8 random queries (also empty and wider than 16 granules) against the linear walk over `Entries()`; plus explicit newest-wins and eviction cases. With the wide-entry list left out of `Newest`, it fails on the first differing query. - **Focused tests**, `main` `0cd07dc4ab` and this change on it, with `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation ctest --test-dir build-tests -V -R '^(agc_driver_copied_writer_copy|agc_driver_copied_writer_label_order|agc_driver_pending_exact_surface|agc_driver_indirect_arguments_pending_producer|agc_driver_gated_dispatch_capture|agc_space_pending_writes|agc_pending_write_snapshot|agc_written_buffer_index)$'`: `main` 7/7 pass, this change 8/8 pass; no `VUID-` line and no missing-layer message in either log. Under gdb, `WrittenBufferIndex::Push` is reached 65 times in `agc_driver_gated_dispatch_capture` and 85 times in `agc_driver_indirect_arguments_pending_producer`, and `Newest` 4 times in the latter; the other tests do not reach the ring, so the lookup's equivalence rests mainly on the new test. - **GTA V** (PPSA04264 01.011.001), `perf record -F 499 -e cpu-clock:u --call-graph dwarf` over the first 20 s of the first two Story cutscenes, one run per build, both on `main` `86fb985abb` + #11580 (which the title needs, #11425) + #12244, the second with this change cherry-picked; same machine, warm shader cache. Share of all samples: | | cutscene 1: base → this | cutscene 2: base → this | |---|---|---| | `newestWriterLocked` (with callees) | 0.65 % → 0.21 % | 0.39 % → 0.04 % | | `classifyPendingWrite` (with callees) | 0.60 % → 0.27 % | 0.44 % → 0.07 % | | `WrittenBufferIndex::Push` + `evictOldest` | – → 0.02 % | – → 0.02 % | | queue worker 0 busy (user time) | 56.8 % → 57.5 % | 64.2 % → 64.2 % | The saving is about 1 % of the packet thread, below the run-to-run variation of whole-thread and frame-time numbers, so I am not claiming a frame-rate change. - **Performance captures** (details, alignment and `trace_digest.py` output in the comment below; traces attached there): `aps5-summary.jsonl` lines of the 75–105 s window, base `9f2d365268` then this PR `e98000093a`: ```json {"commit":"9f2d365268de","dirty":false,"env":{"APS5_TRACE_DIR":"<path>","APS5_TRACE_EVENTS":"4194304","APS5_TRACE_SECONDS":"75:30","APS5_TRACE_SUMMARY_EVERY":"10"},"gpu":"NVIDIA GeForce RTX 4070 SUPER","driver":"NVIDIA 615.78.08","os":"Linux 7.3.0-4-cachyos","cpu":"AMD Ryzen 7 5800X 8-Core Processor","cpu_threads":16,"memory_mib":64203,"title_id":"PPSA04264","title":"Grand Theft Auto V","content_version":"01.011.001","resolution":"3840x2160","window":{"spec":"seconds 75:30","first_present":2444,"ms":30014.412},"presents":403,"frame_ms":{"p50":73.748,"p90":79.862,"p99":110.775,"max":138.755},"gpu_busy_ms_per_present":36.963,"worker_busy_pct":{"queue worker 0x0":97.973},"top_phases_ms_per_frame":{"Driver.Packet":69.797,"Graphics.Draw":41.297,"Driver.Packet.draw":37.758,"Driver.Draw":37.408,"Graphics.Draw.draw_and_resource_release":35.681,"Driver.Packet.dispatch":24.439,"Driver.Draw.shader_compile_and_link":24.424,"Shader.DrawStage":18.971},"trace_dropped":false,"trace":"aps5-trace-9f2d365268de-1333741.json.gz"} {"commit":"e98000093a1a","dirty":false,"env":{"APS5_TRACE_DIR":"<path>","APS5_TRACE_EVENTS":"4194304","APS5_TRACE_SECONDS":"75:30","APS5_TRACE_SUMMARY_EVERY":"10"},"gpu":"NVIDIA GeForce RTX 4070 SUPER","driver":"NVIDIA 615.78.08","os":"Linux 7.3.0-4-cachyos","cpu":"AMD Ryzen 7 5800X 8-Core Processor","cpu_threads":16,"memory_mib":64203,"title_id":"PPSA04264","title":"Grand Theft Auto V","content_version":"01.011.001","resolution":"3840x2160","window":{"spec":"seconds 75:30","first_present":2741,"ms":30014.360},"presents":451,"frame_ms":{"p50":68.988,"p90":76.357,"p99":108.921,"max":588.045},"gpu_busy_ms_per_present":33.496,"worker_busy_pct":{"queue worker 0x0":93.744},"top_phases_ms_per_frame":{"Driver.Packet":59.260,"Graphics.Draw":33.805,"Graphics.Draw.draw_and_resource_release":29.403,"Driver.Packet.draw":29.328,"Driver.Draw":29.035,"Driver.Packet.dispatch":20.850,"Driver.Draw.shader_compile_and_link":18.695,"Recorder.Sync":16.659},"trace_dropped":false,"trace":"aps5-trace-e98000093a1a-1327440.json.gz"} ``` - `python3 tools/check_conventions.py --base origin/main` passes. **Overlap:** `tools/pr_overlap.py` reports #11439, which changes the `program` argument of the `writtenBuffers.push_back` call in `BufferCopy.cpp` (L131) that this PR turns into `writtenBuffers.Push`. Whichever merges second keeps #11439's argument inside the other call; no behaviour overlaps. The 66 pull requests it lists as not compared (they conflict with `main`) share `CMakeLists.txt` or `Driver.hpp`; I checked their diffs (#5021 by its file list and its `CMakeLists.txt` patch, since its full diff is too large to fetch): none adds, removes or edits the `writtenBuffers` member, `WrittenBuffer`, `WrittenBufferRing` or `newestWriterLocked`. ### 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: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: NVIDIA GeForce RTX 4070 SUPER, driver 615.78.08, CachyOS Linux (kernel 7.3.0-4-cachyos) - [x] AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-10-28 09:07:19 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-28T09:07:19Z.

Review: APPROVED


Reviewed the index against the previous reverse linear scan. Each entry is indexed in every 64 KiB granule it overlaps (or the wide-entry list), eviction removes exactly the oldest sequence, and candidates are rechecked with the original half-open overlap predicate before choosing the newest sequence. The randomized differential test also covers empty and wide queries, eviction, and newest-wins behavior. The PR now quantifies index memory and reports paired title captures, trace summaries, same-GPU focused baseline/change tests, no new VUIDs, and validation-layer presence. Hosted Windows and conventions pass; the other product build jobs are skipped by eligibility. The reported modest lookup improvement is scoped appropriately and does not claim a frame-rate win. No remaining blocker found.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5680170438 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12264#pullrequestreview-5680170438). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-28T09:07:19Z. **Review:** APPROVED --- Reviewed the index against the previous reverse linear scan. Each entry is indexed in every 64 KiB granule it overlaps (or the wide-entry list), eviction removes exactly the oldest sequence, and candidates are rechecked with the original half-open overlap predicate before choosing the newest sequence. The randomized differential test also covers empty and wide queries, eviction, and newest-wins behavior. The PR now quantifies index memory and reports paired title captures, trace summaries, same-GPU focused baseline/change tests, no new VUIDs, and validation-layer presence. Hosted Windows and conventions pass; the other product build jobs are skipped by eligibility. The reported modest lookup improvement is scoped appropriately and does not claim a frame-rate win. No remaining blocker found.
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!12264
No description provided.