perf(agc): keep one shadow per writable heap mirror #3248
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3248"
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 ponhei9502 on 2026-10-11T03:25:36Z.
What
UploadFinishcopied every written range of a writable heap mirror into a per-build vector (takeHeapReferences) forWriteBackto diff against, so each dispatch that writes into a heap range allocated and copied that whole range. Measured by the author on Demon's Souls withperf record -e syscalls:sys_enter_mmap --filter 'len > 8388608' -g: 79 allocations of 112 MiB in 25 s, all fromGuestBufferMemory::takeHeapReferences<-UploadFinish<-ShaderResources::buildComplete.A writable heap mirror now keeps the persistent shadow a non-heap writable mirror already has: filled when the mirror is made, updated by every refreshed block (
compareBlock) and byWriteBack, which stores the bytes that differ from the shadow (storeChanged, as before) and then takes the mirror's bytes into it.takeHeapReferencesandheapReferencesare removed.The invariant to review: the shadow is the bytes the GPU started from. Both writers of the shadow run under the device lock, and a refresh first waits for recorded work that writes the range, so a block is not refreshed between a dispatch's upload and its write-back while that dispatch may still write it. With overlapping builds the first write-back moves the shadow forward and the second stores only what changed beyond it.
Two consequences a reviewer may object to:
max(2 GiB, RAM / 4);APS5_HEAP_MIRROR_MIBstill overrides it. A fixed 24 GiB is more than most machines have, but the new default is lower on every machine below 96 GB, writable mirrors now count twice, and passing the budget throws. A title that ran inside 24 GiB can therefore now stop with "past the budget" on a machine with less RAM. On the author's 31 GB machine the game held 5088 MiB of a 7737 MiB budget, which would not fit the 4 GiB default of a 16 GB machine. If you prefer, I will drop the default change from this pull request and keep only the shadow and its accounting.Relation to open pull requests: this is written against plain
mainand does not need #3167, but both changeGuestBufferMemory.cppand they conflict textually (one conflict). Whichever lands second needs a rebase; on top of #3167 the shadow must also follow the sparse fills incompareBlockandWriteBackmust diffstoreSparseagainst the shadow. No conflict with #3137.Tested
main961b25fe.agc_heap_mirror_budget(default budget arithmetic only): passed.libsand ranagc_driver_graphicsandagc_driver_bda_deviceon lavapipe (not on the NVIDIA GPU): passed, but the heap mirror subtests ofagc_driver_graphicswere skipped on this machine ("guest arena unavailable or not write-watched: heap mirrors not tested"), so no unit test I ran exercises the changed write-back path.python3 tools/check_conventions.py --base origin/mainpasses.perftrace shows no allocation fromtakeHeapReferences(7 unrelated arena reservations remain). In-game numbers come from a local tree that also carries other changes (upstreammainplus several open pull requests plus local fixes), not from this branch alone.mainwithout #3167 (no sparse-fill handling), without code comments and without a diagnostic log line.GlobalMemoryStatusExpath is not even compiled here), AMD and Intel GPUs, any other title, machines with less RAM, the full ctest run.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-11T03:25:47Z.
Thank you for your interest in the project! We are sorry, but we cannot accept more PRs while we work through the existing backlog. This PR has been automatically closed and labeled "intake paused". This is not a judgment of the quality of your changes.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-11T05:09:04Z.
Reopened.
Two things:
agc_driver_graphicswhere the arena is write-watched, and Demon's Souls on this branch?Imported from boykopovar/AnyPS5. Originally posted by kr4y4 on 2026-10-11T05:40:32Z.
A run where the guest arena is write-watched: Windows, on this PR's head 23128dbd (base
main961b25fe).Setup: Windows 11 (26200), WinLibs GCC 15.2.0 r7, Release, CI configure flags.
agc_driver_graphicsandagc_heap_mirror_budgetpass with--repeat until-fail:3on an RTX 4070 Laptop GPU and on an Intel Raptor Lake-S iGPU.guest arena unavailable or not write-watched, soheapMirrorTestsandimportedHeapMirrorTestsran.guest_filesystem, which needs Developer Mode for its symlinks on this machine.agc_driver_graphicsdoes exercise the new heap write-back. Each of these two mutations of this branch makes it fail on the RTX 4070:range->writable && !heap, as onmain):AGC graphics: writable mirror write-back has no shadowstoreChanged(begin, current, current)):AGC graphics: a writable heap mirror's write-back lost the GPU's store or rolled back the CPU'sNot run: Demon's Souls, since I have no dump. This head still has the heap mirror budget default change.
Written with AI assistance.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T07:06:44Z.
Review: CHANGES_REQUESTED
The shadow change looks right to us:
compareBlock,WriteBackand the budget accounting are consistent, andagc_heap_mirror_budgetandagc_driver_graphicspass here on Linux/lavapipe. kr4y4's Windows run covers the write-watched path.One thing is still open, the one @oneandonlydean asked for:
GuestBufferMemory.cpp:803(DefaultHeapMirrorBudget,systemMemoryBytes) andtests/HeapMirrorBudget.cpp: the default budget change from 24 GiB tomax(2 GiB, RAM / 4)is a second topic and a behaviour change (titles that fit before can now throw "past the budget" below 96 GB of RAM). Please move it to its own PR and keep the shadow, itsheapFootprintaccounting and the existing 24 GiB default here. The new test goes with the budget PR.Once that is split off we can merge this one.
Imported from boykopovar/AnyPS5. Originally posted by ponhei9502 on 2026-10-11T18:43:03Z.
Rebased onto
main(a11c8f7f) and split as asked. New head: f0dd6505.Removed from this PR: the default budget change (
DefaultHeapMirrorBudget,systemMemoryBytes) andtests/HeapMirrorBudget.cppwith its CMake target. The default is the existing 24 GiB again. The shadow and itsheapFootprintaccounting stay. I have not opened the budget change as a separate PR yet.New in the rebase, please look at this part:
maingained sparse heap mirrors since the first version, and they used the per-dispatch reference copy too. I adapted the shadow to them:compareBlock: the sparse fill path (SparseZero/SparseCopy) now also writes the filled bytes into the shadow, so shadow and mirror stay equal after a refresh.WriteBack: a sparse heap mirror diffs against the shadow throughstoreSparse, a non-sparse one throughstoreChanged, as before.mirror->bytes(the sparse extent) times two for a writable range.Tested here (Linux, GCC, RTX 3080):
agc_driver_graphicsandconventions_function_bodiespass on f0dd6505.Not tested:
guest arena unavailable or not write-watched), so the write-back path, including the new sparse part, did not run here. @kr4y4, if you can repeat your run on the new head, that would cover it; your earlier run was on 23128dbd, before the sparse changes.AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T18:50:15Z.
Review: CHANGES_REQUESTED
Thanks for splitting the budget change out. The diff looks consistent to us:
compareBlock(fill and copy paths),WriteBack(storeSparse/storeChangedagainst the shadow) and theheapFootprintaccounting agree, and the scoped build plus ctest of libSceAgcDriver pass on Linux/lavapipe.What is still missing is evidence for the changed path on this head:
agc_driver_graphicsare skipped too (guest arena unavailable or not write-watched), so the write-back path, including the sparse part added in the rebase, is not exercised by any run we can do. kr4y4's Windows run covers 23128dbd, before the sparse changes. Please post a run ofagc_driver_graphicson f0dd6505 where those subtests run (no skip line), or add a test that exercises the shadow/write-back of a sparse and a non-sparse writable heap mirror on Linux CI.takeHeapReferencesallocations, as @oneandonlydean asked.Once that is posted we can merge.
Imported from boykopovar/AnyPS5. Originally posted by ponhei9502 on 2026-10-11T19:18:43Z.
Follow-up after a second read of the rebased head; new head
f1bb0ca4.Fixed (was in both versions of this PR):
compareBlock's heap branch copied the block from guest memory twice, once into the mirror and once into the shadow. A guest thread writing between the two copies left mirror = old byte, shadow = new byte, and the nextWriteBackover that byte would have stored the old byte back to the guest. It now reads the guest once into the shadow and fills the mirror from the shadow.main's per-dispatch reference copy did not have this, so it was a regression of this PR.agc_driver_graphicsandconventions_function_bodiespass on the new head; the heap mirror subtests still skip here.Same shape in existing code, not touched here: the non-heap branch of
compareBlock(memcmpagainst the guest, then twomemcpyfrom the guest) reads the guest three times. I left it alone to keep this PR to one topic; say if you want it folded in.Question I could not settle from the source: in
WriteBackthe diff reads the live mirror bytes and thenmemcpy(shadow, current)reads them again. If GPU work of another dispatch that writes the same range can still be executing at that point, a byte written between the two reads enters the shadow without being stored and is never stored later. With the per-dispatch reference each dispatch diffed against its own copy. The existing non-heap writable mirrors already work this way, so I assumed the ordering makes it safe (a build waits for recorded work that writes the range before it refreshes). If that does not hold for heap mirrors with overlapping dispatches, the shadow should be taken from the bytes that were compared, in chunks through a scratch span; I can add that.AI-assisted: yes (the double read was found by a second AI review).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T20:51:17Z.
Review: CHANGES_REQUESTED
[review CHANGES_REQUESTED] Thanks for the split and for the double-read fix; the diff is consistent (
compareBlockfill/copy paths,WriteBackviastoreSparse/storeChanged,heapFootprint), and the scoped build + ctest of libSceAgcDriver pass on Linux/lavapipe. One point left, the question you raised:GuestBufferMemory.cpp:3513-3517: the diff readscurrentand thenmemcpy(shadow, current)reads it again. Another dispatch writing the same range can still be executing here, and nothing in the diff orders it against this write-back (the wait inrefreshMirrorcovers refreshes, not a write-back running beside later GPU work). A byte it writes between the two reads goes into the shadow without being stored, and its own write-back then sees no difference, so it is lost. The per-dispatch reference did not have this. Please take the shadow from the bytes that were compared, in chunks through a bounded scratch span (compare a chunk, store, copy that same chunk's scratch into the shadow), which removes the dependence on ordering.guest arena unavailable or not write-watched), so the write-back path (incl. the sparse part) has only the Windows run on 23128dbd (before the sparse rebase). Once the chunked version is pushed, a repeat ofagc_driver_graphicswhere the arena is write-watched (@kr4y4, or any Windows run) would cover it.Imported from boykopovar/AnyPS5. Originally posted by kr4y4 on 2026-10-12T00:16:18Z.
A Windows run of the rebased head
f1bb0ca4, where the heap mirror subtests run.sparseHeapMirrorTestsis under#ifdef _WIN32and needs a write-watched guest arena, so it also doesn't run on Linux.Setup: Windows 11 (26200), WinLibs GCC 15.2.0 r7, Release, CI configure flags, an RTX 4070 Laptop GPU and an Intel Raptor Lake-S iGPU. No
guest arena unavailable or not write-watchedline.agc_driver_graphicsfails onf1bb0ca4on both GPUs. The basea11c8f7f(itsGuestBufferMemory.cpp/.hppwith the same tests) passes on both.AGC graphics: a sparse heap was not mirrored once(BdaResources.cpp:809).heapBytesnow countsheapFootprint(bytes + shadow). The sparse heap is writable, so binding it adds 2 ×extent, and line 809 expects+ extent.2 * extentlocally, the same test stops later:heap mirror of 0x200300000+0x4000000: past the budget; heap mirrors hold 0 MiB of 4 MiB (APS5_HEAP_MIRROR_MIB).Graphics.cppsets the budget to 4 MiB. The mirror grown to 3 MiB is writable, so it now needs 6 MiB.Raising that budget to 8 MiB doesn't fix it:
heapMirrorTests(its sweep case seems to depend on the 4 MiB budget) then fails withheap mirror of 0x200560000+0x240000: vkAllocateMemory buffer: Vulkan result -2; heap mirrors hold 2 MiB of 8 MiB. Only withheapMirrorTestsskipped, the budget at 8 MiB and2 * extentdoes the rest ofagc_driver_graphicspass, on both GPUs. So whether the sparse test gets more room or the shadow stays out of the budget is your call; I haven't changed either in a proposal.Mutations (each build checked, the file restored after each). With
2 * extentand the 4 MiB budget:range->writable && !heap, as onmain): caught,writable mirror write-back has no shadow.storeChanged(begin, current, current)): caught,a writable heap mirror's write-back lost the GPU's store or rolled back the CPU's.These four pass every test that runs. That's everything before the sparse budget stop in the first setup, and all of
sparseHeapMirrorTestsin the second, so nothing here exercises them:memcpy(shadow, target, …);compareBlockcopying guest → mirror only, so the shadow isn't refreshed;storeChangedinstead ofstoreSparse;WriteBackwithout the finalmemcpy(mirror.shadow.data() + offset, current.data(), length).Not checked: your ordering question about the two reads in
WriteBack. Nothing here runs overlapping dispatches on one heap range.Written with AI assistance.
Imported from boykopovar/AnyPS5. Originally posted by Scramblrrrr on 2026-10-12T08:36:26Z.
Windows cross-test of
f1bb0ca4is now built on my 007 public perf stack, plus a WIP adjacent-allocation sparse-mirror fix: https://github.com/Scramblrrrr/AnyPS5/tree/codex/first-light-split-mirror-shadow-cross-test head 991d40bf6a1a53dde0038211db0fefe707e87405. Your commit is preserved with author and cherry-pick attribution as 4bf12ae43; no duplicate upstream PR.Confirmed kr4y4's sparse fixture budget failure after updating writable footprint expectations. Test-only adaptation: budget 4 -> 16 MiB, scale the read-only eviction case large/small allocations by the same factor (36/17 -> 144/68 64 KiB blocks). That keeps the sweep case over its budget instead of skipping it. No production budget changes. Writable sparse and split-range mirror assertions count the shadow too.
Added an overlap case in the Windows write-watched graphics fixture: two uploaded builds share one writable heap mirror; first GPU write changes a byte and is written back; CPU edits an untouched byte; second GPU write returns the first byte to its original value and changes another byte. Both GPU results and the untouched CPU edit must survive. With your production code it passes. Removing only WriteBack's final memcpy into mirror.shadow makes it fail: "overlapping mirror write-back lost a reverted GPU value or rolled back a CPU write". Restored exact source, rebuilt and reran: graphics fixture plus six focused Vulkan tests pass, 7/7 in 7.04 s, with split-range checks actually executed. Windows 11 26200 / GCC 15.2 Release / RTX 5070 Ti.
This is a cross-test stack, not a claim that the unmodified PR alone passes all current-main tests. Quiet 007 run now launched; game result pending. No title data uploaded. AI-assisted: Codex.
Imported from boykopovar/AnyPS5. Originally posted by Scramblrrrr on 2026-10-12T08:46:54Z.
Quiet #3248 combination 991d40bf6 reached the rendered title at frame 813, ~0.98 FPS, ~20.2 GB private memory, one bounded trim. Sparse-mirror-only 6f262 was ~0.97; earlier copy-based 1e3a was ~1.53. One run each, different camera positions. No demonstrated FPS recovery from the persistent shadow in this setup, despite passing the Windows overlap regression. Stopped intentionally at title. Starting same graphics binary SHA256 E51863D9E71ECD25230E500FA55C3AE71967940CF97A27420931DC06AD4745CA with only APS5_NO_SPARSE_HEAP_MIRROR=1 added to the quiet configuration. No new upstream proposal. AI-assisted: Codex.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-14T13:59:37Z.
Review: CHANGES_REQUESTED
Picking this up again, since there's been no push since our last review. Three things block it, and the first one decides whether the other two are worth doing:
mmaps, not frame time. The only in-title run of this head so far is @Scramblrrrr's: ~0.98 FPS with the shadow, ~0.97 without it, one run each with different camera positions, and ~20 GB private memory. That shows no gain. Meanwhile the PR keeps a persistent second copy of every writable heap mirror. Please post a paired measurement on this branch alone:mainvsmain+ this PR, same save and camera, a few runs each, with FPS (or frame time) and the process's peak private memory. If the gain doesn't show up there, the transient per-dispatch copy is the better trade.agc_driver_graphicsfails on Windows onf1bb0ca4, while the base passes (@kr4y4, RTX 4070 and Intel iGPU).heapFootprintcounts the shadow, so a writable sparse heap adds2 * extentwhereBdaResources.cpp:809expectsextent. The 3 MiB writable mirror then needs 6 MiB of the 4 MiB budget set atGraphics.cpp:4245, and raising that budget breaks the sweep case ofheapMirrorTests. Either keep the shadow out ofheapBytes(it replaces the per-dispatch copies, which the budget never counted, so what throws "past the budget" stays as onmain), or count it and rescale the fixtures. In both cases the heap mirror subtests must pass where the arena is write-watched (Windows), since they skip on Linux.GuestBufferMemory.cpp:3512-3517(still open from our last review, and the question you raised): the diff readscurrentand thenmemcpy(shadow, current)reads it a second time. A byte that another dispatch still running on the same range writes between the two reads enters the shadow without being stored, so it is lost. Compare and copy through a bounded scratch chunk instead: copy a chunk of the mirror once, diff and store from that copy, then copy that same copy into the shadow.The branch also conflicts with
mainnow (GuestBufferMemory.hpp,heapReferencesnext to the newreadsOverBase).Imported from boykopovar/AnyPS5. Originally posted by ponhei9502 on 2026-10-15T08:07:23Z.
Thanks, kr4y4 and Scramblrrrr, for the Windows runs and the overlap test.
Where this stands from our side:
agc_driver_graphicsfailure onf1bb0ca4is the sparse-heap fixture expecting+ extentand a 4 MiB budget whileheapBytesnow counts the shadow (2x for a writable heap). Scramblrrrr's adapted fixture and overlap case pass on the production change, so we believe the write-back itself is right. This is read from their comment and our diff; we did not re-run it, because the heap mirror subtests do not run on Linux.Given that, we are closing this PR instead of leaving a failing, conflicting branch open. If a Linux A/B (memory and flip time, same scene, with and without the shadow) shows a gain, we will reopen with the fixture changes from Scramblrrrr's cross-test.
AI-assisted: yes
Pull request closed