fix(agc): keep guest writes over a stale stencil plane #14969
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/14969"
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 JJenkx on 2026-11-02T06:17:49Z.
What
A depth surface's stencil plane reaches guest memory only when something needs it: it is marked stale when a draw writes stencil, and stored later. One later trigger is a GPU write that retires the surface (
RetireDepthSurfaces,RetireCoveredDepthSurfaces); another is a read of the plane (FlushDepthPlanes).That store wrote the stencil over the plane even when the guest had written the plane after the draw, typically because the title had freed the memory and reused it for something else.
The mirror upload inside
StoreStencilPlanetakes the guest bytes at store time, so the guest's later write is already in the "original" bytes. The storage write-back therefore cannot tell that write apart from stale stencil data.On Windows the driver stops write-watching memory it uses as a surface, so the tracker does not see that write either.
Space Adventure Cobra: The Awakening (PPSA17337) crashes this way. Unity's graphics-thread allocator keeps stencil and depth targets in its heap. After the title frees one, the allocator's free-list links in the block are overwritten by the old stencil plane, and the next allocation dereferences them. In a diagnostic build that logged every guest write, the last write over the corrupted links before each crash was a write-back with reason
stencil plane store.How it works now:
The comparison point is the plane's last store, or the last stencil-writing draw or stencil plane fill. HTILE clears and rebinds that mark the plane stale again do not move it, so a guest write before them still counts. On an unwatched plane the guest bytes are copied at that point; a later stencil draw takes a new copy and so supersedes an intervening CPU write.
Before storing a stale stencil plane, both store paths check whether the guest has written the plane since that point. On watched memory this uses
CollectWritesUncachedandWrittenSinceagainst the generation of the last sync or store; otherwise the bytes are compared with the copy.If the guest wrote the plane, it keeps its bytes: the store is dropped and the stale state cleared. Otherwise the plane is stored as before.
#14475 also changes
DepthSurface.cpp, but only for depth-plane clears superseded by a storage write; it touches neither stencil store path.Tested
Linux verification of the allocation fix — 2026-11-09. Public
65ac200c4210ff03f46e0efe3b0a063e7aecbf91merged cleanly onto main7259cce11195f360698772da8c0b3af756bf7c8fas private421dba94b8182362658135bafbd3dbc2987d11ce. No further production change or source push was made. ThecheckAccess,verify,AccessibleandMarkStencilStalebodies are byte-identical to this public fix.Linux 7.2.14-arch1-1, GCC16.2.1 Release:
agc_driver_graphics,agc_driver_graphics_maps_fallbackandagc_graphics_profile_drawpass on both main and the integrated fix (3/3 each, zero CTest skips). These are CPU MockVulkan fixtures, including the glibc repeated-depth-view allocation check; they do not create a physical Vulkan instance. This verifies the three current-main cases reported by @ryanc2112 on Linux. The old broken head was not rerun here.Separately, the physical
agc_driver_stencil_plane_memoryfixture passes on both arms on AMD Radeon RX6650XT / RADV NAVI23, Mesa26.2.6, with required Vulkan, no shader cache and confirmed Khronos insertion, zero VUIDs. It explicitly reports that this memory is not write-watched: conditional guest-write/watched-memory and heap-mirror subcases were not exercised. This adds basic current-head stencil coverage, not new watched memfd-reuse, title, Windows or performance evidence. Earlier external watched-memory reports retain their own head/hardware scope.Raw main/change logs, source proof, exact merge patch and binary hashes, SHA-256
98934a92954fe20d27e93bb21382d8af1623226871e23f38895f74320ad4a4a8(download and all 24 manifest files verified). The generic wrapper initially required layer insertion for the CPU-only main graphics fixtures; its raw result is retained with an explicit reviewed classification, not presented as missing GPU execution for those mocks. Current full CI still requires maintainer dispatch.Earlier qualifications below retain their original pins and platform limits.
A title it unblocks, reported by @milescoviello (comment). STEINS;GATE RE:BOOT (PPSA36591), Ubuntu 26.04, RTX 4070 Ti (NVIDIA 615.71), new game with fast text skip, 900 s runs. On
mainthe title's GPU Heap is corrupted ([SceLibc] A heap error is detected, then a SIGSEGV in its allocator) in 5 of 5 runs one322066f82(333 to 413 s) and on9a4bcc3018(329 s). With this PR merged onto9a4bcc3018(6096b477de), two runs reached the 900 s limit with no heap error. In a tracedmainrun, the last two write-backs over the corrupted chunk werestencil plane stores of two depth targets at that address: the reused-memory case this PR handles. In a later update, on the same merge (6096b477de) the title played through to an ending (Suzuha's, "Irreversible Reboot", shown in its CLEAR LIST), about 3 hours with no heap error or crash, while plainmainstill hit the GPU Heap error a few minutes into a new game in 5 of 5 runs. A re-run on currentmain, with the same 600 s new-game fast skip:main22ae9a397dhit[SceLibc] A heap error is detectedand a SIGSEGV after 398 s, whilemainwith this headed4ae4f33amerged (97eea195bd, clean merge) ran to the 600 s limit with no heap error.Linux re-check of the current head by @hugodearaujo (comment). Arch Linux 7.2.11, RX 9070 XT (RADV GFX1201, Mesa 26.2.6), Release,
main1c8c0efc8c+ #8932 with this PR's four commits up toc1fe457b32. Hollow Knight: Silksong's first-boot route (calibration and profile screens, 420 s, same save and inputs), which crashed 3 of 3 on811f2d92e4, crashes 0 of 3 onc1fe457b32; all three runs reached the limit at 600 presents per 10 s. A shared-memfd fixture of theirs that runs the write-watched branch passes next toCheckGuestWriteBeforeRepeatedClearswith the validation layer inserted and noVUID-line.Windows follow-up for the re-marking report (2026-11-04). @hugodearaujo found on Linux, in Hollow Knight: Silksong (PPSA12544), that an HTILE clear or bind re-marks a plane every frame, and that the previous comparison point (the last stale mark) moved with it. In 1,478 of the stores they traced, the guest had written the plane after its last sync but before its last mark, and the store overwrote it; their first-boot route crashed 3 of 3 with the previous head. Head
c1fe457b32(one commit on811f2d92e4) compares with the last store or stencil write instead. It also covers the unwatched path, where the re-mark re-took the snapshot after the guest write.agc_driver_stencil_plane_memorygets a new case: a draw writes stencil0x18and a read stores it, the guest writes0x77, two HTILE fills over the surface re-mark the plane, and a read follows. The plane must still hold0x77. Windows 11 Enterprise 10.0.22621, AMD Radeon RX 6700 XT, AMD proprietary driver 26.10.1, WinLibs GCC 15.2.0 UCRT r7, Release, through the shared GPU queue withANYPS5_REQUIRE_VULKAN=1,ANYPS5_NO_SHADER_CACHE=1and the Khronos validation layer 1.4.363 inserted. Each arm is merged ontomainb11c7bf84f:mainb11c7bf84f(main's own fixture)811f2d92e4with the new fixtureNo test was skipped. As before on Windows, the fixture's watched-only section reports "guest memory is not write-watched here" in both the
mainand the fix arm, so the Windows run covers the snapshot path; the new case does not depend on write-watching. The watched path follows the reviewer's variant (last sync), which ran 0 of 6 first-boot crashes and 0 of 8 gameplay crashes in their Linux runs; I have not reproduced the title route. The Windows run is a single FIFO job,f878bf6e29d3483887c1799b4d02579c.Earlier Linux refresh (2026-11-03). Head
811f2d92e488fb8b335be520ef9bc74d87074d68is three commits on main04a9eb4fa2877eb6e40bf2c83adf972e40d89b24with no merge commits. The rebase preserves main's unmapped-plane serial/invalidation handling from merged #15466 and adds the guest-write predicate to both stale stencil store paths. The second-draw snapshot-refresh commit is unchanged apart from its parent; the final commit documents partial-write behavior and comparison cost and removes the stray test blank line.On the same Ryzen 9 7950X / Radeon RX 6650 XT (RADV NAVI23) Linux host, main and the change each pass all eight focused stencil/depth cases with
ANYPS5_REQUIRE_VULKAN=1,ANYPS5_NO_SHADER_CACHE=1, and the realVK_LAYER_KHRONOS_validationinserted: zero VUIDs, zero skipped tests, unchanged sources/libraries throughout each arm. Exact selection and commands are in the evidence archive. The fixture reports that these planes are not write-watched, so this is snapshot-path coverage; the watched branch remains unverified on this host.The negative control uses current main's production code with this PR's updated
StencilPlaneMemory.cppfixture. See the linked result for the expected stale-store corruption assertion. It stops at the first failing assertion, so it does not independently prove that every later new case fails on main. No new title, Windows, or frame-time result is claimed in this refresh.Current Linux commands, logs, patches, source pins and negative control (SHA-256
b03befd0d94a1cc1608146652b63eeb7e62641d2e60d576f94e6bedf6ce8f204).Earlier Windows and title measurements follow with their original revisions.
Windows 11 Enterprise 10.0.22621, AMD Ryzen 9 5950X, AMD Radeon RX 6700 XT, AMD proprietary driver 26.10.1, WinLibs GCC 15.2.0 UCRT r7, Release. All runs went through the shared GPU queue with
VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation,ANYPS5_NO_SHADER_CACHE=1andANYPS5_REQUIRE_VULKAN=1.agc_driver_stencil_plane_memorygets a new case: a draw writes stencil0x3c, the guest then writes0x77over the stencil plane, and a GPU write over the depth plane retires the surface. The plane must still hold0x77, and a later read must store nothing. The case runs whether or not the plane is write-watched.main93dbd0f82awith only this test added: fails with "retiring the surface stored its stale stencil 0x3c over the guest's later write of 0x77".This change: passes 3/3 with no VUIDs. The test's existing guest-write-over-a-stored-plane section still runs only where the plane is write-watched, and is not exercised on Windows.
Full GPU suite at
ac9b10b80a(this PR's commit), with the validation layer inserted 1084 times: 3234/3282 pass and 19 skip.All 27 stencil and depth tests pass, including
agc_driver_stencil_plane_memory,agc_driver_stencil_replay,agc_driver_depth_surface_from_storageand theagc_driver_depth_plane_*set.The VUIDs are the same three
mainreports.main0cc3899f69, run the same way, fails the same 28 tests: 26video_out_flip_*, which returnVK_ERROR_SURFACE_LOSTbecause this machine's display was off during both runs, plusagc_driver_sample_order_grid_referenceandngs2_pitchshift.The only difference was
agc_driver_pipeline_journal, which segfaulted once in a validation-layer worker thread on this change. It then passed 3/3 and 20/20 on this change and 3/3 and 20/20 onmain, and this change does not touch that code.Space Adventure Cobra: The Awakening (PPSA17337). Each boot started without a save and ran 120 s with scripted
crosspresses.A diagnostic build of
mainthat skipped every stale stencil store ran 5/5 without a crash. That build is not part of this PR.Boots of unchanged
maincrashed on the allocator corruption at 20–90 s. That includes 2 of 5 on0580e5c951and 2 of 3 withAPS5_NO_HOST_IMPORT=1.Matched boots, five each, in one session through the shared FIFO (all five fix boots ran first, then the five
mainboots):| Libraries | Boots | Crashed |
|---|---:|---|
| this change (
da1cee2240, same content as the PR commit) | 5 | none (120 s each) ||
main93dbd0f82a| 5 | 1, at 21.1 s, the allocator fault atapp.exe+0x17f7e33|Five boots per side is a small sample, but it is consistent with the diagnostic build and the test above. Longer
mainboots crashed every time (89 s and 212 s). Two 300 s boots of heade84452d263both ran to the cap without a crash (follow-up).Cost. On memory that is not write-watched, stores compare the complete plane. Stencil-writing draws compare the guest bytes with the cached baseline and refresh the copy when its size or bytes differ. These operations hold the graphics locks. At 3840x2160 each full-plane comparison reads about 8 MiB. The title timings below do not isolate or establish the cost of a stencil-heavy workload.
Partial-write limitation. A CPU write after the last draw drops the entire pending stencil store. Untouched bytes keep their earlier guest contents instead of the drawn stencil; on watched memory, a write anywhere on an overlapping tracked page can trigger that drop. Bytewise merging is not implemented; this is recorded in
docs/dev/debt/libSceAgcDriver.md.Goat Simulator 3 (PPSA04158) at 3840x2160, with
APS5_TRACE_SECONDS=600:4only and the log not redirected: this change gave p50 181.9 ms (22 presents) andmain93dbd0f82agave p50 178.7 ms (23 presents). These are one capture each; three more arms were lost, two to early title crashes before the window and the rest to the display being off. That is within this scene's run-to-run spread (178.9–185.5 ms onmain), so it is not a measured cost claim. On heade84452d263, two more arms of this change (p50 177.5 and 180.4 ms) straddle one validmainarm (178.3 ms); the othermainarm crashed before the window (follow-up). Still not a cost claim either way.A diagnostic Goat Simulator 3 run that logged every storage-image write-back recorded none, so the Goat numbers show only that nothing else regressed. They may not exercise the copy. The copy is exercised in Cobra, which was not traced.
Pins. The tests and boots ran on
93dbd0f82a, asda1cee2240, then asac9b10b80awith the same content. The PR head is that patch rebased ontomain4569fe654awithout conflicts (git range-diff: identical), and CI builds it.e84452d263then adds a refresh of the snapshot at each stencil draw, after review; its tests are in the review reply. The current head191a4291bbis both commits rebased ontomain4f41f4c375, wheremainhad moved this block intoDepthSurface::MarkStencilStale(). The logic now lives there, and the 7 stencil and depth-plane GPU tests pass 3 of 3 (see the rebase comment).Independent report: @TechLevelZero's NVIDIA CI (RTX 2000 Ada, driver 595.99.02) on head
e84452d263merged ontomain88e804b: 2,494 passed, 0 new failures.Not run in the historical qualification above: Linux and macOS, where the planes are write-watched and the existing generation check applies; other titles.
External validation of head
eb37661035(reports by the named testers, not additional author runs):c76eb6a264: Intel 18/18 and NVIDIA 17 pass/1 unchanged feature skip on both main and merge; validation 1.4.363, no VUID. The stale-stencil negative control fails with main's driver on both GPUs. The write-watched guest-write/reused-plane cases actually execute on the RTX 3060; the Intel run reports those checks unavailable.3cda4698b7: 25 existing native-depth tests × 3 iterations × 2 arms = 150 passing executions, with validation 1.4.363 and no VUID/SYNC-HAZARD/UNASSIGNED messages. The new test passes its three kept-clean cases; its two guest-write cases are unavailable on that host. This is Windows regression coverage, not proof of the write-watched path.Checklist
Based on current
main; no other open PR implements the same functionsOne 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 fileNo notes, investigation
.mdfiles 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: PPSA36591 #7384 (GPU Heap corruption, then a SIGSEGV, a few minutes into a new game on
main; with this PR the title played through to an ending, per @milescoviello); PPSA38010 (Suika Game: a Unity allocator access violation a few minutes into play onmain, none in 12 runs of 800 s with this PR, per @JAB-dev)GPUs tested: AMD Radeon RX 6650 XT (RADV NAVI23), Mesa 26.2.6, Linux 7.2.14 for the current basic stencil fixture; AMD Radeon RX 6700 XT, AMD proprietary driver 26.10.1, Windows 11 10.0.22621 for historical runs
AI-assisted: yes
Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T11:51:58Z.
Review: APPROVED
Reviewed — approved
The stale-stencil store now leaves alone a plane the guest wrote after the last stencil draw. The new cases pass on the merged tree and fail with
main'sDepthSurface.cpp, and nothing I found blocks the merge.What I ran
Head
191a4291bbefac61f96624ee13c025c4d7b1ce9b,main4f41f4c375f5abb487dbd184fbc150f31994d762, merged tree41e494af0edcc143b7b1cdd470c58cedd6b55b73. Debian 13 VM, 32 vCPU Xeon Gold 6136, GCC 14.2.0, Vulkan through lavapipe (Mesa 26.1.6, LLVM 19), no GPU.Results
git diff --checkcheck_conventions.pylibs(script)mainagc_driver_stencil_plane_memory, validation layer onVUID-lines. It printed "guest memory is not write-watched here", so this machine runs the unwatched (snapshot) path the PR targetsnew_vuidinagc_driver_native_depth_uniform_planes(script: "test not run on main")main'sDepthSurface.cppthe test reports the same 4VUID-vkCmdDispatch-groupCountX-00386errorsstencil|depth_plane|depth_surface|native_depthon the merged treeagc_driver_native_depth_bda_clear)Validation run on the merged tree
Negative control
I restored only
core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cppfrommainand rebuilt.agc_driver_stencil_plane_memorythen fails on the first new case:After that I restored the merged file and rebuilt.
git status --porcelainprinted nothing, and the 35 tests above ran on the restored build.The negative control stops at the first failing
Require, so it does not show on its own that the later cases (second draw after the guest write, read path) fail without the fix. The author reports running that check on the previous head in their reply to the review comment.Findings
Blocking
None.
Non-blocking
Every stencil-writing bind now compares the whole plane, while the global locks are held, and the description's cost note is out of date.
DepthSurface.cpp:736. The call is from the bind path atDepthSurface.cpp:2657, underGpuMutexandsurfacesMutex.MarkStencilStale()on an unwatched plane runsEqualsCommittedUnsyncedover the full plane. At 3840x2160 that is 8 MiB per stencil-writing draw.NoteHtileClearandNotePlaneFillcallers. The Goat Simulator 3 numbers do not exercise this path, as the description itself says. A title with many stencil draws per frame on Windows would pay one plane-sized memcmp per draw.A partial guest write drops the whole stencil store.
DepthSurface.cpp:2365-2379.docs/dev/debt/libSceAgcDriver.md.The watched branch of
stencilWrittenSinceStaleis not tested.DepthSurface.cpp:2366.UnchangedSinceCollectedreports a collected CPU store sincestencilStaleGeneration.Stray blank line. The PR adds an empty line before the closing brace of the watched-memory
elseblock inStencilPlaneMemory.cpp:211. It is unrelated to the change and can be removed.On the earlier review comment: the second-draw case it asked for is now in the test, together with both read-path cases, and those cases pass on the merged tree here.
Not verified
Require.Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T22:03:23Z.
Review: APPROVED
Re-checked — approved
What changed: a rebase onto
main04a9eb4fa2that combines #15466'sunmappedSincecheck with this PR's guest-write check in both stale-stencil store paths, a new debt entry for partial writes and comparison cost, an updated cost paragraph and the removal of the stray blank line. Checks and tests pass, and the negative controls fail as expected.What changed since my last review
Rebase. The new base is
main04a9eb4fa2877eb6e40bf2c83adf972e40d89b24. Both store paths now drop the store whenunmappedSince(...) || stencilWrittenSinceStale(...):storeStaleStencilatDepthSurface.cpp:2846(this goes throughretireStencil);FlushDepthPlanesatDepthSurface.cpp:3240-3242.MarkStencilStale()(DepthSurface.cpp:858-872) has the same logic as in191a4291bb.Commit
811f2d92e4.docs/dev/debt/libSceAgcDriver.md:125. It covers dropping the whole store after a partial CPU write, the page-granular drop on watched memory, and the full-plane compare under the graphics locks.StencilPlaneMemory.cpp.Description. The cost paragraph now says that each later stale mark compares the whole plane. A partial-write paragraph was added.
What I ran
Head
811f2d92e488fb8b335be520ef9bc74d87074d68,main04a9eb4fa2877eb6e40bf2c83adf972e40d89b24, merged treecab8c66aeb43838dda1d4067e7d9b0850437e8cd. Debian 13 VM, Xeon Gold 6136, GCC 14.2.0, lavapipe (Mesa 26.1.6), no GPU.git diff --checkcheck_conventions.pylibs(script)mainagc_driver_stencil_plane_memory, validation layer loadedVUID-lines. The test reports that the plane is not write-watched, so the snapshot path runsstencil|depth_plane|depth_surface|native_depth|image_gather_volumeagc_driver_native_depth_bda_clear)new_vuidinagc_driver_image_gather_volume(VUID-VkSamplerCreateInfo-addressMode*, "test not run on main")main'sDepthSurface.cppgives the same 8 lines (2 each ofaddressModeU-01079and ofaddressModeU/V/W-parameter). These are sampler-creation errors, unrelated to stencil storesNegative control
main'sDepthSurface.cpp:agc_driver_stencil_plane_memoryfails withretiring the surface stored its stale stencil 0x3c over the guest's later write of 0x77.DepthSurface.cppfrom the first commit15ef08b3ed, without the snapshot refresh: the test fails withretiring the surface kept the guest's 0x44 over the stencil 0x55 a later draw wrote. This shows on its own that the second-draw case needs the refresh commit. My previous review could not show this.After both runs I restored the merged file and rebuilt.
git status --porcelainprinted nothing.Previous findings
libSceAgcDriver.md:125records it.stencilWrittenSinceStaleis untested. Still open, non-blocking.DepthSurface.cpp:2837still runs only where the plane is watched.StencilPlaneMemory.cpp. Resolved. The watched-memoryelseblock atStencilPlaneMemory.cpp:205-210now closes without it.New findings
Blocking
None.
Non-blocking
None. The rebase resolution looks correct to me:
storeStaleStencil, a guest-written plane now goes throughretireStencil. That clearsstencilStaleand callsforgetStaleStencil, as the earlier explicit branch did.stencilStalein the same branch thatmainuses for an unmapped plane.Not verified