graphics: back the BDA page table with sparse memory #1270

Open
github-bot wants to merge 2 commits from github-bot/gh-1270 into main AGit
Owner

@⁠msfvn on GitHub · 2026-10-09 02:25 UTC · original
msfvn:sparse-bda-pagetable → main · +162 −9 · 6 files · 2 commits · open

Problem

The BDA page table has one 8-byte entry per 16 KiB page of the whole guest address space (1 TiB + the 512 GiB extended range): BDA_PAGETABLE_SIZE = 768 MiB of device-local memory allocated up front. Games map a few tens of GiB of that space (Astro Bot: ~15 GiB), so over 98% of the table is always zero. On a 4-6 GB GPU that is a large share of VRAM.

Change

When the device supports sparseBinding + sparseResidencyBuffer with residencyNonResidentStrict and the graphics queue family supports sparse binding, the table is created as a sparse buffer:

  • Buffer gets a SparseResidency constructor and EnsureResident(offset, size), which binds 1 MiB chunks (each covering 2 GiB of guest addresses) on first use.
  • BufferCache::ChangeRegister<true> calls EnsureResident before writing the entries.
  • Unbound entries read as zero, which get_bda_pointer already treats as a missing page, so the shader side is unchanged.
  • New chunks are zero-filled before the entries are written. Binding waits for the queue to go idle first, so a shader in flight never reads a freshly bound, not yet cleared chunk; this only happens when the guest first maps memory in a new 2 GiB region (a handful of times per run).
    Devices without these features keep the fully resident table.

Testing

Linux, RTX 3050 Laptop 4 GB (NVIDIA 615.71.09), Astro Bot: process VRAM use per nvidia-smi at the same point of the intro dropped from 2991 MiB to 2413 MiB; rendering unchanged in the intro and cutscenes.

Note: NVIDIA's VK_EXT_memory_budget lowers the reported heap budget by the sparse buffer's full range even though the memory is not backed, so budget-based numbers understate the saving; nvidia-smi shows the real figure.

Measurements were taken on a local build that also includes #1102 (so Astro Bot boots without the non-RT patch); regression runs were on main with the community non-RT patch, scripted input through the intro: no new failures (on its own, main still stops at the ship scene with failed to create image on this 4 GB GPU, see #1271).

AI involvement: written with Claude Code (AI assistant) at my request and reviewed by a C++ developer I know; tested on my machine (RTX 3050 Laptop 4 GB, CachyOS) as described above, including playing Astro Bot on this build. Happy to adjust anything you point out.

**@⁠msfvn** on GitHub · 2026-10-09 02:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270) `msfvn:sparse-bda-pagetable` → `main` · +162 −9 · 6 files · 2 commits · open ### Problem The BDA page table has one 8-byte entry per 16 KiB page of the whole guest address space (1 TiB + the 512 GiB extended range): `BDA_PAGETABLE_SIZE` = 768 MiB of device-local memory allocated up front. Games map a few tens of GiB of that space (Astro Bot: ~15 GiB), so over 98% of the table is always zero. On a 4-6 GB GPU that is a large share of VRAM. ### Change When the device supports `sparseBinding` + `sparseResidencyBuffer` with `residencyNonResidentStrict` and the graphics queue family supports sparse binding, the table is created as a sparse buffer: - `Buffer` gets a `SparseResidency` constructor and `EnsureResident(offset, size)`, which binds 1 MiB chunks (each covering 2 GiB of guest addresses) on first use. - `BufferCache::ChangeRegister<true>` calls `EnsureResident` before writing the entries. - Unbound entries read as zero, which `get_bda_pointer` already treats as a missing page, so the shader side is unchanged. - New chunks are zero-filled before the entries are written. Binding waits for the queue to go idle first, so a shader in flight never reads a freshly bound, not yet cleared chunk; this only happens when the guest first maps memory in a new 2 GiB region (a handful of times per run). Devices without these features keep the fully resident table. ### Testing Linux, RTX 3050 Laptop 4 GB (NVIDIA 615.71.09), Astro Bot: process VRAM use per `nvidia-smi` at the same point of the intro dropped from 2991 MiB to 2413 MiB; rendering unchanged in the intro and cutscenes. Note: NVIDIA's `VK_EXT_memory_budget` lowers the reported heap budget by the sparse buffer's full range even though the memory is not backed, so budget-based numbers understate the saving; `nvidia-smi` shows the real figure. Measurements were taken on a local build that also includes #1102 (so Astro Bot boots without the non-RT patch); regression runs were on `main` with the community non-RT patch, scripted input through the intro: no new failures (on its own, `main` still stops at the ship scene with `failed to create image` on this 4 GB GPU, see #1271). **AI involvement:** written with Claude Code (AI assistant) at my request and reviewed by a C++ developer I know; tested on my machine (RTX 3050 Laptop 4 GB, CachyOS) as described above, including playing Astro Bot on this build. Happy to adjust anything you point out.
The BDA page table has one 8-byte entry per 16 KiB page of the whole guest
address space (1 TiB plus the 512 GiB extended range), so it takes 768 MiB
of device memory up front. Games map a few tens of GiB of that space, so
almost all of the table stays zero; on a 4 GB GPU it is a fifth of VRAM.

Where the device supports sparse residency with non-resident reads
returning zero, create the table as a sparse buffer and bind 1 MiB chunks
(each covering 2 GiB of guest addresses) when a game buffer is registered
in them. Unbound entries read as zero, which the shaders already treat as
an unmapped page, so the shader side is unchanged. New chunks are zeroed
before the entries are written, and binding waits for the queue to go idle
so a running shader never sees a chunk before it is cleared; binds only
happen the first few times the guest maps memory in a new region.

Devices without sparse residency keep the fully resident table.

Astro Bot, RTX 3050 Laptop 4 GB: process VRAM use per nvidia-smi at the
same point drops from 2991 MiB to 2413 MiB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Work recorded before EnsureResident but submitted after the bind could
read entries in a freshly bound chunk before the zero fill recorded after
it ran, and use whatever the memory held as a device address. Clear each
new chunk through a temporary buffer in a submission of its own before
binding it, so the table only ever exposes zeros or real entries. This
also removes the need to idle the queue before binding.

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

@⁠coderabbitai[bot] on GitHub · 2026-10-09 02:28 UTC · original · edited 2026-10-11 01:22 UTC

Review in Change Stack →

📝 Walkthrough
📝 Walkthrough

Walkthrough

Device creation detects and enables sparse buffer features when the device and graphics queue meet the stated requirements. Buffer adds sparse chunk allocation, binding, zero-filling, and cleanup. BufferCache uses sparse residency for the BDA page table when sparse buffers are enabled.

Suggested reviewers: nmzik



Priority: ➖ Normal

Change: Feature

Merge Risk: 🟡 Moderate · up to 4301d

Sparse page-table setup may fail on devices with different scratch-buffer memory requirements. Check binding compatibility before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check Passed The title clearly and concisely identifies the main change: using sparse memory for the BDA page table.
Description check Passed The description directly explains the memory-saving problem, sparse-buffer implementation, fallback behavior, and testing results for the changeset.

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

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

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 02:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#issuecomment-6073027243) · edited 2026-10-11 01:22 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/1270?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> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough Device creation detects and enables sparse buffer features when the device and graphics queue meet the stated requirements. `Buffer` adds sparse chunk allocation, binding, zero-filling, and cleanup. `BufferCache` uses sparse residency for the BDA page table when sparse buffers are enabled. **Suggested reviewers:** `nmzik` <hr> </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"4301dad64106828ea388b75a2cc33c6b79da2420" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟡 Moderate** · up to `4301d` <!-- final_review_risk_coverage:{"sourceCommitId":"4301dad64106828ea388b75a2cc33c6b79da2420","coveredCommitId":"4301dad64106828ea388b75a2cc33c6b79da2420","kind":"reviewed"} --> Sparse page-table setup may fail on devices with different scratch-buffer memory requirements. Check binding compatibility before merging. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v1.svg" width="14" height="17" align="middle" alt="Passed" title="Passed"></picture></sup> 4 | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v1.svg" width="14" height="17" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 6 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------- | | 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. | | 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 sparse memory for the BDA page table. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the memory-saving problem, sparse-buffer implementation, fallback behavior, and testing results for the changeset. | </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</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=1270)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -107,0 +205,4 @@
device.destroyFence(fence.value);
for (const auto buffer: scratch) {
device.destroyBuffer(buffer);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 02:28 UTC · original · edited 2026-10-11 02:00 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C3 '\b(Flush|Finish|Submit)\s*\(' --iglob '*commandScheduler*'

Repository: KytyPS5/KytyPS5

Length of output: 5184


🏁 Script executed:

set -e
printf '%s\n' '--- streamBuffer declarations and implementation ---'
rg -n -C4 -F -- 'EnsureResident' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer
rg -n -C5 -F -- 'bindSparse' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
sed -n '1,240p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
printf '%s\n' '--- scheduler interface and implementation ---'
sed -n '1,230p' src/graphics/host_gpu/renderer/commandScheduler.h
sed -n '110,215p' src/graphics/host_gpu/renderer/commandScheduler.cpp
printf '%s\n' '--- scheduler access and EnsureResident callers ---'
rg -n -C5 -F -- 'Scheduler()' src/graphics/host_gpu/renderer | head -240
rg -n -C6 -F -- '.EnsureResident(' src

Repository: KytyPS5/KytyPS5

Length of output: 42312


🏁 Script executed:

set -u
printf '%s\n' '--- commandScheduler.cpp: Finish, Wait, Submit, BeginNext ---'
sed -n '115,215p' src/graphics/host_gpu/renderer/commandScheduler.cpp
sed -n '320,390p' src/graphics/host_gpu/renderer/commandScheduler.cpp
printf '%s\n' '--- bufferCache.cpp: ChangeRegister and WriteDataBuffer callers ---'
sed -n '60,135p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -C8 -F -- 'void BufferCache::ChangeRegister' src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true
rg -n -C8 -F -- 'WriteDataBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true
printf '%s\n' '--- streamBuffer.cpp: Fill ---'
sed -n '268,315p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
printf '%s\n' '--- scheduler call sites for Finish and FlushAndWait ---'
rg -n -C5 -F -- '.Finish()' src/graphics/host_gpu/renderer || true
rg -n -C5 -F -- '.FlushAndWait()' src/graphics/host_gpu/renderer || true

Repository: KytyPS5/KytyPS5

Length of output: 14209


Submit the current command buffer before the sparse bind.

queue.waitIdle() does not submit Scheduler().Current(). If that command already contains a shader read, the later bindSparse can expose uninitialized memory before the subsequent Fill records its zeroing operation. A garbage BDA entry can cause an invalid device address and device loss.

Call Scheduler().Finish() before queue.waitIdle().

Suggested fix
--- "a/src/graphics/host_gpu/renderer/cache/streamBuffer.cpp"
+++ "b/src/graphics/host_gpu/renderer/cache/streamBuffer.cpp"
@@ -151,8 +151,9 @@
 	if (binds.empty()) {
 		return;
 	}
 	{
+		Scheduler().Finish();
 		// Shaders may be reading neighbouring entries. Until the fill below runs, freshly bound
 		// memory holds garbage, so let in-flight work finish before binding. This happens a few
 		// times per run, when the guest first maps memory in a new part of its address space.
 		Common::LockGuard lock(m_graphics->queue_mutex);
📝 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.

	{
		Scheduler().Finish();
		// Shaders may be reading neighbouring entries. Until the fill below runs, freshly bound
		// memory holds garbage, so let in-flight work finish before binding. This happens a few
		// times per run, when the guest first maps memory in a new part of its address space.
		Common::LockGuard lock(m_graphics->queue_mutex);
		EXIT_IF(m_graphics->queue.waitIdle() != vk::Result::eSuccess);
		const vk::SparseBufferMemoryBindInfo buffer_bind {
		    m_buffer, static_cast<uint32_t>(binds.size()), binds.data()};
		vk::BindSparseInfo bind_info {};
		bind_info.bufferBindCount = 1;
		bind_info.pBufferBinds    = &buffer_bind;
		const auto fence          = m_graphics->device.createFence({});
		EXIT_IF(fence.result != vk::Result::eSuccess);
		EXIT_IF(m_graphics->queue.bindSparse(1, &bind_info, fence.value) != vk::Result::eSuccess);
		EXIT_IF(m_graphics->device.waitForFences(1, &fence.value, VK_TRUE, UINT64_MAX) !=
		        vk::Result::eSuccess);
		m_graphics->device.destroyFence(fence.value);
	}
	for (const auto& bind: binds) {
		Fill(bind.resourceOffset, Common::AlignDown(bind.size, 4), 0);
	}

✅ Addressed in commit 4301dad

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 02:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#discussion_r4226057656) · edited 2026-10-11 02:00 UTC **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C3 '\b(Flush|Finish|Submit)\s*\(' --iglob '*commandScheduler*' ``` Repository: KytyPS5/KytyPS5 Length of output: 5184 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- streamBuffer declarations and implementation ---' rg -n -C4 -F -- 'EnsureResident' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer rg -n -C5 -F -- 'bindSparse' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp sed -n '1,240p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp printf '%s\n' '--- scheduler interface and implementation ---' sed -n '1,230p' src/graphics/host_gpu/renderer/commandScheduler.h sed -n '110,215p' src/graphics/host_gpu/renderer/commandScheduler.cpp printf '%s\n' '--- scheduler access and EnsureResident callers ---' rg -n -C5 -F -- 'Scheduler()' src/graphics/host_gpu/renderer | head -240 rg -n -C6 -F -- '.EnsureResident(' src ``` Repository: KytyPS5/KytyPS5 Length of output: 42312 --- 🏁 Script executed: ```bash set -u printf '%s\n' '--- commandScheduler.cpp: Finish, Wait, Submit, BeginNext ---' sed -n '115,215p' src/graphics/host_gpu/renderer/commandScheduler.cpp sed -n '320,390p' src/graphics/host_gpu/renderer/commandScheduler.cpp printf '%s\n' '--- bufferCache.cpp: ChangeRegister and WriteDataBuffer callers ---' sed -n '60,135p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -C8 -F -- 'void BufferCache::ChangeRegister' src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true rg -n -C8 -F -- 'WriteDataBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true printf '%s\n' '--- streamBuffer.cpp: Fill ---' sed -n '268,315p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp printf '%s\n' '--- scheduler call sites for Finish and FlushAndWait ---' rg -n -C5 -F -- '.Finish()' src/graphics/host_gpu/renderer || true rg -n -C5 -F -- '.FlushAndWait()' src/graphics/host_gpu/renderer || true ``` Repository: KytyPS5/KytyPS5 Length of output: 14209 --- </details> **Submit the current command buffer before the sparse bind.** `queue.waitIdle()` does not submit `Scheduler().Current()`. If that command already contains a shader read, the later `bindSparse` can expose uninitialized memory before the subsequent `Fill` records its zeroing operation. A garbage BDA entry can cause an invalid device address and device loss. Call `Scheduler().Finish()` before `queue.waitIdle()`. <details> <summary>Suggested fix</summary> ```diff --- "a/src/graphics/host_gpu/renderer/cache/streamBuffer.cpp" +++ "b/src/graphics/host_gpu/renderer/cache/streamBuffer.cpp" @@ -151,8 +151,9 @@ if (binds.empty()) { return; } { + Scheduler().Finish(); // Shaders may be reading neighbouring entries. Until the fill below runs, freshly bound // memory holds garbage, so let in-flight work finish before binding. This happens a few // times per run, when the guest first maps memory in a new part of its address space. Common::LockGuard lock(m_graphics->queue_mutex); ``` </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 { Scheduler().Finish(); // Shaders may be reading neighbouring entries. Until the fill below runs, freshly bound // memory holds garbage, so let in-flight work finish before binding. This happens a few // times per run, when the guest first maps memory in a new part of its address space. Common::LockGuard lock(m_graphics->queue_mutex); EXIT_IF(m_graphics->queue.waitIdle() != vk::Result::eSuccess); const vk::SparseBufferMemoryBindInfo buffer_bind { m_buffer, static_cast<uint32_t>(binds.size()), binds.data()}; vk::BindSparseInfo bind_info {}; bind_info.bufferBindCount = 1; bind_info.pBufferBinds = &buffer_bind; const auto fence = m_graphics->device.createFence({}); EXIT_IF(fence.result != vk::Result::eSuccess); EXIT_IF(m_graphics->queue.bindSparse(1, &bind_info, fence.value) != vk::Result::eSuccess); EXIT_IF(m_graphics->device.waitForFences(1, &fence.value, VK_TRUE, UINT64_MAX) != vk::Result::eSuccess); m_graphics->device.destroyFence(fence.value); } for (const auto& bind: binds) { Fill(bind.resourceOffset, Common::AlignDown(bind.size, 4), 0); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:300f0d66e74320b4c0fcec13 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 4301dad
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 02:28 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: 1c017c78-784b-4fd5-943b-e446868c72c7
📥 Commits

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

📒 Files selected for processing (6)
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/streamBuffer.h
  • src/graphics/presentation/window/vulkanWindow.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 02:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#pullrequestreview-5465052584) · **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**: `1c017c78-784b-4fd5-943b-e446868c72c7` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 and a042eddb2f287e5d57f212caf0a4a4b662cb7a4f. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/streamBuffer.cpp` * `src/graphics/host_gpu/renderer/cache/streamBuffer.h` * `src/graphics/presentation/window/vulkanWindow.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=e8f80e65-3e4a-4dd7-846a-0a154a861297 attempt=4df8367c-5962-4eb7-97eb-4430611396f7 batch=1/1 -->
@ -107,0 +179,4 @@
buffer_info.usage = vk::BufferUsageFlagBits::eTransferDst;
const auto buffer = device.createBuffer(buffer_info);
EXIT_IF(buffer.result != vk::Result::eSuccess);
EXIT_IF(vmaBindBufferMemory(m_graphics->allocator, fresh[i], buffer.value) != VK_SUCCESS);
Author
Owner

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -e
printf '%s\n' '--- changed file around sparse implementation ---'
nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '1,280p'
printf '%s\n' '--- diff from required merge base ---'
git diff --unified=80 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 4301dad64106828ea388b75a2cc33c6b79da2420 -- src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
printf '%s\n' '--- relevant symbols and allocator declarations ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'm_sparse_memory_types|m_sparse_chunk_size|vmaBindBufferMemory|SparseResidency|EnsureResident' src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 27083


🏁 Script executed:

set -e
printf '%s\n' '--- changed file around sparse implementation ---'
nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '1,300p'
printf '%s\n' '--- diff from required merge base ---'
git diff --unified=80 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 4301dad64106828ea388b75a2cc33c6b79da2420 -- src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
printf '%s\n' '--- relevant symbols and allocator declarations ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'm_sparse_memory_types|m_sparse_chunk_size|vmaBindBufferMemory|SparseResidency|EnsureResident' src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 28368


🏁 Script executed:

set -e
nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '130,225p'
rg -n -F -- 'm_sparse_memory_types' src
rg -n -F -- 'm_sparse_chunk_size' src

Repository: KytyPS5/KytyPS5

Length of output: 6824


Check the scratch buffer's memory requirements before binding it.

fresh[i] is allocated with requirements derived from the sparse buffer. The scratch buffer is created independently with eTransferDst. Its memoryTypeBits, alignment, and required allocation size can differ. vmaBindBufferMemory can therefore violate the Vulkan binding requirements and fail or produce undefined behavior.

Query the scratch requirements once, intersect the memory types, and use compatible size and alignment values.

Suggested fix
+	auto& device = m_graphics->device;
+	vk::BufferCreateInfo probe_info {};
+	probe_info.size  = m_sparse_chunk_size;
+	probe_info.usage = vk::BufferUsageFlagBits::eTransferDst;
+	const auto probe = device.createBuffer(probe_info);
+	EXIT_IF(probe.result != vk::Result::eSuccess);
+	const auto scratch_requirements = device.getBufferMemoryRequirements(probe.value);
+	device.destroyBuffer(probe.value);
+	const auto scratch_memory_types =
+	    m_sparse_memory_types & scratch_requirements.memoryTypeBits;
+	EXIT_IF(scratch_memory_types == 0 ||
+	        scratch_requirements.size > m_sparse_chunk_size);
+
 	std::vector<vk::SparseMemoryBind> binds;
 	std::vector<VmaAllocation>        fresh;
 	for (auto chunk = first; chunk <= last; chunk++) {
 		if (m_sparse_chunks[chunk] != nullptr) {
 			continue;
 		}
 		const VkMemoryRequirements requirements {
 		    .size           = m_sparse_chunk_size,
-		    .alignment      = m_sparse_chunk_size,
-		    .memoryTypeBits = m_sparse_memory_types,
+		    .alignment      = std::max<uint64_t>(
+		        m_sparse_chunk_size, scratch_requirements.alignment),
+		    .memoryTypeBits = scratch_memory_types,
 		};
@@
-	auto&                     device = m_graphics->device;
 	std::vector<vk::Buffer>   scratch;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 01:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#discussion_r4239837489) **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -e printf '%s\n' '--- changed file around sparse implementation ---' nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '1,280p' printf '%s\n' '--- diff from required merge base ---' git diff --unified=80 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 4301dad64106828ea388b75a2cc33c6b79da2420 -- src/graphics/host_gpu/renderer/cache/streamBuffer.cpp printf '%s\n' '--- relevant symbols and allocator declarations ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'm_sparse_memory_types|m_sparse_chunk_size|vmaBindBufferMemory|SparseResidency|EnsureResident' src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 27083 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- changed file around sparse implementation ---' nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '1,300p' printf '%s\n' '--- diff from required merge base ---' git diff --unified=80 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 4301dad64106828ea388b75a2cc33c6b79da2420 -- src/graphics/host_gpu/renderer/cache/streamBuffer.cpp printf '%s\n' '--- relevant symbols and allocator declarations ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'm_sparse_memory_types|m_sparse_chunk_size|vmaBindBufferMemory|SparseResidency|EnsureResident' src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 28368 --- 🏁 Script executed: ```bash set -e nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '130,225p' rg -n -F -- 'm_sparse_memory_types' src rg -n -F -- 'm_sparse_chunk_size' src ``` Repository: KytyPS5/KytyPS5 Length of output: 6824 --- </details> **Check the scratch buffer's memory requirements before binding it.** `fresh[i]` is allocated with requirements derived from the sparse buffer. The scratch buffer is created independently with `eTransferDst`. Its `memoryTypeBits`, `alignment`, and required allocation size can differ. `vmaBindBufferMemory` can therefore violate the Vulkan binding requirements and fail or produce undefined behavior. Query the scratch requirements once, intersect the memory types, and use compatible size and alignment values. <details> <summary>Suggested fix</summary> ```diff + auto& device = m_graphics->device; + vk::BufferCreateInfo probe_info {}; + probe_info.size = m_sparse_chunk_size; + probe_info.usage = vk::BufferUsageFlagBits::eTransferDst; + const auto probe = device.createBuffer(probe_info); + EXIT_IF(probe.result != vk::Result::eSuccess); + const auto scratch_requirements = device.getBufferMemoryRequirements(probe.value); + device.destroyBuffer(probe.value); + const auto scratch_memory_types = + m_sparse_memory_types & scratch_requirements.memoryTypeBits; + EXIT_IF(scratch_memory_types == 0 || + scratch_requirements.size > m_sparse_chunk_size); + std::vector<vk::SparseMemoryBind> binds; std::vector<VmaAllocation> fresh; for (auto chunk = first; chunk <= last; chunk++) { if (m_sparse_chunks[chunk] != nullptr) { continue; } const VkMemoryRequirements requirements { .size = m_sparse_chunk_size, - .alignment = m_sparse_chunk_size, - .memoryTypeBits = m_sparse_memory_types, + .alignment = std::max<uint64_t>( + m_sparse_chunk_size, scratch_requirements.alignment), + .memoryTypeBits = scratch_memory_types, }; @@ - auto& device = m_graphics->device; std::vector<vk::Buffer> scratch; ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:639ce88617d91e5e94067749 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 01:18 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: 5b33b4af-0668-4ae7-b431-8c5372a316c4
📥 Commits

Reviewing files that changed from the base of the PR and between a042eddb2f and 4301dad641.

📒 Files selected for processing (1)
  • src/graphics/host_gpu/renderer/cache/streamBuffer.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-11 01:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#pullrequestreview-5481463144) · **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**: `5b33b4af-0668-4ae7-b431-8c5372a316c4` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between a042eddb2f287e5d57f212caf0a4a4b662cb7a4f and 4301dad64106828ea388b75a2cc33c6b79da2420. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/graphics/host_gpu/renderer/cache/streamBuffer.cpp` </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. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=150f910a-58d8-46b5-ac95-4944a13d9641 attempt=50a618dd-4fc3-42ec-98b4-9e92c6ec8512 batch=1/1 -->
@ -107,0 +205,4 @@
device.destroyFence(fence.value);
for (const auto buffer: scratch) {
device.destroyBuffer(buffer);
}
Author
Owner

@⁠msfvn on GitHub · 2026-10-11 02:00 UTC · original

Right, recorded but unsubmitted work would run after the bind and before the fill. Fixed in 4301dad6 without a mid-draw Finish(): each new chunk is now cleared before it is bound, through a temporary buffer bound to the same allocation and a one-off submission, so the table only ever exposes zeros or real entries regardless of what is already recorded. That also removes the waitIdle.

**@⁠msfvn** on GitHub · 2026-10-11 02:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#discussion_r4239926999) Right, recorded but unsubmitted work would run after the bind and before the fill. Fixed in 4301dad6 without a mid-draw `Finish()`: each new chunk is now cleared before it is bound, through a temporary buffer bound to the same allocation and a one-off submission, so the table only ever exposes zeros or real entries regardless of what is already recorded. That also removes the `waitIdle`.
@ -107,0 +205,4 @@
device.destroyFence(fence.value);
for (const auto buffer: scratch) {
device.destroyBuffer(buffer);
}
Author
Owner

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

@msfvn Thanks for the explanation and fix. The updated code waits for the temporary-buffer clear to complete before bindSparse. This prevents recorded but unsubmitted work from reading uninitialized entries, without a mid-draw Finish() or waitIdle().


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

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 02:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1270#discussion_r4239927770) `@msfvn` Thanks for the explanation and fix. The updated code waits for the temporary-buffer clear to complete before `bindSparse`. This prevents recorded but unsubmitted work from reading uninitialized entries, without a mid-draw `Finish()` or `waitIdle()`. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Sparse%20GPU%20binds%20can%20expose%20garbage%20to%20shaders.%20Clear%20new%20chunks%20before%20binding%20so%20tables%20contain%20only%20zeros%20or%20valid%20entries%E2%80%94without%20%60waitIdle%60.%20Try%20%40coderabbitai%20for%20actionable%20code%20reviews%20%F0%9F%9B%A0%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1270%23discussion_r4226057656)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
This pull request has changes conflicting with the target branch.
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/presentation/window/vulkanWindow.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1270/head:github-bot/gh-1270'
git switch 'github-bot/gh-1270'

Merge

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