fix(agc): copy only the dwords a shader changed back from a GPU-copied buffer #6185
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6185"
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 ee6aba54 on 2026-10-15T01:17:12Z.
What
A buffer region that is staged in device memory (a region the GPU copies in and later copies back,
GuestBufferMemory) was copied back whole when its batch completed, and the CPU write-back path stored every byte that differed from the uploaded bytes. A store the title made into the region after the upload, in bytes the shader never touched or in bytes it touched as well, was overwritten with the GPU's copy of the stale bytes. PPSA15304 corrupted its guest heap this way: the allocator's free-list link in a block it had released after waiting for its label was replaced by texel data, and the title faulted on the next allocation.Two changes:
GuestMemory::WriteChangedKeepingGuest, which stores a byte only where the result differs from the uploaded byte and guest memory still holds the uploaded byte, so a CPU write made after the upload wins (the SSE path masks with both compares; the tail loop does the same).WriteChangedand its other callers (image mirrors, heap mirrors, storage images, tiled colour targets) are unchanged.StagingCopyBack.comp, buffer device addresses) that applies the same per-byte rule to each dword: the shader's bytes land where they differ from the snapshot and the import still holds the snapshot's byte. Unaligned edges copy as before.APS5_NO_CHANGED_COPY_BACK=1restores the whole copies,APS5_CHANGED_COPY_ALWAYS=1makes the kernel store every byte, andAPS5_TRACE_COPY_BACK=1counts the dwords where the shader and the CPU changed the same bytes.Tested
Linux, Ubuntu 24.04, NVIDIA GeForce RTX 5080 (driver 595.99.02). Tests:
testWriteChangedKeepingGuestKeepsCpuWrites(tests/Pm4.cpp) for the per-byte rule of the CPU write-back.agc_copied_write_back(tests/Recorder.cpp): a dispatch over a CPU-copied buffer, CPU stores after the batch completed and before the write-back (a conflicting dword, an untouched dword and a byte inside a dword the shader changed), checked after the write-back and on the next use of the buffer. It fails withWriteChangedin place ofWriteChangedKeepingGuest.changedCopyTests(tests/Recorder.cpp): 70000 dwords with whole-dword and single-byte changes on both sides; every byte is checked against the per-byte rule, and the trace counter against the dwords where both sides changed a byte.bdaStagingTests: CPU stores into the import after the copy-in, one in a byte the fill leaves alone inside a filled dword and one outside the filled range, checked after the copy-back.The tests of
agc_driver_recorder_testsandagc_driver_pm4_testspass onmain(95) and on the change (97,agc_changed_copyandagc_copied_write_backadded) withANYPS5_REQUIRE_VULKAN=1,ANYPS5_NO_SHADER_CACHE=1andVK_LAYER_KHRONOS_validation, with 0VUID-lines in either log; the staging, changed-copy, copied write-back, PM4 and storage write-back tests also pass withAPS5_NO_CHANGED_COPY_BACK=1. In PPSA15304 the earlier per-dword kernel ran through the section after the first drop with no divergence reported by the trace counter; the title's remaining heap corruption came from the deferred DCC key stores, fixed in the follow-up PR.Checklist
main; no other open PR implements the same functions.mdfiles or images added to the repositoryImported from boykopovar/AnyPS5. Originally posted by ee6aba54 on 2026-10-15T01:37:06Z.
The overlap with #6182 is the option list in the test binary's main (tests/Recorder.cpp), both add a
--...-onlyentry at the same spot; whichever lands second rebases in a minute, no dependency.Imported from boykopovar/AnyPS5. Originally posted by ps54all on 2026-10-15T12:45:52Z.
On Windows,
agc_changed_copyexits with 0xc0000135 (a DLL was not found). The otheragc_driver_recorder_testsmodes next to it, such asagc_unit_shadow, get the libs directory on PATH from theset_tests_properties(... ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:...")list, butagc_changed_copyis not in that list. Adding it there makes the test pass (Windows 11, WinLibs GCC 15.2.0, RTX 3080; checked with this PR's commits picked onto a local tree).AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by ee6aba54 on 2026-10-15T14:08:59Z.
Thanks, confirmed.
agc_changed_copywas missing from the WindowsENVIRONMENT_MODIFICATIONlist next toagc_unit_shadow. It is added in cbb060641 (rebased onto main since). #6186 addsagc_guarded_key_storeto the same list, since it runs from the same binary. On Linux, CMake configures cleanly and both tests pass; I could not run the Windows side here.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T02:59:36Z.
CI run 38994492535 on head cbb060641: Linux is green. On Windows, the new
agc_changed_copyfails. The runner has no Vulkan device, so it prints "skipped, no usable Vulkan device" and returns 77. Itsset_tests_properties(agc_changed_copy PROPERTIES TIMEOUT 30)line lacksSKIP_RETURN_CODE 77, unlike its neighbours (agc_sparse_run_import,agc_unit_shadow), so ctest counts the skip as a failure. Suggested fix:set_tests_properties(agc_changed_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30).Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-20T15:35:55Z.
This now conflicts with
maininGuestBufferMemory.cpp(plus a one-line test list inlibSceAgcDriver/CMakeLists.txt). Two of the hunks aren't mechanical, so please rebase it yourself:entry->base - entry->lead. Your change setscopySourceBase = entry->baseand addscopySourceAddress = entry->address. Please re-derive both under theleadoffset, so an unaligned import copies from the right bytes. A test with a non-zeroleadwould pin it.ElideCovered(StagingOut, leading, covered), withleading= ALL_COMMANDS -> TRANSFER, SHADER_WRITE -> TRANSFER_READ. Your version also makes compute a destination stage. If you keep compute,leadinghas to include it too. Otherwise the elision can drop a barrier your compute write-back needs, whenever the covering barrier only reached transfer.After the rebase, the Windows
agc_changed_copyrun and the paired gate run on the card are still the bar.Imported from boykopovar/AnyPS5. Originally posted by ee6aba54 on 2026-10-20T20:04:23Z.
@oneandonlydean Rebased onto
main2185dbf92.leadincluded:HostImportBufferStartreturns{base - lead, address - lead}, and the region takescopySourceBaseandcopySourceAddressfrom it, so the offsetaddress - copySourceBaseis the same oneHostImportOffsetgives.agc_changed_copynow also runs the kernel into a buffer with a 0x1000-byte lead, addressed throughHostImportBufferStartof an import with that lead: the lead bytes stay untouched and the words land after it. With the helper returning{base, address}instead, the test fails.leadingnow carries it:ALL_COMMANDS -> TRANSFER | COMPUTE_SHADER,SHADER_WRITE -> TRANSFER_READ | SHADER_READ, passed toElideCoveredand recorded from the same mask.OrderedByTrailingrequiresSHADER_READin the covered access, and the barriers that mark coverage (MarkCoveredin the fills, the shadow publish, staging in and staging out) all haveALL_COMMANDSas their destination stage.docs/dev/ENVIRONMENT.mdnow listsAPS5_NO_CHANGED_COPY_BACK,APS5_TRACE_COPY_BACKandAPS5_CHANGED_COPY_ALWAYS;agc_changed_copyhasSKIP_RETURN_CODE 77, so a run without the kernel counts as skipped.Tested on Linux, Release,
ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, same machine and GPU; "this head" is #6186's head, which carries this PR:main2185dbf92agc_changed_copy,agc_guarded_key_storemain)agc_recorder_read_list,agc_host_import_unmap,agc_parked_import_unmap,agc_host_import_retirement,agc_sparse_run_import,agc_sparse_run_import_copied,agc_draw_inputs_in_place,agc_draw_inputs_copied,agc_unit_shadow,agc_driver_graphicsVUID-linesOn the previous base
434e965d4(same commits), all 825agctests passed in a parallel run exceptagc_driver_lookup_log_fits_build, which passes when run alone.agc_host_import_sparseskips on this machine (/dev/udmabufnot accessible).check_conventions.pypasses on both branches. #6186 is rebased onto this head.Ubuntu 24.04, kernel 7.0.0, NVIDIA GeForce RTX 5080, driver 595.99.02.
AI-assisted: yes
Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-10-25T16:35:01Z.
Review: COMMENTED
Reviewed head
ce22655(merge basef26434a), merged locally onto current main0119103(clean). WSL2 Ubuntu 24.04, GCC 13.3, Release, lavapipe (llvmpipe, LLVM 20.1.2). No discrete GPU, no title.What I ran:
agc_driver_recorder_testsandagc_driver_pm4_tests. All 85 ctest entries from those two binaries pass,agc_changed_copyincluded (agc_unit_shadowskips here).--changed-copy-only,--sparse-run-copied-onlyand--draw-inputs-copied-onlywithVK_LAYER_KHRONOS_validation: 0VUID-lines.GuestMemory.cpp,agc_driver_pm4fails at "write-back overwrote a byte the CPU changed since the upload", sotestWriteChangedKeepsCpuWritespins the CPU-side change.check_conventions.py --base origin/mainpasses.The kernel's addressing looks right to me: the target offset with
lead, the 4-byte gate, the edge copies, and the added COMPUTE/SHADER bits in both barriers. A few things:1. The snapshot is taken for every GPU-copied region, not only written ones. The loop at GuestBufferMemory.cpp L5268 only checks
changedCopyBacksand the device address.gpuCopyEligiblealso takes read-only regions (hostBacked || writable), and sincegpuCopyUsagenow addsSHADER_DEVICE_ADDRESSwhenever the changed copy is on, those pass the address check. Each one gets an extra device-local buffer and a secondCopyBufferthatRecordCopyBacksnever reads; the comment abovegpuCopiesEnabledcounts ~31000 misaligned copies per run on this path.writable = WritesOverlap(...)is already computed per region at L5212; gating the shadow on it should be enough. This one is from reading the code, no test here hits a read-only GPU copy so I couldn't measure it.2. The kernel compares whole dwords,
WriteChangedcompares bytes. Example: the import dword is 0x11223344 at copy-in, the shader stores 0x11AA3344, then the CPU stores byte 0 = 0x55.heldis 0x11223355, notbefore, so the kernel keeps it and the shader's 0xAA is lost. The CPU path would keep both. A byte mask inStagingCopyBack.compwould matchWriteChanged:mask= bytes wherevalue != beforeandheld == before, store(held & ~mask) | (value & mask)whenmask != 0. Related: the trace counter (L23) also counts dwords the shader did change and the kernel dropped, but the message says "the shader left at the copy-in value".3.
agc_changed_copytests the kernel only. It callsRecordChangedCopydirectly, so the snapshot inrecordGpuCopiesand thecopySourceAddress + (alignedFrom - copySourceBase)target inRecordCopyBacksaren't covered. The lead part passesstart.device + (import.base - start.guest), which is justimport.address.bdaStagingTests(tests/Recorder.cpp L3369) already drivesmemory.RecordCopyBackson a staged region. A CPU store into the import after recording, checked after the batch, would pin the fix end to end.4. The debt entry still describes the old behaviour. "Device-local staging" (docs/dev/debt/libSceAgcDriver.md L241) and the comment at GuestBufferMemory.cpp L4459 say the range is copied back whole and a CPU store is rolled back. Now that only holds for the edge bytes, regions whose
beginorcopySourceBaseisn't 4-aligned, a refused shadow, andAPS5_NO_CHANGED_COPY_BACK(plus the dword case in 2 if it stays).5. Question on the other
WriteChangedcallers. The mirror write-back (GuestBufferMemory.cpp L5785) and the StorageTexture write-back (Texture.cpp L5879, throughWriteChangedCommitted) set their baseline to the GPU result right after the store. With the new rule, a byte the CPU changed keeps the CPU value in guest memory while the mirror or image and its baseline hold the GPU value. Does the CPU's write still get picked up on the next use there, or can they stay apart? The description only covers the copied-buffer path, so a line on this would help either way.Limits: lavapipe only, no PPSA15304, nothing measured on a discrete GPU.
Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T19:52:31Z.
Review: COMMENTED
Points on 6185:
Known data loss accepted in a comment.
GuestBufferMemory.cppadds a comment block: "Accepted trade-off ... a CPU write between the copy-in and the copy-back is rolled back at the unaligned ends of a range, in a region that is not 4-byte aligned and without a shadow copy". That is a lost guest store for some inputs. The repo rule is exact-or-throw: either make the unaligned ends correct or throw for them and record the gap indocs/dev/debt/libSceAgcDriver.md. A comment is neither.Comments in code. The same block, and others in this diff, break the no-comments rule. Please remove them.
Speed claim. The point of the change is a smaller copy-back. Please attach
tools/trace_digest.pysummaries of main and the change, same machine and scene, and say what the changed-dword detection costs per submission on a large buffer.Negative control. Does the new test fail with the fix reverted, and is there a case with a CPU store between copy-in and copy-back at an unaligned end?
Imported from boykopovar/AnyPS5. Originally posted by Superseabas on 2026-11-02T18:17:01Z.
Review: COMMENTED
Windows run of head
f0a15aeb5emerged onto currentmainb28bb77217(clean merge, local only), on two GPUs, plus a read of the change against @CnRJay's points.Windows 11 Home 10.0.26200, Ryzen 7 7700X, WinLibs GCC 16.2.0 (
x86_64-ucrt-posix-seh, r3), Release,BUILD_TESTING=ON.ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, every test ofagc_driver_recorder_testsandagc_driver_pm4_tests,ANYPS5_GPUselecting the device (confirmed bySelected GPU):main10de:2c05)1002:164e)VUID-lines and no missing-layer line on either side.agc_changed_copy,agc_copied_write_backandagc_bda_stagingwithAPS5_TRACE_COPY_BACK=1, 3 runs per GPU: each run logs[copy-back] ... 1 dwords where the shader and the CPU changed the same bytes; the CPU's bytes were kept, and none logsstaged write-backs copy their whole ranges, so the kernel path ran rather than the fallback.check_conventions.py --base mainpasses on the merge.On the earlier review points, at this head:
Accepted trade-offblock is not new:mainalready has it, and it says a CPU write into a staged range is rolled back across the whole written element range. This PR edits it to the remaining case, the unaligned ends. The same case is written out in theDevice-local stagingentry ofdocs/dev/debt/libSceAgcDriver.md, so the gap is recorded there. Whether the code comment should go now that the debt entry carries it is for a maintainer; CONVENTIONS allows debt comments only from a human.maincomment, not a new one.trace_digest.pyrule for speed claims does not seem to apply.agc_copied_write_backfails withWriteChanged, and @ahmadmuj's red check reproduced the CPU-side one. The unaligned-end case is the recorded gap, so no test expects it to keep the CPU's bytes.One question on the kernel:
StagingCopyBack.compreads the import's dword (held) and writes the whole dword back whenstored != 0. A CPU store into another byte of that same dword between the read and the write is rolled back. The window is much smaller than the whole-range copy it replaces, but the debt entry says a CPU store in between survives. Would it be worth either a compare-and-swap loop on the target dword, or a sentence in the debt entry for that race?Smaller: if the copy-back pipeline cannot be created,
RecordChangedCopyprints[gpu] staged write-backs copy their whole rangesand the whole range is copied as before. The debt entry lists the other cases that fall back to the whole copy, but not this one.AI-assisted: yes (Claude Code)