renderer: track native image clears for linear readback #1092

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

@⁠Fayberr on GitHub · 2026-10-06 00:45 UTC · original
Fayberr:fix/linear-image-readback → main · +350 −13 · 4 files · 5 commits · closed without merging

When linear image readback is enabled, native image clears can leave guest memory holding old data after GPU completion. ClearImage marks the image as GPU-written, but neither clear path registers it for download.

This registers both clear paths with the existing download mechanism. It also cancels queued image downloads when a newer CPU write invalidates the same range, so a delayed callback cannot overwrite the CPU's data. Pending downloads remain valid after image eviction unless their range is invalidated or unmapped.

The regression covers repeated clears, CPU writes before and after queueing, eviction, unmap and address reuse, download-buffer reuse, format aliases, array layers and padding. Devices without rasterization support skip only the format-alias subcase.

Testing performed:

  • Built the emulator, GPU test executable and all nine CPU test targets.
  • Passed the focused regression and 50 repetitions on an NVIDIA A10 with synchronization validation and zero Vulkan errors.
  • Removing either enrollment call or CPU cancellation reproduced the corresponding failure. Using the cache lock in the callback stalled at download-buffer reuse, as expected.
  • Passed the missing-rasterization branch using a separate test variant.
  • The full candidate suite passed with separate lab-environment adjustments excluded from this PR: 528 compute results, 17 graphics results and host checks, with zero skips or Vulkan errors.
  • All nine exact CPU binaries and three isolated shader fatal-contract checks passed under WSL2.

Modal also intermittently failed existing fatal-exit checks on both baseline and candidate. Those failures are retained; the full baseline comparison remains blocked by that harness issue.

Upstream GitHub Actions still requires maintainer approval. No game compatibility improvement has been verified.

AI assistance: Developed with Codex, including investigation, implementation and automated testing.

**@⁠Fayberr** on GitHub · 2026-10-06 00:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1092) `Fayberr:fix/linear-image-readback` → `main` · +350 −13 · 4 files · 5 commits · closed without merging When linear image readback is enabled, native image clears can leave guest memory holding old data after GPU completion. `ClearImage` marks the image as GPU-written, but neither clear path registers it for download. This registers both clear paths with the existing download mechanism. It also cancels queued image downloads when a newer CPU write invalidates the same range, so a delayed callback cannot overwrite the CPU's data. Pending downloads remain valid after image eviction unless their range is invalidated or unmapped. The regression covers repeated clears, CPU writes before and after queueing, eviction, unmap and address reuse, download-buffer reuse, format aliases, array layers and padding. Devices without rasterization support skip only the format-alias subcase. Testing performed: - Built the emulator, GPU test executable and all nine CPU test targets. - Passed the focused regression and 50 repetitions on an NVIDIA A10 with synchronization validation and zero Vulkan errors. - Removing either enrollment call or CPU cancellation reproduced the corresponding failure. Using the cache lock in the callback stalled at download-buffer reuse, as expected. - Passed the missing-rasterization branch using a separate test variant. - The full candidate suite passed with separate lab-environment adjustments excluded from this PR: 528 compute results, 17 graphics results and host checks, with zero skips or Vulkan errors. - All nine exact CPU binaries and three isolated shader fatal-contract checks passed under WSL2. Modal also intermittently failed existing fatal-exit checks on both baseline and candidate. Those failures are retained; the full baseline comparison remains blocked by that harness issue. Upstream GitHub Actions still requires maintainer approval. No game compatibility improvement has been verified. AI assistance: Developed with Codex, including investigation, implementation and automated testing.
Cancel overlapping queued downloads on CPU invalidation and unmap. Keep publication independent of the cache lock so download-buffer reuse can wait safely. Guard the rasterized alias subcase and cover queued supersession, eviction, unmap and ring reuse.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:42:43 +00:00
github-bot closed this pull request 2026-11-26 09:42:43 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 00:55 UTC · original · edited 2026-10-08 10:18 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: 31cebaf4-7e2d-48d6-a5dc-052c079dcc99
📥 Commits

Reviewing files that changed from the base of the PR and between eeba795b18 and 5095f8e64c.

📒 Files selected for processing (4)
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.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

TextureCache::ClearImage now tracks images for download after aliased-view and transfer clears. Pending downloads are recorded and cancelled when CPU-alias invalidation or unmapping overlaps their ranges. Deferred callbacks skip guest-memory writes for cancelled downloads. The compute tests cover linear-image clear readback, including repeated clears, CPU writes, buffer reuse, eviction, unmapping, format aliases, tiled-image exclusion, and padded rows. The tests also add a command-line selector and a CTest entry.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 5095f

Clearing native images now registers them for linear readback. A pending download is cancelled when a newer CPU write or an unmap covers its memory range. The new tests cover repeated clears, CPU writes, buffer reuse, eviction, unmapping, format aliases, and padded rows. No outstanding defects were identified, so the change looks ready to merge.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 91756

The change improves protection against stale readbacks overwriting newer memory contents. The examined paths preserve existing memory boundaries and completion ordering. No introduced security vulnerability was established, but some ownership interleavings and failure states remain incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The newly exercised sensitive outcome is host-side publication of clear results into registered image guest backing. The examined clear path requires a valid guest range and exact image-range matching; backing publication uses the existing address-space resolver rather than treating the guest address as an arbitrary host destination.

Trust Boundaries and Controls

  • observed — Cancellation and the deferred check/write operation use the same mutex. CPU invalidation cancels overlapping records before updating image ownership. The coordinated unmap path waits for pending completion operations before retiring guest mappings.

Resilience and Maintainability Implications

  • observed — Priority callbacks execute through a single FIFO worker after their GPU completion tick. Synchronous buffer readback waits for priority publications before writing its newer snapshot, and RenderContext shuts down the scheduler before member destruction. These controls counter callback-order inversion and destruction-time publication risks on the examined owner path.
🚥 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 8 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
Title check ✅ Passed The title clearly and concisely describes the main change: tracking native image clears for linear readback.
Description check ✅ Passed The description directly explains the implementation, cancellation behavior, regression coverage, and testing 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.
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 8 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-06 00:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1092#issuecomment-6006963647) · edited 2026-10-08 10:18 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/1092?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**: `31cebaf4-7e2d-48d6-a5dc-052c079dcc99` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between eeba795b18041c127925b522b1bdb1a2ed169895 and 5095f8e64c0b54fb9af7268e885cb164ddf48bad. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.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 `TextureCache::ClearImage` now tracks images for download after aliased-view and transfer clears. Pending downloads are recorded and cancelled when CPU-alias invalidation or unmapping overlaps their ranges. Deferred callbacks skip guest-memory writes for cancelled downloads. The compute tests cover linear-image clear readback, including repeated clears, CPU writes, buffer reuse, eviction, unmapping, format aliases, tiled-image exclusion, and padded rows. The tests also add a command-line selector and a CTest entry. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"5095f8e64c0b54fb9af7268e885cb164ddf48bad" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **⚪ Minimal** · up to `5095f` <!-- final_review_risk_coverage:{"sourceCommitId":"5095f8e64c0b54fb9af7268e885cb164ddf48bad","coveredCommitId":"5095f8e64c0b54fb9af7268e885cb164ddf48bad","kind":"reviewed"} --> Clearing native images now registers them for linear readback. A pending download is cancelled when a newer CPU write or an unmap covers its memory range. The new tests cover repeated clears, CPU writes, buffer reuse, eviction, unmapping, format aliases, and padded rows. No outstanding defects were identified, so the change looks ready to merge. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `91756` The change improves protection against stale readbacks overwriting newer memory contents. The examined paths preserve existing memory boundaries and completion ordering. No introduced security vulnerability was established, but some ownership interleavings and failure states remain incompletely verified. **Retained concerns** No architecture-level concerns identified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The newly exercised sensitive outcome is host-side publication of clear results into registered image guest backing. The examined clear path requires a valid guest range and exact image-range matching; backing publication uses the existing address-space resolver rather than treating the guest address as an arbitrary host destination. **Trust Boundaries and Controls** - _observed_ — Cancellation and the deferred check/write operation use the same mutex. CPU invalidation cancels overlapping records before updating image ownership. The coordinated unmap path waits for pending completion operations before retiring guest mappings. **Resilience and Maintainability Implications** - _observed_ — Priority callbacks execute through a single FIFO worker after their GPU completion tick. Synchronous buffer readback waits for priority publications before writing its newer snapshot, and RenderContext shuts down the scheduler before member destruction. These controls counter callback-order inversion and destruction-time publication risks on the examined owner path. </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 8 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 | | :------------------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: tracking native image clears for linear readback. | | Description check | ✅ Passed | The description directly explains the implementation, cancellation behavior, regression coverage, and testing 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> <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 8 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=1092)! 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

@⁠coderabbitai[bot] on GitHub · 2026-10-06 00:55 UTC · original · edited 2026-10-06 03:08 UTC
On tests/ShaderRecompilerComputeTests.cpp line 5229 (outdated):

@@ -5107,6 +5110,206 @@ class VulkanHarness {
     std::printf("[host]    %-32s ok\n", name);
   }
 
+  void CheckLinearImageClearReadback() {
+    constexpr const char *name = "LinearImageClearReadback";
+    constexpr uintptr_t base = 0x0000000204800000ull;
+    constexpr uint64_t allocation_size = 0x10000;
+    constexpr uint64_t alignment = 0x10000;
+    constexpr uint32_t stale = 0x10203040u;
+    EnsureRuntimeContext();
+    RenderContext context(m_runtime_context);
+    auto &scheduler = context.GetCommandScheduler();
+    HW::Context registers{};
+    HW::UserConfig user_config{};
+    HW::Shader shaders{};
+    scheduler.Begin(registers, user_config, shaders);
+    context.InitializeGpu(nullptr);
+    int64_t direct_offset = -1;
+    Require(name, "direct allocation",
+            LibKernel::Memory::KernelAllocateDirectMemory(
+                0, LibKernel::Memory::KernelGetDirectMemorySize(),
+                allocation_size, alignment, 0, &direct_offset) == 0,
+            "linear-clear direct-memory allocation failed");
+    void *mapped = reinterpret_cast<void *>(base);
+    Require(name, "direct mapping",
+            LibKernel::Memory::KernelMapDirectMemory(
+                &mapped, allocation_size, 0x3, 0x10, direct_offset, alignment) == 0 &&
+                mapped == reinterpret_cast<void *>(base),
+            "linear-clear fixed direct-memory mapping failed");
+    LibKernel::Memory::InstallGpuResources(&context);
+    auto &cache = context.GetTextureCache();
+    const auto ReadWord = [&](uint64_t address) {
+      uint32_t word = 0;
+      Require(name, "read backing",
+              LibKernel::Memory::TryReadBacking(address, &word, sizeof(word)),
+              "linear-clear guest backing is unreadable");
+      return word;
+    };
+    const auto NewImage = [&](uint64_t offset) {
+      LibKernel::Memory::WriteBacking(base + offset, &stale, sizeof(stale));
+      auto desc = MakeLinearDesc(
+          base + offset, sizeof(uint32_t), vk::Format::eR32Uint,
+          Prospero::BufferFormat::k32UInt, Prospero::ImageType::kColor2D,
+          {1, 1, 1}, 1, 4, 1);
+      return std::pair{cache.FindImage(desc), desc};
+    };
+    const auto Clear = [&](const TextureCache::ImageDesc &desc, uint32_t value) {
+      Require(name, "optimized buffer clear",
+              cache.ClearImageFromBuffer(scheduler.Current(), desc.info.data.address,
+                                          desc.info.data.size, value),
+              "buffer fill was not handled by the native image clear");
+    };
+    const auto Submit = [&](uint64_t address, uint32_t before, uint32_t after) {
+      const auto tick = scheduler.CurrentTick();
+      cache.ProcessDownloadImages();
+      Require(name, "deferred publication",
+              scheduler.CurrentTick() == tick && ReadWord(address) == before,
+              "linear clear submitted or published before GPU completion");
+      scheduler.Finish();
+      scheduler.DrainPriorityOperations();
+      Require(name, "completed publication", ReadWord(address) == after,
+              fmt::format("linear clear readback: actual=0x{:08x} expected=0x{:08x}",
+                          ReadWord(address), after));
+    };
+
+    TextureCacheTestAccess::SetLinearReadback(cache, true);
+    const auto [image, desc] = NewImage(0);
+    Clear(desc, 0xabcdef01u);
+    Submit(desc.info.data.address, stale, 0xabcdef01u);
+    Require(name, "native image retained",
+            TextureCacheTestAccess::Contains(cache, image) &&
+                cache.GetImage(image).SafeToDownload(),
+            "readback retired the native image or lost GPU ownership");
+    Clear(desc, 0x76543210u);
+    Clear(desc, 0x89abcdefu);
+    Submit(desc.info.data.address, 0xabcdef01u, 0x89abcdefu);
+    std::printf("[host]    %-32s optimized/repeated clear ok\n", name);
+
+    TextureCacheTestAccess::SetLinearReadback(cache, false);
+    const auto [disabled_image, disabled_desc] = NewImage(0x1000);
+    Clear(disabled_desc, 0x55555555u);
+    Submit(disabled_desc.info.data.address, stale, stale);
+    Require(name, "disabled readback GPU contents",
+            ReadCachedTexel(name, context, disabled_image) ==
+                std::vector<u32>{0x55555555u},
+            "disabled readback skipped the native GPU clear");
+    TextureCacheTestAccess::SetLinearReadback(cache, true);
+    Clear(disabled_desc, 0x66666666u);
+    Submit(disabled_desc.info.data.address, stale, 0x66666666u);
+    std::printf("[host]    %-32s readback option ok\n", name);
+
+    const auto [cpu_image, cpu_desc] = NewImage(0x2000);
+    Clear(cpu_desc, 0x77777777u);
+    constexpr uint32_t cpu_value = 0x12345678u;
+    cache.InvalidateMemory(cpu_desc.info.data.address, sizeof(cpu_value));
+    LibKernel::Memory::WriteBacking(cpu_desc.info.data.address, &cpu_value,
+                                    sizeof(cpu_value));
+    Submit(cpu_desc.info.data.address, cpu_value, cpu_value);
+    Require(name, "CPU ownership retained",
+            cache.GetImage(cpu_image).IsDefinitelyCpuDirty(),
+            "a stale image readback replaced the newer CPU contents");
+    std::printf("[host]    %-32s CPU supersession ok\n", name);
+
+    const auto [retired_image, retired_desc] = NewImage(0x3000);
+    Clear(retired_desc, 0x88888888u);
+    cache.UnmapMemory(retired_desc.info.data.address, retired_desc.info.data.size);
+    Submit(retired_desc.info.data.address, stale, stale);
+    Require(name, "retired image removed",
+            !TextureCacheTestAccess::Contains(cache, retired_image),
+            "unmapping retained a pending clear readback image");
+    const auto [replacement_image, replacement_desc] = NewImage(0x3000);
+    Clear(replacement_desc, 0x99999999u);
+    Submit(replacement_desc.info.data.address, stale, 0x99999999u);
+    Require(name, "new image generation",
+            replacement_image != retired_image,
+            "readback retirement reused the stale image identity");
+    std::printf("[host]    %-32s retirement/reuse ok\n", name);
+
+    Require(name, "alias clear features", RasterizationSupported(),
+            "production rasterization is required for format-alias clears");

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep the transfer-clear test runnable without rasterization.

If a device supports the compute harness but lacks production rasterization features, --linear-clear-readback-only reaches this Require and aborts. The full-suite guard does not apply to that selector, which is also registered as a CTest test. Run the format-alias case only when RasterizationSupported() is true. Keep the transfer-clear and padding checks active on other supported devices. (raw.githubusercontent.com)

✅ Addressed in commit 91756a2

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 00:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1092#discussion_r4190444452) · edited 2026-10-06 03:08 UTC On `tests/ShaderRecompilerComputeTests.cpp` line 5229 (outdated): ```diff @@ -5107,6 +5110,206 @@ class VulkanHarness { std::printf("[host] %-32s ok\n", name); } + void CheckLinearImageClearReadback() { + constexpr const char *name = "LinearImageClearReadback"; + constexpr uintptr_t base = 0x0000000204800000ull; + constexpr uint64_t allocation_size = 0x10000; + constexpr uint64_t alignment = 0x10000; + constexpr uint32_t stale = 0x10203040u; + EnsureRuntimeContext(); + RenderContext context(m_runtime_context); + auto &scheduler = context.GetCommandScheduler(); + HW::Context registers{}; + HW::UserConfig user_config{}; + HW::Shader shaders{}; + scheduler.Begin(registers, user_config, shaders); + context.InitializeGpu(nullptr); + int64_t direct_offset = -1; + Require(name, "direct allocation", + LibKernel::Memory::KernelAllocateDirectMemory( + 0, LibKernel::Memory::KernelGetDirectMemorySize(), + allocation_size, alignment, 0, &direct_offset) == 0, + "linear-clear direct-memory allocation failed"); + void *mapped = reinterpret_cast<void *>(base); + Require(name, "direct mapping", + LibKernel::Memory::KernelMapDirectMemory( + &mapped, allocation_size, 0x3, 0x10, direct_offset, alignment) == 0 && + mapped == reinterpret_cast<void *>(base), + "linear-clear fixed direct-memory mapping failed"); + LibKernel::Memory::InstallGpuResources(&context); + auto &cache = context.GetTextureCache(); + const auto ReadWord = [&](uint64_t address) { + uint32_t word = 0; + Require(name, "read backing", + LibKernel::Memory::TryReadBacking(address, &word, sizeof(word)), + "linear-clear guest backing is unreadable"); + return word; + }; + const auto NewImage = [&](uint64_t offset) { + LibKernel::Memory::WriteBacking(base + offset, &stale, sizeof(stale)); + auto desc = MakeLinearDesc( + base + offset, sizeof(uint32_t), vk::Format::eR32Uint, + Prospero::BufferFormat::k32UInt, Prospero::ImageType::kColor2D, + {1, 1, 1}, 1, 4, 1); + return std::pair{cache.FindImage(desc), desc}; + }; + const auto Clear = [&](const TextureCache::ImageDesc &desc, uint32_t value) { + Require(name, "optimized buffer clear", + cache.ClearImageFromBuffer(scheduler.Current(), desc.info.data.address, + desc.info.data.size, value), + "buffer fill was not handled by the native image clear"); + }; + const auto Submit = [&](uint64_t address, uint32_t before, uint32_t after) { + const auto tick = scheduler.CurrentTick(); + cache.ProcessDownloadImages(); + Require(name, "deferred publication", + scheduler.CurrentTick() == tick && ReadWord(address) == before, + "linear clear submitted or published before GPU completion"); + scheduler.Finish(); + scheduler.DrainPriorityOperations(); + Require(name, "completed publication", ReadWord(address) == after, + fmt::format("linear clear readback: actual=0x{:08x} expected=0x{:08x}", + ReadWord(address), after)); + }; + + TextureCacheTestAccess::SetLinearReadback(cache, true); + const auto [image, desc] = NewImage(0); + Clear(desc, 0xabcdef01u); + Submit(desc.info.data.address, stale, 0xabcdef01u); + Require(name, "native image retained", + TextureCacheTestAccess::Contains(cache, image) && + cache.GetImage(image).SafeToDownload(), + "readback retired the native image or lost GPU ownership"); + Clear(desc, 0x76543210u); + Clear(desc, 0x89abcdefu); + Submit(desc.info.data.address, 0xabcdef01u, 0x89abcdefu); + std::printf("[host] %-32s optimized/repeated clear ok\n", name); + + TextureCacheTestAccess::SetLinearReadback(cache, false); + const auto [disabled_image, disabled_desc] = NewImage(0x1000); + Clear(disabled_desc, 0x55555555u); + Submit(disabled_desc.info.data.address, stale, stale); + Require(name, "disabled readback GPU contents", + ReadCachedTexel(name, context, disabled_image) == + std::vector<u32>{0x55555555u}, + "disabled readback skipped the native GPU clear"); + TextureCacheTestAccess::SetLinearReadback(cache, true); + Clear(disabled_desc, 0x66666666u); + Submit(disabled_desc.info.data.address, stale, 0x66666666u); + std::printf("[host] %-32s readback option ok\n", name); + + const auto [cpu_image, cpu_desc] = NewImage(0x2000); + Clear(cpu_desc, 0x77777777u); + constexpr uint32_t cpu_value = 0x12345678u; + cache.InvalidateMemory(cpu_desc.info.data.address, sizeof(cpu_value)); + LibKernel::Memory::WriteBacking(cpu_desc.info.data.address, &cpu_value, + sizeof(cpu_value)); + Submit(cpu_desc.info.data.address, cpu_value, cpu_value); + Require(name, "CPU ownership retained", + cache.GetImage(cpu_image).IsDefinitelyCpuDirty(), + "a stale image readback replaced the newer CPU contents"); + std::printf("[host] %-32s CPU supersession ok\n", name); + + const auto [retired_image, retired_desc] = NewImage(0x3000); + Clear(retired_desc, 0x88888888u); + cache.UnmapMemory(retired_desc.info.data.address, retired_desc.info.data.size); + Submit(retired_desc.info.data.address, stale, stale); + Require(name, "retired image removed", + !TextureCacheTestAccess::Contains(cache, retired_image), + "unmapping retained a pending clear readback image"); + const auto [replacement_image, replacement_desc] = NewImage(0x3000); + Clear(replacement_desc, 0x99999999u); + Submit(replacement_desc.info.data.address, stale, 0x99999999u); + Require(name, "new image generation", + replacement_image != retired_image, + "readback retirement reused the stale image identity"); + std::printf("[host] %-32s retirement/reuse ok\n", name); + + Require(name, "alias clear features", RasterizationSupported(), + "production rasterization is required for format-alias clears"); ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Keep the transfer-clear test runnable without rasterization.** If a device supports the compute harness but lacks production rasterization features, `--linear-clear-readback-only` reaches this `Require` and aborts. The full-suite guard does not apply to that selector, which is also registered as a CTest test. Run the format-alias case only when `RasterizationSupported()` is true. Keep the transfer-clear and padding checks active on other supported devices. ([raw.githubusercontent.com](https://raw.githubusercontent.com/Fayberr/KytyPS5/fix/linear-image-readback/CMakeLists.txt)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ff86c94f03d365f251ac953c --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 91756a2
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 00:55 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: fcf1ed22-28e7-440e-96bb-82c7cdb1cba5
📥 Commits

Reviewing files that changed from the base of the PR and between cdb64bfd4f and ff35e8011b.

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

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 00:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1092#pullrequestreview-5422556707) · **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**: `fcf1ed22-28e7-440e-96bb-82c7cdb1cba5` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cdb64bfd4fb4d5312b2542a41a0070f25663166a and ff35e8011b601b843f49facc35d0d31c4bf0dc67. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `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> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=50013dcb-0fd0-4fbb-9c30-0de52d1782aa attempt=f4e286e3-7252-46e4-ba5c-e668097c7d82 batch=1/1 -->

Pull request closed

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