gpu: initialize BDA page table before first use #1065

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

@⁠MehmetCambaz on GitHub · 2026-10-05 10:03 UTC · original
MehmetCambaz:fix/bda-page-table-init → main · +132 −1 · 4 files · 1 commits · closed without merging

Update (review follow-up)

  • GetBdaPageTableBuffer is no longer noexcept. It isn't a plain getter anymore: the first call clears the table through Buffer::Fill, which isn't noexcept. EXIT doesn't throw, so nothing changes at runtime.
  • m_bda_pagetable_initialized is a plain bool on purpose. It's only touched on the GPU thread, like the rest of BufferCache. Other threads (fault handler, unmap) go through SendCommandSync.
  • The clear happens on first use rather than in the constructor because the table is device-local (no mapping to memset), and Fill needs an active command buffer.

Summary

BufferCache allocates the BDA page table in device-local memory, but its untouched entries were never initialized before the table could be populated or bound for shader use.

A zero entry is the BDA unresolved sentinel. If a newly allocated table contains stale non-zero data, a shader can treat an untouched guest page as already resolved to a device address and skip the normal fault path.

This initializes the table once before its first registration write or descriptor consumer.

What is covered

The initialization is reached through both production first-use paths:

  • BufferCache::ChangeRegister clears the full table before publishing mapped-page device addresses.
  • BufferCache::GetBdaPageTableBuffer clears it before the descriptor path can expose it to shaders.

The clear uses the existing Buffer::Fill path. Its transfer barriers order the clear before subsequent page-table writes and shader reads.

Why this test matters

Fresh Vulkan device-local allocations are not guaranteed to contain zeroes. A normal test could therefore pass accidentally when the allocator happens to provide cleared memory.

The new GPU-backed regression first fills the real production BDA table with 0xdeadbeefdeadbeef, verifies that the poison is observable, then checks that never-owned entries return to the required zero/unresolved value.

It covers both:

  • buffer registration as the first production use, including publication of owned pages; and
  • direct table consumption as the first production use.

The checked entries span low memory, extended memory, and an unrelated page-table location.

Regression proof

With only the one-time table initialization disabled, the focused regression fails deterministically in 2/2 runs:

registration failed at never-owned entries are unmapped:
a never-published BDA page-table entry kept uninitialized contents

With the fix, it passes in 2/2 runs (registration ok, consumer ok).

Testing

Windows 11, RTX 4070, Release:

  • bda_page_table_initialization passes, and the same check passes inside the full shader_recompiler_compute run.
  • shader_recompiler_compute (later, after PackedUscaledVertexColor) and buffer_cache_dirty_gc segfault on my machine with and without this PR, at the same spot on base 72e4989b, so they are unrelated to this change.

AI usage

AI assistance was used for investigation, implementation, and testing. I reviewed the final diff and the validation results before updating this PR.

**@⁠MehmetCambaz** on GitHub · 2026-10-05 10:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1065) `MehmetCambaz:fix/bda-page-table-init` → `main` · +132 −1 · 4 files · 1 commits · closed without merging ## Update (review follow-up) - `GetBdaPageTableBuffer` is no longer `noexcept`. It isn't a plain getter anymore: the first call clears the table through `Buffer::Fill`, which isn't `noexcept`. `EXIT` doesn't throw, so nothing changes at runtime. - `m_bda_pagetable_initialized` is a plain `bool` on purpose. It's only touched on the GPU thread, like the rest of `BufferCache`. Other threads (fault handler, unmap) go through `SendCommandSync`. - The clear happens on first use rather than in the constructor because the table is device-local (no mapping to `memset`), and `Fill` needs an active command buffer. ## Summary `BufferCache` allocates the BDA page table in device-local memory, but its untouched entries were never initialized before the table could be populated or bound for shader use. A zero entry is the BDA unresolved sentinel. If a newly allocated table contains stale non-zero data, a shader can treat an untouched guest page as already resolved to a device address and skip the normal fault path. This initializes the table once before its first registration write or descriptor consumer. ## What is covered The initialization is reached through both production first-use paths: - `BufferCache::ChangeRegister` clears the full table before publishing mapped-page device addresses. - `BufferCache::GetBdaPageTableBuffer` clears it before the descriptor path can expose it to shaders. The clear uses the existing `Buffer::Fill` path. Its transfer barriers order the clear before subsequent page-table writes and shader reads. ## Why this test matters Fresh Vulkan device-local allocations are not guaranteed to contain zeroes. A normal test could therefore pass accidentally when the allocator happens to provide cleared memory. The new GPU-backed regression first fills the real production BDA table with `0xdeadbeefdeadbeef`, verifies that the poison is observable, then checks that never-owned entries return to the required zero/unresolved value. It covers both: - buffer registration as the first production use, including publication of owned pages; and - direct table consumption as the first production use. The checked entries span low memory, extended memory, and an unrelated page-table location. ## Regression proof With only the one-time table initialization disabled, the focused regression fails deterministically in 2/2 runs: ```text registration failed at never-owned entries are unmapped: a never-published BDA page-table entry kept uninitialized contents ``` With the fix, it passes in 2/2 runs (`registration ok`, `consumer ok`). ## Testing Windows 11, RTX 4070, Release: - `bda_page_table_initialization` passes, and the same check passes inside the full `shader_recompiler_compute` run. - `shader_recompiler_compute` (later, after `PackedUscaledVertexColor`) and `buffer_cache_dirty_gc` segfault on my machine with and without this PR, at the same spot on base `72e4989b`, so they are unrelated to this change. ## AI usage AI assistance was used for investigation, implementation, and testing. I reviewed the final diff and the validation results before updating this PR.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:41:49 +00:00
github-bot closed this pull request 2026-11-26 09:41:49 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 10:12 UTC · original · edited 2026-10-06 00:28 UTC

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 268af8ce-a4e7-4f2c-8aa9-6c156dd5f10b
📥 Commits

Reviewing files that changed from the base of the PR and between 72e4989b1e and 180e65adec.

📒 Files selected for processing (4)
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • tests/ShaderRecompilerComputeTests.cpp

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


📝 Walkthrough

Walkthrough

BufferCache now zero-fills the BDA page table on first registration change or first access. The compute tests check unowned entries after initialization and verify device addresses for registered buffers. The initialization check runs in the full test sequence and through a dedicated CTest entry.

Suggested reviewers: nmzik

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 180e6

The page table is cleared before registration or first consumption, and the new tests check unowned entries and registered addresses. No merge-blocking issue is established.

Security Architecture Review

Security architecture risk: ⚪ Minimal · up to 180e6

The change prevents uninitialized entries from being treated as valid addresses before first use. The reviewed paths preserve existing access boundaries, and no introduced security architecture concern was identified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The affected security surface is the full context-owned guest-page-to-device-address table, covering low and extended guest memory. The change preserves the existing descriptor publication route and buffer ownership rather than creating a new caller or cross-context handle transfer.

Security Findings and Attack Paths

  • inferred — Before this PR, an untouched nonzero table entry could take the available-address branch instead of the unresolved-page branch. That pre-existing condition is addressed by the first-use clear; the inspected change does not introduce or broaden that path. This is an architecture-level condition, not an independently verified exploit.

Trust Boundaries and Controls

  • observed — Both production publication paths now initialize the cache-owned table before use. The clear and subsequent registration writes use the cache's existing scheduler, while graphics and compute descriptor commitment remain on the GPU command-recording lane.

Resilience and Maintainability Implications

  • inferred — The flag records that clearing has been enqueued, not that GPU execution has completed. Correctness relies on the existing serialized recording and submission lifecycle plus Fill's barriers. Within those inspected paths, repetition does not erase registered entries, submission has no silent cancellation path, and deletion zeroes entries before deferring resource destruction. Concurrent external callers or recovery after forced device loss were not established as supported paths.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. (2 skipped: 1 … 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 describes the main change: initializing the BDA page table before first use.
Description check ✅ Passed The description explains the page-table initialization, its first-use paths, and the regression test for stale entries.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. (2 skipped: 1 unsupported, 1 too large.)

  • 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-05 10:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1065#issuecomment-5992419268) · edited 2026-10-06 00:28 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/1065?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><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> <!-- 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**: `268af8ce-a4e7-4f2c-8aa9-6c156dd5f10b` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 72e4989b1e1643c9237ba68ae4e3fe77fa489c63 and 180e65adecc19651174815fa448ecab10fe6fffe. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `tests/ShaderRecompilerComputeTests.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> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough BufferCache now zero-fills the BDA page table on first registration change or first access. The compute tests check unowned entries after initialization and verify device addresses for registered buffers. The initialization check runs in the full test sequence and through a dedicated CTest entry. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"180e65adecc19651174815fa448ecab10fe6fffe" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `180e6` <!-- final_review_risk_coverage:{"sourceCommitId":"180e65adecc19651174815fa448ecab10fe6fffe","coveredCommitId":"180e65adecc19651174815fa448ecab10fe6fffe","kind":"reviewed"} --> The page table is cleared before registration or first consumption, and the new tests check unowned entries and registered addresses. No merge-blocking issue is established. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _⚪ Minimal_ · up to `180e6` The change prevents uninitialized entries from being treated as valid addresses before first use. The reviewed paths preserve existing access boundaries, and no introduced security architecture concern was identified. **Retained concerns** No architecture-level concerns identified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The affected security surface is the full context-owned guest-page-to-device-address table, covering low and extended guest memory. The change preserves the existing descriptor publication route and buffer ownership rather than creating a new caller or cross-context handle transfer. **Security Findings and Attack Paths** - _inferred_ — Before this PR, an untouched nonzero table entry could take the available-address branch instead of the unresolved-page branch. That pre-existing condition is addressed by the first-use clear; the inspected change does not introduce or broaden that path. This is an architecture-level condition, not an independently verified exploit. **Trust Boundaries and Controls** - _observed_ — Both production publication paths now initialize the cache-owned table before use. The clear and subsequent registration writes use the cache's existing scheduler, while graphics and compute descriptor commitment remain on the GPU command-recording lane. **Resilience and Maintainability Implications** - _inferred_ — The flag records that clearing has been enqueued, not that GPU execution has completed. Correctness relies on the existing serialized recording and submission lifecycle plus Fill's barriers. Within those inspected paths, repetition does not erase registered entries, submission has no silent cancellation path, and deletion zeroes entries before deferring resource destruction. Concurrent external callers or recovery after forced device loss were not established as supported paths. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❓ 1</summary> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :----------------: | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ❓ Inconclusive | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. (2 skipped: 1 … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | 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 describes the main change: initializing the BDA page table before first use. | | Description check | ✅ Passed | The description explains the page-table initialization, its first-use paths, and the regression test for stale entries. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. (2 skipped: 1 unsupported, 1 too large.) </details> </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=1065)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [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) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-06 00:10 UTC · original

Validated locally (read the diff, built on x86_64 macOS no-Qt Release):

  • shader_recompiler_compute_tests binary builds clean (compile coverage for the new GPU test); resource_tracking passes. The new poison-then-verify regression itself needs a real Vulkan device so I couldn't execute it here (no loader in this environment — pre-existing limitation, same as clean main).
  • The fix is small and well-placed: one-time Fill(0) through the existing Buffer::Fill path (so transfer barriers order the clear before page-table writes/shader reads), reached from both first-use paths (ChangeRegister and GetBdaPageTableBuffer). Uninitialized device-local memory being misread as resolved translations is exactly the kind of silent corruption that wastes days downstream, and the poison-with-0xdeadbeef regression design (defeats accidentally-zeroed allocators) is the right way to test it.
  • One question for the author: GetBdaPageTableBuffer lost noexcept — I assume because Fill can EXIT; worth a brief note in the PR. Also, is m_bda_pagetable_initialized only ever touched on the GPU thread (like the rest of BufferCache mutation)? If so no race; if any first-use path can run elsewhere it wants an atomic.

Looks good to me pending those two answers.

**@⁠overlordxrz-source** on GitHub · 2026-10-06 00:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1065#issuecomment-6006152660) Validated locally (read the diff, built on x86_64 macOS no-Qt Release): - `shader_recompiler_compute_tests` binary builds clean (compile coverage for the new GPU test); `resource_tracking` passes. The new poison-then-verify regression itself needs a real Vulkan device so I couldn't execute it here (no loader in this environment — pre-existing limitation, same as clean main). - The fix is small and well-placed: one-time `Fill(0)` through the existing `Buffer::Fill` path (so transfer barriers order the clear before page-table writes/shader reads), reached from both first-use paths (`ChangeRegister` and `GetBdaPageTableBuffer`). Uninitialized device-local memory being misread as resolved translations is exactly the kind of silent corruption that wastes days downstream, and the poison-with-`0xdeadbeef` regression design (defeats accidentally-zeroed allocators) is the right way to test it. - One question for the author: `GetBdaPageTableBuffer` lost `noexcept` — I assume because `Fill` can `EXIT`; worth a brief note in the PR. Also, is `m_bda_pagetable_initialized` only ever touched on the GPU thread (like the rest of `BufferCache` mutation)? If so no race; if any first-use path can run elsewhere it wants an atomic. Looks good to me pending those two answers.
Author
Owner

@⁠MehmetCambaz on GitHub · 2026-10-06 00:23 UTC · original

Thanks for testing it

  1. noexcept: it's not really about EXIT, since that just ends the process and doesn't throw. The getter now does real work the first time it's called (it clears the table through Buffer::Fill), and that isn't noexcept, so I didn't want the signature to promise more than it does. Nothing changes at runtime. Happy to put it back if you prefer.

  2. Threading: yes, it's only touched on the GPU thread, same as the rest of BufferCache. Other threads, like the fault handler and unmap, go through 'SendCommandSync' and never touch it directly, so a plain bool is fine. An atomic wouldn't help anyway, because the Fill it guards has to be recorded on the GPU thread.

I'll add a short note about both to the PR description.

**@⁠MehmetCambaz** on GitHub · 2026-10-06 00:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1065#issuecomment-6006380898) Thanks for testing it 1. `noexcept`: it's not really about `EXIT`, since that just ends the process and doesn't throw. The getter now does real work the first time it's called (it clears the table through `Buffer::Fill`), and that isn't `noexcept`, so I didn't want the signature to promise more than it does. Nothing changes at runtime. Happy to put it back if you prefer. 2. Threading: yes, it's only touched on the GPU thread, same as the rest of `BufferCache`. Other threads, like the fault handler and unmap, go through 'SendCommandSync' and never touch it directly, so a plain bool is fine. An atomic wouldn't help anyway, because the `Fill` it guards has to be recorded on the GPU thread. I'll add a short note about both to the PR description.

Pull request closed

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