gpu: stage buffer downloads in batches instead of aborting on a large one #842

Closed
github-bot wants to merge 2 commits from gh-pr/842/head into gh-pr/842/base
Owner

@⁠theantipopau on GitHub · 2026-09-26 02:18 UTC · original
theantipopau:buffer-download-chunk → main · +328 −50 · 7 files · 2 commits · closed without merging

Problem

BufferCache::DownloadBufferMemory reserved one staging region for a whole buffer read-back and aborted the process if it did not fit:

const auto [mapped, offset] = m_download_buffer.Map(total_size, 64);
if (mapped == nullptr) {
    EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n");
}

total_size is the sum of every dirty range in the download, so the reservation grows with how much of the buffer the GPU dirtied. The limit is not a matter of timing. StreamBuffer::Map contains:

if (mapped_size > Size()) {
    return {nullptr, 0};
}

That is a hard ceiling, checked before any waiting: a single reservation larger than the whole buffer can never succeed, even on an empty, fully drained staging buffer. So any game whose dirty ranges for one download total more than 64 MiB kills the emulator deterministically, and no amount of draining or retrying would have helped. This is what #829 reports for GTA V.

Fix

Stage the download in batches instead. Each batch reserves its own region, records its own barrier and copy, and registers its own deferred write-back. The stream keeps each region reserved until its write-back has consumed it, so consecutive batches cannot overlap.

A range larger than the whole staging buffer is now split across batches rather than dropped, which is the case that could never work before.

Two supporting details:

  • StreamBuffer::MaxReservation() reports the largest reservation Map will accept. It rounds down to a whole device atom, because Map rounds a non-coherent reservation up to nonCoherentAtomSize before comparing it with the buffer size. Sizing a batch to Size() would therefore still be rejected on a device whose atom does not divide the capacity evenly.
  • The packing is unchanged for a download that already fit: each range is still padded up to a 64-byte boundary and the batch total accumulates the same AlignUp(size, 64) sum as before, so offsets and totals are byte-identical to the old single-reservation path.

Tests

SplitBufferDownload is deliberately pure, so tests/BufferDownloadBatchTests.cpp covers the packing with no device:

  • a download that fits stays in one batch, with byte-identical totals to the old packing;
  • packed ranges still land on separate cache lines (a 100-byte range is padded to 128, so the next starts at 128, not 100);
  • a download larger than the capacity is split, and every range is still tiled exactly once;
  • a single range larger than the capacity is split — the case that used to abort the process;
  • a sub-alignment tail is copied rather than dropped;
  • a capacity below the alignment, a zero alignment and a zero capacity stage nothing;
  • forty small ranges pack greedily, each batch within the capacity.

The round-trip check flattens the batches and verifies each input range is tiled by consecutive copies that start where the previous ended and cover the whole range, so the split is proven lossless rather than merely summing correctly.

I confirmed the tests are load-bearing by disabling the batch budget guard: the suite then fails instead of passing.

Verification

  • buffer_download_batch_tests passes, also compiled clean under -Wall -Wextra with g++ directly.
  • kyty_emulator builds and links.
  • shader_recompiler_compute_tests --buffer-cache-range-only still passes its host-side cases, including LeastRecentlyUsedCache.
  • git diff --check clean, no line over the 100-column limit.

Not run: the GPU half of the compute tests, because this machine's AMD driver lacks VK_EXT_attachment_feedback_loop_dynamic_state, so production rasterization features are not supported locally. The copy and barrier path is unchanged apart from being issued per batch, but it has not been exercised on a real device here.

**@⁠theantipopau** on GitHub · 2026-09-26 02:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842) `theantipopau:buffer-download-chunk` → `main` · +328 −50 · 7 files · 2 commits · closed without merging ## Problem `BufferCache::DownloadBufferMemory` reserved **one** staging region for a whole buffer read-back and aborted the process if it did not fit: ```cpp const auto [mapped, offset] = m_download_buffer.Map(total_size, 64); if (mapped == nullptr) { EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n"); } ``` `total_size` is the sum of every dirty range in the download, so the reservation grows with how much of the buffer the GPU dirtied. The limit is not a matter of timing. `StreamBuffer::Map` contains: ```cpp if (mapped_size > Size()) { return {nullptr, 0}; } ``` That is a hard ceiling, checked before any waiting: a single reservation larger than the whole buffer can **never** succeed, even on an empty, fully drained staging buffer. So any game whose dirty ranges for one download total more than 64 MiB kills the emulator deterministically, and no amount of draining or retrying would have helped. This is what #829 reports for GTA V. ## Fix Stage the download in batches instead. Each batch reserves its own region, records its own barrier and copy, and registers its own deferred write-back. The stream keeps each region reserved until its write-back has consumed it, so consecutive batches cannot overlap. A range larger than the whole staging buffer is now **split across batches** rather than dropped, which is the case that could never work before. Two supporting details: - **`StreamBuffer::MaxReservation()`** reports the largest reservation `Map` will accept. It rounds *down* to a whole device atom, because `Map` rounds a non-coherent reservation *up* to `nonCoherentAtomSize` before comparing it with the buffer size. Sizing a batch to `Size()` would therefore still be rejected on a device whose atom does not divide the capacity evenly. - The packing is unchanged for a download that already fit: each range is still padded up to a 64-byte boundary and the batch total accumulates the same `AlignUp(size, 64)` sum as before, so offsets and totals are byte-identical to the old single-reservation path. ## Tests `SplitBufferDownload` is deliberately pure, so `tests/BufferDownloadBatchTests.cpp` covers the packing with no device: - a download that fits stays in one batch, with byte-identical totals to the old packing; - packed ranges still land on separate cache lines (a 100-byte range is padded to 128, so the next starts at 128, not 100); - a download larger than the capacity is split, and every range is still tiled exactly once; - **a single range larger than the capacity is split** — the case that used to abort the process; - a sub-alignment tail is copied rather than dropped; - a capacity below the alignment, a zero alignment and a zero capacity stage nothing; - forty small ranges pack greedily, each batch within the capacity. The round-trip check flattens the batches and verifies each input range is tiled by consecutive copies that start where the previous ended and cover the whole range, so the split is proven lossless rather than merely summing correctly. I confirmed the tests are load-bearing by disabling the batch budget guard: the suite then fails instead of passing. ## Verification - `buffer_download_batch_tests` passes, also compiled clean under `-Wall -Wextra` with g++ directly. - `kyty_emulator` builds and links. - `shader_recompiler_compute_tests --buffer-cache-range-only` still passes its host-side cases, including `LeastRecentlyUsedCache`. - `git diff --check` clean, no line over the 100-column limit. Not run: the GPU half of the compute tests, because this machine's AMD driver lacks `VK_EXT_attachment_feedback_loop_dynamic_state`, so `production rasterization features are not supported` locally. The copy and barrier path is unchanged apart from being issued per batch, but it has not been exercised on a real device here.
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
StreamBuffer::Map can wait for a pending use of the staging buffer to
retire, and waiting submits the current command buffer and begins a new
one. Capture EndRendering and the native handle inside the batch loop so
every batch records into the command buffer that is current at that
point, matching the original single-Map ordering.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:40 +00:00
github-bot closed this pull request 2026-11-26 09:34:40 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:25 UTC · original · edited 2026-09-26 03:13 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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: 1a6fed33-6df6-443e-8cf5-9a231fde17f9

📥 Commits

Reviewing files that changed from the base of the PR and between 858dda5963 and 338380c1c6.

📒 Files selected for processing (1)
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/graphics/host_gpu/renderer/cache/bufferCache.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.


📝 Walkthrough

Walkthrough

The change adds aligned batching for dirty GPU buffer downloads. StreamBuffer exposes the maximum reservation size, and BufferCache::DownloadBufferMemory uses that limit to split transfers into batches. New tests cover batch sizing, alignment, range coverage, and unusable capacity. CMake builds and registers the test executable.

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 33838

The reviewed batching and write-back paths preserve the intended download behavior. No identified issue remains to block merge.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 858dd

A staging-buffer wrap can replace the active graphics command buffer while a download continues using its earlier handle. This may cause an emulator failure or incorrect backing-memory writes. The identified exposure is within the emulator’s graphics and memory path; broader access is not established.

Retained concerns

  • Medium · security · inferred: A download can retain a native command handle across a staging Map that submits that command and starts a new one. Subsequent copies may be recorded against the retired handle, threatening download completion and the correctness of deferred writes to guest backing memory.
Security review details

Security Blast Radius

  • inferred — A workload influencing GPU-dirty download ranges can reach the wrap path through the emulator’s renderer. The supported outcome scope is the emulator’s command execution and guest backing-memory writeback, not a demonstrated cross-service or host-privilege transition.

Security Findings and Attack Paths

  • inferred — If a batch Map wraps over a reservation from the current tick, the scheduler can submit and replace the command whose handle was captured before the loop. Recording the next copy through that handle can fail or leave the deferred backing-memory write without its intended copy.

Trust Boundaries and Controls

  • observed — Batch sizes are bounded by the stream buffer’s atom-aware reservation limit, and reservation reuse waits for GPU and deferred download work. Neither control guarantees that a command handle captured before Map remains active afterward.

Hardening Proposals

  • proposed — Acquire the active native command handle after each potentially waiting Map, and exercise a wrap that submits the current tick before a later batch records its copy.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: staging large buffer downloads in multiple batches instead of aborting.
Description check ✅ Passed The description directly explains the failure, batching fix, supporting APIs, tests, and verification results for the changeset.
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.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#issuecomment-5842358608) · edited 2026-09-26 03:13 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/842"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `1a6fed33-6df6-443e-8cf5-9a231fde17f9` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 858dda5963d232c74586a88aad97eadfc2f77cfb and 338380c1c62063493a7d7ef370554dd461fc9d56. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/graphics/host_gpu/renderer/cache/bufferCache.cpp </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. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change adds aligned batching for dirty GPU buffer downloads. `StreamBuffer` exposes the maximum reservation size, and `BufferCache::DownloadBufferMemory` uses that limit to split transfers into batches. New tests cover batch sizing, alignment, range coverage, and unusable capacity. CMake builds and registers the test executable. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"338380c1c62063493a7d7ef370554dd461fc9d56" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `33838` <!-- final_review_risk_coverage:{"sourceCommitId":"338380c1c62063493a7d7ef370554dd461fc9d56","coveredCommitId":"338380c1c62063493a7d7ef370554dd461fc9d56","kind":"reviewed"} --> The reviewed batching and write-back paths preserve the intended download behavior. No identified issue remains to block merge. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `858dd` A staging-buffer wrap can replace the active graphics command buffer while a download continues using its earlier handle. This may cause an emulator failure or incorrect backing-memory writes. The identified exposure is within the emulator’s graphics and memory path; broader access is not established. **Retained concerns** - **Medium · security · inferred:** A download can retain a native command handle across a staging Map that submits that command and starts a new one. Subsequent copies may be recorded against the retired handle, threatening download completion and the correctness of deferred writes to guest backing memory. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — A workload influencing GPU-dirty download ranges can reach the wrap path through the emulator’s renderer. The supported outcome scope is the emulator’s command execution and guest backing-memory writeback, not a demonstrated cross-service or host-privilege transition. **Security Findings and Attack Paths** - _inferred_ — If a batch Map wraps over a reservation from the current tick, the scheduler can submit and replace the command whose handle was captured before the loop. Recording the next copy through that handle can fail or leave the deferred backing-memory write without its intended copy. **Trust Boundaries and Controls** - _observed_ — Batch sizes are bounded by the stream buffer’s atom-aware reservation limit, and reservation reuse waits for GPU and deferred download work. Neither control guarantees that a command handle captured before Map remains active afterward. **Hardening Proposals** - _proposed_ — Acquire the active native command handle after each potentially waiting Map, and exercise a wrap that submits the current tick before a later batch records its copy. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 10.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 6 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :--------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: staging large buffer downloads in multiple batches instead of aborting. | | Description check | ✅ Passed | The description directly explains the failure, batching fix, supporting APIs, tests, and verification results for the changeset. | | 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. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:25 UTC · original · edited 2026-09-26 03:14 UTC
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 141 (outdated):

@@ -109,68 +110,77 @@ void BufferCache::DeleteBuffer(BufferId id) {
 }
 
 bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) {
-	std::vector<vk::BufferCopy> copies;
-	uint64_t                    total_size     = 0;
-	const auto                  buffer_address = buffer.CpuAddress();
+	std::vector<BufferDownloadRange> ranges;
+	const auto                       buffer_address = buffer.CpuAddress();
 	m_memory_tracker.ForEachDownloadRange<false>(
 	    vaddr, size, [&](uint64_t address, uint64_t bytes) noexcept {
 		    m_memory_tracker.ValidateGpuDirtyPages(m_gpu_modified_ranges, address, bytes,
 		                                           "buffer download");
 		    m_gpu_modified_ranges.ForEachInRange(address, bytes, [&](uint64_t start, uint64_t end) {
-			    copies.emplace_back(start - buffer_address, total_size, end - start);
-			    // Keep packed ranges on separate cache lines, as in shadPS4.
-			    total_size += Common::AlignUp(end - start, 64);
+			    ranges.push_back({start - buffer_address, end - start});
 		    });
 		    m_gpu_modified_ranges.Subtract(address, bytes);
 	    });
-	if (copies.empty()) {
+	if (ranges.empty()) {
 		return false;
 	}
 
-	const auto [mapped, offset] = m_download_buffer.Map(total_size, 64);
-	if (mapped == nullptr) {
-		EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n");
-	}
-	m_download_buffer.Commit();
-	for (auto& copy: copies) {
-		copy.dstOffset += offset;
-	}
-
+	// StreamBuffer::Map refuses a single reservation larger than the staging buffer instead of
+	// waiting for space, so a download whose dirty ranges total more than one staging pass
+	// could never be mapped and used to abort the process here. Stage it in batches instead:
+	// each reserves its own region, and the stream keeps that region reserved until its
+	// deferred write-back has consumed it, so consecutive batches cannot overlap.
 	auto& command = m_scheduler.Current();
 	command.EndRendering();
-	const auto              native = command.Handle();
-	vk::BufferMemoryBarrier before {};
-	before.srcAccessMask       = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite;
-	before.dstAccessMask       = vk::AccessFlagBits::eTransferRead;
-	before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-	before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-	before.buffer              = buffer.Handle();
-	before.offset              = 0;
-	before.size                = buffer.Size();
-	native.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
-	                       vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, &before, 0,
-	                       nullptr);
-	native.copyBuffer(buffer.Handle(), m_download_buffer.Handle(),
-	                  static_cast<uint32_t>(copies.size()), copies.data());
-
-	auto after          = before;
-	after.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
-	after.dstAccessMask = vk::AccessFlagBits::eHostRead;
-	after.buffer        = m_download_buffer.Handle();
-	after.offset        = offset;
-	after.size          = total_size;
-	native.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
-	                       vk::PipelineStageFlagBits::eAllCommands |
-	                           vk::PipelineStageFlagBits::eHost,
-	                       {}, 0, nullptr, 1, &after, 0, nullptr);
-	m_scheduler.DeferPriorityOperation([this, mapped, offset, total_size, buffer_address,
-	                                    copies = std::move(copies)] {
-		m_download_buffer.Invalidate(offset, total_size);
-		for (const auto& copy: copies) {
-			Libs::LibKernel::Memory::WriteBacking(buffer_address + copy.srcOffset,
-			                                      mapped + (copy.dstOffset - offset), copy.size);
+	const auto native = command.Handle();
+	for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) {
+		const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64);
+		if (mapped == nullptr) {
+			EXIT("BufferCache: download batch could not be staged\n");
 		}
-	});
+		m_download_buffer.Commit();

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C8 '\b(Wait|CurrentTick|Flush|Submit)\s*\(' $(fd -i commandScheduler)

Repository: KytyPS5/KytyPS5

Length of output: 18197


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- buffer cache function and declarations ---'
rg -n -C12 'DownloadBufferMemory|SplitBufferDownload|m_download_buffer|const auto native|BeginRendering|EndRendering' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h
printf '%s\n' '--- scheduler transition and current definitions ---'
rg -n -C18 'BeginNext|CommandScheduler::Current|CommandScheduler::Submit|CommandScheduler::Wait|CommandScheduler::BeginCommand' src/graphics/host_gpu/renderer/commandScheduler.cpp
printf '%s\n' '--- command and stream buffer bindings ---'
rg -n -C12 'class CommandBuffer|Handle\\(\\)|Map\\(|Commit\\(|WaitPendingOperations' src/graphics/host_gpu/renderer -g '*.h' -g '*.cpp'

Repository: KytyPS5/KytyPS5

Length of output: 32832


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- buffer cache function and declarations ---'
rg -n -C12 'DownloadBufferMemory|SplitBufferDownload|m_download_buffer|const auto native|BeginRendering|EndRendering' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h
printf '%s\n' '--- scheduler transition and current definitions ---'
rg -n -C18 'BeginNext|CommandScheduler::Current|CommandScheduler::Submit|CommandScheduler::Wait|CommandScheduler::BeginCommand' src/graphics/host_gpu/renderer/commandScheduler.cpp
printf '%s\n' '--- command and stream buffer bindings ---'
rg -n -C12 'class CommandBuffer|Handle\(\)|Map\(|Commit\(|WaitPendingOperations' src/graphics/host_gpu/renderer -g '*.h' -g '*.cpp'

Repository: KytyPS5/KytyPS5

Length of output: 42288


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate files ---'
fd -i 'stream|command.*buffer|buffer.*stream' src/graphics/host_gpu/renderer
printf '%s\n' '--- exact stream-buffer methods and wait calls ---'
rg -n -C20 'StreamBuffer::(Map|Commit|WaitPendingOperations|MaxReservation)|WaitPendingOperations|Scheduler\(\)\.Wait|m_scheduler\.Wait' src/graphics/host_gpu/renderer
printf '%s\n' '--- command-buffer declaration and handle method ---'
rg -n -C15 'class CommandBuffer|struct CommandBuffer|CommandBuffer::Handle|Handle\(\) const|Handle\(\)' src/graphics/host_gpu/renderer -g '*.h' -g '*.cpp' | head -240

Repository: KytyPS5/KytyPS5

Length of output: 42291


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,260p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10778


🏁 Script executed:

#!/bin/bash
set -e
sed -n '250,430p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp

Repository: KytyPS5/KytyPS5

Length of output: 3320


Refresh the command handle after a staging-buffer wrap.

Map can wait when a batch wraps. If the watch belongs to the current tick, CommandScheduler::Wait submits that command and starts a new one. The loop still uses the native handle captured before Map, so later batches can record into the submitted command buffer.

🐛 Suggested fix
 	auto& command = m_scheduler.Current();
 	command.EndRendering();
-	const auto native = command.Handle();
 	for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) {
 		const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64);
 		if (mapped == nullptr) {
 			EXIT("BufferCache: download batch could not be staged\n");
 		}
 		m_download_buffer.Commit();
+		command.EndRendering();
+		const auto native = command.Handle();
📝 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.

	for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) {
		const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64);
		if (mapped == nullptr) {
			EXIT("BufferCache: download batch could not be staged\n");
		}
		m_download_buffer.Commit();
		command.EndRendering();
		const auto native = command.Handle();

✅ Addressed in commit 338380c

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#discussion_r4109877442) · edited 2026-09-26 03:14 UTC On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 141 (outdated): ```diff @@ -109,68 +110,77 @@ void BufferCache::DeleteBuffer(BufferId id) { } bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) { - std::vector<vk::BufferCopy> copies; - uint64_t total_size = 0; - const auto buffer_address = buffer.CpuAddress(); + std::vector<BufferDownloadRange> ranges; + const auto buffer_address = buffer.CpuAddress(); m_memory_tracker.ForEachDownloadRange<false>( vaddr, size, [&](uint64_t address, uint64_t bytes) noexcept { m_memory_tracker.ValidateGpuDirtyPages(m_gpu_modified_ranges, address, bytes, "buffer download"); m_gpu_modified_ranges.ForEachInRange(address, bytes, [&](uint64_t start, uint64_t end) { - copies.emplace_back(start - buffer_address, total_size, end - start); - // Keep packed ranges on separate cache lines, as in shadPS4. - total_size += Common::AlignUp(end - start, 64); + ranges.push_back({start - buffer_address, end - start}); }); m_gpu_modified_ranges.Subtract(address, bytes); }); - if (copies.empty()) { + if (ranges.empty()) { return false; } - const auto [mapped, offset] = m_download_buffer.Map(total_size, 64); - if (mapped == nullptr) { - EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n"); - } - m_download_buffer.Commit(); - for (auto& copy: copies) { - copy.dstOffset += offset; - } - + // StreamBuffer::Map refuses a single reservation larger than the staging buffer instead of + // waiting for space, so a download whose dirty ranges total more than one staging pass + // could never be mapped and used to abort the process here. Stage it in batches instead: + // each reserves its own region, and the stream keeps that region reserved until its + // deferred write-back has consumed it, so consecutive batches cannot overlap. auto& command = m_scheduler.Current(); command.EndRendering(); - const auto native = command.Handle(); - vk::BufferMemoryBarrier before {}; - before.srcAccessMask = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite; - before.dstAccessMask = vk::AccessFlagBits::eTransferRead; - before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - before.buffer = buffer.Handle(); - before.offset = 0; - before.size = buffer.Size(); - native.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, - vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, &before, 0, - nullptr); - native.copyBuffer(buffer.Handle(), m_download_buffer.Handle(), - static_cast<uint32_t>(copies.size()), copies.data()); - - auto after = before; - after.srcAccessMask = vk::AccessFlagBits::eTransferWrite; - after.dstAccessMask = vk::AccessFlagBits::eHostRead; - after.buffer = m_download_buffer.Handle(); - after.offset = offset; - after.size = total_size; - native.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eAllCommands | - vk::PipelineStageFlagBits::eHost, - {}, 0, nullptr, 1, &after, 0, nullptr); - m_scheduler.DeferPriorityOperation([this, mapped, offset, total_size, buffer_address, - copies = std::move(copies)] { - m_download_buffer.Invalidate(offset, total_size); - for (const auto& copy: copies) { - Libs::LibKernel::Memory::WriteBacking(buffer_address + copy.srcOffset, - mapped + (copy.dstOffset - offset), copy.size); + const auto native = command.Handle(); + for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) { + const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64); + if (mapped == nullptr) { + EXIT("BufferCache: download batch could not be staged\n"); } - }); + m_download_buffer.Commit(); ``` _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C8 '\b(Wait|CurrentTick|Flush|Submit)\s*\(' $(fd -i commandScheduler) ``` Repository: KytyPS5/KytyPS5 Length of output: 18197 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- buffer cache function and declarations ---' rg -n -C12 'DownloadBufferMemory|SplitBufferDownload|m_download_buffer|const auto native|BeginRendering|EndRendering' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h printf '%s\n' '--- scheduler transition and current definitions ---' rg -n -C18 'BeginNext|CommandScheduler::Current|CommandScheduler::Submit|CommandScheduler::Wait|CommandScheduler::BeginCommand' src/graphics/host_gpu/renderer/commandScheduler.cpp printf '%s\n' '--- command and stream buffer bindings ---' rg -n -C12 'class CommandBuffer|Handle\\(\\)|Map\\(|Commit\\(|WaitPendingOperations' src/graphics/host_gpu/renderer -g '*.h' -g '*.cpp' ``` Repository: KytyPS5/KytyPS5 Length of output: 32832 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- buffer cache function and declarations ---' rg -n -C12 'DownloadBufferMemory|SplitBufferDownload|m_download_buffer|const auto native|BeginRendering|EndRendering' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h printf '%s\n' '--- scheduler transition and current definitions ---' rg -n -C18 'BeginNext|CommandScheduler::Current|CommandScheduler::Submit|CommandScheduler::Wait|CommandScheduler::BeginCommand' src/graphics/host_gpu/renderer/commandScheduler.cpp printf '%s\n' '--- command and stream buffer bindings ---' rg -n -C12 'class CommandBuffer|Handle\(\)|Map\(|Commit\(|WaitPendingOperations' src/graphics/host_gpu/renderer -g '*.h' -g '*.cpp' ``` Repository: KytyPS5/KytyPS5 Length of output: 42288 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- candidate files ---' fd -i 'stream|command.*buffer|buffer.*stream' src/graphics/host_gpu/renderer printf '%s\n' '--- exact stream-buffer methods and wait calls ---' rg -n -C20 'StreamBuffer::(Map|Commit|WaitPendingOperations|MaxReservation)|WaitPendingOperations|Scheduler\(\)\.Wait|m_scheduler\.Wait' src/graphics/host_gpu/renderer printf '%s\n' '--- command-buffer declaration and handle method ---' rg -n -C15 'class CommandBuffer|struct CommandBuffer|CommandBuffer::Handle|Handle\(\) const|Handle\(\)' src/graphics/host_gpu/renderer -g '*.h' -g '*.cpp' | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 42291 --- 🏁 Script executed: ```bash #!/bin/bash set -e sed -n '1,260p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10778 --- 🏁 Script executed: ```bash #!/bin/bash set -e sed -n '250,430p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 3320 --- </details> **Refresh the command handle after a staging-buffer wrap.** `Map` can wait when a batch wraps. If the watch belongs to the current tick, `CommandScheduler::Wait` submits that command and starts a new one. The loop still uses the `native` handle captured before `Map`, so later batches can record into the submitted command buffer. <details> <summary>🐛 Suggested fix</summary> ```diff auto& command = m_scheduler.Current(); command.EndRendering(); - const auto native = command.Handle(); for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) { const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64); if (mapped == nullptr) { EXIT("BufferCache: download batch could not be staged\n"); } m_download_buffer.Commit(); + command.EndRendering(); + const auto native = command.Handle(); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **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 for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) { const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64); if (mapped == nullptr) { EXIT("BufferCache: download batch could not be staged\n"); } m_download_buffer.Commit(); command.EndRendering(); const auto native = command.Handle(); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:79c05e98a6ca9da6d1224004 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 338380c
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:25 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: ea2744cf-9899-4c59-ad80-e8f1775a3856

📥 Commits

Reviewing files that changed from the base of the PR and between fd2e15ee73 and 858dda5963.

📒 Files selected for processing (7)
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferDownloadBatch.cpp
  • src/graphics/host_gpu/renderer/cache/bufferDownloadBatch.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/streamBuffer.h
  • tests/BufferDownloadBatchTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#pullrequestreview-5324203669) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `ea2744cf-9899-4c59-ad80-e8f1775a3856` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between fd2e15ee737ea9a671619246129bc2aae7e0bfda and 858dda5963d232c74586a88aad97eadfc2f77cfb. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferDownloadBatch.cpp` * `src/graphics/host_gpu/renderer/cache/bufferDownloadBatch.h` * `src/graphics/host_gpu/renderer/cache/streamBuffer.cpp` * `src/graphics/host_gpu/renderer/cache/streamBuffer.h` * `tests/BufferDownloadBatchTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 03:10 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 141 (outdated):

@@ -109,68 +110,77 @@ void BufferCache::DeleteBuffer(BufferId id) {
 }
 
 bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) {
-	std::vector<vk::BufferCopy> copies;
-	uint64_t                    total_size     = 0;
-	const auto                  buffer_address = buffer.CpuAddress();
+	std::vector<BufferDownloadRange> ranges;
+	const auto                       buffer_address = buffer.CpuAddress();
 	m_memory_tracker.ForEachDownloadRange<false>(
 	    vaddr, size, [&](uint64_t address, uint64_t bytes) noexcept {
 		    m_memory_tracker.ValidateGpuDirtyPages(m_gpu_modified_ranges, address, bytes,
 		                                           "buffer download");
 		    m_gpu_modified_ranges.ForEachInRange(address, bytes, [&](uint64_t start, uint64_t end) {
-			    copies.emplace_back(start - buffer_address, total_size, end - start);
-			    // Keep packed ranges on separate cache lines, as in shadPS4.
-			    total_size += Common::AlignUp(end - start, 64);
+			    ranges.push_back({start - buffer_address, end - start});
 		    });
 		    m_gpu_modified_ranges.Subtract(address, bytes);
 	    });
-	if (copies.empty()) {
+	if (ranges.empty()) {
 		return false;
 	}
 
-	const auto [mapped, offset] = m_download_buffer.Map(total_size, 64);
-	if (mapped == nullptr) {
-		EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n");
-	}
-	m_download_buffer.Commit();
-	for (auto& copy: copies) {
-		copy.dstOffset += offset;
-	}
-
+	// StreamBuffer::Map refuses a single reservation larger than the staging buffer instead of
+	// waiting for space, so a download whose dirty ranges total more than one staging pass
+	// could never be mapped and used to abort the process here. Stage it in batches instead:
+	// each reserves its own region, and the stream keeps that region reserved until its
+	// deferred write-back has consumed it, so consecutive batches cannot overlap.
 	auto& command = m_scheduler.Current();
 	command.EndRendering();
-	const auto              native = command.Handle();
-	vk::BufferMemoryBarrier before {};
-	before.srcAccessMask       = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite;
-	before.dstAccessMask       = vk::AccessFlagBits::eTransferRead;
-	before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-	before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-	before.buffer              = buffer.Handle();
-	before.offset              = 0;
-	before.size                = buffer.Size();
-	native.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
-	                       vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, &before, 0,
-	                       nullptr);
-	native.copyBuffer(buffer.Handle(), m_download_buffer.Handle(),
-	                  static_cast<uint32_t>(copies.size()), copies.data());
-
-	auto after          = before;
-	after.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
-	after.dstAccessMask = vk::AccessFlagBits::eHostRead;
-	after.buffer        = m_download_buffer.Handle();
-	after.offset        = offset;
-	after.size          = total_size;
-	native.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
-	                       vk::PipelineStageFlagBits::eAllCommands |
-	                           vk::PipelineStageFlagBits::eHost,
-	                       {}, 0, nullptr, 1, &after, 0, nullptr);
-	m_scheduler.DeferPriorityOperation([this, mapped, offset, total_size, buffer_address,
-	                                    copies = std::move(copies)] {
-		m_download_buffer.Invalidate(offset, total_size);
-		for (const auto& copy: copies) {
-			Libs::LibKernel::Memory::WriteBacking(buffer_address + copy.srcOffset,
-			                                      mapped + (copy.dstOffset - offset), copy.size);
+	const auto native = command.Handle();
+	for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) {
+		const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64);
+		if (mapped == nullptr) {
+			EXIT("BufferCache: download batch could not be staged\n");
 		}
-	});
+		m_download_buffer.Commit();

Fixed in 338380c1.

Confirmed the hazard end-to-end before patching: StreamBuffer::Map (streamBuffer.cpp:278) calls WaitPendingOperations, and CommandScheduler::Wait (commandScheduler.cpp:196-204) submits the current command buffer and calls BeginNext() when the waited tick is the current one, so the pre-loop native could indeed point at a submitted vk::CommandBuffer for all batches after the first wrap-wait. The original single-Map upstream code captured command.Handle() after Map, so only the batched rewrite introduced the reorder.

The fix moves EndRendering() + Handle() inside the loop after Map/Commit:

  • Map records nothing, so capturing after it (and after Commit, which only flushes/advances offsets) keeps each batch's barriers and copyBuffer on the command buffer that is current at that point; a wait-cycled buffer yields the fresh handle.
  • EndRendering() on a freshly re-begun buffer is a no-op (m_rendering == false after CommandBuffer::End() → EndRendering()), and when no wait happened it still ends the render pass exactly once as before.
  • Per-batch copies were already loop-local, so nothing else captured the stale handle.

Rebuilt buffer_download_batch_tests + kyty_emulator clean; the batch suite passes and host-side --buffer-cache-range-only cases are unchanged.

**@⁠theantipopau** on GitHub · 2026-09-26 03:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#discussion_r4109983789) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 141 (outdated): ```diff @@ -109,68 +110,77 @@ void BufferCache::DeleteBuffer(BufferId id) { } bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) { - std::vector<vk::BufferCopy> copies; - uint64_t total_size = 0; - const auto buffer_address = buffer.CpuAddress(); + std::vector<BufferDownloadRange> ranges; + const auto buffer_address = buffer.CpuAddress(); m_memory_tracker.ForEachDownloadRange<false>( vaddr, size, [&](uint64_t address, uint64_t bytes) noexcept { m_memory_tracker.ValidateGpuDirtyPages(m_gpu_modified_ranges, address, bytes, "buffer download"); m_gpu_modified_ranges.ForEachInRange(address, bytes, [&](uint64_t start, uint64_t end) { - copies.emplace_back(start - buffer_address, total_size, end - start); - // Keep packed ranges on separate cache lines, as in shadPS4. - total_size += Common::AlignUp(end - start, 64); + ranges.push_back({start - buffer_address, end - start}); }); m_gpu_modified_ranges.Subtract(address, bytes); }); - if (copies.empty()) { + if (ranges.empty()) { return false; } - const auto [mapped, offset] = m_download_buffer.Map(total_size, 64); - if (mapped == nullptr) { - EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n"); - } - m_download_buffer.Commit(); - for (auto& copy: copies) { - copy.dstOffset += offset; - } - + // StreamBuffer::Map refuses a single reservation larger than the staging buffer instead of + // waiting for space, so a download whose dirty ranges total more than one staging pass + // could never be mapped and used to abort the process here. Stage it in batches instead: + // each reserves its own region, and the stream keeps that region reserved until its + // deferred write-back has consumed it, so consecutive batches cannot overlap. auto& command = m_scheduler.Current(); command.EndRendering(); - const auto native = command.Handle(); - vk::BufferMemoryBarrier before {}; - before.srcAccessMask = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite; - before.dstAccessMask = vk::AccessFlagBits::eTransferRead; - before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - before.buffer = buffer.Handle(); - before.offset = 0; - before.size = buffer.Size(); - native.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, - vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, &before, 0, - nullptr); - native.copyBuffer(buffer.Handle(), m_download_buffer.Handle(), - static_cast<uint32_t>(copies.size()), copies.data()); - - auto after = before; - after.srcAccessMask = vk::AccessFlagBits::eTransferWrite; - after.dstAccessMask = vk::AccessFlagBits::eHostRead; - after.buffer = m_download_buffer.Handle(); - after.offset = offset; - after.size = total_size; - native.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eAllCommands | - vk::PipelineStageFlagBits::eHost, - {}, 0, nullptr, 1, &after, 0, nullptr); - m_scheduler.DeferPriorityOperation([this, mapped, offset, total_size, buffer_address, - copies = std::move(copies)] { - m_download_buffer.Invalidate(offset, total_size); - for (const auto& copy: copies) { - Libs::LibKernel::Memory::WriteBacking(buffer_address + copy.srcOffset, - mapped + (copy.dstOffset - offset), copy.size); + const auto native = command.Handle(); + for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) { + const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64); + if (mapped == nullptr) { + EXIT("BufferCache: download batch could not be staged\n"); } - }); + m_download_buffer.Commit(); ``` Fixed in 338380c1. Confirmed the hazard end-to-end before patching: `StreamBuffer::Map` (streamBuffer.cpp:278) calls `WaitPendingOperations`, and `CommandScheduler::Wait` (commandScheduler.cpp:196-204) submits the current command buffer and calls `BeginNext()` when the waited tick is the current one, so the pre-loop `native` could indeed point at a submitted `vk::CommandBuffer` for all batches after the first wrap-wait. The original single-Map upstream code captured `command.Handle()` after `Map`, so only the batched rewrite introduced the reorder. The fix moves `EndRendering()` + `Handle()` inside the loop after `Map`/`Commit`: - `Map` records nothing, so capturing after it (and after `Commit`, which only flushes/advances offsets) keeps each batch's barriers and `copyBuffer` on the command buffer that is current at that point; a wait-cycled buffer yields the fresh handle. - `EndRendering()` on a freshly re-begun buffer is a no-op (`m_rendering == false` after `CommandBuffer::End()` → `EndRendering()`), and when no wait happened it still ends the render pass exactly once as before. - Per-batch `copies` were already loop-local, so nothing else captured the stale handle. Rebuilt `buffer_download_batch_tests` + `kyty_emulator` clean; the batch suite passes and host-side `--buffer-cache-range-only` cases are unchanged.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 03:15 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 141 (outdated):

@@ -109,68 +110,77 @@ void BufferCache::DeleteBuffer(BufferId id) {
 }
 
 bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) {
-	std::vector<vk::BufferCopy> copies;
-	uint64_t                    total_size     = 0;
-	const auto                  buffer_address = buffer.CpuAddress();
+	std::vector<BufferDownloadRange> ranges;
+	const auto                       buffer_address = buffer.CpuAddress();
 	m_memory_tracker.ForEachDownloadRange<false>(
 	    vaddr, size, [&](uint64_t address, uint64_t bytes) noexcept {
 		    m_memory_tracker.ValidateGpuDirtyPages(m_gpu_modified_ranges, address, bytes,
 		                                           "buffer download");
 		    m_gpu_modified_ranges.ForEachInRange(address, bytes, [&](uint64_t start, uint64_t end) {
-			    copies.emplace_back(start - buffer_address, total_size, end - start);
-			    // Keep packed ranges on separate cache lines, as in shadPS4.
-			    total_size += Common::AlignUp(end - start, 64);
+			    ranges.push_back({start - buffer_address, end - start});
 		    });
 		    m_gpu_modified_ranges.Subtract(address, bytes);
 	    });
-	if (copies.empty()) {
+	if (ranges.empty()) {
 		return false;
 	}
 
-	const auto [mapped, offset] = m_download_buffer.Map(total_size, 64);
-	if (mapped == nullptr) {
-		EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n");
-	}
-	m_download_buffer.Commit();
-	for (auto& copy: copies) {
-		copy.dstOffset += offset;
-	}
-
+	// StreamBuffer::Map refuses a single reservation larger than the staging buffer instead of
+	// waiting for space, so a download whose dirty ranges total more than one staging pass
+	// could never be mapped and used to abort the process here. Stage it in batches instead:
+	// each reserves its own region, and the stream keeps that region reserved until its
+	// deferred write-back has consumed it, so consecutive batches cannot overlap.
 	auto& command = m_scheduler.Current();
 	command.EndRendering();
-	const auto              native = command.Handle();
-	vk::BufferMemoryBarrier before {};
-	before.srcAccessMask       = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite;
-	before.dstAccessMask       = vk::AccessFlagBits::eTransferRead;
-	before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-	before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-	before.buffer              = buffer.Handle();
-	before.offset              = 0;
-	before.size                = buffer.Size();
-	native.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
-	                       vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, &before, 0,
-	                       nullptr);
-	native.copyBuffer(buffer.Handle(), m_download_buffer.Handle(),
-	                  static_cast<uint32_t>(copies.size()), copies.data());
-
-	auto after          = before;
-	after.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
-	after.dstAccessMask = vk::AccessFlagBits::eHostRead;
-	after.buffer        = m_download_buffer.Handle();
-	after.offset        = offset;
-	after.size          = total_size;
-	native.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
-	                       vk::PipelineStageFlagBits::eAllCommands |
-	                           vk::PipelineStageFlagBits::eHost,
-	                       {}, 0, nullptr, 1, &after, 0, nullptr);
-	m_scheduler.DeferPriorityOperation([this, mapped, offset, total_size, buffer_address,
-	                                    copies = std::move(copies)] {
-		m_download_buffer.Invalidate(offset, total_size);
-		for (const auto& copy: copies) {
-			Libs::LibKernel::Memory::WriteBacking(buffer_address + copy.srcOffset,
-			                                      mapped + (copy.dstOffset - offset), copy.size);
+	const auto native = command.Handle();
+	for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) {
+		const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64);
+		if (mapped == nullptr) {
+			EXIT("BufferCache: download batch could not be staged\n");
 		}
-	});
+		m_download_buffer.Commit();

@theantipopau, thanks for the detailed explanation. The current DownloadBufferMemory() code calls EndRendering() and captures Handle() after each batch’s Map() and Commit(). This addresses the stale command-buffer handle when Map() waits and the scheduler begins a new command buffer.

I have not independently run the tests you reported.


✏️ Learnings added
Learnt from: theantipopau
Repo: KytyPS5/KytyPS5 PR: 842
File: src/graphics/host_gpu/renderer/cache/bufferCache.cpp:0-0
Timestamp: 2026-09-26T03:14:58.690Z
Learning: In `src/graphics/host_gpu/renderer/cache/bufferCache.cpp`, capture the current command-buffer handle after each `StreamBuffer::Map()` call when staging GPU downloads. `StreamBuffer::Map()` can wait for pending operations, and `CommandScheduler::Wait()` can submit the current command buffer and begin a new one.

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

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 03:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#discussion_r4109994430) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 141 (outdated): ```diff @@ -109,68 +110,77 @@ void BufferCache::DeleteBuffer(BufferId id) { } bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) { - std::vector<vk::BufferCopy> copies; - uint64_t total_size = 0; - const auto buffer_address = buffer.CpuAddress(); + std::vector<BufferDownloadRange> ranges; + const auto buffer_address = buffer.CpuAddress(); m_memory_tracker.ForEachDownloadRange<false>( vaddr, size, [&](uint64_t address, uint64_t bytes) noexcept { m_memory_tracker.ValidateGpuDirtyPages(m_gpu_modified_ranges, address, bytes, "buffer download"); m_gpu_modified_ranges.ForEachInRange(address, bytes, [&](uint64_t start, uint64_t end) { - copies.emplace_back(start - buffer_address, total_size, end - start); - // Keep packed ranges on separate cache lines, as in shadPS4. - total_size += Common::AlignUp(end - start, 64); + ranges.push_back({start - buffer_address, end - start}); }); m_gpu_modified_ranges.Subtract(address, bytes); }); - if (copies.empty()) { + if (ranges.empty()) { return false; } - const auto [mapped, offset] = m_download_buffer.Map(total_size, 64); - if (mapped == nullptr) { - EXIT("BufferCache: download exceeds 64 MiB staging buffer capacity\n"); - } - m_download_buffer.Commit(); - for (auto& copy: copies) { - copy.dstOffset += offset; - } - + // StreamBuffer::Map refuses a single reservation larger than the staging buffer instead of + // waiting for space, so a download whose dirty ranges total more than one staging pass + // could never be mapped and used to abort the process here. Stage it in batches instead: + // each reserves its own region, and the stream keeps that region reserved until its + // deferred write-back has consumed it, so consecutive batches cannot overlap. auto& command = m_scheduler.Current(); command.EndRendering(); - const auto native = command.Handle(); - vk::BufferMemoryBarrier before {}; - before.srcAccessMask = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite; - before.dstAccessMask = vk::AccessFlagBits::eTransferRead; - before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - before.buffer = buffer.Handle(); - before.offset = 0; - before.size = buffer.Size(); - native.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, - vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, &before, 0, - nullptr); - native.copyBuffer(buffer.Handle(), m_download_buffer.Handle(), - static_cast<uint32_t>(copies.size()), copies.data()); - - auto after = before; - after.srcAccessMask = vk::AccessFlagBits::eTransferWrite; - after.dstAccessMask = vk::AccessFlagBits::eHostRead; - after.buffer = m_download_buffer.Handle(); - after.offset = offset; - after.size = total_size; - native.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eAllCommands | - vk::PipelineStageFlagBits::eHost, - {}, 0, nullptr, 1, &after, 0, nullptr); - m_scheduler.DeferPriorityOperation([this, mapped, offset, total_size, buffer_address, - copies = std::move(copies)] { - m_download_buffer.Invalidate(offset, total_size); - for (const auto& copy: copies) { - Libs::LibKernel::Memory::WriteBacking(buffer_address + copy.srcOffset, - mapped + (copy.dstOffset - offset), copy.size); + const auto native = command.Handle(); + for (const auto& batch: SplitBufferDownload(ranges, m_download_buffer.MaxReservation(), 64)) { + const auto [mapped, offset] = m_download_buffer.Map(batch.total_size, 64); + if (mapped == nullptr) { + EXIT("BufferCache: download batch could not be staged\n"); } - }); + m_download_buffer.Commit(); ``` `@theantipopau`, thanks for the detailed explanation. The current `DownloadBufferMemory()` code calls `EndRendering()` and captures `Handle()` after each batch’s `Map()` and `Commit()`. This addresses the stale command-buffer handle when `Map()` waits and the scheduler begins a new command buffer. I have not independently run the tests you reported. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: theantipopau Repo: KytyPS5/KytyPS5 PR: 842 File: src/graphics/host_gpu/renderer/cache/bufferCache.cpp:0-0 Timestamp: 2026-09-26T03:14:58.690Z Learning: In `src/graphics/host_gpu/renderer/cache/bufferCache.cpp`, capture the current command-buffer handle after each `StreamBuffer::Map()` call when staging GPU downloads. `StreamBuffer::Map()` can wait for pending operations, and `CommandScheduler::Wait()` can submit the current command buffer and begin a new one. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠Zezou-k on GitHub · 2026-09-26 13:58 UTC · original · edited 2026-09-26 14:04 UTC

This fixed the issue! Thank you.

**@⁠Zezou-k** on GitHub · 2026-09-26 13:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#issuecomment-5846852022) · edited 2026-09-26 14:04 UTC This fixed the issue! Thank you.
Author
Owner

@⁠theantipopau on GitHub · 2026-09-29 21:17 UTC · original

Superseded — no longer needed.

Upstream 18a5f04d ("graphics: retain oversized readbacks through GPU completion") landed the same fix for BufferCache::DownloadBufferMemory: instead of batching the dirty ranges across several staging reservations, it stages the whole range in a private Buffer that the deferred write-back retires once the copy has been read.

That is a cleaner shape than the batching I proposed here — one reservation, no split logic in SplitBufferDownload, and the shared staging buffer is left untouched for the small downloads that still fit. Closing in favour of it.

Thanks for reviewing.

**@⁠theantipopau** on GitHub · 2026-09-29 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/842#issuecomment-5899094864) Superseded — no longer needed. Upstream `18a5f04d` ("graphics: retain oversized readbacks through GPU completion") landed the same fix for `BufferCache::DownloadBufferMemory`: instead of batching the dirty ranges across several staging reservations, it stages the whole range in a private `Buffer` that the deferred write-back retires once the copy has been read. That is a cleaner shape than the batching I proposed here — one reservation, no split logic in `SplitBufferDownload`, and the shared staging buffer is left untouched for the small downloads that still fit. Closing in favour of it. Thanks for reviewing.

Pull request closed

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