gpu: cheaper CPU write tracking for uploaded pages #1284

Open
github-bot wants to merge 5 commits from github-bot/gh-1284 into main AGit
Owner

@⁠NeySlim on GitHub · 2026-10-09 07:25 UTC · original
NeySlim:perf/write-tracking → main · +386 −33 · 11 files · 5 commits · open

Problem

The buffer cache keeps the pages it has uploaded write-protected, so that a CPU write marks them dirty through a write fault. In God of War Ragnarök (PPSA08332, 05.005) the guest CPU writes about 2,000 such pages per frame in the opening cutscene and 3,000 in the sled sequence that follows. The GPU command thread protects them again when it uploads them, mostly in the sweep of registered buffers before draws that address memory directly, and the game writes many of them again later in the same frame.

Per frame, before this PR:

Cutscene Sled
Write faults 1,970 3,040
Guest thread time in write faults (sum of threads) 58 ms 110 ms
of which spinning on tracker region locks 27 ms 57 ms
GPU command thread: mprotect time 4.2 ms 6.7 ms
of which waiting for the address space mutex 2.0 ms 3.6 ms
GPU command thread: spinning on tracker region locks 1.3 ms 2.4 ms
GPU command thread: buffer synchronization 6.6 ms 10.8 ms

Three costs add up:

  • every tracker protection change takes the guest address space mutex exclusively (ProtectTransient), although it only reads the mapping list;
  • every write fault also takes the texture cache lock, which the GPU command thread holds while it records, even when no image uses the page (98% of the faults);
  • the GPU command thread takes a tracker region lock for every dirty-page query and every upload check (about 40,000 per frame, most of them on clean pages), and waits whenever a guest thread holds that lock during its own fault.

Change

  • GuestAddressSpace::ProtectTransient takes the address space mutex in shared mode. Mapping changes still take it exclusively. PageManager changes the protection of a page only under its own region lock, so concurrent callers never protect the same page.
  • TextureCache counts the registered images of each page of its page table in atomics written under its lock. InvalidateMemory returns without the lock when the written pages have none. Images count their pages when they register, before they are tracked, so a fault on a page an image protects always finds the count; a write racing with a registration behaves as one just before it, which the lock already allowed.
  • RegionManager publishes its dirty bits in atomic words after each change. MemoryTracker dirty queries, and upload and download checks, read them without the region lock when the range has nothing to do. These calls run on the GPU command thread, which is the only one that clears CPU-dirty bits and the only one that changes GPU-dirty bits; other threads only set CPU-dirty bits, under the lock and before their write. Debug builds check that uploads, downloads and GPU-dirty clears never overlap.

Test

  • virtual_memory_allocation_tests: TrackerProtectionDuringBackingRead. A tracker protection change completes while a sparse backing read holds the address space lock in shared mode.
  • shader_recompiler_compute_tests --imageless-invalidation-only (ctest texture_cache_imageless_invalidation, also in the default run): ImagelessPageInvalidation. While the test holds the texture cache lock, a write to a page without images returns; a write to an image page still marks the image CPU-dirty; after the image is deleted, writes to its pages no longer wait for the lock.
  • memory_tracker_tests:
    • TestQueriesDoNotWaitForWriteFault: while a write fault holds a region (stopped inside its protection change), dirty queries and an upload check of a clean page of the same region complete;
    • debug builds: an unmark started on a second thread while an upload runs exits (death case overlapping-gpu-dirty-owners). TestConcurrentColdUploads now runs its uploads one after the other and checks that a cold writable upload does not block region creation on another thread.

Each new test fails without its change (checked by reverting the change alone).

Validation

Linux, 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 the previous code and this change within one session, so both see the same scenes, on a branch with other pending GPU thread changes: the sled frame time drops by 6.6 ± 2.8 ms (± one standard error). I did not measure the cutscene separately for this change; there the GPU command thread mostly waits for GPU work at its readbacks, so time it saves tends to turn into waiting.

Screenshots of both settings show no rendering difference.

  • memory_tracker_tests, page_manager_tests, virtual_memory_allocation_tests, resource_tracking_tests and resource_materialization_tests pass.
  • shader_recompiler_compute_tests, one case per process: same results as origin/main except the new ImagelessPageInvalidation case, which fails without the change (598 of 608 cases pass with it, 597 without; the other 10 fail on both on this RADV setup).
  • Debug build: memory_tracker_tests passes, and the whole shader_recompiler_compute_tests suite, one case per process, gives the same results as the release build (the overlap check never fires).

Not tested on Windows or macOS. The change adds no platform-specific code: VirtualProtect, like mprotect, can run concurrently on different pages, and the new tests use only the existing portable helpers.

AI use

I used Claude Code (AI agent) to profile the GPU command thread and the guest 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 07:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284) `NeySlim:perf/write-tracking` → `main` · +386 −33 · 11 files · 5 commits · open ## Problem The buffer cache keeps the pages it has uploaded write-protected, so that a CPU write marks them dirty through a write fault. In God of War Ragnarök (PPSA08332, 05.005) the guest CPU writes about 2,000 such pages per frame in the opening cutscene and 3,000 in the sled sequence that follows. The GPU command thread protects them again when it uploads them, mostly in the sweep of registered buffers before draws that address memory directly, and the game writes many of them again later in the same frame. Per frame, before this PR: | | Cutscene | Sled | |---|---|---| | Write faults | 1,970 | 3,040 | | Guest thread time in write faults (sum of threads) | 58 ms | 110 ms | | of which spinning on tracker region locks | 27 ms | 57 ms | | GPU command thread: `mprotect` time | 4.2 ms | 6.7 ms | | of which waiting for the address space mutex | 2.0 ms | 3.6 ms | | GPU command thread: spinning on tracker region locks | 1.3 ms | 2.4 ms | | GPU command thread: buffer synchronization | 6.6 ms | 10.8 ms | Three costs add up: - every tracker protection change takes the guest address space mutex exclusively (`ProtectTransient`), although it only reads the mapping list; - every write fault also takes the texture cache lock, which the GPU command thread holds while it records, even when no image uses the page (98% of the faults); - the GPU command thread takes a tracker region lock for every dirty-page query and every upload check (about 40,000 per frame, most of them on clean pages), and waits whenever a guest thread holds that lock during its own fault. ## Change - `GuestAddressSpace::ProtectTransient` takes the address space mutex in shared mode. Mapping changes still take it exclusively. `PageManager` changes the protection of a page only under its own region lock, so concurrent callers never protect the same page. - `TextureCache` counts the registered images of each page of its page table in atomics written under its lock. `InvalidateMemory` returns without the lock when the written pages have none. Images count their pages when they register, before they are tracked, so a fault on a page an image protects always finds the count; a write racing with a registration behaves as one just before it, which the lock already allowed. - `RegionManager` publishes its dirty bits in atomic words after each change. `MemoryTracker` dirty queries, and upload and download checks, read them without the region lock when the range has nothing to do. These calls run on the GPU command thread, which is the only one that clears CPU-dirty bits and the only one that changes GPU-dirty bits; other threads only set CPU-dirty bits, under the lock and before their write. Debug builds check that uploads, downloads and GPU-dirty clears never overlap. ## Test - `virtual_memory_allocation_tests`: `TrackerProtectionDuringBackingRead`. A tracker protection change completes while a sparse backing read holds the address space lock in shared mode. - `shader_recompiler_compute_tests --imageless-invalidation-only` (ctest `texture_cache_imageless_invalidation`, also in the default run): `ImagelessPageInvalidation`. While the test holds the texture cache lock, a write to a page without images returns; a write to an image page still marks the image CPU-dirty; after the image is deleted, writes to its pages no longer wait for the lock. - `memory_tracker_tests`: - `TestQueriesDoNotWaitForWriteFault`: while a write fault holds a region (stopped inside its protection change), dirty queries and an upload check of a clean page of the same region complete; - debug builds: an unmark started on a second thread while an upload runs exits (death case `overlapping-gpu-dirty-owners`). `TestConcurrentColdUploads` now runs its uploads one after the other and checks that a cold writable upload does not block region creation on another thread. Each new test fails without its change (checked by reverting the change alone). ## Validation Linux, 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 the previous code and this change within one session, so both see the same scenes, on a branch with other pending GPU thread changes: the sled frame time drops by 6.6 ± 2.8 ms (± one standard error). I did not measure the cutscene separately for this change; there the GPU command thread mostly waits for GPU work at its readbacks, so time it saves tends to turn into waiting. Screenshots of both settings show no rendering difference. - `memory_tracker_tests`, `page_manager_tests`, `virtual_memory_allocation_tests`, `resource_tracking_tests` and `resource_materialization_tests` pass. - `shader_recompiler_compute_tests`, one case per process: same results as `origin/main` except the new `ImagelessPageInvalidation` case, which fails without the change (598 of 608 cases pass with it, 597 without; the other 10 fail on both on this RADV setup). - Debug build: `memory_tracker_tests` passes, and the whole `shader_recompiler_compute_tests` suite, one case per process, gives the same results as the release build (the overlap check never fires). Not tested on Windows or macOS. The change adds no platform-specific code: `VirtualProtect`, like `mprotect`, can run concurrently on different pages, and the new tests use only the existing portable helpers. ## AI use I used Claude Code (AI agent) to profile the GPU command thread and the guest 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:51:24 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 07:29 UTC · original · edited 2026-10-16 01:07 UTC

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5c9efa30-c8ad-49ea-bade-5ccdc8129874
📥 Commits

Reviewing files that changed from the base of the PR and between 3385d5fc608da8e1aab029e77e9d76034cd8f93b and 9a1e0cbfba.

📒 Files selected for processing: 4
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • 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; 4 remain after this review.

📝 Walkthrough

Memory tracking now publishes atomic dirty-page snapshots and uses unlocked checks for queries and transfers. GPU-dirty operations use owner scopes. Transient page protection now uses a shared lock. TextureCache tracks image registrations by page and skips invalidation when a valid range has no registered images. Tests cover concurrent memory operations, protection changes, sparse backing reads, and texture invalidation.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Refactor

Merge Risk: ⚪ Minimal · up to 9a1e0

No actionable merge-blocking issue remains in the reviewed changes; proceed with normal checks.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 8 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 describes the main change: reducing CPU write-tracking costs for uploaded GPU pages.
Description check Passed The description is directly related to the changeset and explains the performance problem, implementation, tests, validation results, and platform coverage.
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 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 8 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 07:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284#issuecomment-6076488374) · edited 2026-10-16 01:07 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/1284?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 --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `5c9efa30-c8ad-49ea-bade-5ccdc8129874` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 3385d5fc608da8e1aab029e77e9d76034cd8f93b and 9a1e0cbfba3c767573e844ed15290e8d3d9f62d9. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing: 4</strong></summary> <dl> <dd> * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> Memory tracking now publishes atomic dirty-page snapshots and uses unlocked checks for queries and transfers. GPU-dirty operations use owner scopes. Transient page protection now uses a shared lock. TextureCache tracks image registrations by page and skips invalidation when a valid range has no registered images. Tests cover concurrent memory operations, protection changes, sparse backing reads, and texture invalidation. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"9a1e0cbfba3c767573e844ed15290e8d3d9f62d9" --> **Change:** Refactor <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>9a1e0</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `9a1e0` --> <!-- final_review_risk_coverage:{"sourceCommitId":"9a1e0cbfba3c767573e844ed15290e8d3d9f62d9","coveredCommitId":"9a1e0cbfba3c767573e844ed15290e8d3d9f62d9","kind":"reviewed"} --> No actionable merge-blocking issue remains in the reviewed changes; proceed with normal checks. <!-- 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 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 8 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 describes the main change: reducing CPU write-tracking costs for uploaded GPU 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 performance problem, implementation, tests, validation results, and platform coverage. | | 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 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 8 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=1284)! 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 07:29 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: 9ffac5ec-b917-4ece-913a-66da77f57a6d
📥 Commits

Reviewing files that changed from the base of the PR and between 7b9997baea and 29d49db31ef2c42f2d8851c0e6bca22ec4581bd8.

📒 Files selected for processing (11)
  • CMakeLists.txt
  • src/common/bitArray.h
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/regionManager.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/kernel/memoryAddressSpace.inc
  • tests/MemoryTrackerTests.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; 3 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 07:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284#pullrequestreview-5467131184) · **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**: `9ffac5ec-b917-4ece-913a-66da77f57a6d` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 and 29d49db31ef2c42f2d8851c0e6bca22ec4581bd8. </details> <details> <summary>📒 Files selected for processing (11)</summary> * `CMakeLists.txt` * `src/common/bitArray.h` * `src/graphics/host_gpu/memoryTracker.cpp` * `src/graphics/host_gpu/memoryTracker.h` * `src/graphics/host_gpu/regionManager.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/kernel/memoryAddressSpace.inc` * `tests/MemoryTrackerTests.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; 3 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=30340c0d-aaf4-4719-9382-cb1fbb3f0418 attempt=fd5c1803-e8a9-4315-98d2-3b7bdb5ca250 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 07:29 UTC · original · edited 2026-10-09 07:46 UTC
On tests/MemoryTrackerTests.cpp line 1018 (outdated):

@@ -924,6 +932,110 @@ void TestDownloadDoesNotSerializeDisjointRegion() {
         "download callback serialized an unrelated tracker region");
 }
 
+void TestQueriesDoNotWaitForWriteFault() {
+  constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE;
+  TrackerHarness harness;
+  auto &tracker = harness.tracker;
+  auto *memory = Allocate(harness.page_manager, 4);
+  const auto base = reinterpret_cast<uint64_t>(memory);
+  // A clean page before the faulted one keeps the fault to its own page.
+  const auto faulted = base + page_size;
+  const auto queried = base + page_size * 3;
+  Check(faulted / Libs::Graphics::TRACKER_REGION_SIZE ==
+            (queried + page_size - 1) / Libs::Graphics::TRACKER_REGION_SIZE,
+        "query test pages do not share a tracker region");
+  tracker.ForEachUploadRange(
+      base, page_size * 4, false, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+
+  // A guest write fault holds the region while its pages change protection.
+  std::binary_semaphore fault_entered{0};
+  std::binary_semaphore finish_fault{0};
+  {
+    std::lock_guard lock(g_protection_log_mutex);
+    g_before_next_protection = [&] {
+      fault_entered.release();
+      finish_fault.acquire();
+    };
+  }
+  std::jthread fault([&] {
+    tracker.InvalidateRegion(faulted, 1, [] { Check(false, "clean page needed a flush"); });
+  });
+  fault_entered.acquire();
+  std::binary_semaphore queries_finished{0};
+  std::atomic_bool clean{false};
+  std::jthread queries([&] {
+    bool uploaded = false;
+    tracker.ForEachUploadRange(
+        queried, page_size, false,
+        [&](uint64_t, uint64_t) noexcept { uploaded = true; }, []() noexcept {});
+    clean.store(!tracker.IsRegionCpuModified(queried, page_size) &&
+                    !tracker.IsRegionGpuModified(queried, page_size) && !uploaded,
+                std::memory_order_relaxed);
+    queries_finished.release();
+  });
+  const bool completed_during_fault =
+      queries_finished.try_acquire_for(std::chrono::seconds(5));
+  finish_fault.release();
+  fault.join();
+  queries.join();
+
+  const bool fault_dirtied = tracker.IsRegionCpuModified(faulted, page_size) &&
+                             IsWritable(memory + page_size);
+  tracker.UntrackMemory(base, page_size * 4);
+  Release(memory);
+  Check(completed_during_fault && clean.load(std::memory_order_relaxed),
+        "dirty queries waited for a write fault in the same region");
+  Check(fault_dirtied, "write fault did not dirty its page");
+}
+
+void TestSequentialWritesFaultAhead() {
+  constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE;
+  constexpr uint64_t pages = 48;
+  constexpr uint64_t gpu_page = 40;
+  TrackerHarness harness;
+  auto &tracker = harness.tracker;
+  auto *memory = Allocate(harness.page_manager, pages);
+  const auto base = reinterpret_cast<uint64_t>(memory);
+  const auto page_address = [&](uint64_t page) { return base + page * page_size; };
+  const auto unexpected_flush = [] { Check(false, "CPU-clean page needed a flush"); };
+  tracker.ForEachUploadRange(
+      base, pages * page_size, false, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+  tracker.ForEachUploadRange(
+      page_address(gpu_page), page_size, true, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+
+  // A writer walks the pages up to the GPU-written one; only protected pages fault.
+  uint64_t faults = 0;
+  for (uint64_t page = 0; page < gpu_page; page++) {
+    if (!IsWritable(memory + page * page_size)) {
+      tracker.InvalidateRegion(page_address(page), 1, unexpected_flush);
+      faults++;
+    }
+  }
+  const bool all_dirty = tracker.IsRegionCpuModified(base, gpu_page * page_size) &&
+                         IsWritable(memory + (gpu_page - 1) * page_size);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Check every page after the simulated writes.

IsRegionCpuModified(base, gpu_page * page_size) returns true if only one page is dirty. If an ahead page becomes writable without a CPU-dirty bit, the loop skips its fault and this assertion can still pass. Check both the dirty bit and write permission for each page before accepting the result.

✅ Addressed in commit d23b24d

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 07:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284#discussion_r4227737899) · edited 2026-10-09 07:46 UTC On `tests/MemoryTrackerTests.cpp` line 1018 (outdated): ```diff @@ -924,6 +932,110 @@ void TestDownloadDoesNotSerializeDisjointRegion() { "download callback serialized an unrelated tracker region"); } +void TestQueriesDoNotWaitForWriteFault() { + constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE; + TrackerHarness harness; + auto &tracker = harness.tracker; + auto *memory = Allocate(harness.page_manager, 4); + const auto base = reinterpret_cast<uint64_t>(memory); + // A clean page before the faulted one keeps the fault to its own page. + const auto faulted = base + page_size; + const auto queried = base + page_size * 3; + Check(faulted / Libs::Graphics::TRACKER_REGION_SIZE == + (queried + page_size - 1) / Libs::Graphics::TRACKER_REGION_SIZE, + "query test pages do not share a tracker region"); + tracker.ForEachUploadRange( + base, page_size * 4, false, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + + // A guest write fault holds the region while its pages change protection. + std::binary_semaphore fault_entered{0}; + std::binary_semaphore finish_fault{0}; + { + std::lock_guard lock(g_protection_log_mutex); + g_before_next_protection = [&] { + fault_entered.release(); + finish_fault.acquire(); + }; + } + std::jthread fault([&] { + tracker.InvalidateRegion(faulted, 1, [] { Check(false, "clean page needed a flush"); }); + }); + fault_entered.acquire(); + std::binary_semaphore queries_finished{0}; + std::atomic_bool clean{false}; + std::jthread queries([&] { + bool uploaded = false; + tracker.ForEachUploadRange( + queried, page_size, false, + [&](uint64_t, uint64_t) noexcept { uploaded = true; }, []() noexcept {}); + clean.store(!tracker.IsRegionCpuModified(queried, page_size) && + !tracker.IsRegionGpuModified(queried, page_size) && !uploaded, + std::memory_order_relaxed); + queries_finished.release(); + }); + const bool completed_during_fault = + queries_finished.try_acquire_for(std::chrono::seconds(5)); + finish_fault.release(); + fault.join(); + queries.join(); + + const bool fault_dirtied = tracker.IsRegionCpuModified(faulted, page_size) && + IsWritable(memory + page_size); + tracker.UntrackMemory(base, page_size * 4); + Release(memory); + Check(completed_during_fault && clean.load(std::memory_order_relaxed), + "dirty queries waited for a write fault in the same region"); + Check(fault_dirtied, "write fault did not dirty its page"); +} + +void TestSequentialWritesFaultAhead() { + constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE; + constexpr uint64_t pages = 48; + constexpr uint64_t gpu_page = 40; + TrackerHarness harness; + auto &tracker = harness.tracker; + auto *memory = Allocate(harness.page_manager, pages); + const auto base = reinterpret_cast<uint64_t>(memory); + const auto page_address = [&](uint64_t page) { return base + page * page_size; }; + const auto unexpected_flush = [] { Check(false, "CPU-clean page needed a flush"); }; + tracker.ForEachUploadRange( + base, pages * page_size, false, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + tracker.ForEachUploadRange( + page_address(gpu_page), page_size, true, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + + // A writer walks the pages up to the GPU-written one; only protected pages fault. + uint64_t faults = 0; + for (uint64_t page = 0; page < gpu_page; page++) { + if (!IsWritable(memory + page * page_size)) { + tracker.InvalidateRegion(page_address(page), 1, unexpected_flush); + faults++; + } + } + const bool all_dirty = tracker.IsRegionCpuModified(base, gpu_page * page_size) && + IsWritable(memory + (gpu_page - 1) * page_size); ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Check every page after the simulated writes.** `IsRegionCpuModified(base, gpu_page * page_size)` returns true if only one page is dirty. If an ahead page becomes writable without a CPU-dirty bit, the loop skips its fault and this assertion can still pass. Check both the dirty bit and write permission for each page before accepting the result. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:06e9b60f3ecddc68afc5e598 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit d23b24d
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 07:46 UTC · original
On tests/MemoryTrackerTests.cpp line 1018 (outdated):

@@ -924,6 +932,110 @@ void TestDownloadDoesNotSerializeDisjointRegion() {
         "download callback serialized an unrelated tracker region");
 }
 
+void TestQueriesDoNotWaitForWriteFault() {
+  constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE;
+  TrackerHarness harness;
+  auto &tracker = harness.tracker;
+  auto *memory = Allocate(harness.page_manager, 4);
+  const auto base = reinterpret_cast<uint64_t>(memory);
+  // A clean page before the faulted one keeps the fault to its own page.
+  const auto faulted = base + page_size;
+  const auto queried = base + page_size * 3;
+  Check(faulted / Libs::Graphics::TRACKER_REGION_SIZE ==
+            (queried + page_size - 1) / Libs::Graphics::TRACKER_REGION_SIZE,
+        "query test pages do not share a tracker region");
+  tracker.ForEachUploadRange(
+      base, page_size * 4, false, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+
+  // A guest write fault holds the region while its pages change protection.
+  std::binary_semaphore fault_entered{0};
+  std::binary_semaphore finish_fault{0};
+  {
+    std::lock_guard lock(g_protection_log_mutex);
+    g_before_next_protection = [&] {
+      fault_entered.release();
+      finish_fault.acquire();
+    };
+  }
+  std::jthread fault([&] {
+    tracker.InvalidateRegion(faulted, 1, [] { Check(false, "clean page needed a flush"); });
+  });
+  fault_entered.acquire();
+  std::binary_semaphore queries_finished{0};
+  std::atomic_bool clean{false};
+  std::jthread queries([&] {
+    bool uploaded = false;
+    tracker.ForEachUploadRange(
+        queried, page_size, false,
+        [&](uint64_t, uint64_t) noexcept { uploaded = true; }, []() noexcept {});
+    clean.store(!tracker.IsRegionCpuModified(queried, page_size) &&
+                    !tracker.IsRegionGpuModified(queried, page_size) && !uploaded,
+                std::memory_order_relaxed);
+    queries_finished.release();
+  });
+  const bool completed_during_fault =
+      queries_finished.try_acquire_for(std::chrono::seconds(5));
+  finish_fault.release();
+  fault.join();
+  queries.join();
+
+  const bool fault_dirtied = tracker.IsRegionCpuModified(faulted, page_size) &&
+                             IsWritable(memory + page_size);
+  tracker.UntrackMemory(base, page_size * 4);
+  Release(memory);
+  Check(completed_during_fault && clean.load(std::memory_order_relaxed),
+        "dirty queries waited for a write fault in the same region");
+  Check(fault_dirtied, "write fault did not dirty its page");
+}
+
+void TestSequentialWritesFaultAhead() {
+  constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE;
+  constexpr uint64_t pages = 48;
+  constexpr uint64_t gpu_page = 40;
+  TrackerHarness harness;
+  auto &tracker = harness.tracker;
+  auto *memory = Allocate(harness.page_manager, pages);
+  const auto base = reinterpret_cast<uint64_t>(memory);
+  const auto page_address = [&](uint64_t page) { return base + page * page_size; };
+  const auto unexpected_flush = [] { Check(false, "CPU-clean page needed a flush"); };
+  tracker.ForEachUploadRange(
+      base, pages * page_size, false, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+  tracker.ForEachUploadRange(
+      page_address(gpu_page), page_size, true, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+
+  // A writer walks the pages up to the GPU-written one; only protected pages fault.
+  uint64_t faults = 0;
+  for (uint64_t page = 0; page < gpu_page; page++) {
+    if (!IsWritable(memory + page * page_size)) {
+      tracker.InvalidateRegion(page_address(page), 1, unexpected_flush);
+      faults++;
+    }
+  }
+  const bool all_dirty = tracker.IsRegionCpuModified(base, gpu_page * page_size) &&
+                         IsWritable(memory + (gpu_page - 1) * page_size);

Fixed in d23b24d7: the test now checks every page before the GPU-written one for both the CPU-dirty bit and write permission, instead of one range query plus the last page. It fails when a dirty page is left protected.

**@⁠NeySlim** on GitHub · 2026-10-09 07:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284#discussion_r4227861415) On `tests/MemoryTrackerTests.cpp` line 1018 (outdated): ```diff @@ -924,6 +932,110 @@ void TestDownloadDoesNotSerializeDisjointRegion() { "download callback serialized an unrelated tracker region"); } +void TestQueriesDoNotWaitForWriteFault() { + constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE; + TrackerHarness harness; + auto &tracker = harness.tracker; + auto *memory = Allocate(harness.page_manager, 4); + const auto base = reinterpret_cast<uint64_t>(memory); + // A clean page before the faulted one keeps the fault to its own page. + const auto faulted = base + page_size; + const auto queried = base + page_size * 3; + Check(faulted / Libs::Graphics::TRACKER_REGION_SIZE == + (queried + page_size - 1) / Libs::Graphics::TRACKER_REGION_SIZE, + "query test pages do not share a tracker region"); + tracker.ForEachUploadRange( + base, page_size * 4, false, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + + // A guest write fault holds the region while its pages change protection. + std::binary_semaphore fault_entered{0}; + std::binary_semaphore finish_fault{0}; + { + std::lock_guard lock(g_protection_log_mutex); + g_before_next_protection = [&] { + fault_entered.release(); + finish_fault.acquire(); + }; + } + std::jthread fault([&] { + tracker.InvalidateRegion(faulted, 1, [] { Check(false, "clean page needed a flush"); }); + }); + fault_entered.acquire(); + std::binary_semaphore queries_finished{0}; + std::atomic_bool clean{false}; + std::jthread queries([&] { + bool uploaded = false; + tracker.ForEachUploadRange( + queried, page_size, false, + [&](uint64_t, uint64_t) noexcept { uploaded = true; }, []() noexcept {}); + clean.store(!tracker.IsRegionCpuModified(queried, page_size) && + !tracker.IsRegionGpuModified(queried, page_size) && !uploaded, + std::memory_order_relaxed); + queries_finished.release(); + }); + const bool completed_during_fault = + queries_finished.try_acquire_for(std::chrono::seconds(5)); + finish_fault.release(); + fault.join(); + queries.join(); + + const bool fault_dirtied = tracker.IsRegionCpuModified(faulted, page_size) && + IsWritable(memory + page_size); + tracker.UntrackMemory(base, page_size * 4); + Release(memory); + Check(completed_during_fault && clean.load(std::memory_order_relaxed), + "dirty queries waited for a write fault in the same region"); + Check(fault_dirtied, "write fault did not dirty its page"); +} + +void TestSequentialWritesFaultAhead() { + constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE; + constexpr uint64_t pages = 48; + constexpr uint64_t gpu_page = 40; + TrackerHarness harness; + auto &tracker = harness.tracker; + auto *memory = Allocate(harness.page_manager, pages); + const auto base = reinterpret_cast<uint64_t>(memory); + const auto page_address = [&](uint64_t page) { return base + page * page_size; }; + const auto unexpected_flush = [] { Check(false, "CPU-clean page needed a flush"); }; + tracker.ForEachUploadRange( + base, pages * page_size, false, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + tracker.ForEachUploadRange( + page_address(gpu_page), page_size, true, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + + // A writer walks the pages up to the GPU-written one; only protected pages fault. + uint64_t faults = 0; + for (uint64_t page = 0; page < gpu_page; page++) { + if (!IsWritable(memory + page * page_size)) { + tracker.InvalidateRegion(page_address(page), 1, unexpected_flush); + faults++; + } + } + const bool all_dirty = tracker.IsRegionCpuModified(base, gpu_page * page_size) && + IsWritable(memory + (gpu_page - 1) * page_size); ``` Fixed in d23b24d7: the test now checks every page before the GPU-written one for both the CPU-dirty bit and write permission, instead of one range query plus the last page. It fails when a dirty page is left protected.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 07:46 UTC · original
On tests/MemoryTrackerTests.cpp line 1018 (outdated):

@@ -924,6 +932,110 @@ void TestDownloadDoesNotSerializeDisjointRegion() {
         "download callback serialized an unrelated tracker region");
 }
 
+void TestQueriesDoNotWaitForWriteFault() {
+  constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE;
+  TrackerHarness harness;
+  auto &tracker = harness.tracker;
+  auto *memory = Allocate(harness.page_manager, 4);
+  const auto base = reinterpret_cast<uint64_t>(memory);
+  // A clean page before the faulted one keeps the fault to its own page.
+  const auto faulted = base + page_size;
+  const auto queried = base + page_size * 3;
+  Check(faulted / Libs::Graphics::TRACKER_REGION_SIZE ==
+            (queried + page_size - 1) / Libs::Graphics::TRACKER_REGION_SIZE,
+        "query test pages do not share a tracker region");
+  tracker.ForEachUploadRange(
+      base, page_size * 4, false, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+
+  // A guest write fault holds the region while its pages change protection.
+  std::binary_semaphore fault_entered{0};
+  std::binary_semaphore finish_fault{0};
+  {
+    std::lock_guard lock(g_protection_log_mutex);
+    g_before_next_protection = [&] {
+      fault_entered.release();
+      finish_fault.acquire();
+    };
+  }
+  std::jthread fault([&] {
+    tracker.InvalidateRegion(faulted, 1, [] { Check(false, "clean page needed a flush"); });
+  });
+  fault_entered.acquire();
+  std::binary_semaphore queries_finished{0};
+  std::atomic_bool clean{false};
+  std::jthread queries([&] {
+    bool uploaded = false;
+    tracker.ForEachUploadRange(
+        queried, page_size, false,
+        [&](uint64_t, uint64_t) noexcept { uploaded = true; }, []() noexcept {});
+    clean.store(!tracker.IsRegionCpuModified(queried, page_size) &&
+                    !tracker.IsRegionGpuModified(queried, page_size) && !uploaded,
+                std::memory_order_relaxed);
+    queries_finished.release();
+  });
+  const bool completed_during_fault =
+      queries_finished.try_acquire_for(std::chrono::seconds(5));
+  finish_fault.release();
+  fault.join();
+  queries.join();
+
+  const bool fault_dirtied = tracker.IsRegionCpuModified(faulted, page_size) &&
+                             IsWritable(memory + page_size);
+  tracker.UntrackMemory(base, page_size * 4);
+  Release(memory);
+  Check(completed_during_fault && clean.load(std::memory_order_relaxed),
+        "dirty queries waited for a write fault in the same region");
+  Check(fault_dirtied, "write fault did not dirty its page");
+}
+
+void TestSequentialWritesFaultAhead() {
+  constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE;
+  constexpr uint64_t pages = 48;
+  constexpr uint64_t gpu_page = 40;
+  TrackerHarness harness;
+  auto &tracker = harness.tracker;
+  auto *memory = Allocate(harness.page_manager, pages);
+  const auto base = reinterpret_cast<uint64_t>(memory);
+  const auto page_address = [&](uint64_t page) { return base + page * page_size; };
+  const auto unexpected_flush = [] { Check(false, "CPU-clean page needed a flush"); };
+  tracker.ForEachUploadRange(
+      base, pages * page_size, false, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+  tracker.ForEachUploadRange(
+      page_address(gpu_page), page_size, true, [](uint64_t, uint64_t) noexcept {},
+      []() noexcept {});
+
+  // A writer walks the pages up to the GPU-written one; only protected pages fault.
+  uint64_t faults = 0;
+  for (uint64_t page = 0; page < gpu_page; page++) {
+    if (!IsWritable(memory + page * page_size)) {
+      tracker.InvalidateRegion(page_address(page), 1, unexpected_flush);
+      faults++;
+    }
+  }
+  const bool all_dirty = tracker.IsRegionCpuModified(base, gpu_page * page_size) &&
+                         IsWritable(memory + (gpu_page - 1) * page_size);

@NeySlim, thanks for the fix. The per-page checks in TestSequentialWritesFaultAhead address the finding. Each page must now have both its CPU-dirty bit set and write permission.


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 07:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284#discussion_r4227864117) On `tests/MemoryTrackerTests.cpp` line 1018 (outdated): ```diff @@ -924,6 +932,110 @@ void TestDownloadDoesNotSerializeDisjointRegion() { "download callback serialized an unrelated tracker region"); } +void TestQueriesDoNotWaitForWriteFault() { + constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE; + TrackerHarness harness; + auto &tracker = harness.tracker; + auto *memory = Allocate(harness.page_manager, 4); + const auto base = reinterpret_cast<uint64_t>(memory); + // A clean page before the faulted one keeps the fault to its own page. + const auto faulted = base + page_size; + const auto queried = base + page_size * 3; + Check(faulted / Libs::Graphics::TRACKER_REGION_SIZE == + (queried + page_size - 1) / Libs::Graphics::TRACKER_REGION_SIZE, + "query test pages do not share a tracker region"); + tracker.ForEachUploadRange( + base, page_size * 4, false, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + + // A guest write fault holds the region while its pages change protection. + std::binary_semaphore fault_entered{0}; + std::binary_semaphore finish_fault{0}; + { + std::lock_guard lock(g_protection_log_mutex); + g_before_next_protection = [&] { + fault_entered.release(); + finish_fault.acquire(); + }; + } + std::jthread fault([&] { + tracker.InvalidateRegion(faulted, 1, [] { Check(false, "clean page needed a flush"); }); + }); + fault_entered.acquire(); + std::binary_semaphore queries_finished{0}; + std::atomic_bool clean{false}; + std::jthread queries([&] { + bool uploaded = false; + tracker.ForEachUploadRange( + queried, page_size, false, + [&](uint64_t, uint64_t) noexcept { uploaded = true; }, []() noexcept {}); + clean.store(!tracker.IsRegionCpuModified(queried, page_size) && + !tracker.IsRegionGpuModified(queried, page_size) && !uploaded, + std::memory_order_relaxed); + queries_finished.release(); + }); + const bool completed_during_fault = + queries_finished.try_acquire_for(std::chrono::seconds(5)); + finish_fault.release(); + fault.join(); + queries.join(); + + const bool fault_dirtied = tracker.IsRegionCpuModified(faulted, page_size) && + IsWritable(memory + page_size); + tracker.UntrackMemory(base, page_size * 4); + Release(memory); + Check(completed_during_fault && clean.load(std::memory_order_relaxed), + "dirty queries waited for a write fault in the same region"); + Check(fault_dirtied, "write fault did not dirty its page"); +} + +void TestSequentialWritesFaultAhead() { + constexpr auto page_size = Libs::Graphics::TRACKER_PAGE_SIZE; + constexpr uint64_t pages = 48; + constexpr uint64_t gpu_page = 40; + TrackerHarness harness; + auto &tracker = harness.tracker; + auto *memory = Allocate(harness.page_manager, pages); + const auto base = reinterpret_cast<uint64_t>(memory); + const auto page_address = [&](uint64_t page) { return base + page * page_size; }; + const auto unexpected_flush = [] { Check(false, "CPU-clean page needed a flush"); }; + tracker.ForEachUploadRange( + base, pages * page_size, false, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + tracker.ForEachUploadRange( + page_address(gpu_page), page_size, true, [](uint64_t, uint64_t) noexcept {}, + []() noexcept {}); + + // A writer walks the pages up to the GPU-written one; only protected pages fault. + uint64_t faults = 0; + for (uint64_t page = 0; page < gpu_page; page++) { + if (!IsWritable(memory + page * page_size)) { + tracker.InvalidateRegion(page_address(page), 1, unexpected_flush); + faults++; + } + } + const bool all_dirty = tracker.IsRegionCpuModified(base, gpu_page * page_size) && + IsWritable(memory + (gpu_page - 1) * page_size); ``` `@NeySlim`, thanks for the fix. The per-page checks in `TestSequentialWritesFaultAhead` address the finding. Each page must now have both its CPU-dirty bit set and write permission. --- <!-- 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%20subtle%20test%20gap%3A%20one%20range%20check%20can%20miss%20writable%2C%20non-dirty%20pages.%20Verify%20every%20page%E2%80%99s%20dirty%20bit%20and%20write%20permission%20after%20simulated%20writes.%20Try%20it!%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1284%23discussion_r4227737899)? 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

@⁠NeySlim on GitHub · 2026-10-09 09:43 UTC · original

Updated after an internal review:

  • Dropped the commit that dirtied pages ahead of sequential writers. Its run detection counted any CPU-dirty page (new regions start fully dirty), its limits were tuned on one game, and the pages it dirtied were not logged for the incremental BDA sweep of #1286. The PR now has the first three commits; the description keeps only the numbers measured for them (sled: -6.6 ± 2.8 ms per frame).
  • Debug builds now check that uploads, downloads and GPU-dirty clears never overlap, which the lock-free dirty reads rely on (death case overlapping-gpu-dirty-owners). TestConcurrentColdUploads runs its uploads one after the other and still checks that a cold writable upload does not block region creation on another thread.
  • Fixed the ProtectTransient comment: the guarantee comes from the PageManager region lock.
**@⁠NeySlim** on GitHub · 2026-10-09 09:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1284#issuecomment-6078427191) Updated after an internal review: - Dropped the commit that dirtied pages ahead of sequential writers. Its run detection counted any CPU-dirty page (new regions start fully dirty), its limits were tuned on one game, and the pages it dirtied were not logged for the incremental BDA sweep of #1286. The PR now has the first three commits; the description keeps only the numbers measured for them (sled: -6.6 ± 2.8 ms per frame). - Debug builds now check that uploads, downloads and GPU-dirty clears never overlap, which the lock-free dirty reads rely on (death case `overlapping-gpu-dirty-owners`). `TestConcurrentColdUploads` runs its uploads one after the other and still checks that a cold writable upload does not block region creation on another thread. - Fixed the `ProtectTransient` comment: the guarantee comes from the `PageManager` region lock.
This pull request has changes conflicting with the target branch.
  • src/common/bitArray.h
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/regionManager.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/kernel/memoryAddressSpace.inc
  • tests/VirtualMemoryAllocationTests.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/1284/head:github-bot/gh-1284'
git switch 'github-bot/gh-1284'

Merge

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