gpu: read back tiny GPU-written images before signalling EOP labels (PPSA09809) #1753

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

@⁠MrBigBritches on GitHub · 2026-10-20 06:33 UTC · original
MrBigBritches:lighting-readback-fix → main · +180 −11 · 7 files · 6 commits · closed without merging

Games read small render targets on the CPU after waiting for the GPU. UE4 does this to compute sky-light ambient: it renders the irradiance SH into a 9x1 RGBA16F target and reads it back with ReadSurfaceFloatData. Kyty never wrote tiled images back to guest memory, and it published EOP label writes at command-parse time, so the guest read zeros. In Octopath Traveler II this left everything in shade (characters especially) without ambient light.

  • Always enroll tiny GPU-written images (1 layer, 1 level, <= 64 texels, tiled or linear) for readback, independent of --readback-linear-images.
  • When readbacks are pending at an EOP label write, queue them first and defer the label write (and its interrupt) until they have landed in guest memory, then flush.

Before
image

After
image

Partial Fix: #1617

**@⁠MrBigBritches** on GitHub · 2026-10-20 06:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753) `MrBigBritches:lighting-readback-fix` → `main` · +180 −11 · 7 files · 6 commits · closed without merging Games read small render targets on the CPU after waiting for the GPU. UE4 does this to compute sky-light ambient: it renders the irradiance SH into a 9x1 RGBA16F target and reads it back with ReadSurfaceFloatData. Kyty never wrote tiled images back to guest memory, and it published EOP label writes at command-parse time, so the guest read zeros. In Octopath Traveler II this left everything in shade (characters especially) without ambient light. - Always enroll tiny GPU-written images (1 layer, 1 level, <= 64 texels, tiled or linear) for readback, independent of --readback-linear-images. - When readbacks are pending at an EOP label write, queue them first and defer the label write (and its interrupt) until they have landed in guest memory, then flush. **Before** <img width="1922" height="1119" alt="image" src="https://github.com/user-attachments/assets/4c85edb7-c49a-4937-88db-db4e6d91bc67" /> **After** <img width="1922" height="1118" alt="image" src="https://github.com/user-attachments/assets/b34b15c5-dc9c-4919-af2d-eb3eef60cbe0" /> Partial Fix: https://git.gtahub.st/github/KytyPS5--KytyPS5/issues/1617
Games read small render targets on the CPU after waiting for the GPU. UE4
does this to compute sky-light ambient: it renders the irradiance SH into a
9x1 RGBA16F target and reads it back with ReadSurfaceFloatData. Kyty never
wrote tiled images back to guest memory, and it published EOP label writes
at command-parse time, so the guest read zeros. In Octopath Traveler II
this left everything in shade (characters especially) without ambient
light.

- Always enroll tiny GPU-written images (1 layer, 1 level, <= 64 texels,
  tiled or linear) for readback, independent of --readback-linear-images.
- When readbacks are pending at an EOP label write, queue them first and
  defer the label write (and its interrupt) until they have landed in
  guest memory, then flush.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review feedback on the tiny-image readback:

- Interrupt-only EOP (selector 0x01 on the graphics queue) now queues
  pending readbacks before scheduling the interrupt, and flushes.
- The GDS-read EOP path queues readbacks before SynchronizeGpu() and
  drains the priority operations so the copies have landed.
- 64-bit timestamp EOP writes are no longer excluded from deferral.
- Tiny-image enrollment is factored into EnrollTinyReadback() and also
  runs after depth-target binds, MarkGpuWritten() and image clears.
  Stencil associations are skipped because they cannot be downloaded
  on their own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A label written while an earlier label is still waiting on its readbacks
could become visible first, letting the guest read before the earlier
copies landed. Track labels deferred behind readbacks and, while any are
outstanding, defer later labels too. Priority operations run in FIFO
order, so labels are published in submission order.

The write32/write64 paths now share PublishLabelAfterReadbacks().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
SynchronizeGpu() waits for GPU work but not for priority callbacks, so a
GDS EOP with no new readbacks could signal before an earlier EOP's
readback copies or deferred label had landed. Always drain priority
operations after synchronizing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- ProcessDownloadImages() keeps entries whose download failed transiently
  and retries them at the next signal; entries that are gone, already
  current or can never be downloaded are dropped.
- The texture cache counts readbacks whose guest write has not run yet.
  PublishLabelAfterReadbacks() also defers labels while any are in
  flight, so a readback queued at a suspend point can no longer be
  overtaken by a later label. This is narrower than waiting on all
  pending priority operations, which would defer labels behind every
  flip and interrupt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A label deferred behind readbacks was written with memcpy inside a
priority callback. When the label shares a page with GPU-written data
the buffer cache tracks, that write faults into a buffer readback, which
cannot run from a deferred operation, and the emulator exits (NHL 27:
"unsupported buffer readback from an asynchronous GPU completion").

The callback now only hands the write to the GPU thread, which runs
commands between PM4 packets in FIFO order, so labels stay ordered; the
same command raises the interrupt after the label is visible. The GDS
EOP path runs pending GPU commands after draining priority callbacks so
earlier deferred labels still land first. At shutdown, a callback that
can no longer reach the GPU thread drops its label, and priority
callbacks are drained before the GPU object is destroyed.

The stencil-binding test expected a cleared 2x2 target not to be
pending download after the render-target prefetch. The clear itself now
enrolls tiny targets for readback, so check that and that the prefetch
leaves the enrollment unchanged.

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

@⁠coderabbitai[bot] on GitHub · 2026-10-20 06:39 UTC · original · edited 2026-10-21 16:30 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 3bb73b4f-248a-4cc0-ab82-c25179ae7216
📥 Commits

Reviewing files that changed from the base of the PR and between 6f8fe5cc24 and f01c4cc584.

📒 Files selected for processing: 3
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h

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

📝 Walkthrough

The texture cache enrolls qualifying small GPU-modified images for readback and reports queued and in-flight work. End-of-pipe label writes defer label publication and optional interrupts until readbacks complete. Interrupt-only completion and GDS synchronization also process queued readbacks and deferred operations.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to f01c4

The change makes small GPU-written render targets reach guest memory before completion labels and interrupts are published. No concrete merge-blocking risk remains after review.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 15.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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.
Description check Passed The description directly matches the changes. It explains tiny image readback enrollment and deferred EOP label and interrupt handling.
Title check Passed The title clearly describes the main change: reading back tiny GPU-written images before signalling EOP labels. It is concise and specific.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 06:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6285020446) · edited 2026-10-21 16:30 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1753?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 --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: f01c4cc58475d9bf04f283b0db65b4f8181b1d57 > - Latest commit, not reviewed: b8d609a91e5778e82e54546e0302b25110e52f16 > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `3bb73b4f-248a-4cc0-ab82-c25179ae7216` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 6f8fe5cc2424c6a12d085525c6b15cac8e2a7e68 and f01c4cc58475d9bf04f283b0db65b4f8181b1d57. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing: 3</strong></summary> <dl> <dd> * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The texture cache enrolls qualifying small GPU-modified images for readback and reports queued and in-flight work. End-of-pipe label writes defer label publication and optional interrupts until readbacks complete. Interrupt-only completion and GDS synchronization also process queued readbacks and deferred operations. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"f01c4cc58475d9bf04f283b0db65b4f8181b1d57" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>f01c4</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `f01c4` --> <!-- final_review_risk_coverage:{"sourceCommitId":"f01c4cc58475d9bf04f283b0db65b4f8181b1d57","coveredCommitId":"f01c4cc58475d9bf04f283b0db65b4f8181b1d57","kind":"reviewed"} --> The change makes small GPU-written render targets reach guest memory before completion labels and interrupts are published. No concrete merge-blocking risk remains after review. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 15.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 4 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------ | | 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. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly matches the changes. It explains tiny image readback enrollment and deferred EOP label and interrupt handling. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly describes the main change: reading back tiny GPU-written images before signalling EOP labels. It is concise and specific. | </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1753)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 06:39 UTC · original · edited 2026-10-20 06:49 UTC
On src/graphics/guest_gpu/graphicsRun.cpp line 1081 (outdated):

@@ -1078,6 +1078,16 @@ void CommandProcessor::WriteAtEndOfPipe(uint32_t cache_policy, uint32_t event_wr
 		auto  data = static_cast<uint32_t>(value);
 		EXIT_IF(dst == nullptr);
 		(void)command.Handle();
+		if (QueueReadbacksBeforeLabel()) {

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Queue readbacks before the interrupt-only EOP path.

For selector 0x01 on a non-async queue, WriteAtEndOfPipe() calls TriggerEopEventAtEndOfPipe() and returns at Lines 1065–1069. Neither changed readback check runs. If a guest waits for that interrupt before reading a tiny GPU-written image, the interrupt can arrive while its guest memory still contains stale data. Process pending readbacks before scheduling this interrupt.

Also applies to: 1134-1134

✅ Addressed in commit a4d3583

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 06:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#discussion_r4322150661) · edited 2026-10-20 06:49 UTC On `src/graphics/guest_gpu/graphicsRun.cpp` line 1081 (outdated): ```diff @@ -1078,6 +1078,16 @@ void CommandProcessor::WriteAtEndOfPipe(uint32_t cache_policy, uint32_t event_wr auto data = static_cast<uint32_t>(value); EXIT_IF(dst == nullptr); (void)command.Handle(); + if (QueueReadbacksBeforeLabel()) { ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **⚡ Quick win** **Queue readbacks before the interrupt-only EOP path.** For selector `0x01` on a non-async queue, `WriteAtEndOfPipe()` calls `TriggerEopEventAtEndOfPipe()` and returns at Lines 1065–1069. Neither changed readback check runs. If a guest waits for that interrupt before reading a tiny GPU-written image, the interrupt can arrive while its guest memory still contains stale data. Process pending readbacks before scheduling this interrupt. Also applies to: 1134-1134 <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6658c1965de62672c910a974 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit a4d3583
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 06:39 UTC · original · edited 2026-10-20 06:49 UTC
On src/graphics/host_gpu/renderer/cache/textureCache.cpp line 411 (outdated):

@@ -401,6 +401,26 @@ void TextureCache::UntrackImageTail(ImageId id) {
 }
 
 void TextureCache::TrackImageDownload(ImageId id, Image& image) {
+	// Tiny GPU-written images (a handful of texels) are always read back, tiled or not: games
+	// read them on the CPU after waiting for the GPU (e.g. UE4 reads the sky-light irradiance
+	// SH from a 9x1 render target, and 1x1 targets for exposure/statistics). They are cheap.
+	constexpr uint64_t kMaxTinyReadbackTexels = 64;
+	const auto&        ext  = image.info.extent;
+	const bool         tiny = image.info.resources.layers == 1 && image.info.resources.levels == 1 &&
+	                  uint64_t {ext.width} * ext.height * ext.depth <= kMaxTinyReadbackTexels;
+	if (tiny && image.IsGpuModified()) {

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n 'TrackImageDownload|MarkGpuWritten|SetGpuModified|IsGpuModified|m_download_images|download_images' src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h
rg -n 'FindDepthTarget|ClearImage|FindRenderTarget' src/graphics/host_gpu/renderer/cache/textureCache.cpp
sed -n '395,430p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
sed -n '1970,2000p' src/graphics/host_gpu/renderer/cache/textureCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5177


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- relevant declarations and call sites ---'
rg -n -F --glob '*.{cpp,h}' -e 'TrackImageDownload(' -e 'FindDepthTarget(' -e 'MarkGpuWritten(' -e 'ClearImage(' -e 'ProcessDownloadImages(' -e 'ReadSurfaceFloatData' src/graphics src | head -240
printf '%s\n' '--- TrackImageDownload and nearby callers ---'
sed -n '380,440p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
sed -n '1270,1435p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- MarkGpuWritten and ClearImage ---'
sed -n '1435,1575p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- ProcessDownloadImages and EOP-related callers ---'
sed -n '1925,2005p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -F --glob '*.cpp' -e 'ProcessDownloadImages(' -e 'ReadSurfaceFloatData' src

Repository: KytyPS5/KytyPS5

Length of output: 21049


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- ClearImage remainder ---'
sed -n '1548,1645p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- EOP/readback sequencing ---'
sed -n '120,155p' src/graphics/host_gpu/renderer/renderContext.cpp
sed -n '1235,1275p' src/graphics/guest_gpu/graphicsRun.cpp
printf '%s\n' '--- ReadSurfaceFloatData symbols and likely read paths ---'
rg -n -i -F --glob '*.{cpp,h}' -e 'ReadSurfaceFloatData' -e 'ReadSurface' -e 'FloatData' src || test "$?" -eq 1
printf '%s\n' '--- PR diff for texture cache and related callers ---'
git diff --unified=35 fa8216c4d95bee2dacbc6b2b7c09c3ba49fd1aac ff1ac30272ce310850d8de5bb9c9f661db125719 -- src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h src/graphics/host_gpu/renderer/renderContext.cpp src/graphics/host_gpu/renderer/renderDraw.cpp src/graphics/host_gpu/renderer/depthRenderTarget.cpp src/graphics/host_gpu/renderer/renderCompute.cpp

Repository: KytyPS5/KytyPS5

Length of output: 16605


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- EOP queue/readback call graph ---'
rg -n -F --glob '*.{cpp,h}' -e 'QueueReadbacksBeforeLabel' -e 'WriteAtEndOfPipe' -e 'TriggerEopEventAtEndOfPipe' -e 'RunGarbageCollector' src/graphics
printf '%s\n' '--- image/resource declarations and validation ---'
rg -n -F --glob '*.{cpp,h}' -e 'struct ImageInfo' -e 'class ImageInfo' -e 'resources.layers' -e 'resources.levels' -e 'FindImage(ImageDesc' src/graphics/host_gpu src/graphics/guest_gpu
printf '%s\n' '--- depth/render read-related entrypoints ---'
rg -n -i -F --glob '*.{cpp,h}' -e 'depthtarget' -e 'readsurface' -e 'read_surface' -e 'surfacefloat' -e 'readback' src/graphics/guest_gpu src/graphics/host_gpu | head -260

Repository: KytyPS5/KytyPS5

Length of output: 24336


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- download eligibility and execution ---'
sed -n '900,995p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
sed -n '1675,1810p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- depth target descriptor construction ---'
sed -n '100,245p' src/graphics/host_gpu/renderer/depthRenderTarget.cpp
sed -n '350,395p' src/graphics/host_gpu/renderer/depthRenderTarget.cpp
printf '%s\n' '--- exact EOP label branches ---'
sed -n '1020,1160p' src/graphics/guest_gpu/graphicsRun.cpp

Repository: KytyPS5/KytyPS5

Length of output: 24920


Re-enroll tiny images after every GPU write.

TrackImageDownload() runs for color render-target and storage bindings, but not after FindDepthTarget(), MarkGpuWritten(), or ClearImage() commits a GPU write. A supported depth target can have one layer, one level, and at most 64 texels.

After ProcessDownloadImages() clears the pending set, a later write through one of these paths is absent from the next EOP readback. The EOP label can then become visible while guest memory still contains stale data. Rebinds through FindRenderTarget() re-enroll the image, but TrackImage() and CommitGpuWrite() do not.

Call TrackImageDownload() after each CommitGpuWrite() in these paths. Also enroll an associated stencil image when that path commits the stencil image.

✅ Addressed in commit a4d3583

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 06:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#discussion_r4322150666) · edited 2026-10-20 06:49 UTC On `src/graphics/host_gpu/renderer/cache/textureCache.cpp` line 411 (outdated): ```diff @@ -401,6 +401,26 @@ void TextureCache::UntrackImageTail(ImageId id) { } void TextureCache::TrackImageDownload(ImageId id, Image& image) { + // Tiny GPU-written images (a handful of texels) are always read back, tiled or not: games + // read them on the CPU after waiting for the GPU (e.g. UE4 reads the sky-light irradiance + // SH from a 9x1 render target, and 1x1 targets for exposure/statistics). They are cheap. + constexpr uint64_t kMaxTinyReadbackTexels = 64; + const auto& ext = image.info.extent; + const bool tiny = image.info.resources.layers == 1 && image.info.resources.levels == 1 && + uint64_t {ext.width} * ext.height * ext.depth <= kMaxTinyReadbackTexels; + if (tiny && image.IsGpuModified()) { ``` **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash rg -n 'TrackImageDownload|MarkGpuWritten|SetGpuModified|IsGpuModified|m_download_images|download_images' src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h rg -n 'FindDepthTarget|ClearImage|FindRenderTarget' src/graphics/host_gpu/renderer/cache/textureCache.cpp sed -n '395,430p' src/graphics/host_gpu/renderer/cache/textureCache.cpp sed -n '1970,2000p' src/graphics/host_gpu/renderer/cache/textureCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5177 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- relevant declarations and call sites ---' rg -n -F --glob '*.{cpp,h}' -e 'TrackImageDownload(' -e 'FindDepthTarget(' -e 'MarkGpuWritten(' -e 'ClearImage(' -e 'ProcessDownloadImages(' -e 'ReadSurfaceFloatData' src/graphics src | head -240 printf '%s\n' '--- TrackImageDownload and nearby callers ---' sed -n '380,440p' src/graphics/host_gpu/renderer/cache/textureCache.cpp sed -n '1270,1435p' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- MarkGpuWritten and ClearImage ---' sed -n '1435,1575p' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- ProcessDownloadImages and EOP-related callers ---' sed -n '1925,2005p' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -F --glob '*.cpp' -e 'ProcessDownloadImages(' -e 'ReadSurfaceFloatData' src ``` Repository: KytyPS5/KytyPS5 Length of output: 21049 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- ClearImage remainder ---' sed -n '1548,1645p' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- EOP/readback sequencing ---' sed -n '120,155p' src/graphics/host_gpu/renderer/renderContext.cpp sed -n '1235,1275p' src/graphics/guest_gpu/graphicsRun.cpp printf '%s\n' '--- ReadSurfaceFloatData symbols and likely read paths ---' rg -n -i -F --glob '*.{cpp,h}' -e 'ReadSurfaceFloatData' -e 'ReadSurface' -e 'FloatData' src || test "$?" -eq 1 printf '%s\n' '--- PR diff for texture cache and related callers ---' git diff --unified=35 fa8216c4d95bee2dacbc6b2b7c09c3ba49fd1aac ff1ac30272ce310850d8de5bb9c9f661db125719 -- src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h src/graphics/host_gpu/renderer/renderContext.cpp src/graphics/host_gpu/renderer/renderDraw.cpp src/graphics/host_gpu/renderer/depthRenderTarget.cpp src/graphics/host_gpu/renderer/renderCompute.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 16605 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- EOP queue/readback call graph ---' rg -n -F --glob '*.{cpp,h}' -e 'QueueReadbacksBeforeLabel' -e 'WriteAtEndOfPipe' -e 'TriggerEopEventAtEndOfPipe' -e 'RunGarbageCollector' src/graphics printf '%s\n' '--- image/resource declarations and validation ---' rg -n -F --glob '*.{cpp,h}' -e 'struct ImageInfo' -e 'class ImageInfo' -e 'resources.layers' -e 'resources.levels' -e 'FindImage(ImageDesc' src/graphics/host_gpu src/graphics/guest_gpu printf '%s\n' '--- depth/render read-related entrypoints ---' rg -n -i -F --glob '*.{cpp,h}' -e 'depthtarget' -e 'readsurface' -e 'read_surface' -e 'surfacefloat' -e 'readback' src/graphics/guest_gpu src/graphics/host_gpu | head -260 ``` Repository: KytyPS5/KytyPS5 Length of output: 24336 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- download eligibility and execution ---' sed -n '900,995p' src/graphics/host_gpu/renderer/cache/textureCache.cpp sed -n '1675,1810p' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- depth target descriptor construction ---' sed -n '100,245p' src/graphics/host_gpu/renderer/depthRenderTarget.cpp sed -n '350,395p' src/graphics/host_gpu/renderer/depthRenderTarget.cpp printf '%s\n' '--- exact EOP label branches ---' sed -n '1020,1160p' src/graphics/guest_gpu/graphicsRun.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 24920 --- </details> **Re-enroll tiny images after every GPU write.** `TrackImageDownload()` runs for color render-target and storage bindings, but not after `FindDepthTarget()`, `MarkGpuWritten()`, or `ClearImage()` commits a GPU write. A supported depth target can have one layer, one level, and at most 64 texels. After `ProcessDownloadImages()` clears the pending set, a later write through one of these paths is absent from the next EOP readback. The EOP label can then become visible while guest memory still contains stale data. Rebinds through `FindRenderTarget()` re-enroll the image, but `TrackImage()` and `CommitGpuWrite()` do not. Call `TrackImageDownload()` after each `CommitGpuWrite()` in these paths. Also enroll an associated stencil image when that path commits the stencil image. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:76de61bc44d5f45190a89068 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit a4d3583
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 06:39 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7f1a84d1-d736-4b4f-82d7-9e706573d408
📥 Commits

Reviewing files that changed from the base of the PR and between 1a053f9e13 and ff1ac30272.

📒 Files selected for processing: 4
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h

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-20 06:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#pullrequestreview-5581564798) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `7f1a84d1-d736-4b4f-82d7-9e706573d408` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 1a053f9e13405bf34171a47aae9f2b9a6e7afd7d and ff1ac30272ce310850d8de5bb9c9f661db125719. </details> <details> <summary>📒 Files selected for processing: 4</summary> * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` </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=9db6b088-f9f5-436f-93db-1bf8fa4cac87 attempt=b8315f94-c3f1-44aa-bc87-d445594bea21 batch=1/1 -->
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-20 06:49 UTC · original

Fixed in a4d3583: interrupt-only and GDS EOP paths now land pending readbacks first, and tiny images are also enrolled after depth binds, MarkGpuWritten and clears (stencil associations skipped since they can’t be downloaded standalone).

**@⁠MrBigBritches** on GitHub · 2026-10-20 06:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6285158419) Fixed in a4d3583: interrupt-only and GDS EOP paths now land pending readbacks first, and tiny images are also enrolled after depth binds, MarkGpuWritten and clears (stencil associations skipped since they can’t be downloaded standalone).
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 06:54 UTC · original · edited 2026-10-20 07:09 UTC
On src/graphics/guest_gpu/graphicsRun.cpp line 1144 (outdated):

@@ -1121,6 +1141,16 @@ void CommandProcessor::WriteAtEndOfPipe(uint32_t cache_policy, uint32_t event_wr
 					auto* dst = static_cast<uint64_t*>(dst_gpu_addr);
 					EXIT_IF(dst == nullptr);
 					(void)command.Handle();
+					if (QueueReadbacksBeforeLabel()) {

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Preserve readback ordering across consecutive EOP labels.

If one EOP queues a readback, a following EOP can find no newly enrolled images and write its label directly. The guest can observe the second label before the first readback reaches guest memory. This affects both write64 and the write32 fallback. Defer a label while an earlier priority readback remains pending, even when QueueReadbacksBeforeLabel() returns false. The scheduler executes queued priority operations asynchronously. (raw.githubusercontent.com)

✅ Addressed in commit e11d9a0

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 06:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#discussion_r4322246573) · edited 2026-10-20 07:09 UTC On `src/graphics/guest_gpu/graphicsRun.cpp` line 1144 (outdated): ```diff @@ -1121,6 +1141,16 @@ void CommandProcessor::WriteAtEndOfPipe(uint32_t cache_policy, uint32_t event_wr auto* dst = static_cast<uint64_t*>(dst_gpu_addr); EXIT_IF(dst == nullptr); (void)command.Handle(); + if (QueueReadbacksBeforeLabel()) { ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **🏗️ Heavy lift** **Preserve readback ordering across consecutive EOP labels.** If one EOP queues a readback, a following EOP can find no newly enrolled images and write its label directly. The guest can observe the second label before the first readback reaches guest memory. This affects both `write64` and the `write32` fallback. Defer a label while an earlier priority readback remains pending, even when `QueueReadbacksBeforeLabel()` returns false. The scheduler executes queued priority operations asynchronously. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/main/src/graphics/host_gpu/renderer/commandScheduler.cpp)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0324b183cc8777fbfc8d59f4 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit e11d9a0
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 06:54 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: acada61f-8f42-4ff0-8b50-09f5143590e8
📥 Commits

Reviewing files that changed from the base of the PR and between ff1ac30272 and a4d3583cf3.

📒 Files selected for processing: 4
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
🚧 Files skipped from review as they are similar to previous changes: 2
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/host_gpu/renderer/cache/textureCache.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-20 06:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#pullrequestreview-5581679638) · **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**: `acada61f-8f42-4ff0-8b50-09f5143590e8` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between ff1ac30272ce310850d8de5bb9c9f661db125719 and a4d3583cf34f5a6d34f12bf964a1e2bc9a17e16c. </details> <details> <summary>📒 Files selected for processing: 4</summary> * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes: 2</summary> * src/graphics/guest_gpu/command_processor/commandProcessor.h * src/graphics/host_gpu/renderer/cache/textureCache.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=2decbefc-f6a9-44ac-a077-6c43fb6de358 attempt=c105b05f-87a2-4525-a257-11759106e65d batch=1/1 -->
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-20 07:09 UTC · original

Fixed in e11d9a0: labels deferred behind readbacks are now tracked, and while any are outstanding later labels are deferred behind them as well. Priority operations run FIFO, so labels publish in submission order.

**@⁠MrBigBritches** on GitHub · 2026-10-20 07:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6285442590) Fixed in e11d9a0: labels deferred behind readbacks are now tracked, and while any are outstanding later labels are deferred behind them as well. Priority operations run FIFO, so labels publish in submission order.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 07:17 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Drain earlier priority callbacks before the GDS interrupt. · graphicsRun.cpp:1102-1109

src/graphics/guest_gpu/graphicsRun.cpp:1102-1109
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Drain earlier priority callbacks before the GDS interrupt.

When an earlier EOP has queued a readback or deferred label, and this GDS invocation has no new pending image, QueueReadbacksBeforeLabel() returns false. SynchronizeGpu() waits for GPU work but does not drain priority callbacks. The conditional drain is skipped, so the GDS interrupt can run before the earlier callback completes. The guest can observe stale image or label data.

Suggested fix
-						const bool queued = QueueReadbacksBeforeLabel();
+						QueueReadbacksBeforeLabel();
						SynchronizeGpu();
-						if (queued) {
-							// SynchronizeGpu() waits for the GPU; also wait for the readback copies.
-							GetScheduler().DrainPriorityOperations();
-						}
+						// Wait for earlier readback and label callbacks before signalling the interrupt.
+						GetScheduler().DrainPriorityOperations();

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 45746562-35e8-482e-862d-87e53be7d914
📥 Commits

Reviewing files that changed from the base of the PR and between a4d3583cf3 and e11d9a00d1.

📒 Files selected for processing: 2
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp
🚧 Files skipped from review as they are similar to previous changes: 2
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 07:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#pullrequestreview-5581878491) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong>🟡 Minor</strong> · Drain earlier priority callbacks before the GDS interrupt. · <code>graphicsRun.cpp:1102-1109</code></summary><blockquote> > > `src/graphics/guest_gpu/graphicsRun.cpp:1102-1109` > **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** > > **Drain earlier priority callbacks before the GDS interrupt.** > > When an earlier EOP has queued a readback or deferred label, and this GDS invocation has no new pending image, `QueueReadbacksBeforeLabel()` returns `false`. `SynchronizeGpu()` waits for GPU work but does not drain priority callbacks. The conditional drain is skipped, so the GDS interrupt can run before the earlier callback completes. The guest can observe stale image or label data. > > <details> > <summary>Suggested fix</summary> > > ```diff > - const bool queued = QueueReadbacksBeforeLabel(); > + QueueReadbacksBeforeLabel(); > SynchronizeGpu(); > - if (queued) { > - // SynchronizeGpu() waits for the GPU; also wait for the readback copies. > - GetScheduler().DrainPriorityOperations(); > - } > + // Wait for earlier readback and label callbacks before signalling the interrupt. > + GetScheduler().DrainPriorityOperations(); > ``` > > </details> > > <!-- cr-comment:v1:4d2f0968479428da46562e3f --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `45746562-35e8-482e-862d-87e53be7d914` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between a4d3583cf34f5a6d34f12bf964a1e2bc9a17e16c and e11d9a00d12f017554510cb7cf73f5e20d860e40. </details> <details> <summary>📒 Files selected for processing: 2</summary> * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/graphicsRun.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes: 2</summary> * src/graphics/guest_gpu/command_processor/commandProcessor.h * src/graphics/guest_gpu/graphicsRun.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=177e311d-f656-45cf-b63d-61856a490f89 attempt=040d665a-438b-442f-ba24-a2b1f967b837 batch=1/1 -->
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-20 07:24 UTC · original

Fixed in 6f8fe5c: the GDS EOP path now always drains priority operations after SynchronizeGpu(), so earlier readbacks and deferred labels land before the interrupt.

**@⁠MrBigBritches** on GitHub · 2026-10-20 07:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6285677565) Fixed in 6f8fe5c: the GDS EOP path now always drains priority operations after SynchronizeGpu(), so earlier readbacks and deferred labels land before the interrupt.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 07:33 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟡 Minor · Retry failed tiny-image readbacks. · textureCache.cpp:1991-2004

src/graphics/host_gpu/renderer/cache/textureCache.cpp:1991-2004
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Retry failed tiny-image readbacks.

ProcessDownloadImages() clears m_download_images even when DownloadImageMemory() returns false. A tiny GPU-written image can therefore lose its pending readback after SafeToDownload(), CanDownload(), or TryReadBacking() fails. A later CPU read can observe stale guest memory.

Suggested fix
-	/// Records GPU-to-guest copies for all enrolled images and clears the enrollment set.
+	/// Records GPU-to-guest copies for enrolled images. Failed eligible entries remain pending.
 	/// @return true if at least one copy was queued (its guest write lands as a priority op).
 	bool ProcessDownloadImages();
 	bool queued = false;
-	for (const auto id: m_download_images) {
+	for (auto it = m_download_images.begin(); it != m_download_images.end();) {
+		const auto id = *it;
 		const auto owner = m_slot_images.try_get(id);
 		if (owner != nullptr && owner->registered && owner->IsGpuModified()) {
-			queued |= DownloadImageMemory(id);
+			if (DownloadImageMemory(id)) {
+				queued = true;
+				it = m_download_images.erase(it);
+			} else {
+				++it;
+			}
+		} else {
+			it = m_download_images.erase(it);
 		}
 	}
-	m_download_images.clear();
 	return queued;
🟡 Minor · Defer EOP labels while suspend-point readbacks are pending. · graphicsRun.cpp:1266-1286

src/graphics/guest_gpu/graphicsRun.cpp:1266-1286
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Defer EOP labels while suspend-point readbacks are pending.

RenderContext::RunGarbageCollector() can queue a readback priority callback and clear the enrollment set. The suspend-point path then queues m_suspend_point_ready and flushes, but GuestGpu::SuspendPoint() waits on that semaphore only when the next suspend point is submitted. Ordinary graphics submissions can run before that wait.

A later 32-bit or 64-bit EOP label can therefore call PublishLabelAfterReadbacks() while the earlier readback callback is still pending. The call sees no newly queued copy and no deferred-label count, so it writes the label synchronously. The guest can observe the label and read stale image data before WriteBacking() runs.

Include pending scheduler priority operations in the deferral condition. This preserves FIFO ordering without draining before the suspend-point flush.

Suggested fix
-	if (!queued && m_labels_behind_readbacks->load(std::memory_order_acquire) == 0) {
+	if (!queued && m_labels_behind_readbacks->load(std::memory_order_acquire) == 0 &&
+	    !GetScheduler().HasPendingPriorityOperations()) {
 		return false;
 	}

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 89dbc997-51cd-409d-851a-37979d470737
📥 Commits

Reviewing files that changed from the base of the PR and between e11d9a00d1 and 6f8fe5cc24.

📒 Files selected for processing: 1
  • src/graphics/guest_gpu/graphicsRun.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 07:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#pullrequestreview-5582023918) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (2)** > > <details> > <summary><strong>🟡 Minor</strong> · Retry failed tiny-image readbacks. · <code>textureCache.cpp:1991-2004</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/cache/textureCache.cpp:1991-2004` > **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** > > **Retry failed tiny-image readbacks.** > > `ProcessDownloadImages()` clears `m_download_images` even when `DownloadImageMemory()` returns `false`. A tiny GPU-written image can therefore lose its pending readback after `SafeToDownload()`, `CanDownload()`, or `TryReadBacking()` fails. A later CPU read can observe stale guest memory. > > <details> > <summary>Suggested fix</summary> > > ```diff > - /// Records GPU-to-guest copies for all enrolled images and clears the enrollment set. > + /// Records GPU-to-guest copies for enrolled images. Failed eligible entries remain pending. > /// @return true if at least one copy was queued (its guest write lands as a priority op). > bool ProcessDownloadImages(); > ``` > > ```diff > bool queued = false; > - for (const auto id: m_download_images) { > + for (auto it = m_download_images.begin(); it != m_download_images.end();) { > + const auto id = *it; > const auto owner = m_slot_images.try_get(id); > if (owner != nullptr && owner->registered && owner->IsGpuModified()) { > - queued |= DownloadImageMemory(id); > + if (DownloadImageMemory(id)) { > + queued = true; > + it = m_download_images.erase(it); > + } else { > + ++it; > + } > + } else { > + it = m_download_images.erase(it); > } > } > - m_download_images.clear(); > return queued; > ``` > > </details> > > <!-- cr-comment:v1:7288fb5a83d9499800083e3f --> > > </blockquote></details> > <details> > <summary><strong>🟡 Minor</strong> · Defer EOP labels while suspend-point readbacks are pending. · <code>graphicsRun.cpp:1266-1286</code></summary><blockquote> > > `src/graphics/guest_gpu/graphicsRun.cpp:1266-1286` > **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** > > **Defer EOP labels while suspend-point readbacks are pending.** > > `RenderContext::RunGarbageCollector()` can queue a readback priority callback and clear the enrollment set. The suspend-point path then queues `m_suspend_point_ready` and flushes, but `GuestGpu::SuspendPoint()` waits on that semaphore only when the next suspend point is submitted. Ordinary graphics submissions can run before that wait. > > A later 32-bit or 64-bit EOP label can therefore call `PublishLabelAfterReadbacks()` while the earlier readback callback is still pending. The call sees no newly queued copy and no deferred-label count, so it writes the label synchronously. The guest can observe the label and read stale image data before `WriteBacking()` runs. > > Include pending scheduler priority operations in the deferral condition. This preserves FIFO ordering without draining before the suspend-point flush. > > <details> > <summary>Suggested fix</summary> > > ```diff > - if (!queued && m_labels_behind_readbacks->load(std::memory_order_acquire) == 0) { > + if (!queued && m_labels_behind_readbacks->load(std::memory_order_acquire) == 0 && > + !GetScheduler().HasPendingPriorityOperations()) { > return false; > } > ``` > > </details> > > <!-- cr-comment:v1:45b83b062e332823806817a2 --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `89dbc997-51cd-409d-851a-37979d470737` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e11d9a00d12f017554510cb7cf73f5e20d860e40 and 6f8fe5cc2424c6a12d085525c6b15cac8e2a7e68. </details> <details> <summary>📒 Files selected for processing: 1</summary> * `src/graphics/guest_gpu/graphicsRun.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=67ce0ee5-0c18-4a19-8100-67486844859d attempt=3ddd0808-8901-4285-b4ce-87806aecfdb9 batch=1/1 -->
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-20 07:39 UTC · original

Fixed in f01c4cc. Failed readbacks are retried, but entries that can never be downloaded are dropped so they don’t stay pending forever. For label ordering, I gate on a texture-cache count of in-flight readbacks rather than HasPendingPriorityOperations(), which would also defer labels behind every flip and EOP interrupt.

**@⁠MrBigBritches** on GitHub · 2026-10-20 07:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6285932750) Fixed in f01c4cc. Failed readbacks are retried, but entries that can never be downloaded are dropped so they don’t stay pending forever. For label ordering, I gate on a texture-cache count of in-flight readbacks rather than HasPendingPriorityOperations(), which would also defer labels behind every flip and EOP interrupt.
Author
Owner

@⁠fozter on GitHub · 2026-10-21 12:20 UTC · original

Tested #1753 with NHL 27 (PPSA34063, 01.003.001) on Windows 11, NVIDIA GeForce RTX 3060 Ti (8 GB), driver 617.42. Base: main 4644c529 plus local patches that are not on main (a few NHL-specific fixes from #1101 and #1745), so this is not a clean-main result.

NHL 27 does use what this PR targets: in a session from boot to the end of the first period, the new enrollment picked up 64+ distinct tiny GPU-written images, most of them 1x1 with 8 bytes per texel (exposure/statistics-style targets), and more than 4,000 enrollments.

Two problems I hit:

  1. The deferred label write can need a buffer readback. In the first run the emulator exited in the menus with:

    unsupported buffer readback from an asynchronous GPU completion, addr=0x0000001131fd3428 size=0x0000000000000001
     in src/graphics/host_gpu/renderer/cache/bufferCache.cpp:473
    

    PublishLabelAfterReadbacks writes the label with std::memcpy inside a priority deferred operation. In NHL 27 the label sits in a page the buffer cache tracks (the GPU writes other bytes of that 4 KiB page), so the CPU write faults and BufferCache::ReadMemory refuses to run from a deferred operation. What worked for me: the deferred operation only hands the write to the GPU thread (GetGpu().SendCommand(...); ProcessPm4 runs pending commands between packets, and the FIFO keeps the labels in order), and the interrupt is triggered from that same command after the memcpy, so the guest cannot wake up before the label is visible. The GDS path that calls DrainPriorityOperations() then needs a ProcessCommands() before it writes its own label, so earlier deferred labels still land first. With that change the game plays through a full period, and the frame pacing is unchanged within noise.

  2. shader_recompiler_compute_tests fails (it needs a GPU, so CI does not run it):

    ShaderRecompilerComputeTests: RenderExecutorStencilBindingDiscovery failed at target prefetch purity: target prefetch performed final target acquisition
    

    The test clears a small target and then requires !TextureCacheTestAccess::PendingDownload(...) after binding it; the new EnrollTinyReadback in ClearImage puts it into m_download_images. Either the test's expectation or the enrollment point needs adjusting. audio_out2_port_tests (from #1745) passes.

AI disclosure: the analysis and the fix above were done with an AI assistant (Claude); I ran the tests and the game.

**@⁠fozter** on GitHub · 2026-10-21 12:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6315752427) Tested #1753 with NHL 27 (PPSA34063, 01.003.001) on Windows 11, NVIDIA GeForce RTX 3060 Ti (8 GB), driver 617.42. Base: main 4644c529 plus local patches that are not on main (a few NHL-specific fixes from #1101 and #1745), so this is not a clean-main result. NHL 27 does use what this PR targets: in a session from boot to the end of the first period, the new enrollment picked up 64+ distinct tiny GPU-written images, most of them 1x1 with 8 bytes per texel (exposure/statistics-style targets), and more than 4,000 enrollments. Two problems I hit: 1. **The deferred label write can need a buffer readback.** In the first run the emulator exited in the menus with: ``` unsupported buffer readback from an asynchronous GPU completion, addr=0x0000001131fd3428 size=0x0000000000000001 in src/graphics/host_gpu/renderer/cache/bufferCache.cpp:473 ``` `PublishLabelAfterReadbacks` writes the label with `std::memcpy` inside a priority deferred operation. In NHL 27 the label sits in a page the buffer cache tracks (the GPU writes other bytes of that 4 KiB page), so the CPU write faults and `BufferCache::ReadMemory` refuses to run from a deferred operation. What worked for me: the deferred operation only hands the write to the GPU thread (`GetGpu().SendCommand(...)`; `ProcessPm4` runs pending commands between packets, and the FIFO keeps the labels in order), and the interrupt is triggered from that same command after the `memcpy`, so the guest cannot wake up before the label is visible. The GDS path that calls `DrainPriorityOperations()` then needs a `ProcessCommands()` before it writes its own label, so earlier deferred labels still land first. With that change the game plays through a full period, and the frame pacing is unchanged within noise. 2. **`shader_recompiler_compute_tests` fails** (it needs a GPU, so CI does not run it): ``` ShaderRecompilerComputeTests: RenderExecutorStencilBindingDiscovery failed at target prefetch purity: target prefetch performed final target acquisition ``` The test clears a small target and then requires `!TextureCacheTestAccess::PendingDownload(...)` after binding it; the new `EnrollTinyReadback` in `ClearImage` puts it into `m_download_images`. Either the test's expectation or the enrollment point needs adjusting. `audio_out2_port_tests` (from #1745) passes. AI disclosure: the analysis and the fix above were done with an AI assistant (Claude); I ran the tests and the game.
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-21 15:30 UTC · original

Thanks for testing with another title. I’ll take a look

**@⁠MrBigBritches** on GitHub · 2026-10-21 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6319777705) Thanks for testing with another title. I’ll take a look
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-21 16:17 UTC · original

Thanks for testing on NHL 27 and for the detailed write-up. Both issues are fixed in b8d609a9:

The priority callback now only hands the label write to the GPU thread (FIFO between PM4 packets), and that same command triggers the interrupt after the memcpy. The GDS path runs ProcessCommands() after DrainPriorityOperations(), so earlier deferred labels land first. I also added GuestGpu::TrySendCommand so a callback that runs after the GPU thread stops accepting work drops its label instead of exiting. ShutdownGpu now drains priority callbacks before destroying the GuestGpu.
The stencil-binding test now expects the cleared tiny target to be enrolled by the clear, and checks that the render-target prefetch leaves that unchanged.

If you get a chance to rerun NHL 27 on this head, that would be great.

**@⁠MrBigBritches** on GitHub · 2026-10-21 16:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6320779043) Thanks for testing on NHL 27 and for the detailed write-up. Both issues are fixed in b8d609a9: The priority callback now only hands the label write to the GPU thread (FIFO between PM4 packets), and that same command triggers the interrupt after the memcpy. The GDS path runs ProcessCommands() after DrainPriorityOperations(), so earlier deferred labels land first. I also added GuestGpu::TrySendCommand so a callback that runs after the GPU thread stops accepting work drops its label instead of exiting. ShutdownGpu now drains priority callbacks before destroying the GuestGpu. The stencil-binding test now expects the cleared tiny target to be enrolled by the clear, and checks that the render-target prefetch leaves that unchanged. If you get a chance to rerun NHL 27 on this head, that would be great.
Author
Owner

@⁠Nmzik on GitHub · 2026-10-21 18:55 UTC · original

Credited

**@⁠Nmzik** on GitHub · 2026-10-21 18:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6324022125) Credited
Author
Owner

@⁠fozter on GitHub · 2026-10-21 19:59 UTC · original

Thanks for testing on NHL 27 and for the detailed write-up. Both issues are fixed in b8d609a:

The priority callback now only hands the label write to the GPU thread (FIFO between PM4 packets), and that same command triggers the interrupt after the memcpy. The GDS path runs ProcessCommands() after DrainPriorityOperations(), so earlier deferred labels land first. I also added GuestGpu::TrySendCommand so a callback that runs after the GPU thread stops accepting work drops its label instead of exiting. ShutdownGpu now drains priority callbacks before destroying the GuestGpu. The stencil-binding test now expects the cleared tiny target to be enrolled by the clear, and checks that the render-target prefetch leaves that unchanged.

If you get a chance to rerun NHL 27 on this head, that would be great.

Retested NHL 27 on b8d609a9 (same setup as before: main 4644c529 plus local NHL patches and #1745):

  • Boot, menus, loading and a full first period with no exit; the earlier "unsupported buffer readback from an asynchronous GPU completion" is gone, and closing the emulator afterwards shut down cleanly.
  • The tiny-image enrollment is active as before (64+ distinct images, mostly 1x1 at 8 bytes per texel, several thousand enrollments per session).
  • shader_recompiler_compute_tests passes again (101 checks, including RenderExecutorStencilBindingDiscovery), and audio_out2_port_tests passes.

Thanks for the quick fix.

**@⁠fozter** on GitHub · 2026-10-21 19:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1753#issuecomment-6325266813) > Thanks for testing on NHL 27 and for the detailed write-up. Both issues are fixed in [b8d609a](https://github.com/KytyPS5/KytyPS5/commit/b8d609a91e5778e82e54546e0302b25110e52f16): > > The priority callback now only hands the label write to the GPU thread (FIFO between PM4 packets), and that same command triggers the interrupt after the memcpy. The GDS path runs ProcessCommands() after DrainPriorityOperations(), so earlier deferred labels land first. I also added GuestGpu::TrySendCommand so a callback that runs after the GPU thread stops accepting work drops its label instead of exiting. ShutdownGpu now drains priority callbacks before destroying the GuestGpu. The stencil-binding test now expects the cleared tiny target to be enrolled by the clear, and checks that the render-target prefetch leaves that unchanged. > > If you get a chance to rerun NHL 27 on this head, that would be great. Retested NHL 27 on b8d609a9 (same setup as before: main 4644c529 plus local NHL patches and #1745): - Boot, menus, loading and a full first period with no exit; the earlier "unsupported buffer readback from an asynchronous GPU completion" is gone, and closing the emulator afterwards shut down cleanly. - The tiny-image enrollment is active as before (64+ distinct images, mostly 1x1 at 8 bytes per texel, several thousand enrollments per session). - `shader_recompiler_compute_tests` passes again (101 checks, including RenderExecutorStencilBindingDiscovery), and `audio_out2_port_tests` passes. Thanks for the quick fix.

Pull request closed

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