memory: retry guest accesses while a mapping is briefly replaced (GTA V HDD Streamer crash) #2395

Open
github-bot wants to merge 4 commits from github-bot/gh-2395 into main AGit
Owner

@⁠oguzhanozfe on GitHub · 2026-11-18 22:35 UTC · original
oguzhanozfe:fix/gta5-hdd-streamer-map-fixed-retry → main · +305 −0 · 5 files · 4 commits · open

Summary

Fixes an intermittent crash in Grand Theft Auto V (PPSA04263): roughly once every 100 sessions, the [RAGE] HDD Streamer thread dies with an unhandled access violation inside zlib inflate_fast/inflate. The fault is on a 64 KiB direct-memory page that is mapped again a moment later.

This is a port of TheCruZ's closed #1229 onto current main.

Problem

Two game threads MAP_FIXED the same physical page at the same address. On the console that is an atomic no-op, and the streamer is already decompressing into the page. The emulator replaces a mapping by unmapping it and mapping it again (ReplaceFixedRangeWithReserved), so for that moment the page is gone and the streamer faults.

Windows has the same gap when a partial unmap splits a file view. UnmapOne unmaps the whole view, then maps the survivors again.

Change

  • A small lock-free table of transient-unmap windows (TransientUnmapWindows). A window is open while a MAP_FIXED replacement (flexible and direct maps) is in progress, and while a view split's survivors are remapped. The unmapped part of a split is never published.
  • The runtime linker's fault handler waits until the range is mapped again and retries the access, after the GPU fault tracking has had its chance.
  • A page that keeps faulting once its range is back (16 retries) is still reported. Real access violations are not hidden.

Differences from #1229:

  • main already restores the survivors' protections in UnmapOne.
  • main already keeps Linux direct-over-direct replacements atomic.

So only the retry windows are taken over, wrapped around main's current code. #1229's protection snapshot code and its duplicate Windows permission test are dropped; PartialUnmapPreservesHostPermissions already covers that.

Testing

Windows 11, Ryzen 9 5950X, RTX 3090, clang-cl (LLVM 23), Release.

  • virtual_memory_allocation_tests → new AccessDuringMappingReplacement. A worker thread keeps reading and writing a flexible mapping and a direct mapping, while the main thread:
    • splits the flexible mapping's view 63 times
    • re-maps the direct page with MAP_FIXED 256 times
  • Results:
    • without the change: the process dies with 0xC0000005 (access violation)
    • with the change: ok (4577303 accesses, 305 retried)
  • page_manager_tests and memory_tracker_tests pass.
  • In-game: the crash is rare (about 1 in 100 sessions), so the test above is the deterministic reproduction. TheCruZ played GTA V with the original change in his fork (#1229).

AI usage

AI (Claude Opus 5.5) was used to:

  • port the change onto main and resolve its conflicts
  • run the tests above
  • draft this description

The analysis and the original fix are TheCruZ's (#1229), credited with Co-authored-by.

🤖 Generated with Claude Code

**@⁠oguzhanozfe** on GitHub · 2026-11-18 22:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395) `oguzhanozfe:fix/gta5-hdd-streamer-map-fixed-retry` → `main` · +305 −0 · 5 files · 4 commits · open ## Summary Fixes an intermittent crash in **Grand Theft Auto V** (PPSA04263): roughly once every 100 sessions, the `[RAGE] HDD Streamer` thread dies with an unhandled access violation inside zlib `inflate_fast`/`inflate`. The fault is on a 64 KiB direct-memory page that is mapped again a moment later. This is a port of TheCruZ's closed #1229 onto current `main`. ## Problem Two game threads `MAP_FIXED` the same physical page at the same address. On the console that is an atomic no-op, and the streamer is already decompressing into the page. The emulator replaces a mapping by unmapping it and mapping it again (`ReplaceFixedRangeWithReserved`), so for that moment the page is gone and the streamer faults. Windows has the same gap when a partial unmap splits a file view. `UnmapOne` unmaps the whole view, then maps the survivors again. ## Change - A small lock-free table of transient-unmap windows (`TransientUnmapWindows`). A window is open while a `MAP_FIXED` replacement (flexible and direct maps) is in progress, and while a view split's **survivors** are remapped. The unmapped part of a split is never published. - The runtime linker's fault handler waits until the range is mapped again and retries the access, after the GPU fault tracking has had its chance. - A page that keeps faulting once its range is back (16 retries) is still reported. Real access violations are not hidden. **Differences from #1229:** - `main` already restores the survivors' protections in `UnmapOne`. - `main` already keeps Linux direct-over-direct replacements atomic. So only the retry windows are taken over, wrapped around `main`'s current code. #1229's protection snapshot code and its duplicate Windows permission test are dropped; `PartialUnmapPreservesHostPermissions` already covers that. ## Testing Windows 11, Ryzen 9 5950X, RTX 3090, clang-cl (LLVM 23), Release. - `virtual_memory_allocation_tests` → new `AccessDuringMappingReplacement`. A worker thread keeps reading and writing a flexible mapping and a direct mapping, while the main thread: - splits the flexible mapping's view 63 times - re-maps the direct page with `MAP_FIXED` 256 times - Results: - without the change: the process dies with `0xC0000005` (access violation) - with the change: `ok (4577303 accesses, 305 retried)` - `page_manager_tests` and `memory_tracker_tests` pass. - **In-game:** the crash is rare (about 1 in 100 sessions), so the test above is the deterministic reproduction. TheCruZ played GTA V with the original change in his fork (#1229). ## AI usage AI (Claude Opus 5.5) was used to: - port the change onto `main` and resolve its conflicts - run the tests above - draft this description The analysis and the original fix are TheCruZ's (#1229), credited with `Co-authored-by`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Grand Theft Auto V (PPSA04263) crashes about once every 100 sessions:
its "[RAGE] HDD Streamer" thread faults inside zlib inflate on a 64 KiB
direct-memory page that is mapped again a moment later. Two game
threads MAP_FIXED the same physical page at the same address; on the
console that is an atomic no-op, but the emulator replaces a mapping by
unmapping it and mapping it again (ReplaceFixedRangeWithReserved), so
the streamer's access lands in the gap. Windows has the same gap when
a partial unmap splits a file view: UnmapOne unmaps the whole view and
maps the survivors again.

Publish both gaps in a small lock-free table of transient-unmap
windows. The runtime linker's fault handler waits until the range is
mapped again and retries the access (after the GPU tracking had its
chance). A page that keeps faulting once its range is back is still
reported, so real access violations are not hidden. Only the survivors
of a view split are published, not the unmapped part.

Ported from TheCruZ's closed #1229 onto current main: main already
restores the survivors' protections in UnmapOne and keeps Linux
direct-over-direct replacements atomic, so only the retry windows are
taken over.

Co-authored-by: TheCruZ <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2395:
- Open() picked s_windows[n % 16] without checking whether a Scope still
  held that entry, so enough concurrent replacements could overwrite an
  open range (and its Scope then closed the reused entry). Entries are
  now claimed atomically and only released by their Scope; when all 64
  are open, Open yields until one frees (scopes span a single remap).
- Run GPU fault tracking before waiting for a transient unmap, so a
  fault tracking can resolve does not wait for an unrelated remap.
- AccessDuringMappingReplacement starts replacing only once the worker
  has accessed both mappings, and checks that it made accesses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2395: Wait read closed_ns a second time after the
spin loop. If the entry was reused for another range in between, that
read could return 0, the age check failed, and a fault on a mapping
that was already back was reported as fatal.

Wait now snapshots the entry's id with its range (rejecting a torn
read), keeps the closure time it observed, and treats a reused entry as
just closed, since reuse requires the original Scope to have closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2395: Wait skipped an entry whose id changed while
it read the range, so a window that reopened for a range holding the
fault address could be missed and the fault reported as fatal.

Open now publishes an entry as a seqlock: id 0 while the range is
written, then the new id. Wait re-reads the entry until its id and
range belong to one opening (spinning briefly while an owned entry is
being opened), so it never skips a reopened window and never pairs one
opening's id with another's range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:19:34 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 22:44 UTC · original · edited 2026-11-18 23:31 UTC

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change tracks guest-memory ranges during fixed mapping replacements and Windows view splits. The exception handler waits for matching transient-unmap windows and retries eligible access violations, with a per-page and per-window retry limit. A Windows-only test exercises concurrent access during flexible and direct mapping replacement and checks for mismatches.

Suggested reviewers: nmzik

Change: Bug fix

Merge Risk: Moderate · up to 165cf

This change retries guest memory accesses that land in a brief mapping gap. A rare interleaving of slot reuse may still end in a fatal fault report, and the regression test does not guarantee that it exercises the retry path. Resolve or explicitly accept these before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: guest memory accesses are retried while a mapping is briefly replaced. It also names the GTA V HDD Streamer crash it fixes. The changeset adds transient-unmap windows,…
Description check Passed The description states the crash being fixed, the cause (a transient unmap during MAP_FIXED replacement and Windows view splits), the change itself (TransientUnmapWindows, runtime linker retry, 16-ret…
Linked Issues check Passed The only linked issue, #1229, is closed and marked as historical context only. Its acceptance criteria do not apply to this pull request. No active directly linked target remains, so no linked-issue c…
Out of Scope Changes check Passed All changed files support the transient-unmap objective in the current PR description. src/kernel/memory.cpp and src/kernel/memory.h add WaitForTransientUnmap and RetryTransientUnmapFault, which imple…
Full details: Title check

Explanation

The title names the main change: guest memory accesses are retried while a mapping is briefly replaced. It also names the GTA V HDD Streamer crash it fixes. The changeset adds transient-unmap windows, a runtime linker fault retry path, and a test for mapping replacement, which matches the title.

Full details: Description check

Explanation

The description states the crash being fixed, the cause (a transient unmap during MAP_FIXED replacement and Windows view splits), the change itself (TransientUnmapWindows, runtime linker retry, 16-retry limit), the differences from #1229, and the test results. It matches the changeset closely.

Full details: Linked Issues check

Explanation

The only linked issue, #1229, is closed and marked as historical context only. Its acceptance criteria do not apply to this pull request. No active directly linked target remains, so no linked-issue coding requirements apply. The current PR description states that this pull request ports #1229 onto main. That port is not a coding requirement for this assessment. The changes since the previous review (commits bbd7a79f, 5013e95b, and 165cf609) concern only the window-generation and publication handling in the transient-unmap registry. They do not change the requirement status.

Full details: Out of Scope Changes check

Explanation

All changed files support the transient-unmap objective in the current PR description. src/kernel/memory.cpp and src/kernel/memory.h add WaitForTransientUnmap and RetryTransientUnmapFault, which implement the wait and the bounded retry limit with bounded logging. src/kernel/memoryAddressSpace.inc adds the TransientUnmapWindow and TransientUnmapWindows registry. It opens windows for fixed flexible and direct replacements and for non-empty survivor ranges in the Windows UnmapOne path. src/loader/runtimeLinker.cpp retries eligible faults after GPU fault handling. tests/VirtualMemoryAllocationTests.cpp adds AccessDuringMappingReplacement, which covers this behavior. The PR description states that #1229's protection-snapshot code and duplicate permission test were dropped. The whole-PR summary shows no such code. The later window-reuse and seqlock-style publication changes apply to the same registry, so they remain within scope. This result relies on the whole-PR summary and the commit message in the PR objectives. I did not read the changed code paths directly, so no unrelated change is confirmed absent from the diff itself.

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 5013e95b45 and 165cf6095e.

Files selected for processing: 1

  • src/kernel/memoryAddressSpace.inc

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 22:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#issuecomment-6993834196) · edited 2026-11-18 23:31 UTC <!-- coderabbit-ai-generated:v1 --> <!-- 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/2395?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-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- recent_review_status_start --> No actionable comments were generated in the recent review. <!-- recent_review_status_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The change tracks guest-memory ranges during fixed mapping replacements and Windows view splits. The exception handler waits for matching transient-unmap windows and retries eligible access violations, with a per-page and per-window retry limit. A Windows-only test exercises concurrent access during flexible and direct mapping replacement and checks for mismatches. <!-- <fixed_issue_severity>Medium</fixed_issue_severity> --> **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"165cf6095e0ceeb850e927305afdaebc80f945f9" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · up to <code>165cf</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `165cf` --> <!-- final_review_risk_coverage:{"sourceCommitId":"165cf6095e0ceeb850e927305afdaebc80f945f9","coveredCommitId":"165cf6095e0ceeb850e927305afdaebc80f945f9","kind":"reviewed"} --> This change retries guest memory accesses that land in a brief mapping gap. A rare interleaving of slot reuse may still end in a fatal fault report, and the regression test does not guarantee that it exercises the retry path. Resolve or explicitly accept these before merging. <!-- 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</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title names the main change: guest memory accesses are retried while a mapping is briefly replaced. It also names the GTA V HDD Streamer crash it fixes. The changeset adds transient-unmap windows,… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description states the crash being fixed, the cause (a transient unmap during MAP_FIXED replacement and Windows view splits), the change itself (TransientUnmapWindows, runtime linker retry, 16-ret… | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The only linked issue, `#1229`, is closed and marked as historical context only. Its acceptance criteria do not apply to this pull request. No active directly linked target remains, so no linked-issue c… | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | All changed files support the transient-unmap objective in the current PR description. src/kernel/memory.cpp and src/kernel/memory.h add WaitForTransientUnmap and RetryTransientUnmapFault, which imple… | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **Explanation** The title names the main change: guest memory accesses are retried while a mapping is briefly replaced. It also names the GTA V HDD Streamer crash it fixes. The changeset adds transient-unmap windows, a runtime linker fault retry path, and a test for mapping replacement, which matches the title. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **Explanation** The description states the crash being fixed, the cause (a transient unmap during MAP_FIXED replacement and Windows view splits), the change itself (TransientUnmapWindows, runtime linker retry, 16-retry limit), the differences from `#1229`, and the test results. It matches the changeset closely. </dd> </dl> </details> <details> <summary><strong>Full details: Linked Issues check</strong></summary> <dl> <dd> <br> **Explanation** The only linked issue, `#1229`, is closed and marked as historical context only. Its acceptance criteria do not apply to this pull request. No active directly linked target remains, so no linked-issue coding requirements apply. The current PR description states that this pull request ports `#1229` onto main. That port is not a coding requirement for this assessment. The changes since the previous review (commits bbd7a79f, 5013e95b, and 165cf609) concern only the window-generation and publication handling in the transient-unmap registry. They do not change the requirement status. </dd> </dl> </details> <details> <summary><strong>Full details: Out of Scope Changes check</strong></summary> <dl> <dd> <br> **Explanation** All changed files support the transient-unmap objective in the current PR description. src/kernel/memory.cpp and src/kernel/memory.h add WaitForTransientUnmap and RetryTransientUnmapFault, which implement the wait and the bounded retry limit with bounded logging. src/kernel/memoryAddressSpace.inc adds the TransientUnmapWindow and TransientUnmapWindows registry. It opens windows for fixed flexible and direct replacements and for non-empty survivor ranges in the Windows UnmapOne path. src/loader/runtimeLinker.cpp retries eligible faults after GPU fault handling. tests/VirtualMemoryAllocationTests.cpp adds AccessDuringMappingReplacement, which covers this behavior. The PR description states that `#1229`'s protection-snapshot code and duplicate permission test were dropped. The whole-PR summary shows no such code. The later window-reuse and seqlock-style publication changes apply to the same registry, so they remain within scope. This result relies on the whole-PR summary and the commit message in the PR objectives. I did not read the changed code paths directly, so no unrelated change is confirmed absent from the diff itself. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2395)! 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> <br> - [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> <!-- tips_end --> <!-- recent_review_start --> <h6> <details> <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Recent review info</strong></summary> <dl> <dd> <br> <!-- review_info_content --> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</strong></summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a90be8dd7304640cf4176a975871d51443710292/.coderabbit.yaml>) - **Commit**: [a90be8d](<https://github.com/KytyPS5/KytyPS5/commit/a90be8dd7304640cf4176a975871d51443710292>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `6abe2486-eb91-4d62-aceb-cf5955c5787d` </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</strong></summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 5013e95b4569db5fcec40344d1d120c996b4cc63 and 165cf6095e0ceeb850e927305afdaebc80f945f9. </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 1</strong></summary> <dl> <dd> <br> * `src/kernel/memoryAddressSpace.inc` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review. </dd> </dl> </details> </h6> <!-- recent_review_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 22:44 UTC · original · edited 2026-11-18 23:27 UTC
On src/kernel/memoryAddressSpace.inc line 89 (outdated):

@@ -25,6 +25,87 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with
+// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a
+// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping
+// all of it). On the console these replacements are atomic, so guest threads keep using the
+// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or
+// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried
+// instead of being reported as an access violation.
+struct TransientUnmapWindow {
+	std::atomic<uint64_t> id {0};
+	std::atomic<uint64_t> start {0};
+	std::atomic<uint64_t> end {0};
+	std::atomic<int64_t>  closed_ns {0}; // 0 while the range is being remapped
+};
+
+class TransientUnmapWindows {
+public:
+	using Window = TransientUnmapWindow;
+
+	class Scope {
+	public:
+		Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {}
+		~Scope() { m_window->closed_ns.store(Now(), std::memory_order_release); }
+		KYTY_CLASS_NO_COPY(Scope);
+
+	private:
+		Window* m_window;
+	};
+
+	// The newest range being remapped recently that holds vaddr (0: none). Waits while it still
+	// is being remapped.
+	static uint64_t Wait(uint64_t vaddr) noexcept {
+		constexpr int64_t Second  = 1000000000;
+		uint64_t          matched = 0;
+		for (auto& window: s_windows) {
+			if (vaddr < window.start.load(std::memory_order_acquire) ||
+			    vaddr >= window.end.load(std::memory_order_acquire)) {
+				continue;
+			}
+			const auto begin = Now();
+			for (uint32_t spins = 0; window.closed_ns.load(std::memory_order_acquire) == 0; spins++) {
+				if (Now() - begin > Second * 10) {
+					return 0; // never closed: report the fault
+				}
+				if (spins < 4096) {
+#if defined(_M_X64) || defined(__x86_64__)
+					_mm_pause();
+#endif
+				} else {
+					std::this_thread::yield();
+				}
+			}
+			// The fault may be handled after the mapping is already back.
+			if (Now() - window.closed_ns.load(std::memory_order_acquire) < Second) {
+				matched = std::max(matched, window.id.load(std::memory_order_acquire));
+			}
+		}
+		return matched;
+	}
+
+private:
+	static Window* Open(uint64_t start, uint64_t end) noexcept {
+		auto& window = s_windows[s_next.fetch_add(1, std::memory_order_relaxed) % s_windows.size()];

Major · Stability & Availability · Quick win

Keep an open replacement window from being overwritten on Windows.

On Windows, one MAP_FIXED replacement of a fragmented flexible mapping can open 16 or more windows. MapFlexibleMemory opens the outer replacing window first. Each fragment removal in UnmapOne that leaves a right survivor opens another window. The sixteenth survivor wraps to the outer window's slot, because Open selects s_windows[... % 16] and does not check whether the entry is open. The outer entry's range is then lost while its scope is still open.

Page 0 is unmapped until the new mapping is published. No remaining entry covers it, so Wait returns 0 and a guest access to that page is reported as a fault. The outer Scope destructor also writes closed_ns through its stored pointer, which closes the reused entry.

Open must not overwrite an entry that an open Scope still owns. Reuse only entries whose closed_ns is nonzero, and claim each entry atomically. Define the required behavior when every entry is open; the current code does not define it. Add a regression test that replaces a fragmented mapping with more than 16 survivor windows while a guest access is in progress.

✅ Addressed in commit 165cf60

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 22:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4621888855) · edited 2026-11-18 23:27 UTC On `src/kernel/memoryAddressSpace.inc` line 89 (outdated): ```diff @@ -25,6 +25,87 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with +// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a +// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping +// all of it). On the console these replacements are atomic, so guest threads keep using the +// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or +// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried +// instead of being reported as an access violation. +struct TransientUnmapWindow { + std::atomic<uint64_t> id {0}; + std::atomic<uint64_t> start {0}; + std::atomic<uint64_t> end {0}; + std::atomic<int64_t> closed_ns {0}; // 0 while the range is being remapped +}; + +class TransientUnmapWindows { +public: + using Window = TransientUnmapWindow; + + class Scope { + public: + Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {} + ~Scope() { m_window->closed_ns.store(Now(), std::memory_order_release); } + KYTY_CLASS_NO_COPY(Scope); + + private: + Window* m_window; + }; + + // The newest range being remapped recently that holds vaddr (0: none). Waits while it still + // is being remapped. + static uint64_t Wait(uint64_t vaddr) noexcept { + constexpr int64_t Second = 1000000000; + uint64_t matched = 0; + for (auto& window: s_windows) { + if (vaddr < window.start.load(std::memory_order_acquire) || + vaddr >= window.end.load(std::memory_order_acquire)) { + continue; + } + const auto begin = Now(); + for (uint32_t spins = 0; window.closed_ns.load(std::memory_order_acquire) == 0; spins++) { + if (Now() - begin > Second * 10) { + return 0; // never closed: report the fault + } + if (spins < 4096) { +#if defined(_M_X64) || defined(__x86_64__) + _mm_pause(); +#endif + } else { + std::this_thread::yield(); + } + } + // The fault may be handled after the mapping is already back. + if (Now() - window.closed_ns.load(std::memory_order_acquire) < Second) { + matched = std::max(matched, window.id.load(std::memory_order_acquire)); + } + } + return matched; + } + +private: + static Window* Open(uint64_t start, uint64_t end) noexcept { + auto& window = s_windows[s_next.fetch_add(1, std::memory_order_relaxed) % s_windows.size()]; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Keep an open replacement window from being overwritten on Windows.** On Windows, one `MAP_FIXED` replacement of a fragmented flexible mapping can open 16 or more windows. `MapFlexibleMemory` opens the outer `replacing` window first. Each fragment removal in `UnmapOne` that leaves a right survivor opens another window. The sixteenth survivor wraps to the outer window's slot, because `Open` selects `s_windows[... % 16]` and does not check whether the entry is open. The outer entry's range is then lost while its scope is still open. Page 0 is unmapped until the new mapping is published. No remaining entry covers it, so `Wait` returns 0 and a guest access to that page is reported as a fault. The outer `Scope` destructor also writes `closed_ns` through its stored pointer, which closes the reused entry. `Open` must not overwrite an entry that an open `Scope` still owns. Reuse only entries whose `closed_ns` is nonzero, and claim each entry atomically. Define the required behavior when every entry is open; the current code does not define it. Add a regression test that replaces a fragmented mapping with more than 16 survivor windows while a guest access is in progress. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7fbe032f081dd8e407ac1176 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 165cf60 <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 22:44 UTC · original · edited 2026-11-18 23:01 UTC
On src/loader/runtimeLinker.cpp line 638 (outdated):

@@ -632,6 +632,10 @@ static bool KytyExceptionHandler(const Common::HostException::ExceptionInfo& exc
 	}
 
 	if (info->type == Common::HostException::ExceptionType::AccessViolation) {
+		// A guest range briefly unmapped while the emulator replaced its mapping: wait until it
+		// is mapped again, then retry the access unless the GPU tracking resolves the fault.
+		const auto transient =
+		    Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr);

Minor · Stability & Availability · Quick win

Run GPU fault tracking before the transient-unmap wait.

The wait at line 638 blocks until the mapping replacement closes, up to ten seconds. It runs before HandleGpuFault. A fault that GPU tracking can resolve therefore waits for the replacement, even though tracking could handle it at once. Move the wait to the point where the retry decision needs its result.

Suggested fix

--- "a/src/loader/runtimeLinker.cpp"
+++ "b/src/loader/runtimeLinker.cpp"
@@ -634,30 +634,30 @@
 	if (info->type == Common::HostException::ExceptionType::AccessViolation) {
 		// A guest range briefly unmapped while the emulator replaced its mapping: wait until it
 		// is mapped again, then retry the access unless the GPU tracking resolves the fault.
-		const auto transient =
-		    Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr);
 		using CoreAccess = Common::HostException::AccessViolationType;
 		using GpuAccess  = Libs::Graphics::PageFaultAccess;
 		GpuAccess access;
 		switch (info->access_violation_type) {
 			case CoreAccess::Read: access = GpuAccess::Read; break;
 			case CoreAccess::Write: access = GpuAccess::Write; break;
 			case CoreAccess::Execute: access = GpuAccess::Execute; break;
 			case CoreAccess::Unknown: return false;
 		}
 		if (Libs::LibKernel::Memory::HandleGpuFault(access, info->access_violation_vaddr)) {
 			Common::DebugCounters::Add(Common::DebugCounters::Counter::GpuFaults);
 			return true;
 		}
 		if (const auto length =
 		        Libs::Graphics::ShaderRecompiler::IR::SrtWalkerLoadLength(info->exception_address)) {
 			Loader::X64InstructionEmulator::SkipLoad(info->native_context, length);
 			return true;
 		}
+		const auto transient =
+		    Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr);
 		if (transient != 0 && Libs::LibKernel::Memory::RetryTransientUnmapFault(
 		                          info->access_violation_vaddr, transient)) {
 			return true;
 		}
 	}
 	// Report whatever guest context can be read safely before terminating: which guest thread
 	// faulted, the register file, the faulting code bytes and the top of its stack.

✅ Addressed in commit bbd7a79

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 22:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4621888865) · edited 2026-11-18 23:01 UTC On `src/loader/runtimeLinker.cpp` line 638 (outdated): ```diff @@ -632,6 +632,10 @@ static bool KytyExceptionHandler(const Common::HostException::ExceptionInfo& exc } if (info->type == Common::HostException::ExceptionType::AccessViolation) { + // A guest range briefly unmapped while the emulator replaced its mapping: wait until it + // is mapped again, then retry the access unless the GPU tracking resolves the fault. + const auto transient = + Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Run GPU fault tracking before the transient-unmap wait.** The wait at line 638 blocks until the mapping replacement closes, up to ten seconds. It runs before `HandleGpuFault`. A fault that GPU tracking can resolve therefore waits for the replacement, even though tracking could handle it at once. Move the wait to the point where the retry decision needs its result. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff --- "a/src/loader/runtimeLinker.cpp" +++ "b/src/loader/runtimeLinker.cpp" @@ -634,30 +634,30 @@ if (info->type == Common::HostException::ExceptionType::AccessViolation) { // A guest range briefly unmapped while the emulator replaced its mapping: wait until it // is mapped again, then retry the access unless the GPU tracking resolves the fault. - const auto transient = - Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr); using CoreAccess = Common::HostException::AccessViolationType; using GpuAccess = Libs::Graphics::PageFaultAccess; GpuAccess access; switch (info->access_violation_type) { case CoreAccess::Read: access = GpuAccess::Read; break; case CoreAccess::Write: access = GpuAccess::Write; break; case CoreAccess::Execute: access = GpuAccess::Execute; break; case CoreAccess::Unknown: return false; } if (Libs::LibKernel::Memory::HandleGpuFault(access, info->access_violation_vaddr)) { Common::DebugCounters::Add(Common::DebugCounters::Counter::GpuFaults); return true; } if (const auto length = Libs::Graphics::ShaderRecompiler::IR::SrtWalkerLoadLength(info->exception_address)) { Loader::X64InstructionEmulator::SkipLoad(info->native_context, length); return true; } + const auto transient = + Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr); if (transient != 0 && Libs::LibKernel::Memory::RetryTransientUnmapFault( info->access_violation_vaddr, transient)) { return true; } } // Report whatever guest context can be read safely before terminating: which guest thread // faulted, the register file, the faulting code bytes and the top of its stack. ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8e3880a2d2c9c10d46da3cc5 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit bbd7a79
@ -2477,0 +2522,4 @@
std::atomic<bool> started {false};
std::atomic<uint64_t> mismatches {0};
std::atomic<uint64_t> accesses {0};
std::thread worker([&] {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 22:44 UTC · original · edited 2026-11-18 23:00 UTC

Minor · Functional Correctness · Quick win

Synchronize the worker before starting replacement operations.

If the worker first runs after stop = true, it performs no accesses. mismatches remains zero, so this test reports success without exercising concurrent access.

Add a worker-start handshake before the replacement loops. Use a controlled mapping gap to ensure at least one access reaches the retry path. Assert that the controlled recovery occurred; an unsynchronized retry-count assertion alone would make the test flaky.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 22:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4621888875) · edited 2026-11-18 23:00 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Synchronize the worker before starting replacement operations.** If the worker first runs after `stop = true`, it performs no accesses. `mismatches` remains zero, so this test reports success without exercising concurrent access. Add a worker-start handshake before the replacement loops. Use a controlled mapping gap to ensure at least one access reaches the retry path. Assert that the controlled recovery occurred; an unsynchronized retry-count assertion alone would make the test flaky. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:49c12764bf2d34b4a65ab08a --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 22:44 UTC · original · reviewed

Actionable comments posted: 3

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a90be8dd73 and 7450c00a5b.

Files selected for processing: 5

  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/loader/runtimeLinker.cpp
  • tests/VirtualMemoryAllocationTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 22:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#pullrequestreview-5966399279) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 3** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a90be8dd7304640cf4176a975871d51443710292/.coderabbit.yaml>) - **Commit**: [a90be8d](<https://github.com/KytyPS5/KytyPS5/commit/a90be8dd7304640cf4176a975871d51443710292>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `da1eec47-ea44-4110-b9c2-fb164110ea63` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between a90be8dd7304640cf4176a975871d51443710292 and 7450c00a5b8bb1cde37d05dec5c1190215cbf6ab. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 5</summary> <dl> <dd> <br> * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/loader/runtimeLinker.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=a8a559bc-f6a7-454b-b38a-fff9a5897e85 attempt=f132e588-300a-4d0d-a331-cb58cf01dd78 batch=1/1 -->
Author
Owner

@⁠oguzhanozfe on GitHub · 2026-11-18 22:50 UTC · original
On src/kernel/memoryAddressSpace.inc line 89 (outdated):

@@ -25,6 +25,87 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with
+// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a
+// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping
+// all of it). On the console these replacements are atomic, so guest threads keep using the
+// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or
+// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried
+// instead of being reported as an access violation.
+struct TransientUnmapWindow {
+	std::atomic<uint64_t> id {0};
+	std::atomic<uint64_t> start {0};
+	std::atomic<uint64_t> end {0};
+	std::atomic<int64_t>  closed_ns {0}; // 0 while the range is being remapped
+};
+
+class TransientUnmapWindows {
+public:
+	using Window = TransientUnmapWindow;
+
+	class Scope {
+	public:
+		Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {}
+		~Scope() { m_window->closed_ns.store(Now(), std::memory_order_release); }
+		KYTY_CLASS_NO_COPY(Scope);
+
+	private:
+		Window* m_window;
+	};
+
+	// The newest range being remapped recently that holds vaddr (0: none). Waits while it still
+	// is being remapped.
+	static uint64_t Wait(uint64_t vaddr) noexcept {
+		constexpr int64_t Second  = 1000000000;
+		uint64_t          matched = 0;
+		for (auto& window: s_windows) {
+			if (vaddr < window.start.load(std::memory_order_acquire) ||
+			    vaddr >= window.end.load(std::memory_order_acquire)) {
+				continue;
+			}
+			const auto begin = Now();
+			for (uint32_t spins = 0; window.closed_ns.load(std::memory_order_acquire) == 0; spins++) {
+				if (Now() - begin > Second * 10) {
+					return 0; // never closed: report the fault
+				}
+				if (spins < 4096) {
+#if defined(_M_X64) || defined(__x86_64__)
+					_mm_pause();
+#endif
+				} else {
+					std::this_thread::yield();
+				}
+			}
+			// The fault may be handled after the mapping is already back.
+			if (Now() - window.closed_ns.load(std::memory_order_acquire) < Second) {
+				matched = std::max(matched, window.id.load(std::memory_order_acquire));
+			}
+		}
+		return matched;
+	}
+
+private:
+	static Window* Open(uint64_t start, uint64_t end) noexcept {
+		auto& window = s_windows[s_next.fetch_add(1, std::memory_order_relaxed) % s_windows.size()];

Fixed in bbd7a79f. Entries are now claimed atomically (owned) and released only by their Scope, so an open range is never overwritten. The table grew to 64 entries; when all are open, Open yields until one frees, since a scope spans a single remap.

One correction: a single replacement opens at most two survivor windows, the left part of its first view and the right part of its last one. Views in between are removed whole. So the wrap needed many concurrent replacements, not one fragmented mapping. It is fixed either way. TransientUnmapWindows is internal to memory.cpp, so there is no direct >16-window test.

**@⁠oguzhanozfe** on GitHub · 2026-11-18 22:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4621942651) On `src/kernel/memoryAddressSpace.inc` line 89 (outdated): ```diff @@ -25,6 +25,87 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with +// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a +// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping +// all of it). On the console these replacements are atomic, so guest threads keep using the +// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or +// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried +// instead of being reported as an access violation. +struct TransientUnmapWindow { + std::atomic<uint64_t> id {0}; + std::atomic<uint64_t> start {0}; + std::atomic<uint64_t> end {0}; + std::atomic<int64_t> closed_ns {0}; // 0 while the range is being remapped +}; + +class TransientUnmapWindows { +public: + using Window = TransientUnmapWindow; + + class Scope { + public: + Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {} + ~Scope() { m_window->closed_ns.store(Now(), std::memory_order_release); } + KYTY_CLASS_NO_COPY(Scope); + + private: + Window* m_window; + }; + + // The newest range being remapped recently that holds vaddr (0: none). Waits while it still + // is being remapped. + static uint64_t Wait(uint64_t vaddr) noexcept { + constexpr int64_t Second = 1000000000; + uint64_t matched = 0; + for (auto& window: s_windows) { + if (vaddr < window.start.load(std::memory_order_acquire) || + vaddr >= window.end.load(std::memory_order_acquire)) { + continue; + } + const auto begin = Now(); + for (uint32_t spins = 0; window.closed_ns.load(std::memory_order_acquire) == 0; spins++) { + if (Now() - begin > Second * 10) { + return 0; // never closed: report the fault + } + if (spins < 4096) { +#if defined(_M_X64) || defined(__x86_64__) + _mm_pause(); +#endif + } else { + std::this_thread::yield(); + } + } + // The fault may be handled after the mapping is already back. + if (Now() - window.closed_ns.load(std::memory_order_acquire) < Second) { + matched = std::max(matched, window.id.load(std::memory_order_acquire)); + } + } + return matched; + } + +private: + static Window* Open(uint64_t start, uint64_t end) noexcept { + auto& window = s_windows[s_next.fetch_add(1, std::memory_order_relaxed) % s_windows.size()]; ``` Fixed in bbd7a79f. Entries are now claimed atomically (`owned`) and released only by their `Scope`, so an open range is never overwritten. The table grew to 64 entries; when all are open, `Open` yields until one frees, since a scope spans a single remap. One correction: a single replacement opens at most two survivor windows, the left part of its first view and the right part of its last one. Views in between are removed whole. So the wrap needed many concurrent replacements, not one fragmented mapping. It is fixed either way. `TransientUnmapWindows` is internal to `memory.cpp`, so there is no direct >16-window test.
Author
Owner

@⁠oguzhanozfe on GitHub · 2026-11-18 22:50 UTC · original
On src/loader/runtimeLinker.cpp line 638 (outdated):

@@ -632,6 +632,10 @@ static bool KytyExceptionHandler(const Common::HostException::ExceptionInfo& exc
 	}
 
 	if (info->type == Common::HostException::ExceptionType::AccessViolation) {
+		// A guest range briefly unmapped while the emulator replaced its mapping: wait until it
+		// is mapped again, then retry the access unless the GPU tracking resolves the fault.
+		const auto transient =
+		    Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr);

Fixed in bbd7a79f. GPU tracking and the SRT-walker skip now run first, and the transient wait happens only right before the retry decision. A retried access that then hits GPU write/read tracking faults again and is resolved by HandleGpuFault.

**@⁠oguzhanozfe** on GitHub · 2026-11-18 22:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4621942978) On `src/loader/runtimeLinker.cpp` line 638 (outdated): ```diff @@ -632,6 +632,10 @@ static bool KytyExceptionHandler(const Common::HostException::ExceptionInfo& exc } if (info->type == Common::HostException::ExceptionType::AccessViolation) { + // A guest range briefly unmapped while the emulator replaced its mapping: wait until it + // is mapped again, then retry the access unless the GPU tracking resolves the fault. + const auto transient = + Libs::LibKernel::Memory::WaitForTransientUnmap(info->access_violation_vaddr); ``` Fixed in bbd7a79f. GPU tracking and the SRT-walker skip now run first, and the transient wait happens only right before the retry decision. A retried access that then hits GPU write/read tracking faults again and is resolved by `HandleGpuFault`.
@ -2477,0 +2522,4 @@
std::atomic<bool> started {false};
std::atomic<uint64_t> mismatches {0};
std::atomic<uint64_t> accesses {0};
std::thread worker([&] {
Author
Owner

@⁠oguzhanozfe on GitHub · 2026-11-18 22:50 UTC · original

Fixed in bbd7a79f. The replacement loops start only after the worker has accessed both mappings, and the test checks accesses > 0. Three consecutive runs retried 316, 317 and 313 faults, so the retry path is exercised every time.

**@⁠oguzhanozfe** on GitHub · 2026-11-18 22:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4621943260) Fixed in bbd7a79f. The replacement loops start only after the worker has accessed both mappings, and the test checks `accesses > 0`. Three consecutive runs retried 316, 317 and 313 faults, so the retry path is exercised every time.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 22:58 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Preserve the matched window generation across entry reuse. · memoryAddressSpace.inc:84

src/kernel/memoryAddressSpace.inc:84
Major · Stability & Availability · Heavy lift

Preserve the matched window generation across entry reuse.

A reader can observe closure at Line 71, then pause while 63 disjoint windows complete and the same slot opens for another range. The second closed_ns load can then return 0. The age check rejects the original match, and Wait returns 0 if no other entry covers the address. The runtime handler terminates even though the original mapping is accessible again. (raw.githubusercontent.com)

Preserve the matched generation and its completion across reuse, or prevent reuse until its readers finish. Validate the range and token together. Stronger memory ordering alone does not prevent this interleaving. Add a regression case that pauses the reader after its first nonzero closure read.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7450c00a5b and bbd7a79f16.

Files selected for processing: 3

  • src/kernel/memoryAddressSpace.inc
  • src/loader/runtimeLinker.cpp
  • tests/VirtualMemoryAllocationTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 22:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#pullrequestreview-5966550751) · **reviewed** <!-- coderabbit-ai-generated:v1 --> > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Preserve the matched window generation across entry reuse. · <code>memoryAddressSpace.inc:84</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/kernel/memoryAddressSpace.inc:84` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** > > **Preserve the matched window generation across entry reuse.** > > A reader can observe closure at Line 71, then pause while 63 disjoint windows complete and the same slot opens for another range. The second `closed_ns` load can then return `0`. The age check rejects the original match, and `Wait` returns `0` if no other entry covers the address. The runtime handler terminates even though the original mapping is accessible again. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/bbd7a79f164101bdb1e44a1efe9cd8dfc1a87458/src/kernel/memoryAddressSpace.inc)) > > Preserve the matched generation and its completion across reuse, or prevent reuse until its readers finish. Validate the range and token together. Stronger memory ordering alone does not prevent this interleaving. Add a regression case that pauses the reader after its first nonzero closure read. > > <!-- cr-comment:v1:f2a1f75c5faf023c02fafead --> > > </dd> > </dl> > </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a90be8dd7304640cf4176a975871d51443710292/.coderabbit.yaml>) - **Commit**: [a90be8d](<https://github.com/KytyPS5/KytyPS5/commit/a90be8dd7304640cf4176a975871d51443710292>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `fe5ed817-fc52-46ec-a473-0280e7fff743` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 7450c00a5b8bb1cde37d05dec5c1190215cbf6ab and bbd7a79f164101bdb1e44a1efe9cd8dfc1a87458. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 3</summary> <dl> <dd> <br> * `src/kernel/memoryAddressSpace.inc` * `src/loader/runtimeLinker.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=8f5b3104-19c0-4ea1-a202-96a50d133370 attempt=59f8350a-eed4-41fe-a5d2-a3a6798a2d19 batch=1/1 -->
@ -2477,0 +2522,4 @@
std::atomic<bool> started {false};
std::atomic<uint64_t> mismatches {0};
std::atomic<uint64_t> accesses {0};
std::thread worker([&] {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 23:00 UTC · original

@⁠oguzhanozfe Thanks. The handshake ensures the worker accesses both mappings before the replacement loops start.

The worker can still pause immediately after setting started and resume after both loops finish. The test can then pass with zero retries. Your three runs exercised the retry path, but the test does not guarantee that future runs will do so.

Please use a controlled mapping gap and assert that recovery occurs. I am not marking the finding as addressed yet.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 23:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4622038678) <!-- coderabbit-ai-generated:v1 --> @⁠oguzhanozfe Thanks. The handshake ensures the worker accesses both mappings before the replacement loops start. The worker can still pause immediately after setting `started` and resume after both loops finish. The test can then pass with zero retries. Your three runs exercised the retry path, but the test does not guarantee that future runs will do so. Please use a controlled mapping gap and assert that recovery occurs. I am not marking the finding as addressed yet. --- <!-- 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=A%20worker-start%20handshake%20alone%20isn%E2%80%99t%20enough%E2%80%94force%20a%20mapping%20gap%20and%20verify%20recovery%20so%20the%20test%20proves%20it%20exercised%20the%20retry%20path.%20%40coderabbitai%20helps%20make%20concurrency%20tests%20reliable%20%F0%9F%A7%AA&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2395%23discussion_r4621888875)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 23:03 UTC · original
On src/kernel/memoryAddressSpace.inc line 89 (outdated):

@@ -25,6 +25,87 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with
+// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a
+// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping
+// all of it). On the console these replacements are atomic, so guest threads keep using the
+// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or
+// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried
+// instead of being reported as an access violation.
+struct TransientUnmapWindow {
+	std::atomic<uint64_t> id {0};
+	std::atomic<uint64_t> start {0};
+	std::atomic<uint64_t> end {0};
+	std::atomic<int64_t>  closed_ns {0}; // 0 while the range is being remapped
+};
+
+class TransientUnmapWindows {
+public:
+	using Window = TransientUnmapWindow;
+
+	class Scope {
+	public:
+		Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {}
+		~Scope() { m_window->closed_ns.store(Now(), std::memory_order_release); }
+		KYTY_CLASS_NO_COPY(Scope);
+
+	private:
+		Window* m_window;
+	};
+
+	// The newest range being remapped recently that holds vaddr (0: none). Waits while it still
+	// is being remapped.
+	static uint64_t Wait(uint64_t vaddr) noexcept {
+		constexpr int64_t Second  = 1000000000;
+		uint64_t          matched = 0;
+		for (auto& window: s_windows) {
+			if (vaddr < window.start.load(std::memory_order_acquire) ||
+			    vaddr >= window.end.load(std::memory_order_acquire)) {
+				continue;
+			}
+			const auto begin = Now();
+			for (uint32_t spins = 0; window.closed_ns.load(std::memory_order_acquire) == 0; spins++) {
+				if (Now() - begin > Second * 10) {
+					return 0; // never closed: report the fault
+				}
+				if (spins < 4096) {
+#if defined(_M_X64) || defined(__x86_64__)
+					_mm_pause();
+#endif
+				} else {
+					std::this_thread::yield();
+				}
+			}
+			// The fault may be handled after the mapping is already back.
+			if (Now() - window.closed_ns.load(std::memory_order_acquire) < Second) {
+				matched = std::max(matched, window.id.load(std::memory_order_acquire));
+			}
+		}
+		return matched;
+	}
+
+private:
+	static Window* Open(uint64_t start, uint64_t end) noexcept {
+		auto& window = s_windows[s_next.fetch_add(1, std::memory_order_relaxed) % s_windows.size()];
Analysis chain

Script executed:

#!/bin/bash
git rev-parse HEAD
printf '\n--- Source outlines ---\n'
ast-grep outline src/kernel/memory.cpp --items all --match 'MapFlexibleMemory|MapDirectMemory|Unmap|Transient' 2>/dev/null
ast-grep outline src/kernel/memoryAddressSpace.inc --items all --match 'TransientUnmap|UnmapOne|Unmap' 2>/dev/null
ast-grep outline tests/VirtualMemoryAllocationTests.cpp --items all --match 'MappingReplacement|Transient|Fragment' 2>/dev/null
printf '\n--- Mapping, unmapping and locks ---\n'
rg -n -C 4 'MapFlexibleMemory\s*\(|MapDirectMemory\s*\(|UnmapMemory\s*\(|UnmapBacking\s*\(|g_memory_(operation|state)_mutex|TransientUnmapWindows::Scope' src/kernel/memory.cpp
printf '\n--- Window and view code ---\n'
cat -n src/kernel/memoryAddressSpace.inc | sed -n '35,125p;268,310p;446,510p'
printf '\n--- Test references ---\n'
rg -n -C 4 'AccessDuringMappingReplacement|TransientUnmap|Fragment' tests/VirtualMemoryAllocationTests.cpp
printf '\n--- Mapping implementation windows ---\n'
python3 - <<'PY'
from pathlib import Path
import re
p=Path("src/kernel/memory.cpp")
lines=p.read_text().splitlines()
for pattern in [r'^\s*(?:[\w:<>]+\s+)+MapFlexibleMemory\s*\(', r'^\s*(?:[\w:<>]+\s+)+MapDirectMemory\s*\(', r'^\s*(?:[\w:<>]+\s+)+UnmapMemory\s*\(']:
    for i,s in enumerate(lines):
        if re.search(pattern,s):
            print(f"\n--- {p}:{i+1} ---")
            for j in range(i,min(i+130,len(lines))):
                print(f"{j+1:5}\t{lines[j]}")
PY
printf '\n--- Repository instruction files ---\n'
fd -HI -t f '^(AGENTS\.md|CLAUDE\.md)$' . -d 4 2>/dev/null

Length of output: 98865


Script executed:

#!/bin/bash
printf '%s\n' '--- Relevant source structure ---'
ast-grep outline src/kernel/memory.cpp --items all --match 'VirtualRanges|FlexibleMemory|ReplaceFixedRangeWithReserved|UnmapMemoryOwner|ProtectMemory' 2>/dev/null
printf '\n%s\n' '--- Relevant definitions and calls ---'
rg -n -C 5 'QueryFragments\s*\(|FlexibleMemory::(Map|PrepareMap|Unmap)\s*\(|void Protect\s*\(|bool Protect\s*\(|UnmapMemoryOwner\s*\(|GUEST_MAP_NO_COALESCE' src/kernel/memory.cpp
printf '\n%s\n' '--- Source windows ---'
python3 - <<'PY'
from pathlib import Path
import re
p = Path('src/kernel/memory.cpp')
lines = p.read_text().splitlines()
patterns = [
    r'QueryFragments\s*\(',
    r'FlexibleMemory::(?:Map|PrepareMap|Unmap)\s*\(',
    r'static void UnmapMemoryOwner\s*\(',
    r'static void UnmapMemoryOwners\s*\(',
    r'static int ProtectMemory\s*\(',
]
windows = []
for pat in patterns:
    for i, line in enumerate(lines):
        if re.search(pat, line) and ('{' in line or i+1 < len(lines) and '{' in lines[i+1]):
            windows.append((max(0,i-3),min(len(lines),i+85),pat))
for start, end, pat in windows:
    print(f'\n--- {p}:{start+1}-{end}, {pat} ---')
    for j in range(start,end):
        print(f'{j+1:5} {lines[j]}')
PY
printf '\n%s\n' '--- Original revision, relevant window selection and source calls ---'
git show 7450c00a5b8bb1cde37d05dec5c1190215cbf6ab:src/kernel/memoryAddressSpace.inc | nl -ba | sed -n '35,120p;285,315p;430,490p'
git show 7450c00a5b8bb1cde37d05dec5c1190215cbf6ab:src/kernel/memory.cpp | rg -n -C 5 'QueryFragments\s*\(|UnmapMemoryOwners\s*\(|g_memory_operation_mutex|MapFlexibleMemory\s*\(' | head -n 220

Length of output: 60466


Script executed:

#!/bin/bash
printf '%s\n' '--- Guest range edits ---'
rg -n -C 3 'EditUnlocked\s*\(|SplitAt\s*\(|RenameVirtualRange\s*\(' src/kernel/memory.cpp
cat -n src/kernel/memory.cpp | sed -n '300,345p;475,600p;1745,1765p;1798,1840p;1875,1887p;2478,2493p;2946,2963p'
printf '\n%s\n' '--- Windows view identification ---'
cat -n src/kernel/memoryAddressSpace.inc | sed -n '420,488p'
printf '\n%s\n' '--- Replacement regression test ---'
cat -n tests/VirtualMemoryAllocationTests.cpp | sed -n '2470,2608p'

Length of output: 24691


@oguzhanozfe Thanks. I verified that bbd7a79f claims entries atomically and releases them when their scopes close.

One correction: the two-survivor bound applies to one GuestBackingStore::Unmap call, not necessarily to a whole replacement. Name or protection edits can split the guest ranges without splitting the Windows view. ReplaceFixedRangeWithReserved then unmaps those guest fragments separately. Their sequential survivor windows can wrap the old 16-entry table while the outer window remains open.

The existing replacement test does not cover that case. Please add a deterministic Windows regression test that fragments one view into at least 17 guest ranges and accesses the first range after 16 survivor-window openings, before the replacement is mapped. I have not run the test, so I am not marking the finding as addressed yet.


📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 23:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4622065141) On `src/kernel/memoryAddressSpace.inc` line 89 (outdated): ```diff @@ -25,6 +25,87 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with +// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a +// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping +// all of it). On the console these replacements are atomic, so guest threads keep using the +// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or +// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried +// instead of being reported as an access violation. +struct TransientUnmapWindow { + std::atomic<uint64_t> id {0}; + std::atomic<uint64_t> start {0}; + std::atomic<uint64_t> end {0}; + std::atomic<int64_t> closed_ns {0}; // 0 while the range is being remapped +}; + +class TransientUnmapWindows { +public: + using Window = TransientUnmapWindow; + + class Scope { + public: + Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {} + ~Scope() { m_window->closed_ns.store(Now(), std::memory_order_release); } + KYTY_CLASS_NO_COPY(Scope); + + private: + Window* m_window; + }; + + // The newest range being remapped recently that holds vaddr (0: none). Waits while it still + // is being remapped. + static uint64_t Wait(uint64_t vaddr) noexcept { + constexpr int64_t Second = 1000000000; + uint64_t matched = 0; + for (auto& window: s_windows) { + if (vaddr < window.start.load(std::memory_order_acquire) || + vaddr >= window.end.load(std::memory_order_acquire)) { + continue; + } + const auto begin = Now(); + for (uint32_t spins = 0; window.closed_ns.load(std::memory_order_acquire) == 0; spins++) { + if (Now() - begin > Second * 10) { + return 0; // never closed: report the fault + } + if (spins < 4096) { +#if defined(_M_X64) || defined(__x86_64__) + _mm_pause(); +#endif + } else { + std::this_thread::yield(); + } + } + // The fault may be handled after the mapping is already back. + if (Now() - window.closed_ns.load(std::memory_order_acquire) < Second) { + matched = std::max(matched, window.id.load(std::memory_order_acquire)); + } + } + return matched; + } + +private: + static Window* Open(uint64_t start, uint64_t end) noexcept { + auto& window = s_windows[s_next.fetch_add(1, std::memory_order_relaxed) % s_windows.size()]; ``` <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash git rev-parse HEAD printf '\n--- Source outlines ---\n' ast-grep outline src/kernel/memory.cpp --items all --match 'MapFlexibleMemory|MapDirectMemory|Unmap|Transient' 2>/dev/null ast-grep outline src/kernel/memoryAddressSpace.inc --items all --match 'TransientUnmap|UnmapOne|Unmap' 2>/dev/null ast-grep outline tests/VirtualMemoryAllocationTests.cpp --items all --match 'MappingReplacement|Transient|Fragment' 2>/dev/null printf '\n--- Mapping, unmapping and locks ---\n' rg -n -C 4 'MapFlexibleMemory\s*\(|MapDirectMemory\s*\(|UnmapMemory\s*\(|UnmapBacking\s*\(|g_memory_(operation|state)_mutex|TransientUnmapWindows::Scope' src/kernel/memory.cpp printf '\n--- Window and view code ---\n' cat -n src/kernel/memoryAddressSpace.inc | sed -n '35,125p;268,310p;446,510p' printf '\n--- Test references ---\n' rg -n -C 4 'AccessDuringMappingReplacement|TransientUnmap|Fragment' tests/VirtualMemoryAllocationTests.cpp printf '\n--- Mapping implementation windows ---\n' python3 - <<'PY' from pathlib import Path import re p=Path("src/kernel/memory.cpp") lines=p.read_text().splitlines() for pattern in [r'^\s*(?:[\w:<>]+\s+)+MapFlexibleMemory\s*\(', r'^\s*(?:[\w:<>]+\s+)+MapDirectMemory\s*\(', r'^\s*(?:[\w:<>]+\s+)+UnmapMemory\s*\(']: for i,s in enumerate(lines): if re.search(pattern,s): print(f"\n--- {p}:{i+1} ---") for j in range(i,min(i+130,len(lines))): print(f"{j+1:5}\t{lines[j]}") PY printf '\n--- Repository instruction files ---\n' fd -HI -t f '^(AGENTS\.md|CLAUDE\.md)$' . -d 4 2>/dev/null ``` Length of output: 98865 --- Script executed: ```shell #!/bin/bash printf '%s\n' '--- Relevant source structure ---' ast-grep outline src/kernel/memory.cpp --items all --match 'VirtualRanges|FlexibleMemory|ReplaceFixedRangeWithReserved|UnmapMemoryOwner|ProtectMemory' 2>/dev/null printf '\n%s\n' '--- Relevant definitions and calls ---' rg -n -C 5 'QueryFragments\s*\(|FlexibleMemory::(Map|PrepareMap|Unmap)\s*\(|void Protect\s*\(|bool Protect\s*\(|UnmapMemoryOwner\s*\(|GUEST_MAP_NO_COALESCE' src/kernel/memory.cpp printf '\n%s\n' '--- Source windows ---' python3 - <<'PY' from pathlib import Path import re p = Path('src/kernel/memory.cpp') lines = p.read_text().splitlines() patterns = [ r'QueryFragments\s*\(', r'FlexibleMemory::(?:Map|PrepareMap|Unmap)\s*\(', r'static void UnmapMemoryOwner\s*\(', r'static void UnmapMemoryOwners\s*\(', r'static int ProtectMemory\s*\(', ] windows = [] for pat in patterns: for i, line in enumerate(lines): if re.search(pat, line) and ('{' in line or i+1 < len(lines) and '{' in lines[i+1]): windows.append((max(0,i-3),min(len(lines),i+85),pat)) for start, end, pat in windows: print(f'\n--- {p}:{start+1}-{end}, {pat} ---') for j in range(start,end): print(f'{j+1:5} {lines[j]}') PY printf '\n%s\n' '--- Original revision, relevant window selection and source calls ---' git show 7450c00a5b8bb1cde37d05dec5c1190215cbf6ab:src/kernel/memoryAddressSpace.inc | nl -ba | sed -n '35,120p;285,315p;430,490p' git show 7450c00a5b8bb1cde37d05dec5c1190215cbf6ab:src/kernel/memory.cpp | rg -n -C 5 'QueryFragments\s*\(|UnmapMemoryOwners\s*\(|g_memory_operation_mutex|MapFlexibleMemory\s*\(' | head -n 220 ``` Length of output: 60466 --- Script executed: ```shell #!/bin/bash printf '%s\n' '--- Guest range edits ---' rg -n -C 3 'EditUnlocked\s*\(|SplitAt\s*\(|RenameVirtualRange\s*\(' src/kernel/memory.cpp cat -n src/kernel/memory.cpp | sed -n '300,345p;475,600p;1745,1765p;1798,1840p;1875,1887p;2478,2493p;2946,2963p' printf '\n%s\n' '--- Windows view identification ---' cat -n src/kernel/memoryAddressSpace.inc | sed -n '420,488p' printf '\n%s\n' '--- Replacement regression test ---' cat -n tests/VirtualMemoryAllocationTests.cpp | sed -n '2470,2608p' ``` Length of output: 24691 --- </dd> </dl> </details> `@oguzhanozfe` Thanks. I verified that `bbd7a79f` claims entries atomically and releases them when their scopes close. One correction: the two-survivor bound applies to one `GuestBackingStore::Unmap` call, not necessarily to a whole replacement. Name or protection edits can split the guest ranges without splitting the Windows view. `ReplaceFixedRangeWithReserved` then unmaps those guest fragments separately. Their sequential survivor windows can wrap the old 16-entry table while the outer window remains open. The existing replacement test does not cover that case. Please add a deterministic Windows regression test that fragments one view into at least 17 guest ranges and accesses the first range after 16 survivor-window openings, before the replacement is mapped. I have not run the test, so I am not marking the finding as addressed yet. --- > 📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings. --- <!-- 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%20Windows%20race%20where%20open%20remap%20windows%20could%20be%20overwritten%2C%20causing%20guest%20faults.%20The%20fix%20atomically%20claims%20windows%20and%20waits%20for%20one%20to%20free.%20Try%20%40coderabbitai%20for%20sharper%20reviews!%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2395%23discussion_r4621888855)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠oguzhanozfe on GitHub · 2026-11-18 23:05 UTC · original

@⁠coderabbitai Re the outside-diff comment Preserve the matched window generation across entry reuse (memoryAddressSpace.inc): fixed in 5013e95b.

  • Wait snapshots the entry's id together with its range and re-checks the id, so a torn read against a reopening entry is skipped.
  • It keeps the closed_ns value it observed instead of loading it again.
  • If the id changes while it waits, it treats the matched window as just closed. Reuse requires the original Scope to release the entry, and a Scope closes before it releases.

TransientUnmapWindows is internal to memory.cpp, so there is no direct test that pauses a reader. AccessDuringMappingReplacement still passes; three runs retried 316–317 faults each.

**@⁠oguzhanozfe** on GitHub · 2026-11-18 23:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#issuecomment-6994251412) @⁠coderabbitai Re the outside-diff comment *Preserve the matched window generation across entry reuse* (`memoryAddressSpace.inc`): fixed in 5013e95b. - `Wait` snapshots the entry's `id` together with its range and re-checks the `id`, so a torn read against a reopening entry is skipped. - It keeps the `closed_ns` value it observed instead of loading it again. - If the `id` changes while it waits, it treats the matched window as just closed. Reuse requires the original `Scope` to release the entry, and a `Scope` closes before it releases. `TransientUnmapWindows` is internal to `memory.cpp`, so there is no direct test that pauses a reader. `AccessDuringMappingReplacement` still passes; three runs retried 316–317 faults each.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 23:07 UTC · original

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Revision ==='
git rev-parse HEAD
git show --no-patch --format='%H %s' 5013e95b 2>&1
printf '%s\n' '=== Outlines ==='
ast-grep outline src/kernel/memoryAddressSpace.inc --items all 2>&1 | head -100
ast-grep outline tests/VirtualMemoryAllocationTests.cpp --items all --match 'Transient|AccessDuringMappingReplacement' 2>&1 | head -100
printf '%s\n' '=== Window locations ==='
rg -n -C 3 'class TransientUnmap|struct TransientUnmap|TransientUnmapWindows|closed_ns|TestAccessDuringMappingReplacement' src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp
printf '%s\n' '=== Fix diff ==='
git show --format=fuller --stat 5013e95b -- src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp
git show --format= -- src/kernel/memoryAddressSpace.inc | head -250
printf '%s\n' '=== Window implementation ==='
python - <<'PY'
from pathlib import Path
p = Path('src/kernel/memoryAddressSpace.inc')
lines = p.read_text().splitlines()
hits = [i for i, line in enumerate(lines) if 'class TransientUnmapWindow' in line or 'struct TransientUnmapWindow' in line]
for hit in hits:
    start = max(0, hit - 8)
    end = min(len(lines), hit + 180)
    for i in range(start, end):
        print(f'{i+1:5} {lines[i]}')
PY

Length of output: 24692


Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Revision ==='
git rev-parse HEAD
git show --no-patch --format='%H %s' 5013e95b 2>&1
printf '%s\n' '=== Outlines ==='
ast-grep outline src/kernel/memoryAddressSpace.inc --items all 2>&1 | head -100
ast-grep outline tests/VirtualMemoryAllocationTests.cpp --items all --match 'Transient|AccessDuringMappingReplacement' 2>&1 | head -100
printf '%s\n' '=== Window locations ==='
rg -n -C 3 'class TransientUnmap|struct TransientUnmap|TransientUnmapWindows|closed_ns|TestAccessDuringMappingReplacement' src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp
printf '%s\n' '=== Fix diff ==='
git show --format=fuller --stat 5013e95b -- src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp
git show --format= 5013e95b -- src/kernel/memoryAddressSpace.inc | head -250
printf '%s\n' '=== Window implementation ==='
python - <<'PY'
from pathlib import Path
p = Path('src/kernel/memoryAddressSpace.inc')
lines = p.read_text().splitlines()
hits = [i for i, line in enumerate(lines) if 'class TransientUnmapWindow' in line or 'struct TransientUnmapWindow' in line]
for hit in hits:
    start = max(0, hit - 8)
    end = min(len(lines), hit + 180)
    for i in range(start, end):
        print(f'{i+1:5} {lines[i]}')
PY

Length of output: 24701


Script executed:

#!/bin/bash
printf '%s\n' '=== Fault retry locations ==='
rg -n -C 8 'WaitForTransientUnmap|RetryTransientUnmapFault' src/kernel/memory.cpp src/kernel/memory.h src/loader/runtimeLinker.cpp tests/VirtualMemoryAllocationTests.cpp
printf '%s\n' '=== Memory function outline ==='
ast-grep outline src/kernel/memory.cpp --items all --match 'WaitForTransientUnmap|RetryTransientUnmapFault' 2>&1
printf '%s\n' '=== Window creation call sites ==='
rg -n -C 7 'TransientUnmapWindows::Scope|left_window\.emplace|right_window\.emplace' src/kernel/memory.cpp src/kernel/memoryAddressSpace.inc

Length of output: 11523


@oguzhanozfe Thanks for the update. Wait now retains the observed closed_ns, so it no longer performs the second load that prompted the original comment.

However, the generation and range snapshot can still be inconsistent. In src/kernel/memoryAddressSpace.inc at Line 125, Open stores the new id before the new range. A reader can therefore read window B’s id twice while still reading window A’s range. Wait can then wait for an unrelated window and return B’s ID, which controls the retry budget.

Please use a publication protocol that lets readers detect an update in progress, and add a controlled interleaving test for entry reuse. The reported stress runs do not force this interleaving; I did not run them independently. I’m not marking the finding as addressed yet.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 23:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#issuecomment-6994281237) <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated reply by CodeRabbit --> > [!TIP] > For best results, initiate chat on the files or code changes. <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '=== Revision ===' git rev-parse HEAD git show --no-patch --format='%H %s' 5013e95b 2>&1 printf '%s\n' '=== Outlines ===' ast-grep outline src/kernel/memoryAddressSpace.inc --items all 2>&1 | head -100 ast-grep outline tests/VirtualMemoryAllocationTests.cpp --items all --match 'Transient|AccessDuringMappingReplacement' 2>&1 | head -100 printf '%s\n' '=== Window locations ===' rg -n -C 3 'class TransientUnmap|struct TransientUnmap|TransientUnmapWindows|closed_ns|TestAccessDuringMappingReplacement' src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp printf '%s\n' '=== Fix diff ===' git show --format=fuller --stat 5013e95b -- src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp git show --format= -- src/kernel/memoryAddressSpace.inc | head -250 printf '%s\n' '=== Window implementation ===' python - <<'PY' from pathlib import Path p = Path('src/kernel/memoryAddressSpace.inc') lines = p.read_text().splitlines() hits = [i for i, line in enumerate(lines) if 'class TransientUnmapWindow' in line or 'struct TransientUnmapWindow' in line] for hit in hits: start = max(0, hit - 8) end = min(len(lines), hit + 180) for i in range(start, end): print(f'{i+1:5} {lines[i]}') PY ``` Length of output: 24692 --- Script executed: ```shell #!/bin/bash set -u printf '%s\n' '=== Revision ===' git rev-parse HEAD git show --no-patch --format='%H %s' 5013e95b 2>&1 printf '%s\n' '=== Outlines ===' ast-grep outline src/kernel/memoryAddressSpace.inc --items all 2>&1 | head -100 ast-grep outline tests/VirtualMemoryAllocationTests.cpp --items all --match 'Transient|AccessDuringMappingReplacement' 2>&1 | head -100 printf '%s\n' '=== Window locations ===' rg -n -C 3 'class TransientUnmap|struct TransientUnmap|TransientUnmapWindows|closed_ns|TestAccessDuringMappingReplacement' src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp printf '%s\n' '=== Fix diff ===' git show --format=fuller --stat 5013e95b -- src/kernel/memoryAddressSpace.inc tests/VirtualMemoryAllocationTests.cpp git show --format= 5013e95b -- src/kernel/memoryAddressSpace.inc | head -250 printf '%s\n' '=== Window implementation ===' python - <<'PY' from pathlib import Path p = Path('src/kernel/memoryAddressSpace.inc') lines = p.read_text().splitlines() hits = [i for i, line in enumerate(lines) if 'class TransientUnmapWindow' in line or 'struct TransientUnmapWindow' in line] for hit in hits: start = max(0, hit - 8) end = min(len(lines), hit + 180) for i in range(start, end): print(f'{i+1:5} {lines[i]}') PY ``` Length of output: 24701 --- Script executed: ```shell #!/bin/bash printf '%s\n' '=== Fault retry locations ===' rg -n -C 8 'WaitForTransientUnmap|RetryTransientUnmapFault' src/kernel/memory.cpp src/kernel/memory.h src/loader/runtimeLinker.cpp tests/VirtualMemoryAllocationTests.cpp printf '%s\n' '=== Memory function outline ===' ast-grep outline src/kernel/memory.cpp --items all --match 'WaitForTransientUnmap|RetryTransientUnmapFault' 2>&1 printf '%s\n' '=== Window creation call sites ===' rg -n -C 7 'TransientUnmapWindows::Scope|left_window\.emplace|right_window\.emplace' src/kernel/memory.cpp src/kernel/memoryAddressSpace.inc ``` Length of output: 11523 --- </dd> </dl> </details> `@oguzhanozfe` Thanks for the update. `Wait` now retains the observed `closed_ns`, so it no longer performs the second load that prompted the original comment. However, the generation and range snapshot can still be inconsistent. In `src/kernel/memoryAddressSpace.inc` at Line 125, `Open` stores the new `id` before the new range. A reader can therefore read window B’s `id` twice while still reading window A’s range. `Wait` can then wait for an unrelated window and return B’s ID, which controls the retry budget. Please use a publication protocol that lets readers detect an update in progress, and add a controlled interleaving test for entry reuse. The reported stress runs do not force this interleaving; I did not run them independently. I’m not marking the finding as addressed yet. --- <!-- 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%20highlights%20subtle%20concurrency%20bugs%3A%20snapshot%20an%20entry%E2%80%99s%20generation%20with%20its%20range%2C%20so%20reuse%20can%E2%80%99t%20fool%20a%20waiting%20reader.%20Try%20it%20on%20your%20next%20PR%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2395)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub>
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 23:11 UTC · original · edited 2026-11-18 23:27 UTC
On src/kernel/memoryAddressSpace.inc line 71 (outdated):

@@ -25,6 +25,122 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with
+// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a
+// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping
+// all of it). On the console these replacements are atomic, so guest threads keep using the
+// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or
+// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried
+// instead of being reported as an access violation.
+struct TransientUnmapWindow {
+	std::atomic<uint64_t> id {0};
+	std::atomic<uint64_t> start {0};
+	std::atomic<uint64_t> end {0};
+	std::atomic<int64_t>  closed_ns {0}; // 0 while the range is being remapped
+	std::atomic<bool>     owned {false}; // an open Scope holds this entry
+};
+
+class TransientUnmapWindows {
+public:
+	using Window = TransientUnmapWindow;
+
+	class Scope {
+	public:
+		Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {}
+		~Scope() {
+			m_window->closed_ns.store(Now(), std::memory_order_release);
+			m_window->owned.store(false, std::memory_order_release);
+		}
+		KYTY_CLASS_NO_COPY(Scope);
+
+	private:
+		Window* m_window;
+	};
+
+	// The newest range being remapped recently that holds vaddr (0: none). Waits while it still
+	// is being remapped.
+	static uint64_t Wait(uint64_t vaddr) noexcept {
+		constexpr int64_t Second  = 1000000000;
+		uint64_t          matched = 0;
+		for (auto& window: s_windows) {
+			// The id names one opening of this entry; a changed id means the entry was reused.
+			const auto id    = window.id.load(std::memory_order_acquire);
+			const auto start = window.start.load(std::memory_order_acquire);
+			const auto end   = window.end.load(std::memory_order_acquire);
+			if (id == 0 || vaddr < start || vaddr >= end ||
+			    window.id.load(std::memory_order_acquire) != id) {

Major · Stability & Availability · Quick win

Restart the snapshot when the entry generation changes.

If slot 0 is reused between Line 67 and Line 71, this condition skips the replacement window even when it still covers vaddr.

For example, Wait(x) reads window A's ID and pauses. A closes, 63 unrelated windows open and close, and window B reuses slot 0 for the same address. If B unmaps the address before Wait resumes, the changed ID causes continue. No other entry covers x, so Wait returns 0 and the exception handler reports a guest fault. The previous implementation would wait for B to close.

Restart this entry's snapshot when the ID changes. Keep the captured-generation handling for reuse after a snapshot has passed validation. This preserves the unchanged-generation path and prevents the replacement window from being discarded.

✅ Confirmed as addressed by @⁠oguzhanozfe

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 23:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4622133080) · edited 2026-11-18 23:27 UTC On `src/kernel/memoryAddressSpace.inc` line 71 (outdated): ```diff @@ -25,6 +25,122 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with +// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a +// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping +// all of it). On the console these replacements are atomic, so guest threads keep using the +// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or +// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried +// instead of being reported as an access violation. +struct TransientUnmapWindow { + std::atomic<uint64_t> id {0}; + std::atomic<uint64_t> start {0}; + std::atomic<uint64_t> end {0}; + std::atomic<int64_t> closed_ns {0}; // 0 while the range is being remapped + std::atomic<bool> owned {false}; // an open Scope holds this entry +}; + +class TransientUnmapWindows { +public: + using Window = TransientUnmapWindow; + + class Scope { + public: + Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {} + ~Scope() { + m_window->closed_ns.store(Now(), std::memory_order_release); + m_window->owned.store(false, std::memory_order_release); + } + KYTY_CLASS_NO_COPY(Scope); + + private: + Window* m_window; + }; + + // The newest range being remapped recently that holds vaddr (0: none). Waits while it still + // is being remapped. + static uint64_t Wait(uint64_t vaddr) noexcept { + constexpr int64_t Second = 1000000000; + uint64_t matched = 0; + for (auto& window: s_windows) { + // The id names one opening of this entry; a changed id means the entry was reused. + const auto id = window.id.load(std::memory_order_acquire); + const auto start = window.start.load(std::memory_order_acquire); + const auto end = window.end.load(std::memory_order_acquire); + if (id == 0 || vaddr < start || vaddr >= end || + window.id.load(std::memory_order_acquire) != id) { ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Restart the snapshot when the entry generation changes.** If slot 0 is reused between Line 67 and Line 71, this condition skips the replacement window even when it still covers `vaddr`. For example, `Wait(x)` reads window A's ID and pauses. A closes, 63 unrelated windows open and close, and window B reuses slot 0 for the same address. If B unmaps the address before `Wait` resumes, the changed ID causes `continue`. No other entry covers `x`, so `Wait` returns 0 and the exception handler reports a guest fault. The previous implementation would wait for B to close. Restart this entry's snapshot when the ID changes. Keep the captured-generation handling for reuse after a snapshot has passed validation. This preserves the unchanged-generation path and prevents the replacement window from being discarded. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d5116d9ec34a2873d01b8313 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠oguzhanozfe <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 23:11 UTC · original · reviewed

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between bbd7a79f16 and 5013e95b45.

Files selected for processing: 1

  • src/kernel/memoryAddressSpace.inc

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 23:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#pullrequestreview-5966686132) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a90be8dd7304640cf4176a975871d51443710292/.coderabbit.yaml>) - **Commit**: [a90be8d](<https://github.com/KytyPS5/KytyPS5/commit/a90be8dd7304640cf4176a975871d51443710292>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `aefb894d-e720-4fa3-b20a-b821fdb0cddd` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between bbd7a79f164101bdb1e44a1efe9cd8dfc1a87458 and 5013e95b4569db5fcec40344d1d120c996b4cc63. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 1</summary> <dl> <dd> <br> * `src/kernel/memoryAddressSpace.inc` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=4e580445-1e99-4ad6-b860-8cbeece1637e attempt=e7a9a764-d471-4393-a398-19eea73ec8ce batch=1/1 -->
Author
Owner

@⁠oguzhanozfe on GitHub · 2026-11-18 23:26 UTC · original
On src/kernel/memoryAddressSpace.inc line 71 (outdated):

@@ -25,6 +25,122 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) {
 }
 #endif
 
+// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with
+// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a
+// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping
+// all of it). On the console these replacements are atomic, so guest threads keep using the
+// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or
+// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried
+// instead of being reported as an access violation.
+struct TransientUnmapWindow {
+	std::atomic<uint64_t> id {0};
+	std::atomic<uint64_t> start {0};
+	std::atomic<uint64_t> end {0};
+	std::atomic<int64_t>  closed_ns {0}; // 0 while the range is being remapped
+	std::atomic<bool>     owned {false}; // an open Scope holds this entry
+};
+
+class TransientUnmapWindows {
+public:
+	using Window = TransientUnmapWindow;
+
+	class Scope {
+	public:
+		Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {}
+		~Scope() {
+			m_window->closed_ns.store(Now(), std::memory_order_release);
+			m_window->owned.store(false, std::memory_order_release);
+		}
+		KYTY_CLASS_NO_COPY(Scope);
+
+	private:
+		Window* m_window;
+	};
+
+	// The newest range being remapped recently that holds vaddr (0: none). Waits while it still
+	// is being remapped.
+	static uint64_t Wait(uint64_t vaddr) noexcept {
+		constexpr int64_t Second  = 1000000000;
+		uint64_t          matched = 0;
+		for (auto& window: s_windows) {
+			// The id names one opening of this entry; a changed id means the entry was reused.
+			const auto id    = window.id.load(std::memory_order_acquire);
+			const auto start = window.start.load(std::memory_order_acquire);
+			const auto end   = window.end.load(std::memory_order_acquire);
+			if (id == 0 || vaddr < start || vaddr >= end ||
+			    window.id.load(std::memory_order_acquire) != id) {

Fixed in 165cf609.

  • Open now publishes an entry as a seqlock. It writes id = 0, then a release fence, then the range, then the new id with seq_cst.
  • Wait re-reads the entry until the id it read before the range matches the id after an acquire fence. While an owned entry shows id 0, it spins briefly because Open is still writing it.
  • A reopened window that holds the address is therefore read again instead of skipped, and an id is never paired with another opening's range. The previous order, id before start/end, allowed that pairing.

AccessDuringMappingReplacement passes (three runs retried 303–318 faults each), and so do page_manager_tests and memory_tracker_tests.

**@⁠oguzhanozfe** on GitHub · 2026-11-18 23:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2395#discussion_r4622269273) On `src/kernel/memoryAddressSpace.inc` line 71 (outdated): ```diff @@ -25,6 +25,122 @@ static bool CoalescePlaceholders(uint64_t vaddr, uint64_t size) { } #endif +// Ranges whose guest mapping is briefly absent while the emulator replaces it: a guest mmap with +// MAP_FIXED over an existing mapping (unmapped, then mapped again), and, on Windows, the parts of a +// file view that stay mapped when part of it is unmapped (Windows splits a view only by unmapping +// all of it). On the console these replacements are atomic, so guest threads keep using the +// memory: GTA V's streamer decompresses into buffers whose 64 KiB pages are mapped again or +// neighbour an unmap. A fault inside such a range waits until the mapping is back and is retried +// instead of being reported as an access violation. +struct TransientUnmapWindow { + std::atomic<uint64_t> id {0}; + std::atomic<uint64_t> start {0}; + std::atomic<uint64_t> end {0}; + std::atomic<int64_t> closed_ns {0}; // 0 while the range is being remapped + std::atomic<bool> owned {false}; // an open Scope holds this entry +}; + +class TransientUnmapWindows { +public: + using Window = TransientUnmapWindow; + + class Scope { + public: + Scope(uint64_t start, uint64_t end) noexcept: m_window(Open(start, end)) {} + ~Scope() { + m_window->closed_ns.store(Now(), std::memory_order_release); + m_window->owned.store(false, std::memory_order_release); + } + KYTY_CLASS_NO_COPY(Scope); + + private: + Window* m_window; + }; + + // The newest range being remapped recently that holds vaddr (0: none). Waits while it still + // is being remapped. + static uint64_t Wait(uint64_t vaddr) noexcept { + constexpr int64_t Second = 1000000000; + uint64_t matched = 0; + for (auto& window: s_windows) { + // The id names one opening of this entry; a changed id means the entry was reused. + const auto id = window.id.load(std::memory_order_acquire); + const auto start = window.start.load(std::memory_order_acquire); + const auto end = window.end.load(std::memory_order_acquire); + if (id == 0 || vaddr < start || vaddr >= end || + window.id.load(std::memory_order_acquire) != id) { ``` Fixed in 165cf609. - `Open` now publishes an entry as a seqlock. It writes `id = 0`, then a release fence, then the range, then the new `id` with `seq_cst`. - `Wait` re-reads the entry until the `id` it read before the range matches the `id` after an acquire fence. While an owned entry shows `id` 0, it spins briefly because `Open` is still writing it. - A reopened window that holds the address is therefore read again instead of skipped, and an `id` is never paired with another opening's range. The previous order, `id` before `start`/`end`, allowed that pairing. `AccessDuringMappingReplacement` passes (three runs retried 303–318 faults each), and so do `page_manager_tests` and `memory_tracker_tests`.
This pull request has changes conflicting with the target branch.
  • src/kernel/memory.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/2395/head:github-bot/gh-2395'
git switch 'github-bot/gh-2395'

Merge

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