feat(agc): track guest memory writes on Linux with async userfaultfd write protection #121
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/121"
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 oneandonlydean on 2026-09-29T00:24:57Z.
What
GuestMemory::CollectWritesis built on the Windows arena'sMEM_WRITE_WATCHand answers 0 on Linux, so every cached copy of guest memory (textures, resident render targets, buffers, DCC key proofs) reads as changed at every check: resident targets are stored and re-uploaded at every refresh and unit shadows stay off.libc gains
GuestWriteWatch, the Linux counterpart ofGetWriteWatch:MapAligned: fixed, hinted, aligned) is registered with one userfaultfd in asynchronous write-protect mode (UFFD_FEATURE_WP_ASYNC: the kernel lifts a page's protection on its first write without a handler thread, for user and kernel-mode writes);Unmapforgets the range;MAP_FIXED, which drops the old registration. Both register the new mapping afresh (AddMapping,RemapFixedIntoRegistered);PAGEMAP_SCANwithPM_SCAN_WP_MATCHINGreports the pages written since the last scan of a range and re-protects them in one call.UFFDIO_WRITEPROTECT, which puts markers on unpopulated pages (UFFD_FEATURE_WP_UNPOPULATED). From then on only real writes report.Fallback: the userfaultfd is opened with
UFFD_USER_MODE_ONLYwherevm.unprivileged_userfaultfd=0requires it, and a startup probe checks the whole mechanism on scratch pages: a populated page and an unpopulated page written after protection report exactly, and untouched pages don't. Without it (kernel < 6.7, no userfaultfd permission, build headers withoutPAGEMAP_SCAN, orAPS5_NO_WRITE_WATCH=1) the watch reports unavailable and the tracker stays unwatched exactly as on main:CollectWritesanswers 0 and callers compare bytes; unit shadows stay off. A range with a page outside the registered mappings also answers 0, and a protection or scan that fails reports its remaining pages as written and answers 0.In the driver the tracker keeps its contract and generations. On Linux its block stamps live in 4 GiB leaves over the user address space made on first stamp; the collect memo now runs on both platforms.
GuestMemory::WriteWatched/Watchedreplace the arena queries inUnitShadowEnabled/ShadowDestinationFor, so unit shadows run on Linux over watched memory. The Windows path is unchanged apart from going through the same stamp helpers;GuestWriteWatchreports unavailable there.Host imports
@Pacuka found that on an RX 6650 XT (RADV, kernel 7.2.2) the presented image went black with host imports on: every present saw CPU writes all over the resident display image, and
StorageTexture::Refreshmerged stale guest bytes over the GPU results. His diagnosis is right: amdgpu validates the userptr BO behind aVK_EXT_external_memory_hostimport with a writable HMM fault on every submission after the pages were protected again, which lifts the async write protection, soPAGEMAP_SCANreports those pages as written although no CPU store happened. NVIDIA pins the pages once at the import, so there the watch stays exact, and most tracked memory is imported; taking every import off the watch would lose most of the gain on NVIDIA.So a probe decides per device, at device setup before the first real import:
GuestMemory::Unwatch) before it is made, soWatchedis false for it,CollectWritesanswers 0 and callers compare bytes (as in @Pacuka's fix). GPU writes into watched memory keep theirMarkWrittenstamps;[write-watch] host imports resolve write protection: yes/no (N of M scratch pages written after a GPU read, K after the import);APS5_WRITE_WATCH_IMPORTS=watch|unwatchoverrides the probe (defaultprobe, anything else throws).APS5_NO_WRITE_WATCH=1still turns the whole watch off.An unwatched import stays off the watch for the rest of its mapping: a remap registers the range afresh, the import kept over it takes it off again at the next reconcile, and a re-import after an unmap follows the decision.
Unwatchalso invalidates the collect memo, so a collect memoized before the import answers 0.The import itself also lifts the protection once where imports stay watched: on the RTX 4090 the pinning at
vkAllocateMemoryreports every imported page as written (4 of 4 in the probe) with no CPU store, which would read as a CPU write over any GPU results pending there and drop them. So every import of a watched range is made inside an import window (GuestMemory::ImportWatched, under the tracker lock):UnchangedSincefails), so caches re-upload or compare. Decisions about pending GPU results treat it as untracked:ChangedBlocksnow tellsBlockMaybeWrittenfromBlockWritten, and the drop rule, the write-back's keep blocks, the alias checks, the unit shadow's stale drop and the whole-image stale checks (through the newWrittenSince) store the results instead of dropping them;One more case needed care: a storage image may hold a generation taken while its memory was still watched, and then the memory is imported and leaves the watch.
ChangedBlocksreports every block of an unwatched range as changed, and the drop rule read that as "the CPU wrote this unit" and dropped the pending GPU results (the same black-image outcome, by another route).ChangedBlocksnow says whether the range is watched, and the drop rule, the write-back's keep blocks and the alias borrow treat an unwatched range as untracked: results are stored, never dropped, as with a generation of 0.Tested
vm.unprivileged_userfaultfd=0, so the user-mode-only path is used; RTX 4090).guest_memory(ctest) checks the watch through libkernel mappings: CPU store, read, kernel write throughread(), another thread, memcpy across pages, mprotect cycle, partial munmap, fixed remap. It also checks a fresh 2 MiB-aligned mapping with no page tables, and direct memory: a direct mapping is watched, an alias takes the shared pages off the watch in both mappings while the unshared pages stay watched, and a fixed direct remap over flexible memory is watched afresh. A failing check names its line and the pages reported.guest_memorypasses. I confirmed it runs rather than being skipped with a throwaway run that failed if the watch was unavailable. An earlier revision failed here on the fresh-mapping check.agc_driver_recorder_tests: the UnchangedSince, key proof, close race and unit shadow tests now run on Linux against watched memory, and the storage refresh test gains a watched variant (results kept on the GPU reach a CPU reader; a plain CPU store into one unit with newer results pending is found by the watch alone). On main these skip on Linux.APS5_NO_WRITE_WATCH=1ctest and the recorder tests pass with the watched tests reported as not run.host imports resolve write protection: no (0 of 4 scratch pages written after a GPU read, 4 after the import), so imports stay watched. The AMD path can't run here; @Pacuka, could you re-test on your RX 6650 XT with host imports on? The log line should sayyes, and the image should be back.agc_driver_recorder_testsruns the real probe and checks the decision with the result injected. Unwatch: an import leaves the watch, a memoized collect, a partly imported range and the unimported neighbour answer as they should,MarkWrittenstamps only watched memory, a remap and a re-import after an unmap follow the decision. Watch: the import stays watched and stamped. A further test checks that results pending when their memory leaves the watch are stored, not dropped; it fails without theChangedBlockschange. Another imports the memory of a storage image with results pending in watch mode: the results survive and reach guest memory, a cache generation taken before the import sees a change, the window reads as maybe written rather than as a CPU store, and a CPU store after it reads as one again. It fails without the import window.APS5_WRITE_WATCH_IMPORTS=unwatch(the AMD path forced; unit shadows and the watched storage refresh report themselves as not run), withAPS5_WRITE_WATCH_IMPORTS=watchand withAPS5_NO_WRITE_WATCH=1;agc_driver_flip_testspasses too.agc_driver_graphics_testspasses with #113 merged in.ctest: 64/64 pass on current main (65/65 with #113 merged); also withAPS5_NO_WRITE_WATCH=1.agc_driver_recorder_testspasses with the probe and withAPS5_WRITE_WATCH_IMPORTS=watch,=unwatchandAPS5_NO_WRITE_WATCH=1.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 repositoryImported from boykopovar/AnyPS5. Originally posted by Pacuka on 2026-09-29T19:48:32Z.
Tested #121 locally (Linux 7.2.2, RX 6650 XT / RADV) together with host imports (
VK_EXT_external_memory_host, i.e. withoutAPS5_NO_HOST_IMPORT): the presented image became completely black. Every present reported the resident display image as "refreshed first", i.e.GuestMemory::UnchangedSincesaw CPU writes all over the display buffer andStorageTexture::Refreshmerged stale guest bytes over the GPU results.Cause as far as I can tell: the amdgpu userptr BO behind a host import is validated with a writable HMM fault per submission, which resolves the async userfaultfd write protection of those pages, so
PAGEMAP_SCANreports them as written although no CPU store happened.What fixed the black image here: unregistering a range from the write watch (
GuestWriteWatchUnregister_nid_postfix) once it is successfully host-imported, so imported ranges fall back to comparison; GPU writes to them are already stamped byMarkWritteninWriteBack. Without host imports the tracking works as intended.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-09-29T19:52:50Z.
Thanks for testing on AMD, and for tracking it down. Your diagnosis is right: a false "written" from the import's HMM validation makes the refresh merge stale guest bytes over GPU results. Unregistering imported ranges fixes it, but on NVIDIA (where the import pins pages once and the watch stays accurate) most of the tracked memory is imported, so doing it unconditionally would lose most of the benefit there. I'll add a startup probe: import a scratch page, submit work that uses it, and scan it. If the driver's validation resolves the write protection, imported ranges are unregistered and fall back to comparison, as in your fix; otherwise they stay watched. Could you re-test on the RX 6650 XT once it's pushed?
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-09-29T20:24:22Z.
@Pacuka pushed. At startup the driver now imports a few scratch pages, runs a GPU copy from them and scans them. If the scan reports them written after the submission (what you saw on amdgpu), imported ranges are taken off the watch and compared instead; otherwise they stay watched. It logs one line,
[write-watch] host imports resolve write protection: yes/no (...). On my RTX 4090 it says "no", so on your RX 6650 XT it should say "yes".Two related fixes came out of this:
APS5_WRITE_WATCH_IMPORTS=probe|watch|unwatchoverrides the decision (defaultprobe). Rebased on current main. Could you re-test with host imports on?