fix(agc): evict unreferenced heap mirrors under memory pressure #13581
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/13581"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by ashwin280802 on 2026-10-30T18:47:06Z.
What
When device heap mirrors exceed
heapMirrorBudget(),reserveHeapBytesandgrowResidentinvokesweepMirrors(need, address)to reclaim memory. Previously,sweepMirrorsonly 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 withpast the budget.This change extends
sweepMirrorsunder budget pressure (neededBytes != 0 && state.heapBytes + neededBytes > heapMirrorBudget()) to evict unreferenced heap mirrors (it->second->heap && it->first != protectAddress, withuse_count() == 1, or== 2for a read-only mirror the active build holds):lastDispatch), tie-broken by preferring read-only mirrors (!writable) over writable mirrors to avoid dirty copy-backs.(buildingHolds && !it->second->writable) ? 2 : 1) while allowing speculative read-only mirrors to yield. Evicted addresses are recorded viaRecordEvictedso the same build does not re-acquire them.EvictMirrorresets the evicted mirror's region in place (host-backed, with its committed ranges recorded asbacked/sparse). It does not add regions whileregionsis being iterated. The rawheapslist used byrefreshHeapMirrorsis 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 afterstate.mutexis released.sweepMirrorsskips any mirror that hasRefreshBlocks queued in that build. Those blocks hold rawImageMirror*pointers and are used bycompareBlocks/bindHeapBlocks, andgrowResidentcan reachsweepMirrorsfrom inside them. If no other candidate is left, the build throwspast the budget, as it did before this change.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 inSpaces().current.evictionscounter tostruct MirrorStats,MirrorCounters(), and formatted inAgcDriver::ProfilePrint_nid_no_patch.Tested
/dev/udmabuf,ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1, run with--security-opt seccomp=unconfined --cap-add SYS_PTRACEso the guest write watch is available.agc_driver_resident_heap_mirrorpasses.agc_driver_resident_heap_mirror(ResidentHeapMirror.cpp), covering:HoldHeapMirrorprevents eviction and throwspast the budget.allowedCount == 2), its region reset in place byEvictMirror, recorded inevictedRangesto prevent re-acquire, and the shader output bits verified exactly.Block) and whole-copy fallback (HeapBytes) configurations.past the budget.ctest -V:sweepMirrorsreplaced bywhile (false): fails on Windows and on Linux/lavapipe withAGC 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 samepast the budgeterror.agc_driver_resident_heap_mirrorstill passes on Windows and on Linux, and anANYPS5_ENABLE_ASAN=ONbuild 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.VK_LAYER_KHRONOS_validation):ctest -R '^agc_driver_(resident|host_import|bda|address)', 19 of 19 passed.ctest --test-dir build-full -R "agc_driver_resident_heap_mirror|agc_driver_bda_span_reads|agc_driver_address_passes" -VwithANYPS5_REQUIRE_VULKAN=1,ANYPS5_NO_SHADER_CACHE=1, andVK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation.VK_LAYER_KHRONOS_validationloaded cleanly.VUID-validation errors logged. The Linux/lavapipe run did not use the validation layers.python3 tools/check_conventions.py --base origin/mainpassed with 0 errors.APS5_HEAP_MIRROR_MIB=1536) on Ghost of Yōtei (PPSA26344, 1920x1080).past the budgetwhen unreferenced direct-memory-backed mirrors saturate the budget ceiling.evictions > 0), and bounds device heap consumption within the configured limit without leaks or corruptions.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)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 wheneverneededBytes != 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 theheapBytes + neededBytes > heapMirrorBudget()branch.ResidentHeapMirror.cpp:390-453: the mutation controls @oneandonlydean asked for are missing. Show that removing only theuse_count()eviction loop, and separately thecurrent.exchange(nullptr)line, turnsagc_driver_resident_heap_mirrorred.GuestBufferMemory.cpp:3345-3364,4427-4445: the build-time path (read-only mirror held by the current build is evicted withallowedCount == 2,EvictMirrorresets the region andaddCopiedRange,evictedRangesskips 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.c2181e0e05d2 (dirty), not this head. Please attach the rawaps5-summary.jsonllines (main and this head, same scene/machine) and the image-mirror report of both arms showingevictions. Both arms finish all 624 presents, so the numbers don't show thepast the budgetfailure; either show a run where main aborts and this head doesn't, or drop the perf claim (theperflabel asks for the two summary lines).GuestBufferMemory.cppL3299-3301 (sweepMirrors); please check the conflict and list it under Depends on if related.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.buildLateris never dispatched, soHeapMirrorsWithin(buildLater...) == 1has nothing to count, and afterDispatch(device, buildEarly, ...)the mirror ofbuildEarlyexists (the eviction under budget hitsfirst), so== 0fails too. TheallowedCount == 2path 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 freshwrittenheap, budget for one mirror). Add that dispatch and check the result bits.922e388) failedagc_driver_resident_heap_mirroratbudget 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 withANYPS5_REQUIRE_VULKAN=1,ANYPS5_NO_SHADER_CACHE=1,VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation(log, not a summary).use_count()loop, nocurrent.exchange(nullptr)) are described in prose; paste the failing ctest output for each once the test above is fixed, since the test changes.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_mirrorfails after 0.74 s with the uncaughtAGC graphics: heap mirror of 0x78e414600000+0x800000: past the budget. Main does not have this test, so it comes from this PR.mirrorUnitisBlock. The exception comes from one of the dispatches inBudgetEvictionTeststhat 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 holdsfreshRead's mirror (the cached address space or a lease), itsuse_count()is aboveallowedCount == 2and it is not evicted. I could not run it here to confirm.Please reproduce with lavapipe (
VK_ICD_FILENAMESfor 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.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-31T06:54:45Z.
Review: COMMENTED
Linux run of head
ddac45718d, plus the old head922e3888f4that the NVIDIA CI failed on. On Linux,agc_driver_resident_heap_mirrorfails on both devices at this head, and the uncaughtpast the budgetfrom 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 viaVK_DRIVER_FILES. Each head is merged--no-ffontomain6a691f69eewith 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.heap mirror of …+0x800000: past the budgetimage mirror range became inaccessibleThe 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
fprintfmarkers inBudgetEvictionTestsand insweepMirrors/prepareRange(local only):ResidentHeapMirror.cpp:467, on both devices. The held-mirror block,secondand the re-upload all pass. On the 3070, in the build,freshWrittengets its mirror first. WhenfreshReadasks for one, the only candidate isfreshWritten, and it can't be evicted: So in this run theallowedCount == 2read-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, andfreshWrittengot 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.first(:448). Lines 444-446 pass just before it. In that dispatch's sweep,prepareRangegets a range that belongs to none of the test's heaps: 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
blockedis unmapped at the end of itstryscope, andsecondlands on the same address (second == blockedin 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 thecatchprintingwhat(), both devices showresident heap mirror: cannot map the guest heap. That matches your explanation:blockedatfirstAddress + HeapBytescollides with the+ Blocktail offirstunderMAP_FIXED_NOREPLACE.Red check: the test doesn't build on
main(SetHeapMirrorBudgetis new). The mutations (no eviction loop,allowedCountalways 1, nocurrent.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.
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_mirrorafter 0.44 s, with Windows green:BudgetEvictionTests(ResidentHeapMirror.cpp:464-486, budget of one mirror unit, host import budgetBlock, the log showshost import budget: 0 MiB live of 0 MiB). AfterfreshRead's mirror is evicted, the shader still readsfreshRead's address and finds neither a mirror nor a copied fallback on Linux. Either the eviction insweepMirrorsdrops 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 withANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1on lavapipe without/dev/udmabufand fix whichever side is wrong, then check that the test still fails with the eviction loop removed.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.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_mirrorstill 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-ffontomain809c7fa2df.ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1,ctest -j1.Unmodified head
^agcsuite: fails on both devices withguest address outside its resident heap mirror, the same as the CI run. The other 1131 of 1132 tests pass on each device.image mirror range became inaccessible.Where it comes from (
fprintfmarkers, local only)AcquireRegistered, withbuildingBufferMemoryset. Each victim is a read-only, non-sparse heap mirror.heapsvector (heaps.push_back(region.mirror.get())). WhensweepMirrorsevicts it,EvictMirrorresetsregion.mirroranddroppedreleases the lastshared_ptr. So the mirror is freed whileheapsstill points at it.refreshHeapMirrors(heaps, blocks)then runs at the end ofAcquireRegisteredand reads the freed mirror. Right before that call,heapsstill holds the evicted pointer, in every failing run on both devices.base/bytesstill pass, soappendHeapRunqueues blocks against it. ThencompareBlocks→ResidentBuffer::Block→blockIndexthrows, because the released buffer'ssizeis 0.prepareRangegets that garbage as a range and throws, e.g.0xa500000000a5+0x1from my previous comment.Confirmation
As a local experiment, I kept each evicted mirror alive until
AcquireRegisteredreturns:sweepMirrorsstashes the victim'sshared_ptr, andBuildingScope'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 fromheapsand from any queuedRefreshBlockbefore they are freed.RefreshBlock::mirroris 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:
EvictMirrorcallsaddCopiedRangeinsidefor (auto& region : regions), andaddCopiedRangedoesregions.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.