memory: write-protect tracked guest pages with userfaultfd #1307

Open
github-bot wants to merge 2 commits from github-bot/gh-1307 into main AGit
Owner

@⁠NeySlim on GitHub · 2026-10-09 14:10 UTC · original
NeySlim:perf/uffd-write-watch → main · +731 −31 · 13 files · 2 commits · open

Problem

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 mprotect calls 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 mprotect takes 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 mprotect path:

Cutscene Sled
Write faults 1,960 2,780
Guest threads: time in write faults (sum of threads) 25.7 ms 32.6 ms
of which mprotect 8.4 ms 7.8 ms
of which spinning on tracker region locks 10.5 ms 12.6 ms
GPU command thread: tracker protection calls 510 610
GPU command thread: tracker protection time 2.7 ms 2.6 ms
GPU command thread: spinning on tracker region locks 0.6 ms 0.6 ms

Change

  • On Linux, when the kernel supports userfaultfd write protection of shared memory (5.19 and later; usable without privileges through UFFD_USER_MODE_ONLY), the backing store opens a userfaultfd at startup and registers every guest view for write protection when it maps it.
  • A write watch is then a page-table write protection (UFFDIO_WRITEPROTECT) and leaves the view read-write: no mapping split or merge, and the mmap lock is taken in read mode. The userfaultfd uses UFFD_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.
  • Access watches (pages written by the GPU) still use mprotect with no access. PageManager now 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.
  • The setup checks that the kernel reports shared-memory write protection and the register ioctl. If registering one view fails, that view keeps mprotect write 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.
  • The fault handler only claims tracking faults. A fault is resolved by the tracker when the guest protection of the page allows the access and the page is watched against it, or its watch was released since the fault and the access now succeeds (checked under the tracker lock with MADV_POPULATE_READ/MADV_POPULATE_WRITE on Linux, VirtualQuery on Windows). Only SEGV_ACCERR and, with userfaultfd, the BUS_ADRERR of write faults are considered; other codes such as BUS_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 on main it already does when the page is not watched; a watched page was made writable and the write went through.
  • Without userfaultfd (older kernels, a seccomp policy that denies it, macOS, Windows), protections go through mprotect or VirtualProtect as before. The log states which mode is used. vm.unprivileged_userfaultfd=0 does not matter: user-mode-only file descriptors are always allowed.

Kernel writes into a watched page, such as a read() or process_vm_writev into it, fail with EFAULT as they did with mprotect. File reads release the watches on their buffer before reading, as before.

On Windows, GetWriteWatch only covers private MEM_WRITE_WATCH allocations, 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 the mprotect path 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 the mprotect path.
  • virtual_memory_allocation_tests, Linux: TrackerWriteWatchRegistrationFallback. A registration failure injected for one view leaves it mapped, write-watched with mprotect, 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.
  • The existing address-space tests that check host write protection (PartialUnmapPreservesHostPermissions, FixedDirectReplacementPreservesAccess) pass in the userfaultfd mode. The first one probes a write-watched page with process_vm_writev, which gets EFAULT.

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 mprotect and 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):

Per frame Cutscene Sled
Frame time 66.5 -> 65.8 ms (-0.7 ± 1.6) 61.0 -> 57.7 ms (-3.2 ± 1.5)
Guest threads: time in write faults 25.7 -> 12.6 ms 32.6 -> 18.7 ms
of which spinning on tracker region locks 10.5 -> 2.6 ms 12.6 -> 3.7 ms
GPU command thread: tracker protection time 2.7 -> 1.7 ms 2.6 -> 1.6 ms
GPU command thread: spinning on tracker region locks 0.60 -> 0.17 ms 0.60 -> 0.18 ms
GPU command thread: PrepareBda 4.4 -> 3.0 ms 4.4 -> 3.0 ms

(± 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_tests and resource_materialization_tests pass.

  • shader_recompiler_compute_tests, one case per process (the buffer and texture cache cases run through this path): same results as origin/main apart 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

  • Conflicts in one line with #1284, which takes a shared lock in AddressSpace::ProtectTransient. Resolution: keep the std::shared_lock and its comment from #1284, and the ForEachMappedPartUnlocked call from this change.
  • #1147 registers the same guest views with its own userfaultfd for asynchronous write watches (opt-in). With this change those registrations would fail with 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.

**@⁠NeySlim** on GitHub · 2026-10-09 14:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307) `NeySlim:perf/uffd-write-watch` → `main` · +731 −31 · 13 files · 2 commits · open ## Problem 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 `mprotect` calls 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 `mprotect` takes 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 `mprotect` path: | | Cutscene | Sled | |---|---|---| | Write faults | 1,960 | 2,780 | | Guest threads: time in write faults (sum of threads) | 25.7 ms | 32.6 ms | | of which `mprotect` | 8.4 ms | 7.8 ms | | of which spinning on tracker region locks | 10.5 ms | 12.6 ms | | GPU command thread: tracker protection calls | 510 | 610 | | GPU command thread: tracker protection time | 2.7 ms | 2.6 ms | | GPU command thread: spinning on tracker region locks | 0.6 ms | 0.6 ms | ## Change - On Linux, when the kernel supports userfaultfd write protection of shared memory (5.19 and later; usable without privileges through `UFFD_USER_MODE_ONLY`), the backing store opens a userfaultfd at startup and registers every guest view for write protection when it maps it. - A write watch is then a page-table write protection (`UFFDIO_WRITEPROTECT`) and leaves the view read-write: no mapping split or merge, and the mmap lock is taken in read mode. The userfaultfd uses `UFFD_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. - Access watches (pages written by the GPU) still use `mprotect` with no access. `PageManager` now 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. - The setup checks that the kernel reports shared-memory write protection and the register ioctl. If registering one view fails, that view keeps `mprotect` write 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. - The fault handler only claims tracking faults. A fault is resolved by the tracker when the guest protection of the page allows the access and the page is watched against it, or its watch was released since the fault and the access now succeeds (checked under the tracker lock with `MADV_POPULATE_READ`/`MADV_POPULATE_WRITE` on Linux, `VirtualQuery` on Windows). Only `SEGV_ACCERR` and, with userfaultfd, the `BUS_ADRERR` of write faults are considered; other codes such as `BUS_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 on `main` it already does when the page is not watched; a watched page was made writable and the write went through. - Without userfaultfd (older kernels, a seccomp policy that denies it, macOS, Windows), protections go through `mprotect` or `VirtualProtect` as before. The log states which mode is used. `vm.unprivileged_userfaultfd=0` does not matter: user-mode-only file descriptors are always allowed. Kernel writes into a watched page, such as a `read()` or `process_vm_writev` into it, fail with `EFAULT` as they did with `mprotect`. File reads release the watches on their buffer before reading, as before. On Windows, `GetWriteWatch` only covers private `MEM_WRITE_WATCH` allocations, 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 the `mprotect` path 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 the `mprotect` path. - `virtual_memory_allocation_tests`, Linux: `TrackerWriteWatchRegistrationFallback`. A registration failure injected for one view leaves it mapped, write-watched with `mprotect`, 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. - The existing address-space tests that check host write protection (`PartialUnmapPreservesHostPermissions`, `FixedDirectReplacementPreservesAccess`) pass in the userfaultfd mode. The first one probes a write-watched page with `process_vm_writev`, which gets `EFAULT`. ## 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 `mprotect` and 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): | Per frame | Cutscene | Sled | |---|---|---| | Frame time | 66.5 -> 65.8 ms (-0.7 ± 1.6) | 61.0 -> 57.7 ms (-3.2 ± 1.5) | | Guest threads: time in write faults | 25.7 -> 12.6 ms | 32.6 -> 18.7 ms | | of which spinning on tracker region locks | 10.5 -> 2.6 ms | 12.6 -> 3.7 ms | | GPU command thread: tracker protection time | 2.7 -> 1.7 ms | 2.6 -> 1.6 ms | | GPU command thread: spinning on tracker region locks | 0.60 -> 0.17 ms | 0.60 -> 0.18 ms | | GPU command thread: `PrepareBda` | 4.4 -> 3.0 ms | 4.4 -> 3.0 ms | (± 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_tests` and `resource_materialization_tests` pass. - `shader_recompiler_compute_tests`, one case per process (the buffer and texture cache cases run through this path): same results as `origin/main` apart 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 - Conflicts in one line with #1284, which takes a shared lock in `AddressSpace::ProtectTransient`. Resolution: keep the `std::shared_lock` and its comment from #1284, and the `ForEachMappedPartUnlocked` call from this change. - #1147 registers the same guest views with its own userfaultfd for asynchronous write watches (opt-in). With this change those registrations would fail with `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.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:52:20 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 14:15 UTC · original · edited 2026-10-20 14:41 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 19fc882c0a3d3a74d2f6f312396d4fc6c044db5a
  • Latest commit, not reviewed: d44a0511a5

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

The change adds Linux userfaultfd write protection for tracked guest memory views, with an mprotect fallback when setup or registration is unavailable. Protection calls now carry an access_changed flag. 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: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🔵 Low · up to 19fc8

The new fault test may pass without exercising the userfaultfd-watched path. Production behavior is not affected. Tighten the test when convenient.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive 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:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: using userfaultfd to write-protect tracked guest pages.
Description check Passed The description is directly related to the changeset and explains the problem, implementation, fallback behavior, tests, and validation results.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
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.)

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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 help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 14:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#issuecomment-6082711670) · edited 2026-10-20 14:41 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1307?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 19fc882c0a3d3a74d2f6f312396d4fc6c044db5a > - Latest commit, not reviewed: d44a0511a5322bb4194b801fc31a9d9b55447d2e > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The change adds Linux `userfaultfd` write protection for tracked guest memory views, with an `mprotect` fallback when setup or registration is unavailable. Protection calls now carry an `access_changed` flag. 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:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"19fc882c0a3d3a74d2f6f312396d4fc6c044db5a" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🔵 Low</strong> · up to <code>19fc8</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🔵 Low** · up to `19fc8` --> <!-- final_review_risk_coverage:{"sourceCommitId":"19fc882c0a3d3a74d2f6f312396d4fc6c044db5a","coveredCommitId":"19fc882c0a3d3a74d2f6f312396d4fc6c044db5a","kind":"reviewed"} --> The new fault test may pass without exercising the userfaultfd-watched path. Production behavior is not affected. Tighten the test when convenient. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | 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:… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: using userfaultfd to write-protect tracked guest pages. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description is directly related to the changeset and explains the problem, implementation, fallback behavior, tests, and validation results. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **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.) </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1307)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 14:15 UTC · original · edited 2026-10-09 15:33 UTC
On src/kernel/memoryAddressSpace.inc line 79 (outdated):

@@ -28,6 +28,71 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+#if KYTY_PLATFORM == KYTY_PLATFORM_LINUX && !defined(__APPLE__)
+// Page-tracker write watches as page-table write protection (userfaultfd): watching a page
+// neither changes nor splits its view. A write to a protected page raises SIGBUS, which the
+// host fault handler resolves like a protection fault.
+class GuestWriteProtection {
+public:
+	GuestWriteProtection() {
+		const int fd = static_cast<int>(
+		    syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY));
+		if (fd < 0) {
+			LOGF("\t guest write tracking: mprotect (userfaultfd unavailable: %d)\n", errno);
+			return;
+		}
+		uffdio_api api {};
+		api.api      = UFFD_API;
+		api.features = UFFD_FEATURE_SIGBUS | UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
+		if (ioctl(fd, UFFDIO_API, &api) != 0) {
+			LOGF("\t guest write tracking: mprotect (no shared-memory write protection: %d)\n",
+			     errno);
+			close(fd);
+			return;
+		}
+		m_fd = fd;
+		LOGF("\t guest write tracking: userfaultfd write protection\n");
+	}
+
+	~GuestWriteProtection() {
+		if (m_fd >= 0) {
+			close(m_fd);
+		}
+	}
+
+	KYTY_CLASS_NO_COPY(GuestWriteProtection);
+
+	[[nodiscard]] bool Enabled() const { return m_fd >= 0; }
+
+	void Register(uint64_t vaddr, uint64_t size) const {
+		uffdio_register range {};
+		range.range.start = vaddr;
+		range.range.len   = size;
+		range.mode        = UFFDIO_REGISTER_MODE_WP;
+		// An unregistered view would let writes to watched pages through unseen.
+		if (ioctl(m_fd, UFFDIO_REGISTER, &range) != 0 ||
+		    (range.ioctls & (uint64_t {1} << _UFFDIO_WRITEPROTECT)) == 0) {
+			EXIT("userfaultfd registration failed: addr=0x%016" PRIx64 " size=0x%016" PRIx64
+			     " errno=%d\n",
+			     vaddr, size, errno);
+		}
+	}

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '25,100p' src/kernel/memoryAddressSpace.inc
rg -n 'm_write_protection|Register\(' src/kernel/memoryAddressSpace.inc

Repository: KytyPS5/KytyPS5

Length of output: 3026


🏁 Script executed:

set -eu
printf '%s\n' '--- relevant source ---'
nl -ba src/kernel/memoryAddressSpace.inc | sed -n '1,115p;520,790p'
printf '%s\n' '--- userfaultfd references and local contracts ---'
rg -n -F --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' 'UFFDIO_API|UFFD_FEATURE_WP_HUGETLBFS_SHMEM|_UFFDIO_REGISTER|UFFDIO_REGISTER|userfaultfd|GuestWriteProtection|WriteProtectsViews' .
printf '%s\n' '--- installed userfaultfd definitions, if available ---'
for f in /usr/include/linux/userfaultfd.h /usr/src/linux-headers-*/include/uapi/linux/userfaultfd.h; do
  if [ -f "$f" ]; then
    echo "FILE $f"
    nl -ba "$f" | sed -n '100,270p'
  fi
done

Repository: KytyPS5/KytyPS5

Length of output: 15772


🏁 Script executed:

printf '%s\n' '--- installed userfaultfd definitions ---'
found=0
for f in /usr/include/linux/userfaultfd.h /usr/src/linux-headers-*/include/uapi/linux/userfaultfd.h; do
  if [ -f "$f" ]; then
    found=1
    echo "FILE $f"
    rg -n -C 5 'UFFDIO_API|UFFD_FEATURE_WP_HUGETLBFS_SHMEM|UFFDIO_REGISTER|UFFD_API_IOCTLS|UFFD_API_FEATURES' "$f" || :
  fi
done
if [ "$found" -eq 0 ]; then
  echo 'No installed userfaultfd header found'
fi
printf '%s\n' '--- mapping callers and size/alignment inputs ---'
rg -n -F -- 'MapView(' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp src/kernel || :
rg -n -F -- 'GuestBackingStore' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp src/kernel || :

Repository: KytyPS5/KytyPS5

Length of output: 9930


🌐 Web query:

Linux userfaultfd UFFDIO_API unsupported requested feature EINVAL returned ioctls UFFDIO_REGISTER official documentation

💡 Result:

Yes. **`UFFDIO_API` can return `EINVAL` when you request an unsupported feature bit.** The Linux man page says the kernel zeroes the returned `uffdio_api` structure in that case. A recommended feature-probe is to first call `UFFDIO_API` with `features = 0`, then inspect the returned supported features. ([man7.org](https://www.man7.org/linux/man-pages/man2/UFFDIO_API.2const.html?utm_source=openai))

On success, `UFFDIO_API` also returns the generic ioctl bitmask in `uffdio_api.ioctls`. Check for `1ULL << _UFFDIO_REGISTER` before calling `UFFDIO_REGISTER`; after registration, that ioctl returns a separate bitmask of operations supported for that memory range. ([cdn.kernel.org](https://cdn.kernel.org/doc/html/latest/admin-guide/mm/userfaultfd.html?utm_source=openai))

So an `EINVAL` from **`UFFDIO_API`** is consistent with an unsupported requested feature; it is not a returned “unsupported `UFFDIO_REGISTER`” status. If the API handshake succeeds but `UFFDIO_REGISTER` is absent from `ioctls`, don’t call it. The exact cause of an `EINVAL` from your call still depends on the request and kernel version.

Citations:

- 1: https://www.man7.org/linux/man-pages/man2/UFFDIO_API.2const.html?utm_source=openai
- 2: https://cdn.kernel.org/doc/html/latest/admin-guide/mm/userfaultfd.html?utm_source=openai

🏁 Script executed:

printf '%s\n' '--- backing store setup and mapping caller ---'
nl -ba src/kernel/memoryAddressSpace.inc | sed -n '109,195p;330,405p;885,965p'
printf '%s\n' '--- userfaultfd API and registration contract in installed header ---'
nl -ba /usr/include/linux/userfaultfd.h | sed -n '84,155p;155,230p;255,305p'

Repository: KytyPS5/KytyPS5

Length of output: 17776


🏁 Script executed:

printf '%s\n' '--- MapBacking callers ---'
rg -n -F -- 'MapBacking(' src || :
printf '%s\n' '--- mapping API and alignment checks ---'
rg -n -F -- 'Map(' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp | head -80 || :
rg -n -F -- 'Page' src/kernel/memoryAddressSpace.inc | head -80 || :
nl -ba src/kernel/memoryAddressSpace.inc | sed -n '780,890p;965,1045p'

Repository: KytyPS5/KytyPS5

Length of output: 11436


Fall back when view registration fails.

UFFDIO_API already rejects an unsupported requested feature with EINVAL, so the existing setup path falls back to mprotect. A successful handshake also returns the supported ioctl mask, which this code does not check.

MapView still calls Register after each successful mmap, and Register calls EXIT when UFFDIO_REGISTER fails. A registration failure therefore terminates the process instead of selecting the mprotect path. Check _UFFDIO_REGISTER before enabling this mode, and make registration failure disable userfaultfd protection and use mprotect rather than aborting.

✅ Addressed in commit 5078858

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 14:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#discussion_r4231074789) · edited 2026-10-09 15:33 UTC On `src/kernel/memoryAddressSpace.inc` line 79 (outdated): ```diff @@ -28,6 +28,71 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +#if KYTY_PLATFORM == KYTY_PLATFORM_LINUX && !defined(__APPLE__) +// Page-tracker write watches as page-table write protection (userfaultfd): watching a page +// neither changes nor splits its view. A write to a protected page raises SIGBUS, which the +// host fault handler resolves like a protection fault. +class GuestWriteProtection { +public: + GuestWriteProtection() { + const int fd = static_cast<int>( + syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY)); + if (fd < 0) { + LOGF("\t guest write tracking: mprotect (userfaultfd unavailable: %d)\n", errno); + return; + } + uffdio_api api {}; + api.api = UFFD_API; + api.features = UFFD_FEATURE_SIGBUS | UFFD_FEATURE_WP_HUGETLBFS_SHMEM; + if (ioctl(fd, UFFDIO_API, &api) != 0) { + LOGF("\t guest write tracking: mprotect (no shared-memory write protection: %d)\n", + errno); + close(fd); + return; + } + m_fd = fd; + LOGF("\t guest write tracking: userfaultfd write protection\n"); + } + + ~GuestWriteProtection() { + if (m_fd >= 0) { + close(m_fd); + } + } + + KYTY_CLASS_NO_COPY(GuestWriteProtection); + + [[nodiscard]] bool Enabled() const { return m_fd >= 0; } + + void Register(uint64_t vaddr, uint64_t size) const { + uffdio_register range {}; + range.range.start = vaddr; + range.range.len = size; + range.mode = UFFDIO_REGISTER_MODE_WP; + // An unregistered view would let writes to watched pages through unseen. + if (ioctl(m_fd, UFFDIO_REGISTER, &range) != 0 || + (range.ioctls & (uint64_t {1} << _UFFDIO_WRITEPROTECT)) == 0) { + EXIT("userfaultfd registration failed: addr=0x%016" PRIx64 " size=0x%016" PRIx64 + " errno=%d\n", + vaddr, size, errno); + } + } ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '25,100p' src/kernel/memoryAddressSpace.inc rg -n 'm_write_protection|Register\(' src/kernel/memoryAddressSpace.inc ``` Repository: KytyPS5/KytyPS5 Length of output: 3026 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- relevant source ---' nl -ba src/kernel/memoryAddressSpace.inc | sed -n '1,115p;520,790p' printf '%s\n' '--- userfaultfd references and local contracts ---' rg -n -F --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' 'UFFDIO_API|UFFD_FEATURE_WP_HUGETLBFS_SHMEM|_UFFDIO_REGISTER|UFFDIO_REGISTER|userfaultfd|GuestWriteProtection|WriteProtectsViews' . printf '%s\n' '--- installed userfaultfd definitions, if available ---' for f in /usr/include/linux/userfaultfd.h /usr/src/linux-headers-*/include/uapi/linux/userfaultfd.h; do if [ -f "$f" ]; then echo "FILE $f" nl -ba "$f" | sed -n '100,270p' fi done ``` Repository: KytyPS5/KytyPS5 Length of output: 15772 --- 🏁 Script executed: ```bash printf '%s\n' '--- installed userfaultfd definitions ---' found=0 for f in /usr/include/linux/userfaultfd.h /usr/src/linux-headers-*/include/uapi/linux/userfaultfd.h; do if [ -f "$f" ]; then found=1 echo "FILE $f" rg -n -C 5 'UFFDIO_API|UFFD_FEATURE_WP_HUGETLBFS_SHMEM|UFFDIO_REGISTER|UFFD_API_IOCTLS|UFFD_API_FEATURES' "$f" || : fi done if [ "$found" -eq 0 ]; then echo 'No installed userfaultfd header found' fi printf '%s\n' '--- mapping callers and size/alignment inputs ---' rg -n -F -- 'MapView(' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp src/kernel || : rg -n -F -- 'GuestBackingStore' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp src/kernel || : ``` Repository: KytyPS5/KytyPS5 Length of output: 9930 --- 🌐 Web query: `Linux userfaultfd UFFDIO_API unsupported requested feature EINVAL returned ioctls UFFDIO_REGISTER official documentation` 💡 Result: ``` Yes. **`UFFDIO_API` can return `EINVAL` when you request an unsupported feature bit.** The Linux man page says the kernel zeroes the returned `uffdio_api` structure in that case. A recommended feature-probe is to first call `UFFDIO_API` with `features = 0`, then inspect the returned supported features. ([man7.org](https://www.man7.org/linux/man-pages/man2/UFFDIO_API.2const.html?utm_source=openai)) On success, `UFFDIO_API` also returns the generic ioctl bitmask in `uffdio_api.ioctls`. Check for `1ULL << _UFFDIO_REGISTER` before calling `UFFDIO_REGISTER`; after registration, that ioctl returns a separate bitmask of operations supported for that memory range. ([cdn.kernel.org](https://cdn.kernel.org/doc/html/latest/admin-guide/mm/userfaultfd.html?utm_source=openai)) So an `EINVAL` from **`UFFDIO_API`** is consistent with an unsupported requested feature; it is not a returned “unsupported `UFFDIO_REGISTER`” status. If the API handshake succeeds but `UFFDIO_REGISTER` is absent from `ioctls`, don’t call it. The exact cause of an `EINVAL` from your call still depends on the request and kernel version. Citations: - 1: https://www.man7.org/linux/man-pages/man2/UFFDIO_API.2const.html?utm_source=openai - 2: https://cdn.kernel.org/doc/html/latest/admin-guide/mm/userfaultfd.html?utm_source=openai ``` --- 🏁 Script executed: ```bash printf '%s\n' '--- backing store setup and mapping caller ---' nl -ba src/kernel/memoryAddressSpace.inc | sed -n '109,195p;330,405p;885,965p' printf '%s\n' '--- userfaultfd API and registration contract in installed header ---' nl -ba /usr/include/linux/userfaultfd.h | sed -n '84,155p;155,230p;255,305p' ``` Repository: KytyPS5/KytyPS5 Length of output: 17776 --- 🏁 Script executed: ```bash printf '%s\n' '--- MapBacking callers ---' rg -n -F -- 'MapBacking(' src || : printf '%s\n' '--- mapping API and alignment checks ---' rg -n -F -- 'Map(' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp | head -80 || : rg -n -F -- 'Page' src/kernel/memoryAddressSpace.inc | head -80 || : nl -ba src/kernel/memoryAddressSpace.inc | sed -n '780,890p;965,1045p' ``` Repository: KytyPS5/KytyPS5 Length of output: 11436 --- </details> **Fall back when view registration fails.** `UFFDIO_API` already rejects an unsupported requested feature with `EINVAL`, so the existing setup path falls back to `mprotect`. A successful handshake also returns the supported ioctl mask, which this code does not check. `MapView` still calls `Register` after each successful `mmap`, and `Register` calls `EXIT` when `UFFDIO_REGISTER` fails. A registration failure therefore terminates the process instead of selecting the `mprotect` path. Check `_UFFDIO_REGISTER` before enabling this mode, and make registration failure disable userfaultfd protection and use `mprotect` rather than aborting. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ee490fc14fc781f4f4fb68de --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 5078858
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 14:15 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4028922e-294f-469b-bb0b-b2f2141a9bb9
📥 Commits

Reviewing files that changed from the base of the PR and between 4c8fc53a85 and 7daef13d1b0572b3123a033606c3550b5b767f43.

📒 Files selected for processing (7)
  • src/graphics/host_gpu/pageManager.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • tests/MemoryTrackerTests.cpp
  • tests/PageManagerTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 14:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#pullrequestreview-5471260247) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `4028922e-294f-469b-bb0b-b2f2141a9bb9` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 4c8fc53a8582543200caa697acad2a9f09937cec and 7daef13d1b0572b3123a033606c3550b5b767f43. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `src/graphics/host_gpu/pageManager.cpp` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `tests/MemoryTrackerTests.cpp` * `tests/PageManagerTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=dd10cf12-f5f7-4f7d-8d51-719652bdfa89 attempt=68551f1a-d49d-460a-990d-6ad126805ac9 batch=1/1 -->
Author
Owner

@⁠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) and TrackerWriteWatchRegistrationFallback; description updated.

**@⁠NeySlim** on GitHub · 2026-10-09 15:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#issuecomment-6083863032) 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) and `TrackerWriteWatchRegistrationFallback`; description updated.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 15:21 UTC · original
On src/kernel/memoryAddressSpace.inc line 79 (outdated):

@@ -28,6 +28,71 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+#if KYTY_PLATFORM == KYTY_PLATFORM_LINUX && !defined(__APPLE__)
+// Page-tracker write watches as page-table write protection (userfaultfd): watching a page
+// neither changes nor splits its view. A write to a protected page raises SIGBUS, which the
+// host fault handler resolves like a protection fault.
+class GuestWriteProtection {
+public:
+	GuestWriteProtection() {
+		const int fd = static_cast<int>(
+		    syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY));
+		if (fd < 0) {
+			LOGF("\t guest write tracking: mprotect (userfaultfd unavailable: %d)\n", errno);
+			return;
+		}
+		uffdio_api api {};
+		api.api      = UFFD_API;
+		api.features = UFFD_FEATURE_SIGBUS | UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
+		if (ioctl(fd, UFFDIO_API, &api) != 0) {
+			LOGF("\t guest write tracking: mprotect (no shared-memory write protection: %d)\n",
+			     errno);
+			close(fd);
+			return;
+		}
+		m_fd = fd;
+		LOGF("\t guest write tracking: userfaultfd write protection\n");
+	}
+
+	~GuestWriteProtection() {
+		if (m_fd >= 0) {
+			close(m_fd);
+		}
+	}
+
+	KYTY_CLASS_NO_COPY(GuestWriteProtection);
+
+	[[nodiscard]] bool Enabled() const { return m_fd >= 0; }
+
+	void Register(uint64_t vaddr, uint64_t size) const {
+		uffdio_register range {};
+		range.range.start = vaddr;
+		range.range.len   = size;
+		range.mode        = UFFDIO_REGISTER_MODE_WP;
+		// An unregistered view would let writes to watched pages through unseen.
+		if (ioctl(m_fd, UFFDIO_REGISTER, &range) != 0 ||
+		    (range.ioctls & (uint64_t {1} << _UFFDIO_WRITEPROTECT)) == 0) {
+			EXIT("userfaultfd registration failed: addr=0x%016" PRIx64 " size=0x%016" PRIx64
+			     " errno=%d\n",
+			     vaddr, size, errno);
+		}
+	}

Fixed in 5078858c. Setup now requires the shared-memory write-protection feature and _UFFDIO_REGISTER in the UFFDIO_API result. A failed UFFDIO_REGISTER no longer exits: that view is logged and keeps mprotect write 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 by TrackerWriteWatchRegistrationFallback, which injects a registration failure.

**@⁠NeySlim** on GitHub · 2026-10-09 15:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#discussion_r4231707190) On `src/kernel/memoryAddressSpace.inc` line 79 (outdated): ```diff @@ -28,6 +28,71 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +#if KYTY_PLATFORM == KYTY_PLATFORM_LINUX && !defined(__APPLE__) +// Page-tracker write watches as page-table write protection (userfaultfd): watching a page +// neither changes nor splits its view. A write to a protected page raises SIGBUS, which the +// host fault handler resolves like a protection fault. +class GuestWriteProtection { +public: + GuestWriteProtection() { + const int fd = static_cast<int>( + syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY)); + if (fd < 0) { + LOGF("\t guest write tracking: mprotect (userfaultfd unavailable: %d)\n", errno); + return; + } + uffdio_api api {}; + api.api = UFFD_API; + api.features = UFFD_FEATURE_SIGBUS | UFFD_FEATURE_WP_HUGETLBFS_SHMEM; + if (ioctl(fd, UFFDIO_API, &api) != 0) { + LOGF("\t guest write tracking: mprotect (no shared-memory write protection: %d)\n", + errno); + close(fd); + return; + } + m_fd = fd; + LOGF("\t guest write tracking: userfaultfd write protection\n"); + } + + ~GuestWriteProtection() { + if (m_fd >= 0) { + close(m_fd); + } + } + + KYTY_CLASS_NO_COPY(GuestWriteProtection); + + [[nodiscard]] bool Enabled() const { return m_fd >= 0; } + + void Register(uint64_t vaddr, uint64_t size) const { + uffdio_register range {}; + range.range.start = vaddr; + range.range.len = size; + range.mode = UFFDIO_REGISTER_MODE_WP; + // An unregistered view would let writes to watched pages through unseen. + if (ioctl(m_fd, UFFDIO_REGISTER, &range) != 0 || + (range.ioctls & (uint64_t {1} << _UFFDIO_WRITEPROTECT)) == 0) { + EXIT("userfaultfd registration failed: addr=0x%016" PRIx64 " size=0x%016" PRIx64 + " errno=%d\n", + vaddr, size, errno); + } + } ``` Fixed in 5078858c. Setup now requires the shared-memory write-protection feature and `_UFFDIO_REGISTER` in the `UFFDIO_API` result. A failed `UFFDIO_REGISTER` no longer exits: that view is logged and keeps `mprotect` write 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 by `TrackerWriteWatchRegistrationFallback`, which injects a registration failure.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 15:33 UTC · original
On src/kernel/memoryAddressSpace.inc line 79 (outdated):

@@ -28,6 +28,71 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+#if KYTY_PLATFORM == KYTY_PLATFORM_LINUX && !defined(__APPLE__)
+// Page-tracker write watches as page-table write protection (userfaultfd): watching a page
+// neither changes nor splits its view. A write to a protected page raises SIGBUS, which the
+// host fault handler resolves like a protection fault.
+class GuestWriteProtection {
+public:
+	GuestWriteProtection() {
+		const int fd = static_cast<int>(
+		    syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY));
+		if (fd < 0) {
+			LOGF("\t guest write tracking: mprotect (userfaultfd unavailable: %d)\n", errno);
+			return;
+		}
+		uffdio_api api {};
+		api.api      = UFFD_API;
+		api.features = UFFD_FEATURE_SIGBUS | UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
+		if (ioctl(fd, UFFDIO_API, &api) != 0) {
+			LOGF("\t guest write tracking: mprotect (no shared-memory write protection: %d)\n",
+			     errno);
+			close(fd);
+			return;
+		}
+		m_fd = fd;
+		LOGF("\t guest write tracking: userfaultfd write protection\n");
+	}
+
+	~GuestWriteProtection() {
+		if (m_fd >= 0) {
+			close(m_fd);
+		}
+	}
+
+	KYTY_CLASS_NO_COPY(GuestWriteProtection);
+
+	[[nodiscard]] bool Enabled() const { return m_fd >= 0; }
+
+	void Register(uint64_t vaddr, uint64_t size) const {
+		uffdio_register range {};
+		range.range.start = vaddr;
+		range.range.len   = size;
+		range.mode        = UFFDIO_REGISTER_MODE_WP;
+		// An unregistered view would let writes to watched pages through unseen.
+		if (ioctl(m_fd, UFFDIO_REGISTER, &range) != 0 ||
+		    (range.ioctls & (uint64_t {1} << _UFFDIO_WRITEPROTECT)) == 0) {
+			EXIT("userfaultfd registration failed: addr=0x%016" PRIx64 " size=0x%016" PRIx64
+			     " errno=%d\n",
+			     vaddr, size, errno);
+		}
+	}

@NeySlim, thanks for the clarification. The supplied code addresses this finding: setup checks the required feature and ioctl, and registration failure selects mprotect for that view without aborting.

Per-view fallback is appropriate. A global switch could leave existing userfaultfd write protections active on other views.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1307
File: src/kernel/memoryAddressSpace.inc:0-0
Timestamp: 2026-10-09T15:33:36.642Z
Learning: In src/kernel/memoryAddressSpace.inc, Linux GuestBackingStore selects userfaultfd or mprotect write-watch protection per view through MapEntry::write_protected. Registration failure must fall back for that view, not globally: other views can already have userfaultfd write protections active. Watch updates and releases for a page use the same view's protection mechanism.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


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-09 15:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#discussion_r4231815552) On `src/kernel/memoryAddressSpace.inc` line 79 (outdated): ```diff @@ -28,6 +28,71 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +#if KYTY_PLATFORM == KYTY_PLATFORM_LINUX && !defined(__APPLE__) +// Page-tracker write watches as page-table write protection (userfaultfd): watching a page +// neither changes nor splits its view. A write to a protected page raises SIGBUS, which the +// host fault handler resolves like a protection fault. +class GuestWriteProtection { +public: + GuestWriteProtection() { + const int fd = static_cast<int>( + syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY)); + if (fd < 0) { + LOGF("\t guest write tracking: mprotect (userfaultfd unavailable: %d)\n", errno); + return; + } + uffdio_api api {}; + api.api = UFFD_API; + api.features = UFFD_FEATURE_SIGBUS | UFFD_FEATURE_WP_HUGETLBFS_SHMEM; + if (ioctl(fd, UFFDIO_API, &api) != 0) { + LOGF("\t guest write tracking: mprotect (no shared-memory write protection: %d)\n", + errno); + close(fd); + return; + } + m_fd = fd; + LOGF("\t guest write tracking: userfaultfd write protection\n"); + } + + ~GuestWriteProtection() { + if (m_fd >= 0) { + close(m_fd); + } + } + + KYTY_CLASS_NO_COPY(GuestWriteProtection); + + [[nodiscard]] bool Enabled() const { return m_fd >= 0; } + + void Register(uint64_t vaddr, uint64_t size) const { + uffdio_register range {}; + range.range.start = vaddr; + range.range.len = size; + range.mode = UFFDIO_REGISTER_MODE_WP; + // An unregistered view would let writes to watched pages through unseen. + if (ioctl(m_fd, UFFDIO_REGISTER, &range) != 0 || + (range.ioctls & (uint64_t {1} << _UFFDIO_WRITEPROTECT)) == 0) { + EXIT("userfaultfd registration failed: addr=0x%016" PRIx64 " size=0x%016" PRIx64 + " errno=%d\n", + vaddr, size, errno); + } + } ``` `@NeySlim`, thanks for the clarification. The supplied code addresses this finding: setup checks the required feature and ioctl, and registration failure selects `mprotect` for that view without aborting. Per-view fallback is appropriate. A global switch could leave existing userfaultfd write protections active on other views. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1307 File: src/kernel/memoryAddressSpace.inc:0-0 Timestamp: 2026-10-09T15:33:36.642Z Learning: In src/kernel/memoryAddressSpace.inc, Linux GuestBackingStore selects userfaultfd or mprotect write-watch protection per view through MapEntry::write_protected. Registration failure must fall back for that view, not globally: other views can already have userfaultfd write protections active. Watch updates and releases for a page use the same view's protection mechanism. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20crash%20risk%3A%20failed%20UFFD%20registration%20now%20falls%20back%20to%20mprotect%20per%20view%2C%20preserving%20write%20watches%20without%20aborting.%20Try%20CodeRabbit%20for%20safer%20reviews!%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1307%23discussion_r4231074789)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-16 02:34 UTC · original · reviewed

🧹 Nitpick comments: 1
tests/ShaderRecompilerComputeTests.cpp: 1

5515-5515: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Ensure the child retains a userfaultfd write watch.

GuestWriteProtection does not request UFFD_FEATURE_EVENT_FORK. Linux duplicates the userfaultfd context into a forked child only when this feature is enabled. Without it, the child can satisfy this assertion with a plain SIGSEGV from KernelMprotect(..., 0x11) without exercising the watched-page fault path.

Enable and handle UFFD_FEATURE_EVENT_FORK, or register the write watch in the child before the write.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 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.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-16 02:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#pullrequestreview-5542349404) · **reviewed** <details> <summary>🧹 Nitpick comments: 1</summary><blockquote> <details> <summary>tests/ShaderRecompilerComputeTests.cpp: 1</summary><blockquote> `5515-5515`: **🎯 Functional Correctness** | **🔵 Trivial** | **🏗️ Heavy lift** **Ensure the child retains a userfaultfd write watch.** `GuestWriteProtection` does not request `UFFD_FEATURE_EVENT_FORK`. Linux duplicates the userfaultfd context into a forked child only when this feature is enabled. Without it, the child can satisfy this assertion with a plain `SIGSEGV` from `KernelMprotect(..., 0x11)` without exercising the watched-page fault path. Enable and handle `UFFD_FEATURE_EVENT_FORK`, or register the write watch in the child before the write. <!-- cr-comment:v1:4ba8069f9b92a791ecf604c2 --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `a4115a95-166d-43fb-94a0-dbeb21b7ec4a` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 9d56751e2a97aefcadb73671124cbb5588bcd208 and 19fc882c0a3d3a74d2f6f312396d4fc6c044db5a. </details> <details> <summary>📒 Files selected for processing: 3</summary> * `src/kernel/memory.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=9464c76d-7add-4bfc-835d-ef3b5244e6e5 attempt=e0e45028-986b-4b62-afe5-060e56434d43 batch=1/1 -->
Author
Owner

@⁠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.

**@⁠NeySlim** on GitHub · 2026-10-16 03:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1307#issuecomment-6207455242) 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.
This pull request has changes conflicting with the target branch.
  • src/common/hostException.cpp
  • src/graphics/host_gpu/pageManager.cpp
  • src/kernel/memory.cpp
  • src/kernel/memoryAddressSpace.inc
  • src/loader/runtimeLinker.cpp
  • tests/ShaderRecompilerComputeTests.cpp
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.
git fetch -u origin '+refs/pull/1307/head:github-bot/gh-1307'
git switch 'github-bot/gh-1307'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1307'
git switch 'github-bot/gh-1307'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1307'
git switch 'github-bot/gh-1307'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1307'
git switch 'main'
git merge --squash 'github-bot/gh-1307'
git switch 'main'
git merge --ff-only 'github-bot/gh-1307'
git switch 'main'
git merge 'github-bot/gh-1307'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.