fix(agc): stop frame capture deltas from collecting the previous delta's pages again #14137
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/14137"
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 thuanquang on 2026-10-31T20:30:34Z.
What
docs/dev/BUILD.mddescribes each memory delta of a frame capture as the guest pages the CPU wrote since the previous call that handed work to the GPU. Onmaineach delta also collects again the pages the previous delta collected (line numbers onmain91ecd2d974):emitDeltagives every rangesince = generation, readsmark = WriteGeneration()before the walk and setsgeneration = markafter it (FrameRecorder.cppL329-334).CollectWrittenBlocksraises the tracker generation and only then stamps the pages its walk finds (GuestMemory.cppL1681, L1608-1610). So every page a delta's own walk reports carries a stamp newer thanmark, and the next delta lists it again.markthe same way (L401, L409) and start fromgeneration(L405), andemitDeltaclears their marks (L335). A page a full delta collected is therefore collected again by the next shader delta of its 64 KiB block as well.Each repeat is read and written again, and a delta made only of repeats still waits for the driver to go idle before the call it precedes (L422), so that call is recorded with nothing in flight. In a Persona 5 Royal capture made on
mainat86fb985abb(the delta bookkeeping is unchanged since), the second full delta (group 47) holds every page of the first, 2,610.9 MiB by the chunk headers.This change:
keeps, for each watched or unwatched range, the generation its last
CollectWrittenBlocksreturned (read under the tracker lock after the walk), and starts the range's next collect there.start()takes these values from its reset walks;keeps, for each shader block, the generation its last collect returned. A block lying wholly inside those ranges starts from the newer of that value and the oldest value of its ranges, so it skips what their full deltas took. Any other block starts from its own value, and the first time from the tracker generation read right after the reset walks (
GuestMemory::TrackerGeneration), so it never lists a page stamped before the capture started;collects a watched or unwatched range the registry gained just before reading it, so the next delta takes only what was written after that collect, and writes every 64 KiB block of such a range in the delta that adds it, zero or not.
mainwrites only the nonzero blocks there and records what the CPU wrote before the add, a clear included, in its next delta. That delta now starts after the add's collect, so a skipped all-zero block would keep what the replay already holds at its address (found by @chitters2004;late_clearbelow);reads every delta through
GuestMemory::ReadCommitted, as the snapshot already does. A delta read onmainusesReadCommittedUnsynced, so it can miss a result the driver still keeps on the GPU for that page (pending_resultbelow). Since the next delta no longer reads the page again, the read now stores those results first;has the replay land those results too:
agc_frame_replayreads each delta chunk, callsAgcDriverPrepareCommandWrite_nid_no_patchover its range and then copies it, the order #12567'srestoreGroupuses.calls.binbecomes format 2 (aps5-frame-calls 2);FrameCaptureReaderstill reads format 1 and reports the format (Version()), and the replay refuses a format 1 capture before it restores any memory, since such a capture does not record whether GPU writes had landed before each delta was read. With theReadCommittedread in the bullet above, these are the four items @chitters2004 asked for on #12567 and we agreed on in #12568's thread;closes the two tracker gaps @oneandonlydean named, which
main's repeated read covered:GuestMemory::StoreOwnBytes. While a capture records (the recorder turnsGuestMemory::SetOwnStoreCompareon instart()before its reset collects, and off instop()andfinish()), a driver store from the CPU that gives its bytes (Write,WriteChanged, the guest label store, the span form ofStoreOwnBytes, and a newStoreOwnBytesform whose callback writes the bytes it stores into a span it receives) copies its page-rounded range before its first walk and applies its own bytes to the copy; a page its second walk takes that then differs from the copy, or can no longer be read, is noted, andCollectWrittenBlockslists it. A store that gives no bytes (MEM_SEMAPHORE signal and wait, buffer copies on the CPU, andmain's compare-exchange write-backWriteChangedIfHeld, which stops at the first byte it loses) notes every page its second walk takes. A keep-guest write-back (WriteChangedKeepingGuest, #6185) leaves the guest's bytes in its copy, as its store does. No stamp changes, soUnchangedSince,StoredOver,UnchangedSinceCollectedandChangedBlocksanswer as before, with or without a capture;MarkWrittenfresh collect noted.CollectWrittenBlocksalso admits a 64 KiB block whose block stamp is newer thansince, so such a page is listed: the fresh collect raises the block stamp, not the CPU block stamp the loop checked first. The whole clip of a block is listed only when its CPU block stamp is newer and no page in the clip has a newer CPU note.agc_driver_frame_replay_store_between_walksandagc_driver_frame_replay_fresh_noteare @chitters2004's tests (c9a87b435c, unchanged). His fix (5458ad80b2) is not taken; the reason and the measurements are in the comment with this push.Not changed here:
Unwatch, an import that unwatches it, a failed fresh collect) after a delta collected it is not recorded until the tracker notes the page again;mainread such a page once more in the next delta. A delta's own walk also skips every 64 KiB block that holds such a page, as onmain. Debt entry "Pages that leave the write watch during a frame capture".mainalso recorded it when the previous delta had found the page written. Debt entry "Driver stores during a frame capture".WriteChangedIfHeld) are listed after every such store, and the replay writes the captured bytes there over what its own semaphore or copy stored. How much of the casino capture below they make up, and whether they change replayed waits, is not measured.windowPagesmap in every run; onlyCollectWrittenBlocksreads it, and its memory is not measured.UnchangedSinceCollected, the CPU flag ofChangedBlocksandStoredOverbeside the stored bytes, as onmain. This PR changes only whatCollectWrittenBlockslists while a capture records. Debt entry "CPU stores during driver stores".Write,WriteChanged, the guest label store or the span form ofStoreOwnBytes. On Windows none of them runs anything between its two walks, andWriteChangedand the label store run nothing there on any OS; on Linux the span form and aWriteof 4 KiB or more call the shared-backing writer between the walks, which no row drives. Each store builds its copy from its own input (source, value, current), never by reading memory back.start()turns the switch on after its reset collects instead of before them.main.Side effect: a call whose delta would have held only repeated pages now gets no memory record and no idle wait, so a new capture records it at the depth the title had; a delta made only of pages of stores that give no bytes still gets both. That is not the aim of this PR: #12568 makes every full delta wait for a settled driver while work is in flight, and recording the in-flight depth stays with the follow-up stacked on #12568 (#15136).
Overlap (trial merges of each open PR's head with this head, listing only conflicts this PR adds to what the PR already has with
main91ecd2d974):GuestMemory.cppstruct and write-tracking test registration; the merge ofmainkeeps both sides.tools/FrameReplay.cpp, the mode list of the state tests and the frame capture paragraph ofdocs/dev/BUILD.md. It has the identicalreadGuestchange and already flushes before each delta copy inrestoreGroup; whichever merges second drops its copy.FrameRecorder.hpp/.cpp, the tool, the mode list and BUILD.md. As before, it moves theCollectWrittenBlocksloop behind its settled wait and collects per 64 KiB piece; whichever merges second keeps asinceper collect call set to the value that call returned, gives every piece a starting value from a reset walk, dropsshaderMarks.clear()fromemitDeltaand passes!collected && zerofor added ranges. I'll post a rebase of #12568 onto this PR.restoreGroup, which has no flush; #12567, stacked on it, adds the flush there. Whichever of this PR and #12318 merges second keeps theAgcDriverPrepareCommandWrite_nid_no_patchcall before each delta copy.FrameRecorder::finish().storeOwn's signature next to this PR's newimagedparameter and the compare switch inGuestMemory.cpp.WindowCopy::Holds, where this PR adds the store-image compare.FrameRecorder.hpp, BUILD.md), #13984 (mine;FrameReplayState.cpp), #12696 and #11436 (the mode list) conflict mechanically.main.Tested
Windows 11 26200, Ryzen 5 5600X, Radeon RX 6700 XT (gfx1031), AMD driver 32.0.21045.16010, WinLibs GCC 15.2.0 r7, Release,
BUILD_TESTING=ON, full builds with submodules at their pins:main91ecd2d9743b831b575d293e6c8fafbe737e1e88(merged into this branch) and this PR's head702492e63e.This head (
ca4553365f) mergesmain1c8c0efc8cto resolve the conflict with #13021 inGuestMemory.cpp:storeOwnkeeps #13021'scompleteflag next to this PR'simagedflag, andWriteChangedIfHeld(new onmain) stores through the form that gives no bytes. On it, the focused set below passes 36 of 36 in 3 of 3 runs (main1c8c0efc8c: 23 of 23),agc_driver_native_multisample_depth(aWriteChangedIfHeldcaller) 1 of 1 in 3 runs on both, the validation-layer run shows 0VUID-lines on both, andgit diff --checkis clean. Every other result below is from the previous head702492e63e(main91ecd2d974merged), whose capture and tracker code is the same apart from that store.Modes of
agc_driver_frame_replay_state_testsdriveFrameRecorderdirectly and need no GPU. From the previous revision:agc_driver_frame_replay_oncewrites a page before each of two suspend points and commits a range during the capture. Between the suspend points it writes a page in the second of the two 64 KiB blocks a shader header marks, and registers that shader twice; the header shares the first page's block. The page written before each suspend point, and the written page of the added range, must each be in exactly one memory delta, the one before their suspend point, and the second registration must collect nothing. Every page of both ranges is written before the capture or before the add, so no snapshot or delta read is a page's first access.agc_driver_frame_replay_pending_resultinstalls a flush hook that stores a result word over a page the CPU wrote, standing in for a storage result the driver keeps on the GPU until the page is read. The delta before the first suspend point, and the delta that adds a range committed during the capture, must each hold the stored value.agc_driver_frame_replay_partly_coveredwrites a 16 KiB allocation before the capture and registers a shader whose header lies in it, so the header's 64 KiB block is only partly inside the captured ranges. The written page must be in no memory delta, since the snapshot holds it.agc_driver_frame_replay_late_clear(@chitters2004's test from this thread) starts the capture, then commits a range, writes a page in it, registers a shader whose header lies in the 64 KiB block before that page's block, clears the page and reaches two suspend points. The last memory delta holding the page must hold the clear.New in this push:
gpu_write_before_delta: a delta copy over a GPU write the replay still has pending must hold the delta's bytes;calls_v1: a calls format 1 capture is refused before any memory is restored.store_between_walks,fresh_note(@chitters2004's).store_window: a label store through theStoreOwnBytesform that gives no bytes while another thread writes the same page, then four driver stores with given bytes into pages nothing else writes; the other thread's byte must be in a delta and the four pages in none, and a driver store afterfinish()must not be listed.store_window_unwritten: the same store from another thread into a page the CPU has not written.store_window_stopped: the capture stops when it starts (APS5_FRAME_CAPTURE_MIN_FREE_BYTESabove any free space); a driver store after that must not be listed.agc_write_tracking_fresh_view(Windows): a section view whose first page alone is collected before a GPU write's fresh collect takes the rest; those pages must be listed.agc_write_trackinggains two guards: a page only an import window stamped is listed, a block only a GPU write stamped lists nothing.agc_write_tracking_own_store_images(Windows; on Linux the last check ofagc_write_tracking): a driver store made before the compare is on lists nothing; then with it on, aWrite, a store of given bytes, a label store, a write-back and a keep-guest write-back over a page the guest wrote list nothing; a store from another thread beside the bytes of a two-page driver store lists only its page; one over a driver store's bytes is listed; one that undoes a store which gives no bytes is listed; a listed page is not listed again.Each row, 3 runs per tree:
main91ecd2d974+ the rowsstore_between_walksfresh_notestore_windowstore_window_unwrittenstore_window_stoppedagc_write_tracking_fresh_viewagc_write_tracking_own_store_imagesmain(it callsSetOwnStoreCompareand the newStoreOwnBytesform)Messages on
main(store_between_walkspasses there becausemain's repeated read records the store; it guards this PR's cutoff, aslate_cleardoes):With the three tracker commits reverted on this head (
git revert --no-commitof the keep-guest, store-compare and fresh-collect fixes;GuestMemory.cppthen equalsmain's apart from theStoreOwnBytesform refactor), the same four fail with the same messages, and also:Each term of the tracker change, dropped one at a time (incremental build of the two test executables and
libs), turns a named row red. 31 drop runs (29 distinct terms) on2710134746(D14 and Dkeep again on this head), each red: the window-page note and listing (D1, D2, D19), the held stamp kind (D3, D9a, D9b), the window passed to the second walk (D4), which stores take an image (D5, D6, D20, D21), the store and page offsets into the image (D7, D23), the empty-image check before the compare (D8), each store's own bytes applied to its image (D10-D14), the recorder turning the compare on (D15), the fresh and CPU block-stamp admission terms (D16, D17, and the same two again as TB-no-stamp-admission and TB-no-cpu-admission), the whole-clip fallback condition (D18), the copy itself (D22), the keep-guest rule (Dkeep), the switch forced on, default and setter (Don), the compare forced on outside a capture (Dcmp), and the switch cleared infinish()(Dfin) and instop()(Dstop). For example Dstop:store_window_stopped: a driver store made after the capture stopped was listed as a CPU write; Dkeep:own_store_images: a keep-guest write-back that kept a guest byte was listed as a CPU write.ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ctest --test-dir build -R "frame_(replay|capture)|^agc_write_tracking|^agc_(resident_direct_remap|rewatched_direct_shared|import_alias_shared|compared_shared_generations)$", 3 runs per build, then one run withVK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validationand-V, a local Vulkan-ValidationLayers build, implicit layers disabled andVK_LOADER_DEBUG=layer:VUID-linesmain91ecd2d974702492e63eNo test in this set creates a Vulkan instance (the loader inserted the layer 0 times in both logs), so the layer had nothing to check here.
ANYPS5_REQUIRE_VULKAN=1 ctest -R "^(agc|shader)_"on the previous local revision2710134746(the same code; this head adds one premise check to a test and rewords a debt entry): 1310 passed, 15 skipped, 3 failed of 1328. The three,agc_driver_direct_write_completion,agc_driver_scratch_poolandagc_driver_sample_order_grid_reference, also fail onmain91ecd2d974on this GPU (3 of 3 runs each).Linux: a WSL2 build of this head (Ubuntu 24.04, lavapipe) compiles, and
gpu_write_before_delta,calls_v1,order,zero,tokens,blocking,unwatchedandagc_frame_capturepass there (3 runs withAPS5_WRITE_WATCH_IMPORTS=unwatch, 1 without).agc_write_trackingskips and the capture rows cannot start: this WSL2 kernel (5.15) has no asynchronous userfaultfd write protection, so the guest write watch is unavailable. The new rows have not run on Linux.Persona 5 Royal (PPSA05110), casino gameplay, shared GPU, one 20-frame capture per build, each started 45 s after the gameplay HUD appeared in its own run of the same route:
main91ecd2d974recorded 1,554 memory groups and 1,114.4 MiB of deltas, this head 692 and 610.6 MiB (capture.jsonmemory_groups,delta_bytes). The runs reached the scene separately, so the title's own work differs between them.agc_frame_replay --strictof each capture through its own build, twice each: 20 frames and 120 submits, 0 unfinished, 0 pacing timeouts, and both reference frames pixel-identical (pixels_identical1.000000).Not tested: macOS (frame capture throws there), a native Linux run, other GPUs. @chitters2004's runs of his two tests on an RTX 3080 (
c9a87b435c,5458ad80b2) and TechLevelZero's NVIDIA CI run ofc7a4fc97bbare on earlier revisions.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-03T13:03:58Z.
Review: APPROVED
Reviewed — approved
The merged tree builds, and all 28 frame capture/replay and write-tracking tests pass on native Linux with the guest write watch active. That includes the capture rows the description says have not run on Linux. A three-stage negative control made every new row fail, and I found nothing blocking.
What I ran
Head
702492e63ea6f9b96280654c1b1733a02e059377,main4f41f4c375f5abb487dbd184fbc150f31994d762, merged with--no-ff(tree23da7e8b9297967958c6b8f5082d0550652a760e). Machine: Debian 13 VM, 32 vCPU Xeon Gold 6136, GCC 14.2.0, Release, Ninja,BUILD_TESTING=ON, lavapipe (Mesa 26.1.6), no GPU.Results
git diff --checkcheck_conventions.pylibs(script)main(agc_driver_division, the denormal-mode rows,vector_constant_factor_tininess, one unwrap test)VUID-linesagc_write_tracking*The capture rows run on native Linux (excerpt)
agc_write_trackingreports Passed, not Skipped, so on Linux it also runsCheckOwnStoreImages.The description says the new capture rows and
agc_write_trackinghave not run on Linux, because the author's WSL2 kernel has no asynchronous userfaultfd write protection. On this kernel (6.12) the write watch is available. Here they run and pass:once,pending_result,partly_covered,late_clear,store_between_walks,store_window,store_window_unwritten,store_window_stopped,gpu_write_before_delta,calls_v1,agc_frame_captureandagc_write_tracking, including the Linux tail ofown_store_images.fresh_note,agc_write_tracking_fresh_viewand the separateown_store_imagesregistration are Windows-only and were not run.Negative control
The new tests call the new API (
SetOwnStoreCompare, the span form ofStoreOwnBytes,FrameCaptureReader::Version()). Restoring every production file frommainwould therefore not compile, so I reverted in three stages.A.
FrameRecorder.hpp,FrameRecorder.cppandtools/FrameReplay.cpprestored frommain(tracker and reader as merged). Six rows failed:Stage A failures
late_clear,store_between_walksandpartly_coveredpass withmain's recorder. This matches the description:main's repeated read covers them, and they guard the new cutoff.B. Merged recorder, with two tracker terms disabled in
GuestMemory.cpp:compareforced tofalseinstoreOwn, and the block-stamp admission inCollectWrittenBlocksremoved (if (!cpu) continue;). Four rows failed:store_window,store_window_unwritten,store_between_walks("has byte 0, not the 107"), andagc_write_tracking("a store another thread made beside a driver store during the store did not list exactly its page; ... over a driver store's bytes ... was not listed; ... that undid a driver store which gives no bytes was not listed").C. Two single terms dropped: the keep-guest condition in
writeChanged's image update, and|| collectedin the added-range loop. Two rows failed:agc_write_tracking("a keep-guest write-back that kept a guest byte was listed as a CPU write") andlate_clear("group 1 of 1 holding it) has byte 90, not the 0").After restoring with
git show 23da7e8b…:<path>,git status --porcelainwas empty, the rebuild includinglibssucceeded, and the focused set passed 28/28 again.Findings
Blocking
None.
Non-blocking
start()throws after turning it on.FrameRecorder::start()callsGuestMemory::SetOwnStoreCompare(true)atcore/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp:548. It then creates the writer at line 553, and that can throw: FrameRecorder.cpp L547-L553.FrameCaptureWriter's constructor throws when the capture directory cannot be created (FrameCapture.cpp L202-L205). On that path neitherstop()norfinish()runs. The process-wide switch then stays on with no capture, so every driver store from the CPU keeps copying its pages under the tracker lock and noting pages inwindowPages. Onmainthis throw left no global state behind.start()exits by an exception.Not verified
fresh_note,agc_write_tracking_fresh_view, theown_store_imagesregistration) and any Windows-only paths of the store compare (the section view and fresh-collect cases): this host is Linux.mainagainst 610.6 MiB here) and the--strictreplays: I did not launch any title.windowPagesuses in long runs, beyond the author's single-run figures.Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T23:43:46Z.
Review: APPROVED
Re-checked — approved
The only change since my last review is the merge of
main1c8c0efc8c(ca4553365f). It resolves thestoreOwnconflict with #13021 correctly. The focused set passes on the merged tree, and the negative control still makes the tracker rows fail. One non-blocking finding from my last review is still open.What changed since my last review
f0ef36adee…702492e63e). The only new commit is the mergeca4553365fofmain1c8c0efc8c.GuestMemory.cpp:storeOwnnow takes this PR'simagedflag together with #13021'scompletedefault argument.WriteChangedIfHeld, which is new onmain, stores through the form that gives no bytes (storeOwn(address, size, false, …)atcore/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp:3170). That gives it an empty image.WindowCopy::Holdsreturns false for an empty image, so while a capture records, every page its second walk takes is listed. This matches the description and the debt entry: a compare-exchange write-back that can stop at the first lost byte has no complete image to compare against, so treating it like the MEM_SEMAPHORE and CPU-copy stores is the conservative choice.What I ran
Head
ca4553365ffc41b27ee5aed87322616b071db376,main1c8c0efc8c41314402e6966da5bef6ea3d639d10, merged tree0d003ec7f41be0a5c2e7c456ca988f6c2878f520. Debian 13 VM, Xeon Gold 6136, GCC 14.2.0, Release, lavapipe, no GPU.git diff --checkcheck_conventions.pylibs(script)mainVUID-lines,agc_driver_image_gather_volume. That test came in withmain's side of the merge (ImageGatherVolume.cppis not in the PR's files) and is marked "test not run on main" because the baseline1e658521a0is older thanmain. It is not counted against this PRagc_driver_native_multisample_depth(aWriteChangedIfHeldcaller)libsOK, 6/6 passNegative control (compare forced off on the merged tree)
Previous findings
start()throws after turning it on.GuestMemory::SetOwnStoreCompare(true)still runs atcore/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp:548, beforestd::make_unique<FrameCaptureWriter>(directory)at line 553, and the writer can throw: FrameRecorder.cpp L547-L553. The fix suggested last time still applies: turn the switch on after the writer exists and before the reset collects, or add a guard that turns it off whenstart()exits by an exception.New findings
Blocking
None.
Non-blocking
None.
Not verified
fresh_note,agc_write_tracking_fresh_view, the separateown_store_imagesregistration): this host runs Linux.--strictreplays on a title: I launched no title.WriteChangedIfHeldpages. It is not measured anywhere.702492e63e.