memory: write-protect tracked guest pages with userfaultfd #1307
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1307
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1307"
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?
@NeySlim on GitHub · 2026-10-09 14:10 UTC · original
NeySlim:perf/uffd-write-watch→main· +731 −31 · 13 files · 2 commits · openProblem
The page tracker watches uploaded guest pages for CPU writes by write-protecting them, and gives the protection back when a write faults. On Linux both directions are
mprotectcalls on the guest views. In God of War Ragnarök (PPSA08332, 05.005) the guest threads take about 2,000 such write faults per frame in the opening cutscene and 2,800 in the sled sequence, and the GPU command thread protects about 500 to 600 ranges again per frame, mostly in the sweep before draws that address memory directly.Each
mprotecttakes the process mmap lock in write mode, which also stalls every page fault of the other threads, and splits or merges the guest views: the process has 9,000 to 10,000 mappings during gameplay, about 4,000 of them read-only tracked pages. The tracker region lock is held across the call, so other threads spin on it meanwhile.Per frame, measured as below with the
mprotectpath:mprotectChange
UFFD_USER_MODE_ONLY), the backing store opens a userfaultfd at startup and registers every guest view for write protection when it maps it.UFFDIO_WRITEPROTECT) and leaves the view read-write: no mapping split or merge, and the mmap lock is taken in read mode. The userfaultfd usesUFFD_FEATURE_SIGBUS, so a write to a watched page raises SIGBUS in the writing thread, which the host fault handler already resolves like SIGSEGV. Every write is still seen before it lands, by the same fault path and tracker code.mprotectwith no access.PageManagernow tells the address space whether a protection change adds or removes an access watch, or only moves a write watch between read-only and read-write; only the former changes the view protection, and a page whose access watch ends is write-protected before it becomes writable again.mprotectwrite watches for its lifetime (logged), and the other views keep userfaultfd: each view uses one mechanism for every watch and release on its pages, so the two never mix on a page.MADV_POPULATE_READ/MADV_POPULATE_WRITEon Linux,VirtualQueryon Windows). OnlySEGV_ACCERRand, with userfaultfd, theBUS_ADRERRof write faults are considered; other codes such asBUS_MCEERR_*are not. A write to a page that the guest made read-only now takes the unhandled guest fault path (fault context and exit), as without tracking. Before, the handler claimed every fault in a GPU-mapped range: with this change such a write would retry forever, and onmainit already does when the page is not watched; a watched page was made writable and the write went through.mprotectorVirtualProtectas before. The log states which mode is used.vm.unprivileged_userfaultfd=0does not matter: user-mode-only file descriptors are always allowed.Kernel writes into a watched page, such as a
read()orprocess_vm_writevinto it, fail withEFAULTas they did withmprotect. File reads release the watches on their buffer before reading, as before.On Windows,
GetWriteWatchonly covers privateMEM_WRITE_WATCHallocations, not the section views that hold guest memory, so it is not a drop-in equivalent there.Test
virtual_memory_allocation_tests, Linux:TrackerWriteWatchKeepsView. Every other page of a guest view is write-watched. The view stays one read-write host mapping; a write to a watched page faults as a write at its address and lands once the fault releases the watch; reads of watched pages and writes to unwatched pages do not fault; an access watch added and removed over a write-watched page leaves the page readable and still write-watched. With themprotectpath the view is split into read-only mappings, which the test rejects in the userfaultfd mode. Without userfaultfd the test checks the same fault behaviour on themprotectpath.virtual_memory_allocation_tests, Linux:TrackerWriteWatchRegistrationFallback. A registration failure injected for one view leaves it mapped, write-watched withmprotect, and a write to a watched page faults and lands. Fails without the fallback (the process exited).shader_recompiler_compute_tests:TrackedGuestWriteFaults, through the production fault route. A write to a tracked writable page faults, lands and marks the range CPU-modified. In a child process, a write to a tracked page the guest made read-only (still watched, and already released) must raise an access violation within 10 s. Fails without the change (the write was retried forever).page_manager_tests:TestTrackingFaults. Faults on a never-tracked page, or on an unwatched page whose protection forbids the access, are not claimed; a watched page, or a released page that allows the access, is. Fails without the change.page_manager_tests:TestWriteWatchesKeepAccess. Adding and removing write watchers reports no access change, adding and removing access watchers does. Fails without the change.PartialUnmapPreservesHostPermissions,FixedDirectReplacementPreservesAccess) pass in the userfaultfd mode. The first one probes a write-watched page withprocess_vm_writev, which getsEFAULT.Validation
Linux 6.18, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3.
God of War Ragnarök from a new game, alternating every 5 s between
mprotectand userfaultfd write watches within one session (the watches in place are converted at each switch), so both see the same scenes, on a branch with other pending GPU thread changes (#1284, #1286):PrepareBda(± one standard error of the paired differences; GPU clock held at its highest level.) The number of faults and protection calls does not change; each one costs less. In three earlier sessions where other load on the machine lowered the GPU clock, the fault and protection costs dropped the same way, and the frame time changed by -27.9 ± 4.7, -2.1 ± 1.2 and -8.4 ± 4.5 ms in the cutscene, -0.4 ± 3.0, -9.4 ± 4.9 and -11.7 ± 5.0 ms in the sled. Screenshots of both modes show no rendering difference.
Write-protecting a large range that is already populated costs more with userfaultfd than with
mprotect(about 1.5 ms against 0.4 ms for 64 MiB in a microbenchmark); in the game the longest frames of each period did not get longer.page_manager_tests,memory_tracker_tests,virtual_memory_allocation_tests,resource_tracking_testsandresource_materialization_testspass.shader_recompiler_compute_tests, one case per process (the buffer and texture cache cases run through this path): same results asorigin/mainapart from the new case, 601 of 611 cases pass, the same 10 fail on both on this RADV setup.The address-space tests also pass with userfaultfd denied by a seccomp filter (fallback to
mprotect).Not tested on Windows or macOS. The userfaultfd code is compiled only on Linux. The fault claim rule applies to all platforms; on Windows the released-page probe uses
VirtualQuery, and macOS has no probe and keeps retrying such faults as before.Notes
AddressSpace::ProtectTransient. Resolution: keep thestd::shared_lockand its comment from #1284, and theForEachMappedPartUnlockedcall from this change.EBUSY; one of the two would have to reuse the other's descriptor.AI use
I used Claude Code (AI agent) to profile the fault path, write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results before opening this PR.
@coderabbitai[bot] on GitHub · 2026-10-09 14:15 UTC · original · edited 2026-10-20 14:41 UTC
📝 Walkthrough
The change adds Linux
userfaultfdwrite protection for tracked guest memory views, with anmprotectfallback when setup or registration is unavailable. Protection calls now carry anaccess_changedflag. Host access violations carry a cause, and GPU fault handling checks that cause, guest permissions, and page-tracker state. Tests cover protection flags, fault classification, write watches, and fallback behavior.Suggested reviewers:
nmzikPriority: ➖ Normal
Change: Feature
Merge Risk: 🔵 Low · up to
19fc8The new fault test may pass without exercising the userfaultfd-watched path. Production behavior is not affected. Tighten the test when convenient.
Pre-merge checks:
4 ·
1
Full details: Docstring Coverage
Explanation
Docstring coverage is 21.28% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 47 functions across 11 files. (1 skipped: 1 too large.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@coderabbitai[bot] on GitHub · 2026-10-09 14:15 UTC · original · edited 2026-10-09 15:33 UTC
On
src/kernel/memoryAddressSpace.incline 79 (outdated):🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 3026
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 15772
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 9930
🌐 Web query:
Linux userfaultfd UFFDIO_API unsupported requested feature EINVAL returned ioctls UFFDIO_REGISTER official documentation💡 Result:
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 17776
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 11436
Fall back when view registration fails.
UFFDIO_APIalready rejects an unsupported requested feature withEINVAL, so the existing setup path falls back tomprotect. A successful handshake also returns the supported ioctl mask, which this code does not check.MapViewstill callsRegisterafter each successfulmmap, andRegistercallsEXITwhenUFFDIO_REGISTERfails. A registration failure therefore terminates the process instead of selecting themprotectpath. Check_UFFDIO_REGISTERbefore enabling this mode, and make registration failure disable userfaultfd protection and usemprotectrather than aborting.✅ Addressed in commit 5078858
@coderabbitai[bot] on GitHub · 2026-10-09 14:15 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
4028922e-294f-469b-bb0b-b2f2141a9bb9📥 Commits
Reviewing files that changed from the base of the PR and between
4c8fc53a85and 7daef13d1b0572b3123a033606c3550b5b767f43.📒 Files selected for processing (7)
src/graphics/host_gpu/pageManager.cppsrc/kernel/memory.cppsrc/kernel/memory.hsrc/kernel/memoryAddressSpace.inctests/MemoryTrackerTests.cpptests/PageManagerTests.cpptests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@NeySlim on GitHub · 2026-10-09 15:21 UTC · original
Pushed 5078858c. The fault handler now claims a fault only when it comes from page tracking: the guest protection of the page allows the access, and the page is watched against it or the access succeeds now (a watch released since the fault). A write to a page the guest made read-only takes the unhandled guest fault path instead of being retried forever, and SIGBUS codes other than the userfaultfd one are not treated as tracking faults. The retry loop for an unwatched read-only page already existed on main. New tests:
TrackedGuestWriteFaults(GPU suite),TestTrackingFaults(page manager) andTrackerWriteWatchRegistrationFallback; description updated.@NeySlim on GitHub · 2026-10-09 15:21 UTC · original
On
src/kernel/memoryAddressSpace.incline 79 (outdated):Fixed in 5078858c. Setup now requires the shared-memory write-protection feature and
_UFFDIO_REGISTERin theUFFDIO_APIresult. A failedUFFDIO_REGISTERno longer exits: that view is logged and keepsmprotectwrite watches for its lifetime, while other views keep userfaultfd. Switching globally would leave write protections already set in the page tables of other views, so the mode is chosen per view; every watch and release on a page goes through the same view, so the two never mix on a page. Covered byTrackerWriteWatchRegistrationFallback, which injects a registration failure.@coderabbitai[bot] on GitHub · 2026-10-09 15:33 UTC · original
On
src/kernel/memoryAddressSpace.incline 79 (outdated):@NeySlim, thanks for the clarification. The supplied code addresses this finding: setup checks the required feature and ioctl, and registration failure selectsmprotectfor that view without aborting.Per-view fallback is appropriate. A global switch could leave existing userfaultfd write protections active on other views.
✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-10-16 02:34 UTC · original · reviewed
🧹 Nitpick comments: 1
ℹ️ Review info
⚙️ Run configuration
a4115a95-166d-43fb-94a0-dbeb21b7ec4a📥 Commits
Reviewing files that changed from the base of the PR and between 9d56751e2a97aefcadb73671124cbb5588bcd208 and 19fc882c0a3d3a74d2f6f312396d4fc6c044db5a.
📒 Files selected for processing: 3
src/kernel/memory.cpptests/ShaderRecompilerComputeTests.cpptests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.
@NeySlim on GitHub · 2026-10-16 03:31 UTC · original
The child case is about the claim decision, not the watch itself. After the guest mprotect the view has no write permission, so the write is a SIGSEGV with SEGV_ACCERR before userfaultfd is involved, in the parent as well. That fault used to be claimed and retried forever, and the test fails without the change. Handling EVENT_FORK just for this test would add fork handling that games never need, so I left it as is.
View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.