graphics: take the GPU's pages for the CPU in one critical section #1412

Open
github-bot wants to merge 1 commit from github-bot/gh-1412 into main AGit
Owner

@⁠Franseven on GitHub · 2026-10-11 08:52 UTC · original
Franseven:pr/dirty-ownership → main · +32 −2 · 3 files · 1 commits · open

Game

Marvel's Wolverine PPSA03671.

Problem

BufferCache::ReadMemory releases the GPU's ownership of a page and claims it for the CPU as two
separate calls:

		if (DownloadBufferMemory<false>(buffer, vaddr, size)) {
			m_memory_tracker.UnmarkRegionAsGpuModified(vaddr, size);
		}
		if (is_write) {
			m_memory_tracker.MarkRegionAsCpuModified(vaddr, size);
		}

Each call takes the region lock on its own. In between them, a SynchronizeBuffer on another
thread — an upload from the renderer thread — can mark the same page GPU-dirty, and RegionManager
then ends the process on its own invariant:

EXIT("CPU dirty state conflicts with GPU dirty state\n");

regionManager.h:106. That is an EXIT, not an assert: a page that a command still in flight names
ends the session, from a fault path the guest cannot avoid — it is the guest's own read that
triggered the fault.

The same window is reachable without a download. When DownloadBufferMemory returns false the
write branch still runs, and it marks the page CPU-dirty on top of the GPU's untouched claim; the
release never happened at all. That is the path the crash was first reproduced on.

Change

One call that does both halves under one lock:

void MemoryTracker::TakeGpuPagesForCpu(uint64_t vaddr, uint64_t size) {
	CheckNotInUploadCallback();
	// Iterate<true>: the CPU claim creates a region that does not exist yet, which is what
	// MarkRegionAsCpuModified did on its own.
	Iterate<true>(vaddr, size, [](RegionManager* manager, uint64_t offset, uint64_t bytes) {
		std::scoped_lock lock(manager->lock);
		const auto     address = manager->GetCpuAddr() + offset;
		manager->ChangeState<DirtySource::Gpu, false>(address, bytes);
		manager->ChangeState<DirtySource::Cpu, true>(address, bytes);
	});
}

and the caller uses it whenever the guest is about to write:

		if (DownloadBufferMemory<false>(buffer, vaddr, size)) {
			// A write releases the same range below, in the same critical section as its CPU
			// claim: releasing it here as well would be a second lock acquisition on it.
			if (!is_write) {
				m_memory_tracker.UnmarkRegionAsGpuModified(vaddr, size);
			}
		}
		if (is_write) {
			m_memory_tracker.TakeGpuPagesForCpu(vaddr, size);
		}

Three notes:

  • The claim covers whole pages, not the requested bytes. Iterate walks tracker regions page by
    page, so a claim narrower than a page is not expressible; this is strictly more than the two calls
    did, and costs only redundant uploads.
  • Only the enable direction asserts. ChangeState checks the other source's bits only when
    setting them, so clearing an already-clean range is not an error; the release-then-claim order
    above is what keeps the CPU claim from tripping its own invariant.
  • No call site is left holding the pair. MarkRegionAsCpuModified had exactly one caller — this
    one — and it now goes through the take. The only other UnmarkRegionAsGpuModified caller is the
    buffer-cache retire path, which releases the pages as the buffer is deleted and makes no CPU
    claim.

Testing

Built with clang-cl 23.1.3 (Release) on Windows; the emulator links and memory_tracker_tests and
page_manager_tests pass.

The same change has been running in a downstream tree, on a much larger ReadMemoryStep that
carries the same two-call sequence: there Wolverine ran 3933 frames past the point where it
previously ended around 2000, with EXIT("CPU dirty state conflicts with GPU dirty state") in the
log. That tree sits on a different base, so what this PR adds is the change against this tree's own
ReadMemory, which is where the pair is simplest to see.

**@⁠Franseven** on GitHub · 2026-10-11 08:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1412) `Franseven:pr/dirty-ownership` → `main` · +32 −2 · 3 files · 1 commits · open ### Game Marvel's Wolverine PPSA03671. ### Problem `BufferCache::ReadMemory` releases the GPU's ownership of a page and claims it for the CPU as two separate calls: ```cpp if (DownloadBufferMemory<false>(buffer, vaddr, size)) { m_memory_tracker.UnmarkRegionAsGpuModified(vaddr, size); } if (is_write) { m_memory_tracker.MarkRegionAsCpuModified(vaddr, size); } ``` Each call takes the region lock on its own. In between them, a `SynchronizeBuffer` on another thread — an upload from the renderer thread — can mark the same page GPU-dirty, and `RegionManager` then ends the process on its own invariant: ```cpp EXIT("CPU dirty state conflicts with GPU dirty state\n"); ``` `regionManager.h:106`. That is an `EXIT`, not an assert: a page that a command still in flight names ends the session, from a fault path the guest cannot avoid — it is the guest's own read that triggered the fault. The same window is reachable *without* a download. When `DownloadBufferMemory` returns false the write branch still runs, and it marks the page CPU-dirty on top of the GPU's untouched claim; the release never happened at all. That is the path the crash was first reproduced on. ### Change One call that does both halves under one lock: ```cpp void MemoryTracker::TakeGpuPagesForCpu(uint64_t vaddr, uint64_t size) { CheckNotInUploadCallback(); // Iterate<true>: the CPU claim creates a region that does not exist yet, which is what // MarkRegionAsCpuModified did on its own. Iterate<true>(vaddr, size, [](RegionManager* manager, uint64_t offset, uint64_t bytes) { std::scoped_lock lock(manager->lock); const auto address = manager->GetCpuAddr() + offset; manager->ChangeState<DirtySource::Gpu, false>(address, bytes); manager->ChangeState<DirtySource::Cpu, true>(address, bytes); }); } ``` and the caller uses it whenever the guest is about to write: ```cpp if (DownloadBufferMemory<false>(buffer, vaddr, size)) { // A write releases the same range below, in the same critical section as its CPU // claim: releasing it here as well would be a second lock acquisition on it. if (!is_write) { m_memory_tracker.UnmarkRegionAsGpuModified(vaddr, size); } } if (is_write) { m_memory_tracker.TakeGpuPagesForCpu(vaddr, size); } ``` Three notes: - **The claim covers whole pages, not the requested bytes.** `Iterate` walks tracker regions page by page, so a claim narrower than a page is not expressible; this is strictly more than the two calls did, and costs only redundant uploads. - **Only the `enable` direction asserts.** `ChangeState` checks the other source's bits only when setting them, so clearing an already-clean range is not an error; the release-then-claim order above is what keeps the CPU claim from tripping its own invariant. - **No call site is left holding the pair.** `MarkRegionAsCpuModified` had exactly one caller — this one — and it now goes through the take. The only other `UnmarkRegionAsGpuModified` caller is the buffer-cache retire path, which releases the pages as the buffer is deleted and makes no CPU claim. ### Testing Built with clang-cl 23.1.3 (Release) on Windows; the emulator links and `memory_tracker_tests` and `page_manager_tests` pass. The same change has been running in a downstream tree, on a much larger `ReadMemoryStep` that carries the same two-call sequence: there Wolverine ran 3933 frames past the point where it previously ended around 2000, with `EXIT("CPU dirty state conflicts with GPU dirty state")` in the log. That tree sits on a different base, so what this PR adds is the change against this tree's own `ReadMemory`, which is where the pair is simplest to see.
BufferCache::ReadMemory released the GPU's ownership of a page and claimed it
for the CPU as two calls, each taking the region lock on its own. Between them a
SynchronizeBuffer on another thread can mark the same page GPU-dirty, and
RegionManager then ends the process on its own invariant:

	EXIT("CPU dirty state conflicts with GPU dirty state\n");   // regionManager.h:106

That is an EXIT, not an assert, and it runs on a fault path the guest cannot
avoid: it is the guest's own read that faulted. The same window is reachable
without a download -- when DownloadBufferMemory returns false the write branch
still marks the page CPU-dirty over the GPU's untouched claim.

Add MemoryTracker::TakeGpuPagesForCpu, which clears the GPU bits and sets the
CPU bits for the range under one lock, and use it wherever the guest is about to
write. The claim covers whole pages, which is strictly more than the pair of
calls did and costs only redundant uploads; clearing an already-clean range does
not assert, so a write to a page the GPU never owned behaves as before.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:56:19 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 08:55 UTC · original

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0aaea92c-572f-4643-91aa-bc34fc7b32dd

📥 Commits

Reviewing files that changed from the base of the PR and between 6f0cddd440 and 1a65d2638a.


📒 Files selected for processing (3)
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp

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



📝 Walkthrough

Walkthrough

MemoryTracker adds TakeGpuPagesForCpu to clear GPU-modified state and mark the requested bytes CPU-modified under region locks. BufferCache uses this operation for writes in ReadMemory, including when no download is needed. For reads, it unmarks GPU-modified pages after a successful download.

Suggested reviewers: nmzik


Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 1a65d

No concrete merge-blocking issue is established. The change is mergeable after normal checks.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check Passed The description clearly explains the GPU-to-CPU ownership race, the new atomic operation, the affected write path, and the reported testing results.
Title check Passed The title clearly and concisely summarizes the main change: transferring GPU pages to the CPU in one critical section.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 08:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1412#issuecomment-6107335333) <!-- 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/1412?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `0aaea92c-572f-4643-91aa-bc34fc7b32dd` <hr> </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 6f0cddd4404ec5203e71fea77e75fc373299ba3f and 1a65d2638a78c4ad950bb640964156c1b9c598bc. <hr> </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (3)</strong></summary> <dl> <dd> * `src/graphics/host_gpu/memoryTracker.cpp` * `src/graphics/host_gpu/memoryTracker.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` <hr> </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. <hr> </dd> </dl> </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough MemoryTracker adds `TakeGpuPagesForCpu` to clear GPU-modified state and mark the requested bytes CPU-modified under region locks. BufferCache uses this operation for writes in `ReadMemory`, including when no download is needed. For reads, it unmarks GPU-modified pages after a successful download. **Suggested reviewers:** `nmzik` <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"1a65d2638a78c4ad950bb640964156c1b9c598bc" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **⚪ Minimal** · up to `1a65d` <!-- final_review_risk_coverage:{"sourceCommitId":"1a65d2638a78c4ad950bb640964156c1b9c598bc","coveredCommitId":"1a65d2638a78c4ad950bb640964156c1b9c598bc","kind":"reviewed"} --> No concrete merge-blocking issue is established. The change is mergeable after normal checks. <!-- final_review_risk_end --> <!-- 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-v1.svg" width="14" height="17" align="middle" alt="Passed" title="Passed"></picture></sup> 4 | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v1.svg" width="14" height="17" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 3 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the GPU-to-CPU ownership race, the new atomic operation, the affected write path, and the reported testing results. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely summarizes the main change: transferring GPU pages to the CPU in one critical section. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1412)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠theantipopau on GitHub · 2026-10-12 11:11 UTC · original

Read the diff against main. The fix is sound and the claim matches the code:

  • In regionManager.h:106 ChangeState<Cpu, true> hard-EXITs when any page in the range is still GPU-dirty, so the two-step UnmarkRegionAsGpuModified → MarkRegionAsCpuModified in ReadMemory's write path did have a race window against a concurrent MarkRegionAsGpuModified (SynchronizeBuffer/upload): release, then re-mark, then the CPU claim walks in between and kills the process. TakeGpuPagesForCpu does both halves under the same manager->lock, which removes the window deterministically.
  • The read path keeps UnmarkRegionAsGpuModified (no CPU claim happens there, so nothing to make atomic), and skipping it on writes is right since TakeGpuPagesForCpu releases the same range under its own lock — double release would just be a redundant second lock acquisition.
  • Whole-page claim is indeed a superset of the old per-byte behavior: MarkRegionAsCpuModified also iterated whole pages (GetPageRange), so there's no semantic widening beyond redundant uploads.

One note: the changelog-worthy behavior change is that a guest write now releases GPU dirty state even when DownloadBufferMemory had nothing to download — previously the page stayed GPU-dirty under the new CPU-dirty mark, which was exactly the inconsistent state that could never be reached before EXIT'ing. So this is strictly better on that path.

Holding off on a formal approve only because CI on this branch is sitting in action_required (maintainer-approval-gated workflow runs) rather than verified green — no objection to whoever can see the result approving it.

**@⁠theantipopau** on GitHub · 2026-10-12 11:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1412#issuecomment-6123102124) Read the diff against main. The fix is sound and the claim matches the code: - In [regionManager.h:106](https://github.com/KytyPS5/KytyPS5/blob/main/src/graphics/host_gpu/regionManager.h) `ChangeState<Cpu, true>` hard-EXITs when any page in the range is still GPU-dirty, so the two-step `UnmarkRegionAsGpuModified` → `MarkRegionAsCpuModified` in `ReadMemory`'s write path did have a race window against a concurrent `MarkRegionAsGpuModified` (SynchronizeBuffer/upload): release, then re-mark, then the CPU claim walks in between and kills the process. `TakeGpuPagesForCpu` does both halves under the same `manager->lock`, which removes the window deterministically. - The read path keeps `UnmarkRegionAsGpuModified` (no CPU claim happens there, so nothing to make atomic), and skipping it on writes is right since `TakeGpuPagesForCpu` releases the same range under its own lock — double release would just be a redundant second lock acquisition. - Whole-page claim is indeed a superset of the old per-byte behavior: `MarkRegionAsCpuModified` also iterated whole pages (`GetPageRange`), so there's no semantic widening beyond redundant uploads. One note: the changelog-worthy behavior change is that a guest write now releases GPU dirty state even when `DownloadBufferMemory` had nothing to download — previously the page stayed GPU-dirty under the new CPU-dirty mark, which was exactly the inconsistent state that could never be reached before EXIT'ing. So this is strictly better on that path. Holding off on a formal approve only because CI on this branch is sitting in `action_required` (maintainer-approval-gated workflow runs) rather than verified green — no objection to whoever can see the result approving it.
This pull request has changes conflicting with the target branch.
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.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/1412/head:github-bot/gh-1412'
git switch 'github-bot/gh-1412'

Merge

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