fix(agc): keep heap mirror slabs within device memory #15295
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/15295"
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 Prophet069 on 2026-11-02T23:01:04Z.
What
A heap mirror slab refused by a full device heap stopped the title. The slab now falls back to host memory, as buffers and images already do, and a refusal lowers the heap mirror budget, evicts down to it and retries; a failed bind gives back the blocks it took.
Slabs are refused before the device heap is exhausted: when all live slabs would pass
APS5_HEAP_MIRROR_MIBor when the device heap would keep less than 256 MiB of its reported budget, so the shrink and sweep path runs before Windows starts paging device memory. A budget lowered by refusals is a soft target that a mirror may pass up to the configured budget when nothing can be evicted, and the headroom refusal is not repeated within two seconds on the same thread.Blocks are taken from the fullest slab, so partly used slabs drain and are freed instead of every slab staying partly used after evictions.
Nonzero scans of a heap remember each 64 KiB block with its write generation and read only blocks written since, instead of reading the whole multi-GiB heap again on every rebuild.
Tested
NVIDIA GeForce RTX 3080 Laptop GPU, driver 616.64, Windows 10 Pro 22H2 (19045.6466).
Focused tests on
main(9090972b7e) and on this branch withVK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation,ANYPS5_NO_SHADER_CACHE=1,ANYPS5_REQUIRE_VULKAN=1,ctest -V -R "heap_mirror|^agc_driver_graphics$|^agc_driver_key_miss$|^agc_driver_bda_device$|^agc_driver_recorder$|native_multisample_depth|depth_storage|^agc_host_import_retire$|^agc_host_import_sparse$":main: 17 of 20 selected tests passed (agc_host_import_sparse skips on this machine; the three agc_driver_depth_storage_* tests were not built in this run); validation layer loaded in both logs;VUID-errors: none.VUID-errors: none.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)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T00:10:49Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
The merged tree builds and the heap mirror and resident tests pass. However, a new pre-allocation refusal can now stop a title on a nearly full device heap when the heap mirrors hold 256 MiB or less, where
mainwould have tried the allocation. None of the new paths has a test.What I ran
Head
1743177ae4af40502f26cd384d2376d555074681,main5cb015caaaaf83f8ee431414ee6a457b5b307d49, merged tree7895dfbc86c6627273ff29b2d3bbc7eed5af335f.Results
git diff --checkcheck_conventions.pylibs(script)mainagc_driver_image_sample_lod_clamp_shader_lanemain5cb015ca. The baseline (096c4557) is older, so this failure comes frommain, not this PR.unwrap_self_..._destination_directory_groupos.chownon a temporary directory (EINVAL). This is atools/Python test the PR doesn't touch, and the failure comes from the sandbox.agc_host_import_sparse, an expected skip)VUID-lines: 0lod_clamp failure, same output with the PR and on main
Negative control
There is none, because the PR adds and changes no tests. I used the restore-from-
mainprocedure only to clear the PR of thelod_clampfailure (see Results).Findings
Blocking
The headroom refusal stops the title when the heap mirrors hold 256 MiB or less. In
core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp:153,Take()callsrefuseSlab()before anyvkAllocateMemory. AtResidentMirror.cpp:188,refuseSlab()throws when the device heap would keep less than 256 MiB of its reported budget. The only recovery isshrinkHeapMirrorBudget, and it returnsfalsewhenheld <= step(256 MiB) (core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp:2823). Both callers then rethrow the error wrapped inheapMirrorError:growResidentatGuestBufferMemory.cpp:2852-2866;acquireMirroratGuestBufferMemory.cpp:3396-3407.So when the device heap is close to its budget for reasons other than the heap mirrors (textures, render targets), the first slab of a small mirror is refused with nothing to evict, and the title stops. On
mainthe same slab would go tovkAllocateMemory. With this PR it would even fall back to host memory, but that fallback is never reached. This is most likely on GPUs with little VRAM, which this PR is meant to help.The
APS5_HEAP_MIRROR_MIBrefusal atResidentMirror.cpp:184hits the same dead end. It counts whole 16 MiB slabs, fragmentation included, whilestate.heapBytescounts only accounted blocks. A small configured budget can therefore refuse a slab whileheld <= 256 MiB.Suggested fix: treat a refusal as a request to shrink and sweep, not as a final error. When
shrinkHeapMirrorBudgetcan't lower anything, or the retries run out, go on to the real allocation and its host-memory fallback. Add a test that sets a heap budget the refusal triggers on (or a test hook forReportedHeap) with fewer than 256 MiB of mirrors, and checks that the mirror is still created.None of the new behaviour has a test. The PR changes several things:
Bindfails partway;It adds no test for any of them. All 27 existing heap mirror, resident and host-import tests pass with and without the change, so none of them covers these paths. Finding 1 shows a regression these paths can hide. At least the refusal/shrink/retry path and the
Bindgive-back need a test that fails onmain(SetHeapMirrorBudgetalready exists for that). A scan-cache test should write a block after a first scan and check that the next scan sees it.Non-blocking
UnchangedSinceeven for content the write watch may not record. AtResidentMirror.cpp:401, a cached "zero" result is reused whileGuestMemory::UnchangedSinceholds. On Windows,possiblyNonzeroreturns the whole range as readable, so the result there depends entirely on the write watch.docs/dev/debt/libc.mddescribes direct-memory pages that are kept in a private reservation while unmapped and mapped again later, and pages mapped at a second address that become views tracked by write protection. Content can then appear at a guest address without a CPU write there. If no stamp covers that case, the mirror leaves a nonzero block unbacked, and the GPU reads zeros. Please confirm that guest maps and alias writes stamp the tracker, or useCollectCommittedWrites/UnchangedCommittedSince(which also check refusals). If neither covers it, record the gap indocs/dev/debt/libSceAgcDriver.md.ResidentMirror.cpp:382-383, the map grows to 2^22 entries before it is cleared. That is a few hundred MiB ofunordered_mapnodes and buckets for a process-lifetime cache, and the whole cache is then dropped at once. A per-heap bitmap of generations, or a smaller limit, would bound this better.heapMirrorMemoryLimit(GuestBufferMemory.cpp:2714) is only ever set from the currentheapBytesminus 256 MiB, never back toward the configured budget. A single transient headroom refusal, for example during a loading spike, caps the heap mirrors for the rest of the run. This is mitigated by the "soft target", but it is still surprising.shrinkHeapMirrorBudgetmatches"of a heap mirror slab"inerror.what()(GuestBufferMemory.cpp:2816). A dedicated exception type would be more robust to message edits.docs/dev/debt/libSceAgcDriver.mdalready lists similar choices for the heap mirror reference storage ("unmeasured choices"); these belong there too.Not verified
To get this to a good state
mainfor the refusal/shrink/retry path, theBindgive-back on failure, and the scan cache seeing a later write.Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T06:17:43Z.
Review: DISMISSED
Re-checked — changes still requested
Commit
89e3292072now lets a refusal fall through to the real allocation while the live slabs hold 256 MiB or less. It replaces text matching withHeapMirrorSlabRefused, lets a lowered budget recover after 30 s, and adds one full-device-heap test, whose negative control fails as it should. Three paths still have no test: the shrink/evict/retry path, theBindgive-back and the scan cache. A refusal can also still stop the title when fragmented slabs keep the slab count above the gate while the accounted heap mirror bytes are below the shrink step.What changed since my last review
89e3292072("let a small heap mirror reach the slab allocation and its host fallback"). The first commit1743177ae4is unchanged.refuseSlab()returns early while the live slabs hold 256 MiB or less.HeapMirrorSlabRefused.heapMirrorBudget()restores a lowered limit after 30 s.Context::HeapReport::Fits.SetDeviceHeapFullForTestsand testFullDeviceHeapTestsintests/execution/ResidentHeapMirror.cpp.What I ran
Head
89e3292072015ff5710305f6fd2e097545a0bb50,maind1ae628bc2f62459cce1e9872ba5632c938c71f2, merged treee656cfa05a1d3ab6e971f1f891ce43a02603f091.git diff --checkcheck_conventions.pylibs(script)main(baseline =maind1ae628b)VUID-lines: 0agc_driver_resident_heap_mirror2.1 s. The sparse branch runs on lavapipe (no skip message), soFullDeviceHeapTestsis exercised.Negative control
The new test calls
SetDeviceHeapFullForTests, whichmaindoes not have, so it cannot be built againstmain's production files. Instead I removed only the new early return inrefuseSlab(ResidentMirror.cpp:188). The test then fails with the same message the author reported:output
With the merged file restored, the test passes and the worktree matches the merged tree.
Previous findings
shrinkHeapMirrorBudget→ sweep → retry path, theBindgive-back whenTake()orsubmitfails partway, the host-memory fallback for slabs, and the generation-keyed cache inGuestNonzeroBlocks. oneandonlydean's review asked for the same three cases. TheAPS5_HEAP_MIRROR_MIBrefusal can be forced deterministically withSetHeapMirrorBudget: build more than 256 MiB of slabs (or lower the gate for tests), then check the "budget lowered" path evicts and the retry succeeds.UnchangedSincefor remapped or aliased content): still open. The code is unchanged (ResidentMirror.cpp:409), with no reply and no debt entry.ResidentMirror.cpp:419).heapMirrorBudget()restores the limit 30 s after the last lowering (GuestBufferMemory.cpp:2734).shrinkHeapMirrorBudgetusesdynamic_cast<const HeapMirrorSlabRefused*>(GuestBufferMemory.cpp:2834).docs/dev/debt/changes.New findings
Blocking
The refusal gate and the shrink gate count different things, so a refusal can still stop the title.
refuseSlab()skips the refusal on live slab memory (Slabs().slabs * 16 MiB,ResidentMirror.cpp:187-188).shrinkHeapMirrorBudget()gives up on accounted heap mirror bytes (state.heapBytes <= 256 MiB,GuestBufferMemory.cpp:2841).A slab is freed only when every block in it is free (
ResidentMirror.cpp:175). After evictions, surviving mirrors keep blocks scattered across many slabs, so the live slabs can stay well above 256 MiB whileheapBytesis far below it. That is exactly the state the shrink-and-sweep path leaves behind.What happens then on a device heap near its budget:
shrinkHeapMirrorBudgetreturnsfalse.GuestBufferMemory.cpp:2872and:3416) rethrow without a retry, so the title stops.mainwould have attempted the allocation, and with this PR that allocation even has a host fallback. The 2 s throttle (ResidentMirror.cpp:193-198) does not help, because the first refusal is already final. TheAPS5_HEAP_MIRROR_MIBrefusal has the same mismatch.Suggested fix: when
shrinkHeapMirrorBudgetreturnsfalsefor aHeapMirrorSlabRefusedthat came fromrefuseSlab(not from a failed allocation), retry once with the refusal bypassed, so the real allocation and its fallback run. Alternatively, gaterefuseSlaband the shrink on the same counter. Add a test that fragments slabs past the gate (or lowers the gate through a hook) with a full device heap, and checks the mirror is still made.Non-blocking
shrankreport prints whenever the last slab is freed.count % 32 == 0is true forcount == 0(ResidentMirror.cpp:181), so each mirror whose release empties the slab list logs a line. The test log shows several[heap-mirror] shrank: slabs 0 (0 MiB) ...lines in a row. Suggested fix: usecount != 0 && count % 32 == 0.GuestBufferMemory.cpp:2734). Under sustained pressure, this can cycle every 30 s: the mirrors grow, a refusal fires, the budget shrinks and the sweep runs again. Raising the limit in steps, or only while the heap reports headroom, would avoid the cycle. This is not shown on hardware; it comes from reading the code.Not verified
To get this to a good state
shrinkHeapMirrorBudgetcannot act on go on to the real allocation, whatever the slab fragmentation.Bindgive-back, and the scan cache seeing a write made after an earlier scan cached the block as zero.docs/dev/debt/libSceAgcDriver.mdhow the scan cache stays sound for remapped or aliased guest memory, and record the new constants (256 MiB reserve and step, 2 s throttle, 8 retries, 30 s recovery, 2^22-entry cache limit).Imported from boykopovar/AnyPS5. Originally posted by Superseabas on 2026-11-06T09:24:51Z.
Review: APPROVED
Windows run of the current head,
c75bd0a393, on an RTX 5070 Ti and on the integrated Radeon of a Ryzen 7 7700X, the first AMD result on Windows here. Nothing regresses, and the newFullDeviceHeapPastReserveTestscatches the loss of the retry. One non-blocking note on what it doesn't cover.Head merged onto
mained41d86d32(clean merge, local only). Windows 11 Home 10.0.26200, WinLibs GCC 16.2.0 (x86_64-ucrt-posix-seh, r3), Release.ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, no missing-layer line,ANYPS5_GPUselecting the device, confirmed bySelected GPU:10de:2c05), 621.011002:164e, integrated), AMD 26.10.2 (32.0.21045.20006)Focused set. The 17 tests matching
heap_mirror|resident(agc_driver_resident_heap_mirror, theagc_heap_mirror_*andagc_sparse_heap_mirror_*entries,agc_driver_partially_resident_*,agc_resident_*and the others) pass 3 of 3 on both GPUs, onmainand on this PR. NoVUID-lines. Both devices take the sparse path:agc_driver_resident_heap_mirrorprints no skip line, and the[heap-mirror] refusedline shows the full-heap cases ran.Whole AGC set.
ctest -R '^agc' -j 8 --timeout 300, 1,388 tests: 1,386 pass on the RTX and 1,385 on the Radeon, the same asmainon this machine. Every failure is tracked:agc_driver_direct_write_completion(#15564),agc_driver_quad_pixel_maskon the RTX (#14341), and on the Radeonagc_driver_scratch_pool(#15566) andagc_driver_sample_order_grid_reference(#9503).Red checks on
agc_driver_resident_heap_mirror, 3 runs per GPU, each a local edit of the merged tree:if (!waive && dynamic_cast<const HeapMirrorSlabRefused*>(&error) != nullptr) { waive = true; continue; }retries removed (growResident,acquireMirror)vkAllocateMemory of a heap mirror slab refused: its device heap would keep less than 256 MiB of its reported budgetif (slabRefusalWaived) return;removed fromrefuseSlabnow - lastHeadroomRefusal > std::chrono::seconds(2)) disabledNon-blocking. The test covers the retry, but not the waive itself. Its refusal is the headroom one, and
lastHeadroomRefusalwas set by the refusal a moment earlier on the same thread, so the throttle already lets the retry's allocation through, with or withoutslabRefusalWaived. The waive matters for the other reason,the heap mirrors' slabs would pass APS5_HEAP_MIRROR_MIB, which has no throttle. A case refused through the budget hook, with too little held forshrinkHeapMirrorBudgetto act, would cover it.check_conventions.py --base mainpasses.AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by gabichuuuuu on 2026-11-08T15:48:37Z.
Review: COMMENTED
Ran
c75bd0a393merged onmain302864d48con Windows 11 x64 (WinLibs GCC 15.2), on an NVIDIA laptop GPU (Turing, driver 621) and an Intel iGPU (driver 101.70xx), withANYPS5_REQUIRE_VULKAN=1,ANYPS5_NO_SHADER_CACHE=1andVK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation(Khronos validation layer 1.4.368),ctest -R '^agc_driver_resident_heap_mirror' -V:mainResidentHeapMirror.cppusesSetDeviceHeapFullForTestsandSetHeapMirrorSlabReserveForTests, which this PR adds, so there's no run of the tests without the change.was not found but was requested by env var VK_INSTANCE_LAYERS, and no log on either side has aVUID-. To be sure validation messages reach these logs, the same layer with best practices on printed 28BestPractices-warnings into anagc_driver_recorderlog on each GPU.AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T21:19:44Z.
Review: COMMENTED
Reviewed — no blocking findings
The reviewed changes at head
4c3e5d198988d477f2471f1cfc1cc62171ffb8a3show no verified blocking defect; runtime checks were not run here.What I ran
No commands or tests were run. I read the prepared description, commits, manifest and diff, plus the changed code sections and related context through
repo_read.py.Results
Findings
Blocking
None verified in the code reviewed.
Non-blocking
None.
Not verified
The complete
GuestBufferMemory.cppfile was excluded from the review folder because it was too large; I read its changed hunks and surrounding functions throughrepo_read.py. The full repository test suite and the author-reported GPU and game integration checks were not run or independently confirmed.To get this to a good state
Nothing is required.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T12:13:56Z.
Review: COMMENTED
Reviewed — no blocking findings
Nothing blocks this change; the points below are optional.
What I ran
Reviewed head
515aeee17bdcdfa5fc01e8a6ac2f62d671cbecf9. I did not run commands or tests.Results
Findings
Blocking
None.
Non-blocking
GuestNonzeroBlocksuses a process-wide cache keyed only by guest block address. Consider including the guest-memory identity in the key or invalidating entries when an address range is reused; otherwise a new allocation at a reused address may inherit a previous scan result if write tracking does not distinguish the allocations. Seecore/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp:397.Not verified
core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cppwas excluded from the prepared full-text files because it is too large. I read the relevant changed regions through the pinned reader, but did not read the entire file.ResidentMirror.hpp,ResidentMirror.cpp,ResidentHeapMirror.cpp, andlibSceAcm.mdwere listed as included; the full changed text oflibSceAcm.mdwas not read.files.jsonwas not available as a review document; the changed-file inclusion list came from the review-folder listing and manifest.To get this to a good state
Nothing is required. Optional: key the scan cache by guest-memory identity or ensure address reuse invalidates it.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T14:30:13Z.
Review: COMMENTED
Reviewed — comments
Changes are required before merge: address the findings below.
What I ran
901975c9ef9be1d42ba811f31ec5f8443a834f4b; no build or test commands were run.description.md,commits.md,manifest.json,diff.patch, and all included changed files.GuestBufferMemory.cppwas excluded from the review folder and read throughrepo_read.pyat the allocation and retry paths it changes.Results
Findings
Blocking
None verified.
Non-blocking
core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp:403:GuestNonzeroBlockscollects a generation for the entire candidate range, then reuses a cached block result whenUnchangedSincesays the block has not changed since its cached generation. A write to a different block in the same page can causeCollectWritesto stamp both blocks, so this check invalidates the cache for the unchanged block and triggers a rescan. This weakens the stated scan optimization for workloads that write many distinct blocks on shared pages. Consider tracking cache validity at the same granularity as the write stamps, or confirm with targeted profiling that this behavior is acceptable.core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp:397: the scan cache is keyed only by block address and is process-global. If guest address ranges are reused for a new allocation without a write stamp changing that block, the cached nonzero result can be reused for different contents. Confirm the allocator's write-watch and address-reuse guarantees, or include allocation identity in the cache key.Not verified
GuestBufferMemory.cppwas not read in full; only the changed budget, retry, and allocation sections were inspected. Other portions of that file and files excluded by review-folder rules were not reviewed.To get this to a good state
Nothing is required. Optional points: assess the scan cache's invalidation granularity and address reuse behavior, and run the focused tests on the reviewed head.
Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T22:45:13Z.
Review: COMMENTED
The trial merge onto
c1601e56d5was clean. The new headroom check suppresses repeated refusals for two seconds per thread. Please describe the 256 MiB figure as a retry threshold or show how retry still respects it during that interval. Keep the fixture that distinguishes a refused allocation from a failed bind, which separately needs to return its reserved blocks. Paired lavapipe controls are pending.AI-assisted: yes.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.