fix(agc): evict unreferenced heap mirrors under memory pressure #13581

Merged
ashwin280802 merged 3 commits from upstream-pr/13581 into main 2026-10-31 20:01:11 +00:00
ashwin280802 commented 2026-10-30 18:47:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ashwin280802 on 2026-10-30T18:47:06Z.


What

When device heap mirrors exceed heapMirrorBudget(), reserveHeapBytes and growResident invoke sweepMirrors(need, address) to reclaim memory. Previously, sweepMirrors only freed mirrors whose underlying registered guest range had expired (range.expired()). In titles where numerous heap ranges are registered upfront via direct memory allocations (sceKernelAllocateDirectMemory), ranges do not expire during execution, leading to heap mirror memory accumulation and aborting with past the budget.

This change extends sweepMirrors under budget pressure (neededBytes != 0 && state.heapBytes + neededBytes > heapMirrorBudget()) to evict unreferenced heap mirrors (it->second->heap && it->first != protectAddress, with use_count() == 1, or == 2 for a read-only mirror the active build holds):

  • LRU & Writability Selection: Candidates are ranked by LRU dispatch timestamp (lastDispatch), tie-broken by preferring read-only mirrors (!writable) over writable mirrors to avoid dirty copy-backs.
  • Active Build Protection: Building dispatches protect active writable targets ((buildingHolds && !it->second->writable) ? 2 : 1) while allowing speculative read-only mirrors to yield. Evicted addresses are recorded via RecordEvicted so the same build does not re-acquire them.
  • Eviction inside a build: EvictMirror resets the evicted mirror's region in place (host-backed, with its committed ranges recorded as backed/sparse). It does not add regions while regions is being iterated. The raw heaps list used by refreshHeapMirrors is collected after the region loop from the regions that still hold a non-sparse heap mirror, so a mirror evicted mid-build never reaches it. Evicted mirrors are moved into a list that is destroyed after state.mutex is released.
  • Mirrors with queued refresh blocks are not evicted: while a build runs, sweepMirrors skips any mirror that has RefreshBlocks queued in that build. Those blocks hold raw ImageMirror* pointers and are used by compareBlocks / bindHeapBlocks, and growResident can reach sweepMirrors from inside them. If no other candidate is left, the build throws past the budget, as it did before this change.
  • Scoped Cache Invalidation: The cached address space is dropped (Spaces().current.exchange(nullptr)) only when the sweep is under memory pressure, not on ordinary cache misses. A build that evicted a mirror does not store its address space in Spaces().current.
  • Telemetry: Added evictions counter to struct MirrorStats, MirrorCounters(), and formatted in AgcDriver::ProfilePrint_nid_no_patch.

Tested

  • Windows 11 24H2, Intel Core i5-14600K, NVIDIA GeForce RTX 5070 (Driver 617.42, Vulkan API 1.4.303).
  • Linux: Docker container (Ubuntu 24.04), WSL2 kernel 6.18.54.1, Mesa llvmpipe (lavapipe), no /dev/udmabuf, ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1, run with --security-opt seccomp=unconfined --cap-add SYS_PTRACE so the guest write watch is available. agc_driver_resident_heap_mirror passes.
  • Unit tests: agc_driver_resident_heap_mirror (ResidentHeapMirror.cpp), covering:
    • Multi-dispatch eviction: live registered heap mirror is evicted under budget constraint when a subsequent dispatch requires memory.
    • Reference retention: active mirror handle held via HoldHeapMirror prevents eviction and throws past the budget.
    • Build-time eviction: an earlier read-only mirror held by the active build is evicted under budget constraint (allowedCount == 2), its region reset in place by EvictMirror, recorded in evictedRanges to prevent re-acquire, and the shader output bits verified exactly.
    • Re-upload correctness: evicted live range is seamlessly re-uploaded into a mirror on subsequent dispatch, evicting the older mirror.
    • Fallback budget scaling: budget scales across sparse (Block) and whole-copy fallback (HeapBytes) configurations.
    • Negative control: dispatches exceeding budget without evictable unreferenced mirrors throw past the budget.
    • Mutation controls, each run with the test rebuilt and ctest -V:
      • Eviction loop in sweepMirrors replaced by while (false): fails on Windows and on Linux/lavapipe with AGC graphics: heap mirror of 0x...+0x800000: past the budget; heap mirrors hold 0 MiB of 0 MiB (APS5_HEAP_MIRROR_MIB).
      • Spaces().current.exchange(nullptr) removed from the pressure branch: fails on Windows with the same past the budget error.
    • Not covered by a test: the skip of mirrors with queued refresh blocks. With the skip removed, agc_driver_resident_heap_mirror still passes on Windows and on Linux, and an ANYPS5_ENABLE_ASAN=ON build on lavapipe reports nothing. A subcase that grows a second mirror under an exact budget passed with and without the skip, so it is not included. That change is argued from the code, not demonstrated by a failing test.
  • Broader suite on the rebased branch (Windows, RTX 5070, VK_LAYER_KHRONOS_validation): ctest -R '^agc_driver_(resident|host_import|bda|address)', 19 of 19 passed.
  • Vulkan validation layer comparison:
    • Ran ctest --test-dir build-full -R "agc_driver_resident_heap_mirror|agc_driver_bda_span_reads|agc_driver_address_passes" -V with ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1, and VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation.
    • Confirmed VK_LAYER_KHRONOS_validation loaded cleanly.
    • Verified 0 new VUID- validation errors logged. The Linux/lavapipe run did not use the validation layers.
  • Conventions check: python3 tools/check_conventions.py --base origin/main passed with 0 errors.
  • Memory pressure robustness verification (before the later review fixes; not re-run on the latest head):
    • Validated under constrained heap mirror budgets (APS5_HEAP_MIRROR_MIB=1536) on Ghost of Yōtei (PPSA26344, 1920x1080).
    • Baseline aborts with past the budget when unreferenced direct-memory-backed mirrors saturate the budget ceiling.
    • Candidate survives, actively evicts unreferenced heap mirrors (evictions > 0), and bounds device heap consumption within the configured limit without leaks or corruptions.

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 5070, Driver 617.42, Windows 11 24H2
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5089441789 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581). Originally posted by [ashwin280802](https://github.com/ashwin280802) on 2026-10-30T18:47:06Z. --- ### What When device heap mirrors exceed `heapMirrorBudget()`, `reserveHeapBytes` and `growResident` invoke `sweepMirrors(need, address)` to reclaim memory. Previously, `sweepMirrors` only freed mirrors whose underlying registered guest range had expired (`range.expired()`). In titles where numerous heap ranges are registered upfront via direct memory allocations (`sceKernelAllocateDirectMemory`), ranges do not expire during execution, leading to heap mirror memory accumulation and aborting with `past the budget`. This change extends `sweepMirrors` under budget pressure (`neededBytes != 0 && state.heapBytes + neededBytes > heapMirrorBudget()`) to evict unreferenced heap mirrors (`it->second->heap && it->first != protectAddress`, with `use_count() == 1`, or `== 2` for a read-only mirror the active build holds): - **LRU & Writability Selection**: Candidates are ranked by LRU dispatch timestamp (`lastDispatch`), tie-broken by preferring read-only mirrors (`!writable`) over writable mirrors to avoid dirty copy-backs. - **Active Build Protection**: Building dispatches protect active writable targets (`(buildingHolds && !it->second->writable) ? 2 : 1`) while allowing speculative read-only mirrors to yield. Evicted addresses are recorded via `RecordEvicted` so the same build does not re-acquire them. - **Eviction inside a build**: `EvictMirror` resets the evicted mirror's region in place (host-backed, with its committed ranges recorded as `backed`/`sparse`). It does not add regions while `regions` is being iterated. The raw `heaps` list used by `refreshHeapMirrors` is collected after the region loop from the regions that still hold a non-sparse heap mirror, so a mirror evicted mid-build never reaches it. Evicted mirrors are moved into a list that is destroyed after `state.mutex` is released. - **Mirrors with queued refresh blocks are not evicted**: while a build runs, `sweepMirrors` skips any mirror that has `RefreshBlock`s queued in that build. Those blocks hold raw `ImageMirror*` pointers and are used by `compareBlocks` / `bindHeapBlocks`, and `growResident` can reach `sweepMirrors` from inside them. If no other candidate is left, the build throws `past the budget`, as it did before this change. - **Scoped Cache Invalidation**: The cached address space is dropped (`Spaces().current.exchange(nullptr)`) only when the sweep is under memory pressure, not on ordinary cache misses. A build that evicted a mirror does not store its address space in `Spaces().current`. - **Telemetry**: Added `evictions` counter to `struct MirrorStats`, `MirrorCounters()`, and formatted in `AgcDriver::ProfilePrint_nid_no_patch`. ### Tested - Windows 11 24H2, Intel Core i5-14600K, NVIDIA GeForce RTX 5070 (Driver 617.42, Vulkan API 1.4.303). - Linux: Docker container (Ubuntu 24.04), WSL2 kernel 6.18.54.1, Mesa llvmpipe (lavapipe), no `/dev/udmabuf`, `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1`, run with `--security-opt seccomp=unconfined --cap-add SYS_PTRACE` so the guest write watch is available. `agc_driver_resident_heap_mirror` passes. - Unit tests: `agc_driver_resident_heap_mirror` (`ResidentHeapMirror.cpp`), covering: - Multi-dispatch eviction: live registered heap mirror is evicted under budget constraint when a subsequent dispatch requires memory. - Reference retention: active mirror handle held via `HoldHeapMirror` prevents eviction and throws `past the budget`. - Build-time eviction: an earlier read-only mirror held by the active build is evicted under budget constraint (`allowedCount == 2`), its region reset in place by `EvictMirror`, recorded in `evictedRanges` to prevent re-acquire, and the shader output bits verified exactly. - Re-upload correctness: evicted live range is seamlessly re-uploaded into a mirror on subsequent dispatch, evicting the older mirror. - Fallback budget scaling: budget scales across sparse (`Block`) and whole-copy fallback (`HeapBytes`) configurations. - Negative control: dispatches exceeding budget without evictable unreferenced mirrors throw `past the budget`. - Mutation controls, each run with the test rebuilt and `ctest -V`: - Eviction loop in `sweepMirrors` replaced by `while (false)`: fails on Windows and on Linux/lavapipe with `AGC graphics: heap mirror of 0x...+0x800000: past the budget; heap mirrors hold 0 MiB of 0 MiB (APS5_HEAP_MIRROR_MIB)`. - `Spaces().current.exchange(nullptr)` removed from the pressure branch: fails on Windows with the same `past the budget` error. - **Not covered by a test**: the skip of mirrors with queued refresh blocks. With the skip removed, `agc_driver_resident_heap_mirror` still passes on Windows and on Linux, and an `ANYPS5_ENABLE_ASAN=ON` build on lavapipe reports nothing. A subcase that grows a second mirror under an exact budget passed with and without the skip, so it is not included. That change is argued from the code, not demonstrated by a failing test. - Broader suite on the rebased branch (Windows, RTX 5070, `VK_LAYER_KHRONOS_validation`): `ctest -R '^agc_driver_(resident|host_import|bda|address)'`, 19 of 19 passed. - Vulkan validation layer comparison: - Ran `ctest --test-dir build-full -R "agc_driver_resident_heap_mirror|agc_driver_bda_span_reads|agc_driver_address_passes" -V` with `ANYPS5_REQUIRE_VULKAN=1`, `ANYPS5_NO_SHADER_CACHE=1`, and `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`. - Confirmed `VK_LAYER_KHRONOS_validation` loaded cleanly. - Verified 0 new `VUID-` validation errors logged. The Linux/lavapipe run did not use the validation layers. - Conventions check: `python3 tools/check_conventions.py --base origin/main` passed with 0 errors. - Memory pressure robustness verification (before the later review fixes; not re-run on the latest head): - Validated under constrained heap mirror budgets (`APS5_HEAP_MIRROR_MIB=1536`) on *Ghost of Yōtei* (`PPSA26344`, 1920x1080). - Baseline aborts with `past the budget` when unreferenced direct-memory-backed mirrors saturate the budget ceiling. - Candidate survives, actively evicts unreferenced heap mirrors (`evictions > 0`), and bounds device heap consumption within the configured limit without leaks or corruptions. ### 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 5070, Driver 617.42, Windows 11 24H2 - [x] AI-assisted: yes
adriadam10 commented 2026-10-31 03:52:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-31T03:52:01Z.

Review: CHANGES_REQUESTED


Thanks for the rework; points 2 (budget per sparse/whole-copy mode) and the scoping of the cache invalidation are addressed. Still open:

  • GuestBufferMemory.cpp:3312-3316: Spaces().current.exchange(nullptr) runs whenever neededBytes != 0, before the budget is checked again after the expired-range sweep, so the cached space is dropped even if the expired sweep already freed enough. The description says it only happens under memory pressure; move it inside the heapBytes + neededBytes > heapMirrorBudget() branch.
  • ResidentHeapMirror.cpp:390-453: the mutation controls @oneandonlydean asked for are missing. Show that removing only the use_count() eviction loop, and separately the current.exchange(nullptr) line, turns agc_driver_resident_heap_mirror red.
  • GuestBufferMemory.cpp:3345-3364,4427-4445: the build-time path (read-only mirror held by the current build is evicted with allowedCount == 2, EvictMirror resets the region and addCopiedRange, evictedRanges skips re-acquire) is not exercised by any test: the test dispatches complete before the next one starts. Add a dispatch where the budget is hit while an earlier region of the same build holds a read-only heap mirror, and check the result bits.
  • Evidence: the candidate trace is c2181e0e05d2 (dirty), not this head. Please attach the raw aps5-summary.jsonl lines (main and this head, same scene/machine) and the image-mirror report of both arms showing evictions. Both arms finish all 624 presents, so the numbers don't show the past the budget failure; either show a run where main aborts and this head doesn't, or drop the perf claim (the perf label asks for the two summary lines).
  • PR overlap bot lists #8874 on GuestBufferMemory.cpp L3299-3301 (sweepMirrors); please check the conflict and list it under Depends on if related.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5721043166 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581#pullrequestreview-5721043166). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-31T03:52:01Z. **Review:** CHANGES_REQUESTED --- Thanks for the rework; points 2 (budget per sparse/whole-copy mode) and the scoping of the cache invalidation are addressed. Still open: - `GuestBufferMemory.cpp:3312-3316`: `Spaces().current.exchange(nullptr)` runs whenever `neededBytes != 0`, before the budget is checked again after the expired-range sweep, so the cached space is dropped even if the expired sweep already freed enough. The description says it only happens under memory pressure; move it inside the `heapBytes + neededBytes > heapMirrorBudget()` branch. - `ResidentHeapMirror.cpp:390-453`: the mutation controls @oneandonlydean asked for are missing. Show that removing only the `use_count()` eviction loop, and separately the `current.exchange(nullptr)` line, turns `agc_driver_resident_heap_mirror` red. - `GuestBufferMemory.cpp:3345-3364,4427-4445`: the build-time path (read-only mirror held by the current build is evicted with `allowedCount == 2`, `EvictMirror` resets the region and `addCopiedRange`, `evictedRanges` skips re-acquire) is not exercised by any test: the test dispatches complete before the next one starts. Add a dispatch where the budget is hit while an earlier region of the same build holds a read-only heap mirror, and check the result bits. - Evidence: the candidate trace is `c2181e0e05d2 (dirty)`, not this head. Please attach the raw `aps5-summary.jsonl` lines (main and this head, same scene/machine) and the image-mirror report of both arms showing `evictions`. Both arms finish all 624 presents, so the numbers don't show the `past the budget` failure; either show a run where main aborts and this head doesn't, or drop the perf claim (the `perf` label asks for the two summary lines). - PR overlap bot lists #8874 on `GuestBufferMemory.cpp` L3299-3301 (`sweepMirrors`); please check the conflict and list it under Depends on if related.
adriadam10 commented 2026-10-31 04:58:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-31T04:58:33Z.

Review: CHANGES_REQUESTED


Thanks for the update; the cache-invalidation scoping, the dropped perf claim and the #8874 answer are fine. Still open:

  • ResidentHeapMirror.cpp:444-456: the build-time block can't pass as written. buildLater is never dispatched, so HeapMirrorsWithin(buildLater...) == 1 has nothing to count, and after Dispatch(device, buildEarly, ...) the mirror of buildEarly exists (the eviction under budget hits first), so == 0 fails too. The allowedCount == 2 path needs one build that holds a read-only heap mirror and then hits the budget while acquiring another new heap in the same dispatch (e.g. read heap fresh and a fresh written heap, budget for one mirror). Add that dispatch and check the result bits.
  • The NVIDIA run (RTX 2000 Ada, head 922e388) failed agc_driver_resident_heap_mirror at budget eviction: referenced mirror was evicted under budget constraint (ResidentHeapMirror.cpp:420): the dispatch with both mirrors held did not throw. Please explain why that happens on NVIDIA and show the test green on the new head with ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1, VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation (log, not a summary).
  • The mutation controls (no use_count() loop, no current.exchange(nullptr)) are described in prose; paste the failing ctest output for each once the test above is fixed, since the test changes.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5721370676 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581#pullrequestreview-5721370676). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-31T04:58:33Z. **Review:** CHANGES_REQUESTED --- Thanks for the update; the cache-invalidation scoping, the dropped perf claim and the #8874 answer are fine. Still open: - `ResidentHeapMirror.cpp:444-456`: the build-time block can't pass as written. `buildLater` is never dispatched, so `HeapMirrorsWithin(buildLater...) == 1` has nothing to count, and after `Dispatch(device, buildEarly, ...)` the mirror of `buildEarly` exists (the eviction under budget hits `first`), so `== 0` fails too. The `allowedCount == 2` path needs one build that holds a read-only heap mirror and then hits the budget while acquiring another new heap in the same dispatch (e.g. read heap fresh and a fresh `written` heap, budget for one mirror). Add that dispatch and check the result bits. - The NVIDIA run (RTX 2000 Ada, head `922e388`) failed `agc_driver_resident_heap_mirror` at `budget eviction: referenced mirror was evicted under budget constraint` (`ResidentHeapMirror.cpp:420`): the dispatch with both mirrors held did not throw. Please explain why that happens on NVIDIA and show the test green on the new head with `ANYPS5_REQUIRE_VULKAN=1`, `ANYPS5_NO_SHADER_CACHE=1`, `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation` (log, not a summary). - The mutation controls (no `use_count()` loop, no `current.exchange(nullptr)`) are described in prose; paste the failing ctest output for each once the test above is fixed, since the test changes.
adriadam10 commented 2026-10-31 06:40:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-31T06:40:46Z.

Review: CHANGES_REQUESTED


The full Build on this head fails on Linux (lavapipe, no /dev/udmabuf), run 41176505024:

  • agc_driver_resident_heap_mirror fails after 0.74 s with the uncaught AGC graphics: heap mirror of 0x78e414600000+0x800000: past the budget. Main does not have this test, so it comes from this PR.
  • The device is sparse-capable (no whole-copy notice in the log), so mirrorUnit is Block. The exception comes from one of the dispatches in BudgetEvictionTests that has no try/catch: the first dispatch, second, the re-upload, or the build-time block with a 1-unit budget (ResidentHeapMirror.cpp:456-474). My suspect is the build-time one: if anything else still holds freshRead's mirror (the cached address space or a lease), its use_count() is above allowedCount == 2 and it is not evicted. I could not run it here to confirm.

Please reproduce with lavapipe (VK_ICD_FILENAMES for lvp, ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1) and fix either the eviction rule or the test so it passes on both RTX and lavapipe. The test also has to hold without /dev/udmabuf, as on the CI runner.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5721669912 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581#pullrequestreview-5721669912). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-31T06:40:46Z. **Review:** CHANGES_REQUESTED --- The full Build on this head fails on Linux (lavapipe, no `/dev/udmabuf`), run 41176505024: - `agc_driver_resident_heap_mirror` fails after 0.74 s with the uncaught `AGC graphics: heap mirror of 0x78e414600000+0x800000: past the budget`. Main does not have this test, so it comes from this PR. - The device is sparse-capable (no whole-copy notice in the log), so `mirrorUnit` is `Block`. The exception comes from one of the dispatches in `BudgetEvictionTests` that has no try/catch: the first dispatch, `second`, the re-upload, or the build-time block with a 1-unit budget (`ResidentHeapMirror.cpp:456-474`). My suspect is the build-time one: if anything else still holds `freshRead`'s mirror (the cached address space or a lease), its `use_count()` is above `allowedCount == 2` and it is not evicted. I could not run it here to confirm. Please reproduce with lavapipe (`VK_ICD_FILENAMES` for lvp, `ANYPS5_REQUIRE_VULKAN=1`, `ANYPS5_NO_SHADER_CACHE=1`) and fix either the eviction rule or the test so it passes on both RTX and lavapipe. The test also has to hold without `/dev/udmabuf`, as on the CI runner.
jotitadev commented 2026-10-31 06:54:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-31T06:54:45Z.

Review: COMMENTED


Linux run of head ddac45718d, plus the old head 922e3888f4 that the NVIDIA CI failed on. On Linux, agc_driver_resident_heap_mirror fails on both devices at this head, and the uncaught past the budget from the CI run comes from the build-time block.

Setup: Ubuntu 26.04, GCC 15.2, Release, kernel 7.0, no /dev/udmabuf. RTX 3070 with NVIDIA 595.99.02 (the CI's driver) and lavapipe (Mesa 26.0.3), one at a time via VK_DRIVER_FILES. Each head is merged --no-ff onto main 6a691f69ee with no conflicts. ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1, ctest -j1. Both devices take the sparse path (mirrorUnit = Block).

ddac45718d: fails in every run on both devices, at one of two points depending on the validation layer.

RTX 3070 lavapipe
no layer ❌ 6/6, uncaught heap mirror of …+0x800000: past the budget ❌ 2/2, same
VVL 1.3.275 ❌ 1/1, same ❌ 1/1, same
VVL 1.4.341 ❌ 5/5, image mirror range became inaccessible ❌ 4/4, same

The rest of ^agc (minus dcc/flip/lds_atomics64) passes on both devices: 1131 of 1132 each, and the one failure is this test.

To find where each one throws, I put fprintf markers in BudgetEvictionTests and in sweepMirrors/prepareRange (local only):

  1. Without the layer, the throw is the build-time dispatch, ResidentHeapMirror.cpp:467, on both devices. The held-mirror block, second and the re-upload all pass. On the 3070, in the build, freshWritten gets its mirror first. When freshRead asks for one, the only candidate is freshWritten, and it can't be evicted:
    sweep need=0x10000 heapBytes=0       budget=0x10000 protect=<freshWritten> entries=0
    sweep need=0x10000 heapBytes=0x10000 budget=0x10000 protect=<freshRead>    entries=1
      candidate <freshWritten> use_count=2 writable=1 held-by-build=1   -> allowedCount 1, no victim -> past the budget
    
    So in this run the allowedCount == 2 read-only path never comes up. The order is the reverse of what the description assumes (read heap first, written heap second). On this run both heaps reuse addresses that the first block freed, and freshWritten got the lower one. Whatever sets the acquisition order, the test needs to force the read-only heap to come first, or set things up so either order works.
  2. With VVL 1.4.341, it fails earlier, at the re-upload dispatch of first (:448). Lines 444-446 pass just before it. In that dispatch's sweep, prepareRange gets a range that belongs to none of the test's heaps:
    inaccessible 0xa500000000a5+0x1
    
    That looks like a mirror read after it was freed, maybe the one evicted in that same sweep. The message is the same in all 9 runs with this layer, across both devices. I didn't run ASan to confirm it.

Also, on Linux blocked is unmapped at the end of its try scope, and second lands on the same address (second == blocked in both instrumented runs).

Old head 922e3888f4 (the NVIDIA CI's ❌): not NVIDIA-specific. It fails the same way on lavapipe (referenced mirror was evicted under budget constraint). With the catch printing what(), both devices show resident heap mirror: cannot map the guest heap. That matches your explanation: blocked at firstAddress + HeapBytes collides with the + Block tail of first under MAP_FIXED_NOREPLACE.

Red check: the test doesn't build on main (SetHeapMirrorBudget is new). The mutations (no eviction loop, allowedCount always 1, no current.exchange(nullptr)) can't be judged on Linux while the unmodified test is red: all of them fail too.

GPUs tested: NVIDIA GeForce RTX 3070, 595.99.02, Ubuntu 26.04; Mesa 26.0.3 lavapipe, Ubuntu 26.04

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

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5721708614 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581#pullrequestreview-5721708614). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-31T06:54:45Z. **Review:** COMMENTED --- Linux run of head `ddac45718d`, plus the old head `922e3888f4` that the NVIDIA CI failed on. On Linux, `agc_driver_resident_heap_mirror` fails on both devices at this head, and the uncaught `past the budget` from the CI run comes from the build-time block. Setup: Ubuntu 26.04, GCC 15.2, Release, kernel 7.0, no `/dev/udmabuf`. RTX 3070 with NVIDIA 595.99.02 (the CI's driver) and lavapipe (Mesa 26.0.3), one at a time via `VK_DRIVER_FILES`. Each head is merged `--no-ff` onto `main` `6a691f69ee` with no conflicts. `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1`, `ctest -j1`. Both devices take the sparse path (`mirrorUnit` = `Block`). **`ddac45718d`: fails in every run on both devices, at one of two points depending on the validation layer.** | | RTX 3070 | lavapipe | |---|---|---| | no layer | ❌ 6/6, uncaught `heap mirror of …+0x800000: past the budget` | ❌ 2/2, same | | VVL 1.3.275 | ❌ 1/1, same | ❌ 1/1, same | | VVL 1.4.341 | ❌ 5/5, `image mirror range became inaccessible` | ❌ 4/4, same | The rest of `^agc` (minus dcc/flip/lds_atomics64) passes on both devices: 1131 of 1132 each, and the one failure is this test. To find where each one throws, I put `fprintf` markers in `BudgetEvictionTests` and in `sweepMirrors`/`prepareRange` (local only): 1. **Without the layer, the throw is the build-time dispatch, `ResidentHeapMirror.cpp:467`, on both devices.** The held-mirror block, `second` and the re-upload all pass. On the 3070, in the build, `freshWritten` gets its mirror first. When `freshRead` asks for one, the only candidate is `freshWritten`, and it can't be evicted: ``` sweep need=0x10000 heapBytes=0 budget=0x10000 protect=<freshWritten> entries=0 sweep need=0x10000 heapBytes=0x10000 budget=0x10000 protect=<freshRead> entries=1 candidate <freshWritten> use_count=2 writable=1 held-by-build=1 -> allowedCount 1, no victim -> past the budget ``` So in this run the `allowedCount == 2` read-only path never comes up. The order is the reverse of what the description assumes (read heap first, written heap second). On this run both heaps reuse addresses that the first block freed, and `freshWritten` got the lower one. Whatever sets the acquisition order, the test needs to force the read-only heap to come first, or set things up so either order works. 2. **With VVL 1.4.341, it fails earlier, at the re-upload dispatch of `first` (`:448`).** Lines 444-446 pass just before it. In that dispatch's sweep, `prepareRange` gets a range that belongs to none of the test's heaps: ``` inaccessible 0xa500000000a5+0x1 ``` That looks like a mirror read after it was freed, maybe the one evicted in that same sweep. The message is the same in all 9 runs with this layer, across both devices. I didn't run ASan to confirm it. Also, on Linux `blocked` is unmapped at the end of its `try` scope, and `second` lands on the same address (`second == blocked` in both instrumented runs). **Old head `922e3888f4` (the NVIDIA CI's ❌): not NVIDIA-specific.** It fails the same way on lavapipe (`referenced mirror was evicted under budget constraint`). With the `catch` printing `what()`, both devices show `resident heap mirror: cannot map the guest heap`. That matches your explanation: `blocked` at `firstAddress + HeapBytes` collides with the `+ Block` tail of `first` under `MAP_FIXED_NOREPLACE`. Red check: the test doesn't build on `main` (`SetHeapMirrorBudget` is new). The mutations (no eviction loop, `allowedCount` always 1, no `current.exchange(nullptr)`) can't be judged on Linux while the unmodified test is red: all of them fail too. GPUs tested: NVIDIA GeForce RTX 3070, 595.99.02, Ubuntu 26.04; Mesa 26.0.3 lavapipe, Ubuntu 26.04 Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
adriadam10 commented 2026-10-31 08:17:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-31T08:17:01Z.

Review: CHANGES_REQUESTED


The full Build on this head (run 41181993829, Linux on lavapipe) still fails agc_driver_resident_heap_mirror after 0.44 s, with Windows green:

AGC graphics: guest address outside its resident heap mirror
  • It comes from the build-time block of BudgetEvictionTests (ResidentHeapMirror.cpp:464-486, budget of one mirror unit, host import budget Block, the log shows host import budget: 0 MiB live of 0 MiB). After freshRead's mirror is evicted, the shader still reads freshRead's address and finds neither a mirror nor a copied fallback on Linux. Either the eviction in sweepMirrors drops a mirror the running build already resolved addresses against, or the copied-range fallback (addCopiedRange) is not taken when the host import budget is exhausted. Please reproduce with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 on lavapipe without /dev/udmabuf and fix whichever side is wrong, then check that the test still fails with the eviction loop removed.
  • The other five failures in that run (agc_driver_frame_capture_eop, agc_driver_frame_replay, _concurrent, _shader, _shader_host) are the runner running out of disk (less than 4 GiB free on the capture volume), not this PR.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5721962405 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581#pullrequestreview-5721962405). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-31T08:17:01Z. **Review:** CHANGES_REQUESTED --- The full Build on this head (run 41181993829, Linux on lavapipe) still fails `agc_driver_resident_heap_mirror` after 0.44 s, with Windows green: ``` AGC graphics: guest address outside its resident heap mirror ``` - It comes from the build-time block of `BudgetEvictionTests` (`ResidentHeapMirror.cpp:464-486`, budget of one mirror unit, host import budget `Block`, the log shows `host import budget: 0 MiB live of 0 MiB`). After `freshRead`'s mirror is evicted, the shader still reads `freshRead`'s address and finds neither a mirror nor a copied fallback on Linux. Either the eviction in `sweepMirrors` drops a mirror the running build already resolved addresses against, or the copied-range fallback (`addCopiedRange`) is not taken when the host import budget is exhausted. Please reproduce with `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1` on lavapipe without `/dev/udmabuf` and fix whichever side is wrong, then check that the test still fails with the eviction loop removed. - The other five failures in that run (`agc_driver_frame_capture_eop`, `agc_driver_frame_replay`, `_concurrent`, `_shader`, `_shader_host`) are the runner running out of disk (`less than 4 GiB free on the capture volume`), not this PR.
jotitadev commented 2026-10-31 10:17:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-31T10:17:44Z.

Review: COMMENTED


Linux run of head 73de525a17, with a cause for the failure in run 41181993829 and in the NVIDIA CI's ❌ on this head, which has the same message on the RTX 2000 Ada. agc_driver_resident_heap_mirror still fails on both of my devices. Both errors come from the same use after free: a heap mirror is evicted in the middle of a build, and the build still holds a raw pointer to it.

Setup: same box as before. Ubuntu 26.04, GCC 15.2, Release, no /dev/udmabuf. RTX 3070 with NVIDIA 595.99.02 and lavapipe (Mesa 26.0.3), one at a time. The head is merged --no-ff onto main 809c7fa2df. ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1, ctest -j1.

Unmodified head

  • No layer, in the ^agc suite: fails on both devices with guest address outside its resident heap mirror, the same as the CI run. The other 1131 of 1132 tests pass on each device.
  • VVL 1.4.341: fails 3/3 on each device with image mirror range became inaccessible.

Where it comes from (fprintf markers, local only)

  • Every eviction happens inside AcquireRegistered, with buildingBufferMemory set. Each victim is a read-only, non-sparse heap mirror.
  • That mirror was already pushed into the build's local heaps vector (heaps.push_back(region.mirror.get())). When sweepMirrors evicts it, EvictMirror resets region.mirror and dropped releases the last shared_ptr. So the mirror is freed while heaps still points at it.
  • refreshHeapMirrors(heaps, blocks) then runs at the end of AcquireRegistered and reads the freed mirror. Right before that call, heaps still holds the evicted pointer, in every failing run on both devices.
  • The two messages are two ways that freed read can go wrong:
    • No layer: the mirror's base/bytes still pass, so appendHeapRun queues blocks against it. Then compareBlocks → ResidentBuffer::Block → blockIndex throws, because the released buffer's size is 0.
    • VVL 1.4.341: the heap layout is different and the freed memory holds garbage. prepareRange gets that garbage as a range and throws, e.g. 0xa500000000a5+0x1 from my previous comment.

Confirmation

As a local experiment, I kept each evicted mirror alive until AcquireRegistered returns: sweepMirrors stashes the victim's shared_ptr, and BuildingScope's destructor releases it. With that, the unmodified test passes on both devices with no layer, VVL 1.3.275 and VVL 1.4.341 (6 of 6). So on Linux the eviction choice is fine. What breaks is that the victim is freed while the build still uses it.

Possible fix

Defer the destruction of evicted mirrors until the build ends: keep them on the GuestBufferMemory, or drop them from heaps and from any queued RefreshBlock before they are freed. RefreshBlock::mirror is a raw pointer too. In my runs no queued block pointed at an evicted mirror, but nothing prevents it.

From reading the code, not observed: EvictMirror calls addCopiedRange inside for (auto& region : regions), and addCopiedRange does regions.push_back. If that push reallocates, the loop keeps going over freed storage. Collecting the ranges first and adding them after the loop would avoid that.

GPUs tested: NVIDIA GeForce RTX 3070, 595.99.02, Ubuntu 26.04; Mesa 26.0.3 lavapipe, Ubuntu 26.04

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

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5722316299 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13581#pullrequestreview-5722316299). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-31T10:17:44Z. **Review:** COMMENTED --- Linux run of head `73de525a17`, with a cause for the failure in run 41181993829 and in the NVIDIA CI's ❌ on this head, which has the same message on the RTX 2000 Ada. `agc_driver_resident_heap_mirror` still fails on both of my devices. Both errors come from the same use after free: a heap mirror is evicted in the middle of a build, and the build still holds a raw pointer to it. Setup: same box as before. Ubuntu 26.04, GCC 15.2, Release, no `/dev/udmabuf`. RTX 3070 with NVIDIA 595.99.02 and lavapipe (Mesa 26.0.3), one at a time. The head is merged `--no-ff` onto `main` `809c7fa2df`. `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1`, `ctest -j1`. **Unmodified head** - No layer, in the `^agc` suite: fails on both devices with `guest address outside its resident heap mirror`, the same as the CI run. The other 1131 of 1132 tests pass on each device. - VVL 1.4.341: fails 3/3 on each device with `image mirror range became inaccessible`. **Where it comes from** (`fprintf` markers, local only) - Every eviction happens inside `AcquireRegistered`, with `buildingBufferMemory` set. Each victim is a read-only, non-sparse heap mirror. - That mirror was already pushed into the build's local `heaps` vector (`heaps.push_back(region.mirror.get())`). When `sweepMirrors` evicts it, `EvictMirror` resets `region.mirror` and `dropped` releases the last `shared_ptr`. So the mirror is freed while `heaps` still points at it. - `refreshHeapMirrors(heaps, blocks)` then runs at the end of `AcquireRegistered` and reads the freed mirror. Right before that call, `heaps` still holds the evicted pointer, in every failing run on both devices. - The two messages are two ways that freed read can go wrong: - **No layer:** the mirror's `base`/`bytes` still pass, so `appendHeapRun` queues blocks against it. Then `compareBlocks` → `ResidentBuffer::Block` → `blockIndex` throws, because the released buffer's `size` is 0. - **VVL 1.4.341:** the heap layout is different and the freed memory holds garbage. `prepareRange` gets that garbage as a range and throws, e.g. `0xa500000000a5+0x1` from my previous comment. **Confirmation** As a local experiment, I kept each evicted mirror alive until `AcquireRegistered` returns: `sweepMirrors` stashes the victim's `shared_ptr`, and `BuildingScope`'s destructor releases it. With that, the unmodified test passes on both devices with no layer, VVL 1.3.275 and VVL 1.4.341 (6 of 6). So on Linux the eviction choice is fine. What breaks is that the victim is freed while the build still uses it. **Possible fix** Defer the destruction of evicted mirrors until the build ends: keep them on the `GuestBufferMemory`, or drop them from `heaps` and from any queued `RefreshBlock` before they are freed. `RefreshBlock::mirror` is a raw pointer too. In my runs no queued block pointed at an evicted mirror, but nothing prevents it. **From reading the code, not observed:** `EvictMirror` calls `addCopiedRange` inside `for (auto& region : regions)`, and `addCopiedRange` does `regions.push_back`. If that push reallocates, the loop keeps going over freed storage. Collecting the ranges first and adding them after the loop would avoid that. GPUs tested: NVIDIA GeForce RTX 3070, 595.99.02, Ubuntu 26.04; Mesa 26.0.3 lavapipe, Ubuntu 26.04 Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
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!13581
No description provided.