gpu: upload BDA synchronization through one staging copy #1932

Closed
github-bot wants to merge 1 commit from gh-pr/1932/head into gh-pr/1932/base
Owner

@⁠MrBigBritches on GitHub · 2026-10-27 03:24 UTC · original
MrBigBritches:bda-sync-batch → main · +276 −14 · 4 files · 1 commits · closed without merging

Before every BDA draw, BDA synchronization uploads the CPU-written pages that shaders may read through buffer device addresses. It handled one buffer at a time. Each buffer that still had dirty pages took its own staging allocation and two whole-buffer barriers. A busy draw in Octopath Traveler II found a few hundred such buffers.

Now all of a synchronization's copies go through one staging allocation, recorded between a single pair of global barriers.

This is the first part of #1809, split out on its own. The other two parts of #1809, holding game-thread BDA events until promotion and releasing unbound buffers, will follow as separate PRs after rework.

Changes

  • BufferCache::SynchronizeBda replaces SynchronizeBuffersInRange. It takes the queued ranges inside mapped memory and collects the runs that are still CPU-modified, with one tracker walk per buffer range.
  • All the runs go into one staging allocation. Copies into the same buffer share one copy command, and the copies sit between one pair of global barriers.
  • The collected copies are kept in a member, so their storage is reused from one draw to the next. Only the GPU thread synchronizes BDA, so it needs no lock.
  • Size cap: if the next buffer could push the upload past the 512 MiB staging ring, what has been collected so far is uploaded first. Without this, an upload past the ring's size would fall back to a one-off host allocation of the whole total. That could be a GB-sized allocation, which can fail on drivers with small upload heaps.

Correctness

  • The global barriers cover the same access and stage masks as the old per-buffer ones.
  • Pages are still write-protected as they are collected, before the guest data is read. A write that races with the read faults and queues its page for the next synchronization, so at worst a page is uploaded twice.
  • Mapping staging memory can submit or wait. It never runs deferred operations, so the buffers collected for the upload stay valid.

Testing

  • Octopath Traveler II: ran on a clean build of this branch, and everything looks fine.
  • New test BdaSyncBatchesBuffers in shader_recompiler_compute_tests: dirties pages in two separate buffers, including two separate runs in one buffer. It checks that one synchronization uploads each page into the right buffer at the right offset. It checks the data, not the number of staging allocations.
  • The existing BdaSyncUploads and BdaPageTableUploads tests pass unchanged.
  • No test covers the size cap. Reaching it needs over 512 MiB of dirty buffer pages, or a test-only way to set the ring size.
  • ctest on Windows: 63 of 65 pass. The two failures also fail on main:
    • vdecsw doesn't build, because std::aligned_alloc isn't available in MSVC's C runtime.
    • kernel_file_system crashes with 0xc0000028.
  • Linux and macOS CI: both currently fail on main, and #1922 fixes them.
**@⁠MrBigBritches** on GitHub · 2026-10-27 03:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932) `MrBigBritches:bda-sync-batch` → `main` · +276 −14 · 4 files · 1 commits · closed without merging Before every BDA draw, BDA synchronization uploads the CPU-written pages that shaders may read through buffer device addresses. It handled one buffer at a time. Each buffer that still had dirty pages took its own staging allocation and two whole-buffer barriers. A busy draw in Octopath Traveler II found a few hundred such buffers. Now all of a synchronization's copies go through one staging allocation, recorded between a single pair of global barriers. This is the first part of #1809, split out on its own. The other two parts of #1809, holding game-thread BDA events until promotion and releasing unbound buffers, will follow as separate PRs after rework. ## Changes - `BufferCache::SynchronizeBda` replaces `SynchronizeBuffersInRange`. It takes the queued ranges inside mapped memory and collects the runs that are still CPU-modified, with one tracker walk per buffer range. - All the runs go into one staging allocation. Copies into the same buffer share one copy command, and the copies sit between one pair of global barriers. - The collected copies are kept in a member, so their storage is reused from one draw to the next. Only the GPU thread synchronizes BDA, so it needs no lock. - **Size cap:** if the next buffer could push the upload past the 512 MiB staging ring, what has been collected so far is uploaded first. Without this, an upload past the ring's size would fall back to a one-off host allocation of the whole total. That could be a GB-sized allocation, which can fail on drivers with small upload heaps. ## Correctness - The global barriers cover the same access and stage masks as the old per-buffer ones. - Pages are still write-protected as they are collected, before the guest data is read. A write that races with the read faults and queues its page for the next synchronization, so at worst a page is uploaded twice. - Mapping staging memory can submit or wait. It never runs deferred operations, so the buffers collected for the upload stay valid. ## Testing - **Octopath Traveler II:** ran on a clean build of this branch, and everything looks fine. - **New test** `BdaSyncBatchesBuffers` in `shader_recompiler_compute_tests`: dirties pages in two separate buffers, including two separate runs in one buffer. It checks that one synchronization uploads each page into the right buffer at the right offset. It checks the data, not the number of staging allocations. - The existing `BdaSyncUploads` and `BdaPageTableUploads` tests pass unchanged. - No test covers the size cap. Reaching it needs over 512 MiB of dirty buffer pages, or a test-only way to set the ring size. - **ctest on Windows:** 63 of 65 pass. The two failures also fail on `main`: - `vdecsw` doesn't build, because `std::aligned_alloc` isn't available in MSVC's C runtime. - `kernel_file_system` crashes with `0xc0000028`. - **Linux and macOS CI:** both currently fail on `main`, and #1922 fixes them.
BDA synchronization synchronized every registered buffer that a queued
range touched, one buffer at a time. Each buffer that still had dirty
pages took its own staging allocation and two whole-buffer barriers. A
busy draw found a few hundred such buffers.

BufferCache::SynchronizeBda now takes the queued ranges inside mapped
memory and collects the runs that are still CPU-modified, with one
tracker walk per buffer range. It uploads them all through one staging
allocation, with the copies recorded between a single pair of global
barriers, and copies into the same buffer share one copy command. The
collected copies are kept in a member so their storage is reused.

If the collected copies could outgrow the staging ring, what has been
collected so far is uploaded first. Past the ring's size the upload
would otherwise fall back to a one-off host allocation of the whole
total.

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

@⁠coderabbitai[bot] on GitHub · 2026-10-27 03:31 UTC · original

Review in Change Stack →

Walkthrough

BufferCache now synchronizes CPU-modified BDA pages across mapped ranges and batches their uploads through staging memory. RenderContext::PrepareBda passes the mapped-range set to the cache. A Vulkan test checks synchronization and copied values across two cached buffers.

Suggested reviewers: nmzik

Priority: Low

Change: Refactor

Merge Risk: Moderate · up to 9eb20

Large BDA uploads can still require the one-off host allocation this change is meant to avoid. Enforce the staging limit during collection before merging.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: using one staging copy for BDA synchronization.
Description check Passed The description directly explains the BDA synchronization batching change, its rationale, correctness considerations, and testing results.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 7 functions across 3 files. (1 skipped: 1 too large.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • 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-27 03:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932#issuecomment-6433047439) <!-- 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/1932?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 --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> `BufferCache` now synchronizes CPU-modified BDA pages across mapped ranges and batches their uploads through staging memory. `RenderContext::PrepareBda` passes the mapped-range set to the cache. A Vulkan test checks synchronization and copied values across two cached buffers. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <strong>Priority: <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/priority-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> <!-- change_assessment_commit:"9eb20be515560e9a2e9799bb611f6b023405486e" --> **Change:** Refactor <!-- 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>9eb20</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `9eb20` --> <!-- final_review_risk_coverage:{"sourceCommitId":"9eb20be515560e9a2e9799bb611f6b023405486e","coveredCommitId":"9eb20be515560e9a2e9799bb611f6b023405486e","kind":"reviewed"} --> Large BDA uploads can still require the one-off host allocation this change is meant to avoid. Enforce the staging limit during collection 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 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: using one staging copy for BDA synchronization. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the BDA synchronization batching change, its rationale, correctness considerations, and testing results. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 7 functions across 3 files. (1 skipped: 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1932)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -752,0 +823,4 @@
}
}
upload.batches.push_back({&buffer, first, added});
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 03:31 UTC · original · edited 2026-10-27 03:45 UTC

Minor · Performance & Scalability · Quick win

Supported by static analysis

Script executed:

sed -n '730,895p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n 'ForEachUploadRange|StagingBufferSize|Staging.*Size|Allocate.*Staging' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache

Repository: KytyPS5/KytyPS5

Length of output: 7452


Script executed:

set -e
printf '%s\n' '--- UploadMemory and staging definitions ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'UploadMemory' -e 'ForEachUploadRange' -e 'class MemoryTracker' -e 'struct MemoryTracker' -e 'StagingCopyAlignment' -e 'm_staging_buffer' src
printf '%s\n' '--- likely definitions ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'ForEachUploadRange' src/graphics src/libs
printf '%s\n' '--- changed file diff ---'
git diff --find-renames 986721f5bca49e20d0e3312782882429dd5cfcb6 9eb20be515560e9a2e9799bb611f6b023405486e -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h
printf '%s\n' '--- base implementation excerpts ---'
git show 986721f5bca49e20d0e3312782882429dd5cfcb6:src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '380,510p;700,860p'
printf '%s\n' '--- candidate implementation excerpts ---'
sed -n '360,470p;730,855p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 32168


Script executed:

set -e
printf '%s\n' '--- memory tracker declaration and implementation ---'
nl -ba src/graphics/host_gpu/memoryTracker.h | sed -n '1,150p'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'class StreamBuffer' -e 'struct StreamBuffer' -e 'StreamBuffer::' -e 'StreamBuffer(' src/graphics src
printf '%s\n' '--- UploadMemory and constructor ---'
nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '1,110p;235,270p'
printf '%s\n' '--- StreamBuffer implementation candidates ---'
for f in $(rg -l -F --glob '*.{cpp,h,hpp}' -e 'class StreamBuffer' -e 'StreamBuffer::' src/graphics src); do
  echo "--- $f"
  nl -ba "$f" | sed -n '1,260p'
done

Repository: KytyPS5/KytyPS5

Length of output: 42013


Script executed:

set -e
printf '%s\n' '--- modified-range implementation and constants ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'ForEachModifiedRange' -e 'TRACKER_PAGE_SIZE' -e 'TRACKER_REGION_SIZE' -e 'DirtySource' src/graphics/host_gpu
printf '%s\n' '--- region manager declarations and implementation ---'
for f in $(rg -l -F --glob '*.{cpp,h,hpp}' -e 'ForEachModifiedRange' src/graphics/host_gpu); do
  echo "--- $f"
  nl -ba "$f" | sed -n '1,280p'
done
printf '%s\n' '--- BDA synchronization callers and mapped-range construction ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'SynchronizeBda' -e 'QueueBdaSync' -e 'TakeBdaSync' -e 'mapped' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -240

Repository: KytyPS5/KytyPS5

Length of output: 40301


Script executed:

set -e
printf '%s\n' '--- buffer creation and request paths ---'
nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '270,355p;600,735p'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'CreateBuffer(' -e 'ObtainBuffer(' -e 'SynchronizeBda(' -e 'BDA' -e 'max.*buffer' -e 'Maximum.*Buffer' -e '512 * MiB' -e '512 * 1024' src/graphics src | head -320
printf '%s\n' '--- guest range and relevant size constraints ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'struct GuestRange' -e 'class GuestRange' -e 'GuestRange {' -e 'kExtendedMemorySize' -e 'MAX_BUFFER' -e 'MaxBuffer' src | head -240

Repository: KytyPS5/KytyPS5

Length of output: 23212


Script executed:

set -e
printf '%s\n' '--- RenderContext BDA map and synchronization entrypoints ---'
nl -ba src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '70,150p'
nl -ba src/graphics/host_gpu/renderer/renderContext.h | sed -n '45,105p'
printf '%s\n' '--- draw synchronization call site ---'
nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1070,1110p'
printf '%s\n' '--- GuestRange contract ---'
nl -ba src/graphics/host_gpu/regionDefinitions.h | sed -n '1,45p'

Repository: KytyPS5/KytyPS5

Length of output: 10666


Flush the staging batch while collecting a large buffer.

CollectBdaBufferCopies checks the full overlap only before ForEachUploadRange. A mapped and invalidated BDA buffer can exceed 512 MiB. The tracker reports that buffer in multiple runs, so the callback can append more than 512 MiB after the pre-append flush. UploadMemory then falls back to a temporary host allocation for the full upload.

Suggested fix
 	auto&      upload = m_bda_upload;
-	const auto first  = upload.copies.size();
+	auto       first  = upload.copies.size();

 	// Most queued pages were uploaded by an ordinary binding after they were queued. The tracker
 	// only reports the runs of pages that are still CPU-modified, and marks them clean and
 	// write-protected as it reports them. Each run goes into the staging allocation after the
 	// previous one.
 	const auto add_copy = [&](uint64_t address, uint64_t size) noexcept {
+		if (upload.size + size > m_staging_buffer.Size()) {
+			if (upload.copies.size() != first) {
+				upload.batches.push_back(
+				    {&buffer, first, upload.copies.size() - first});
+			}
+			FlushBdaCopies();
+			first = upload.copies.size();
+		}
 		upload.copies.emplace_back(upload.size, buffer.Offset(address), size);
 		upload.sources.push_back(address);
 		upload.size += size;
 	};
Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

void BufferCache::CollectBdaBufferCopies(Buffer& buffer, uint64_t begin, uint64_t end) {
	// Past the staging ring's size, UploadMemory makes a one-off host allocation of the whole
	// upload. So if this range could push the upload past it, upload what was collected so far
	// first. The range size is an upper bound on what this buffer adds.
	if (m_bda_upload.size + (end - begin) > m_staging_buffer.Size()) {
		FlushBdaCopies();
	}
	auto&      upload = m_bda_upload;
	auto       first  = upload.copies.size();

	// Most queued pages were uploaded by an ordinary binding after they were queued. The tracker
	// only reports the runs of pages that are still CPU-modified, and marks them clean and
	// write-protected as it reports them. Each run goes into the staging allocation after the
	// previous one.
	const auto add_copy = [&](uint64_t address, uint64_t size) noexcept {
		if (upload.size + size > m_staging_buffer.Size()) {
			if (upload.copies.size() != first) {
				upload.batches.push_back(
				    {&buffer, first, upload.copies.size() - first});
			}
			FlushBdaCopies();
			first = upload.copies.size();
		}
		upload.copies.emplace_back(upload.size, buffer.Offset(address), size);
		upload.sources.push_back(address);
		upload.size += size;
	};
	m_memory_tracker.ForEachUploadRange(begin, end - begin, false, add_copy, []() noexcept {});

	const auto added = upload.copies.size() - first;
	// An ordinary binding already uploaded every page queued here.
	if (added == 0) {
		return;
	}

	// Copies into the same buffer that directly follow the previous batch are joined to it and
	// share one copy command.
	if (!upload.batches.empty()) {
		auto& last = upload.batches.back();
		if (last.buffer == &buffer && last.first + last.count == first) {
			last.count += added;
			return;
		}
	}
	upload.batches.push_back({&buffer, first, added});
}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 03:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932#discussion_r4384818130) · edited 2026-10-27 03:45 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** · **Performance & Scalability** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> Script executed: ```bash sed -n '730,895p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n 'ForEachUploadRange|StagingBufferSize|Staging.*Size|Allocate.*Staging' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache ``` Repository: KytyPS5/KytyPS5 Length of output: 7452 --- Script executed: ```bash set -e printf '%s\n' '--- UploadMemory and staging definitions ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'UploadMemory' -e 'ForEachUploadRange' -e 'class MemoryTracker' -e 'struct MemoryTracker' -e 'StagingCopyAlignment' -e 'm_staging_buffer' src printf '%s\n' '--- likely definitions ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'ForEachUploadRange' src/graphics src/libs printf '%s\n' '--- changed file diff ---' git diff --find-renames 986721f5bca49e20d0e3312782882429dd5cfcb6 9eb20be515560e9a2e9799bb611f6b023405486e -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h printf '%s\n' '--- base implementation excerpts ---' git show 986721f5bca49e20d0e3312782882429dd5cfcb6:src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '380,510p;700,860p' printf '%s\n' '--- candidate implementation excerpts ---' sed -n '360,470p;730,855p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 32168 --- Script executed: ```bash set -e printf '%s\n' '--- memory tracker declaration and implementation ---' nl -ba src/graphics/host_gpu/memoryTracker.h | sed -n '1,150p' rg -n -F --glob '*.{cpp,h,hpp}' -e 'class StreamBuffer' -e 'struct StreamBuffer' -e 'StreamBuffer::' -e 'StreamBuffer(' src/graphics src printf '%s\n' '--- UploadMemory and constructor ---' nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '1,110p;235,270p' printf '%s\n' '--- StreamBuffer implementation candidates ---' for f in $(rg -l -F --glob '*.{cpp,h,hpp}' -e 'class StreamBuffer' -e 'StreamBuffer::' src/graphics src); do echo "--- $f" nl -ba "$f" | sed -n '1,260p' done ``` Repository: KytyPS5/KytyPS5 Length of output: 42013 --- Script executed: ```bash set -e printf '%s\n' '--- modified-range implementation and constants ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'ForEachModifiedRange' -e 'TRACKER_PAGE_SIZE' -e 'TRACKER_REGION_SIZE' -e 'DirtySource' src/graphics/host_gpu printf '%s\n' '--- region manager declarations and implementation ---' for f in $(rg -l -F --glob '*.{cpp,h,hpp}' -e 'ForEachModifiedRange' src/graphics/host_gpu); do echo "--- $f" nl -ba "$f" | sed -n '1,280p' done printf '%s\n' '--- BDA synchronization callers and mapped-range construction ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'SynchronizeBda' -e 'QueueBdaSync' -e 'TakeBdaSync' -e 'mapped' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 40301 --- Script executed: ```bash set -e printf '%s\n' '--- buffer creation and request paths ---' nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '270,355p;600,735p' rg -n -F --glob '*.{cpp,h,hpp}' -e 'CreateBuffer(' -e 'ObtainBuffer(' -e 'SynchronizeBda(' -e 'BDA' -e 'max.*buffer' -e 'Maximum.*Buffer' -e '512 * MiB' -e '512 * 1024' src/graphics src | head -320 printf '%s\n' '--- guest range and relevant size constraints ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'struct GuestRange' -e 'class GuestRange' -e 'GuestRange {' -e 'kExtendedMemorySize' -e 'MAX_BUFFER' -e 'MaxBuffer' src | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 23212 --- Script executed: ```bash set -e printf '%s\n' '--- RenderContext BDA map and synchronization entrypoints ---' nl -ba src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '70,150p' nl -ba src/graphics/host_gpu/renderer/renderContext.h | sed -n '45,105p' printf '%s\n' '--- draw synchronization call site ---' nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1070,1110p' printf '%s\n' '--- GuestRange contract ---' nl -ba src/graphics/host_gpu/regionDefinitions.h | sed -n '1,45p' ``` Repository: KytyPS5/KytyPS5 Length of output: 10666 --- </dd> </dl> </details> **Flush the staging batch while collecting a large buffer.** `CollectBdaBufferCopies` checks the full overlap only before `ForEachUploadRange`. A mapped and invalidated BDA buffer can exceed 512 MiB. The tracker reports that buffer in multiple runs, so the callback can append more than 512 MiB after the pre-append flush. `UploadMemory` then falls back to a temporary host allocation for the full upload. <details> <summary>Suggested fix</summary> <dl> <dd> ```diff auto& upload = m_bda_upload; - const auto first = upload.copies.size(); + auto first = upload.copies.size(); // Most queued pages were uploaded by an ordinary binding after they were queued. The tracker // only reports the runs of pages that are still CPU-modified, and marks them clean and // write-protected as it reports them. Each run goes into the staging allocation after the // previous one. const auto add_copy = [&](uint64_t address, uint64_t size) noexcept { + if (upload.size + size > m_staging_buffer.Size()) { + if (upload.copies.size() != first) { + upload.batches.push_back( + {&buffer, first, upload.copies.size() - first}); + } + FlushBdaCopies(); + first = upload.copies.size(); + } upload.copies.emplace_back(upload.size, buffer.Offset(address), size); upload.sources.push_back(address); upload.size += size; }; ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion void BufferCache::CollectBdaBufferCopies(Buffer& buffer, uint64_t begin, uint64_t end) { // Past the staging ring's size, UploadMemory makes a one-off host allocation of the whole // upload. So if this range could push the upload past it, upload what was collected so far // first. The range size is an upper bound on what this buffer adds. if (m_bda_upload.size + (end - begin) > m_staging_buffer.Size()) { FlushBdaCopies(); } auto& upload = m_bda_upload; auto first = upload.copies.size(); // Most queued pages were uploaded by an ordinary binding after they were queued. The tracker // only reports the runs of pages that are still CPU-modified, and marks them clean and // write-protected as it reports them. Each run goes into the staging allocation after the // previous one. const auto add_copy = [&](uint64_t address, uint64_t size) noexcept { if (upload.size + size > m_staging_buffer.Size()) { if (upload.copies.size() != first) { upload.batches.push_back( {&buffer, first, upload.copies.size() - first}); } FlushBdaCopies(); first = upload.copies.size(); } upload.copies.emplace_back(upload.size, buffer.Offset(address), size); upload.sources.push_back(address); upload.size += size; }; m_memory_tracker.ForEachUploadRange(begin, end - begin, false, add_copy, []() noexcept {}); const auto added = upload.copies.size() - first; // An ordinary binding already uploaded every page queued here. if (added == 0) { return; } // Copies into the same buffer that directly follow the previous batch are joined to it and // share one copy command. if (!upload.batches.empty()) { auto& last = upload.batches.back(); if (last.buffer == &buffer && last.first + last.count == first) { last.count += added; return; } } upload.batches.push_back({&buffer, first, added}); } ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5c71890198ff2c8175c847a1 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 03:31 UTC · original · reviewed

Actionable comments posted: 1


Review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between db12f0c5fb and 9eb20be515.

Files selected for processing: 4
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 03:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932#pullrequestreview-5661901322) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** --- <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="16" height="16" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <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> - **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/db12f0c5fb1617b7ce5eaffba0d6be8d9b042bc1/.coderabbit.yaml>) - **Commit**: [db12f0c](<https://github.com/KytyPS5/KytyPS5/commit/db12f0c5fb1617b7ce5eaffba0d6be8d9b042bc1>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `c18334cb-5cf3-431a-b174-379889697e21` </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> Reviewing files that changed from the base of the PR and between db12f0c5fb1617b7ce5eaffba0d6be8d9b042bc1 and 9eb20be515560e9a2e9799bb611f6b023405486e. </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: 4</summary> <dl> <dd> * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </dd> </dl> </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=0bff6086-17f8-42bf-be7a-205963ecbeac attempt=57bc540d-d2ac-420d-9828-742afedc8d54 batch=1/1 -->
@ -752,0 +823,4 @@
}
}
upload.batches.push_back({&buffer, first, added});
}
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-27 03:45 UTC · original

A single buffer with more than 512 MiB of dirty pages still takes the one-off host allocation, the same as main, where SynchronizeBuffer uploads a buffer's dirty runs in one UploadMemory call. The pre-walk flush only keeps earlier buffers' copies out of that upload. Flushing inside the ForEachUploadRange callback isn't safe: it runs with the region's tracking spin lock held, and the flush can wait on the GPU and copy up to 512 MiB while guest write faults on those pages spin. If a cap is needed later, walking the range in ring-sized chunks keeps the flush outside the tracker walk.

**@⁠MrBigBritches** on GitHub · 2026-10-27 03:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932#discussion_r4384884156) A single buffer with more than 512 MiB of dirty pages still takes the one-off host allocation, the same as main, where SynchronizeBuffer uploads a buffer's dirty runs in one UploadMemory call. The pre-walk flush only keeps earlier buffers' copies out of that upload. Flushing inside the ForEachUploadRange callback isn't safe: it runs with the region's tracking spin lock held, and the flush can wait on the GPU and copy up to 512 MiB while guest write faults on those pages spin. If a cap is needed later, walking the range in ring-sized chunks keeps the flush outside the tracker walk.
@ -752,0 +823,4 @@
}
}
upload.batches.push_back({&buffer, first, added});
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 03:46 UTC · original

@⁠MrBigBritches You're right. SynchronizeBuffer already sends a buffer's collected dirty runs through one UploadMemory call. The pre-walk flush prevents earlier buffers' copies from enlarging that upload. It does not impose a strict per-buffer cap.

I withdraw this finding and the callback-flush suggestion. I overlooked the tracking spin lock held during the callback. GPU waits and large memory copies should not run under that lock.

If a strict cap becomes necessary, ring-sized range walks can keep each flush outside the tracker walk. No change is needed for this finding.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 03:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932#discussion_r4384886002) <!-- coderabbit-ai-generated:v1 --> @⁠MrBigBritches You're right. `SynchronizeBuffer` already sends a buffer's collected dirty runs through one `UploadMemory` call. The pre-walk flush prevents earlier buffers' copies from enlarging that upload. It does not impose a strict per-buffer cap. I withdraw this finding and the callback-flush suggestion. I overlooked the tracking spin lock held during the callback. GPU waits and large memory copies should not run under that lock. If a strict cap becomes necessary, ring-sized range walks can keep each flush outside the tracker walk. No change is needed for this finding. <!-- <review_comment_withdrawn> --> ✅ Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-27 04:49 UTC · original

Measurements from Octopath Traveler II, taken with a temporary per-second log of the emulator's debug counters. The logging isn't part of either PR.

I ran the same route on three builds, all based on main 986721f5:

  • main.
  • #1933 on its own.
  • #1933 together with this PR.

I didn't run this PR on its own, so its effect is the difference between the last two rows of each stretch.

Stretch Build BDA syncs/s FPS Faults per frame Upload MB per frame
Heavy scene (~2 BDA syncs per frame) main 100 50.2 1,675 6.5
#1933 100 50.0 1,802 7.0
#1933 + this PR 110 55.2 1,716 6.6
Burst of BDA draws (~35 per frame) main 2,127 53.9 3,259 12.7
#1933 2,402 59.0 2,044 7.9
#1933 + this PR 2,366 59.1 2,122 8.2
60 fps stretches all three 120 60 1,533–1,708 6.0–6.6
  • In the heavy scene, this PR lifts the frame rate by about 10%, from 50 to 55 fps. Faults and uploads per frame stay about the same. Each synchronization is just cheaper on the GPU thread: one staging allocation and one pair of barriers, where before each buffer still holding dirty pages got its own. That lets more frames through.
  • In the burst, both builds with #1933 reach the 60 fps cap, so this PR's effect there can't be seen.
  • Where the game is already at 60 fps, the builds don't differ beyond noise.

Each build ran once, so run-to-run variance isn't measured.

**@⁠MrBigBritches** on GitHub · 2026-10-27 04:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1932#issuecomment-6434026280) Measurements from Octopath Traveler II, taken with a temporary per-second log of the emulator's debug counters. The logging isn't part of either PR. I ran the same route on three builds, all based on `main` 986721f5: - `main`. - #1933 on its own. - #1933 together with this PR. I didn't run this PR on its own, so its effect is the difference between the last two rows of each stretch. | Stretch | Build | BDA syncs/s | FPS | Faults per frame | Upload MB per frame | |---|---|---|---|---|---| | **Heavy scene** (~2 BDA syncs per frame) | `main` | 100 | 50.2 | 1,675 | 6.5 | | | #1933 | 100 | 50.0 | 1,802 | 7.0 | | | #1933 + this PR | 110 | **55.2** | 1,716 | 6.6 | | **Burst of BDA draws** (~35 per frame) | `main` | 2,127 | 53.9 | 3,259 | 12.7 | | | #1933 | 2,402 | 59.0 | 2,044 | 7.9 | | | #1933 + this PR | 2,366 | 59.1 | 2,122 | 8.2 | | **60 fps stretches** | all three | 120 | 60 | 1,533–1,708 | 6.0–6.6 | - **In the heavy scene, this PR lifts the frame rate by about 10%, from 50 to 55 fps.** Faults and uploads per frame stay about the same. Each synchronization is just cheaper on the GPU thread: one staging allocation and one pair of barriers, where before each buffer still holding dirty pages got its own. That lets more frames through. - **In the burst, both builds with #1933 reach the 60 fps cap,** so this PR's effect there can't be seen. - **Where the game is already at 60 fps,** the builds don't differ beyond noise. Each build ran once, so run-to-run variance isn't measured.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.