Windows stability fixes found while bringing up Tekken 8 (PPSA10595) #833

Open
github-bot wants to merge 13 commits from github-bot/gh-833 into main AGit
Owner

@⁠hamzashakir99 on GitHub · 2026-09-25 18:09 UTC · original
hamzashakir99:pr/windows-stability-fixes → main · +831 −105 · 23 files · 13 commits · open

Summary

Windows stability fixes found while bringing up Tekken 8 (PPSA10595), an Unreal Engine 5 title. Before these changes the game crashed silently during boot. With them it reaches the title screen, the EULA, the main menu, character select, stage select and an in-game fight (HUD rendered).

None of the changes are game-specific; each fixes a general emulator bug that this title happened to expose.

Changes

CPU / kernel (Windows)

  • Red-zone patcher tracks the RBP frame pointer. Functions that address their red zone through rbp rather than rsp were not patched, so Windows exception frames corrupted live locals.
  • Red-zone patcher resolves jump tables outside the code segment, bounds-checked against the module, so switch targets are no longer missed.
  • Signal APC frames are kept out of the guest red zone. A thread interrupted by sceKernelRaiseException is parked below its 128-byte red zone before the handler runs.
  • Live guest thread and fiber stacks are never write-protected for GPU tracking. If a stack page was protected, Windows could not deliver the exception to the faulting thread and terminated the process through WER without any log. Fiber stacks are now registered and unregistered in FiberInitialize / FiberFinalize.

GPU

  • Readbacks of already-submitted GPU writes no longer drain the command buffer currently being recorded.
  • Large readbacks are chunked so they fit the 64 MiB staging buffer, and the aggressive buffer GC keeps its downloads within that budget. Stage loading previously exited on "download exceeds staging buffer".
  • DCC clear readbacks are skipped when the metadata was last written by a known uniform-fill compute dispatch.
  • Texture cache: a 3D volume reused at the same address for a deeper volume is expanded instead of hitting "unresolvable equal-address overlap". A 3D→3D copy only copies the smaller depth.
  • Sampler cache: reserved anisotropy ratios 5–7 map to 16× instead of asserting.
  • Shader LDS is clamped to maxComputeSharedMemorySize. PS5 shaders can request up to 64 KiB, but NVIDIA RTX 40 exposes 48 KiB in Vulkan. The oversized pipeline was invalid and lost the device.
  • Shader recompiler: V_NOT_B32 with an SDWA partial destination accepts any source selector; MaxBuffers is raised to 64. Covered by shaderCfgTests.

Other

  • The pipeline cache is also saved every 30 s, not only on a clean exit, so a crash no longer throws away the compiled pipelines.
  • The audio queue target latency defaults to 100 ms (override with KYTY_AUDIO_LATENCY_MS), which reduces crackling when a frame takes longer than usual.
  • A gamepad SDL cannot open is logged and skipped instead of asserting.
  • KYTY_VALIDATION_NONFATAL=1 prints each unique Vulkan validation error instead of exiting on the first one.

Testing

  • Windows 11, NVIDIA RTX 40-series laptop GPU, Release build (clang-cl, Ninja).
  • shaderCfgTests and virtual_memory_allocation_tests pass.
  • Tekken 8 (PPSA10595) was played from boot through the menus into a fight. The main menu, character select and stage select render correctly.

Known remaining issues (not addressed here)

  • Performance is limited by CPU↔GPU readbacks on shared memory (about 160 per second in the main menu), so the game runs at about 9 fps.
  • In-fight 3D lighting: one clustered-lighting compute pass still loses the device on NVIDIA. It needs further investigation, so this PR includes no workaround for it.

🤖 Generated with Claude Code

**@⁠hamzashakir99** on GitHub · 2026-09-25 18:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833) `hamzashakir99:pr/windows-stability-fixes` → `main` · +831 −105 · 23 files · 13 commits · open ## Summary Windows stability fixes found while bringing up **Tekken 8 (PPSA10595)**, an Unreal Engine 5 title. Before these changes the game crashed silently during boot. With them it reaches the title screen, the EULA, the main menu, character select, stage select and an in-game fight (HUD rendered). None of the changes are game-specific; each fixes a general emulator bug that this title happened to expose. ## Changes ### CPU / kernel (Windows) - **Red-zone patcher tracks the RBP frame pointer.** Functions that address their red zone through `rbp` rather than `rsp` were not patched, so Windows exception frames corrupted live locals. - **Red-zone patcher resolves jump tables outside the code segment**, bounds-checked against the module, so switch targets are no longer missed. - **Signal APC frames are kept out of the guest red zone.** A thread interrupted by `sceKernelRaiseException` is parked below its 128-byte red zone before the handler runs. - **Live guest thread and fiber stacks are never write-protected for GPU tracking.** If a stack page was protected, Windows could not deliver the exception to the faulting thread and terminated the process through WER without any log. Fiber stacks are now registered and unregistered in `FiberInitialize` / `FiberFinalize`. ### GPU - **Readbacks of already-submitted GPU writes** no longer drain the command buffer currently being recorded. - **Large readbacks are chunked** so they fit the 64 MiB staging buffer, and the aggressive buffer GC keeps its downloads within that budget. Stage loading previously exited on "download exceeds staging buffer". - **DCC clear readbacks are skipped** when the metadata was last written by a known uniform-fill compute dispatch. - **Texture cache:** a 3D volume reused at the same address for a deeper volume is expanded instead of hitting "unresolvable equal-address overlap". A 3D→3D copy only copies the smaller depth. - **Sampler cache:** reserved anisotropy ratios 5–7 map to 16× instead of asserting. - **Shader LDS is clamped to `maxComputeSharedMemorySize`.** PS5 shaders can request up to 64 KiB, but NVIDIA RTX 40 exposes 48 KiB in Vulkan. The oversized pipeline was invalid and lost the device. - **Shader recompiler:** `V_NOT_B32` with an SDWA partial destination accepts any source selector; `MaxBuffers` is raised to 64. Covered by `shaderCfgTests`. ### Other - The pipeline cache is also saved every 30 s, not only on a clean exit, so a crash no longer throws away the compiled pipelines. - The audio queue target latency defaults to 100 ms (override with `KYTY_AUDIO_LATENCY_MS`), which reduces crackling when a frame takes longer than usual. - A gamepad SDL cannot open is logged and skipped instead of asserting. - `KYTY_VALIDATION_NONFATAL=1` prints each unique Vulkan validation error instead of exiting on the first one. ## Testing - Windows 11, NVIDIA RTX 40-series laptop GPU, Release build (clang-cl, Ninja). - `shaderCfgTests` and `virtual_memory_allocation_tests` pass. - Tekken 8 (PPSA10595) was played from boot through the menus into a fight. The main menu, character select and stage select render correctly. ## Known remaining issues (not addressed here) - Performance is limited by CPU↔GPU readbacks on shared memory (about 160 per second in the main menu), so the game runs at about 9 fps. - In-fight 3D lighting: one clustered-lighting compute pass still loses the device on NVIDIA. It needs further investigation, so this PR includes no workaround for it. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Frame-pointer leaf functions address red-zone locals through RBP below
RSP (e.g. [rbp-0x108] with rsp = rbp-0xc8). The patcher only modeled
RSP-relative operands, so such functions were left unprotected and a
handled access fault overwrote their locals (PPSA10595 crash in a
decompressor on Background Worker #2).

Track RBP - RSP through the CFG, translate frame-relative operands into
the red-zone model, resolve mov rsp,rbp / lea rsp,[rbp+k] / leave deltas,
and fall back to conservative protection when the offset is unknown.
Also follow resolved jump-table successors in the liveness pass.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
sceKernelRaiseException delivers SIGUSR1 as a Windows special user APC.
Windows builds the APC frame directly below the interrupted RSP, which
overwrites live red-zone locals of SysV leaf functions. PPSA10595 (UE5)
signals worker threads while they run a zstd Huffman decoder whose
tableLog slot sits below RSP; the slot came back as zero and the decoder
faulted on a wild table index.

Suspend the target before queuing the APC and, when it is in guest code,
move RSP below the red zone with RIP parked on a "ret 0x80" stub that
restores it in one instruction. The APC handler unparks the context
first, so the guest handler sees and resumes at the real RIP/RSP.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Jump tables usually sit in a read-only data segment, but the resolver
only accepted tables inside the executable segment being patched. Every
function with a switch was treated as having an unknown indirect branch,
which disables neighbour relocation, so its short memory instructions
stayed unprotected: 178406 of 520371 in PPSA10595's eboot.bin, including
the zstd decoder stores whose handled GPU-tracking faults wiped its red
zone. Accept tables anywhere in the loaded module once readable.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The SDWA source extract and destination insert are applied independently in Translate.cpp, so a partial destination can combine with any source selector (PPSA10595 uses v_not_b32 v28.word0, v8.word1 with UNUSED_PRESERVE). The CFG test now covers that form instead of rejecting it.

Raise ShaderInfo::MaxBuffers from 32 to 64 for PPSA10595's compute shader 0x861b5c2f3b868f59; nothing else sizes or packs buffer indices to 32.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Windows builds the exception frame on the faulting thread's stack. When GPU memory tracking had write-protected that stack, the kernel could not deliver the fault at all and WerSvc terminated the process with no report. PPSA10595 runs UE task fibers (TeTask) on stacks carved from game memory that shares tracked pages.

Keep a registry of every live pthread and sceFiber stack, make each range writable when registered, and have PageManager refuse to protect any page overlapping one. Emulator-allocated stacks also get a 512 KiB host-only area below the guest stack for host fault handling. Guest exit() and sceKernelDebugRaiseException now print their caller.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CPU reads of GPU-written memory copied through the command buffer being recorded and waited for its whole tick. Track each buffer's last GPU write tick; when that work was already submitted, copy on a dedicated command buffer with its own timeline semaphore, which only waits for earlier submissions. Writes from the recording command buffer keep the old path. KYTY_SLOW_READBACK=1 forces the old path.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
MaterializeDccClear read GPU-written DCC metadata back to the CPU, draining the GPU several times per frame. In PPSA10595 that metadata is written by compute shaders the recompiler already recognises as uniform buffer fills (ResolveComputeBufferFill), but the value was only used for image clears.

The buffer cache now remembers the value of GPU-side uniform fills (FillBuffer and uniform-fill compute dispatches) per range, forgetting it on any other GPU or CPU write. DCC clear discovery uses a known fill instead of reading back. In PPSA10595's main menu readbacks drop from about 1 in 7 lookups to about 1 in 90, and fps rises from 6-7 to 9.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- BufferCache::ReadMemory reads back in 8 MiB chunks. PPSA10595's stage select read more than the 64 MiB download staging buffer at once and exited.
- The Vulkan pipeline cache was only written on a clean window close, so a crash lost every compiled pipeline. Snapshot it at most every 30 s while new pipelines are created.
- Raise the blocking audio output queue target from 40 ms to 100 ms (KYTY_AUDIO_LATENCY_MS) so short emulator stalls do not drain it and crackle.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Aggressive garbage collection queued downloads for up to 64 dirty buffers in one command buffer, all sharing the 64 MiB download staging buffer; PPSA10595's stage load exceeded it and exited. Retire dirty buffers only while the round's total stays under 48 MiB; the rest stay cached for a later round.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
PPSA10595's stage load reuses the memory of a 9 MiB 3D texture for a 24 MiB one with equal pitch, height, format and levels. ResolveOverlap only expanded equal-size volumes and exited on this. Expand to the deeper volume instead.

Image::CopyImage used the destination depth for volume-to-volume copies, which would read past a shallower source; copy only the depth both volumes have.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
MaxAnisoRatio is a 3-bit field with 0-4 defined; PPSA10595 uses 7 in a fight and the emulator exited. The hardware saturates reserved values at 16x.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Guest compute shaders sized for the PS5's 64 KiB of LDS are clamped to the
host's maxComputeSharedMemorySize (48 KiB on NVIDIA RTX 40), which previously
produced invalid pipelines and lost the device. A gamepad SDL cannot open is
logged and skipped instead of asserting. KYTY_VALIDATION_NONFATAL=1 prints
each unique validation error instead of exiting on the first.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:10 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original · edited 2026-09-25 18:30 UTC

Review in Change Stack →

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

📝 Walkthrough

Walkthrough

The changes add submitted-work GPU buffer readback, known-fill tracking, and limits on dirty-buffer downloads. Guest-stack tracking and Windows signal handling now account for stack ranges and the guest red zone. The red-zone patcher analyzes frame-pointer accesses and jump-table control flow. Other changes update shader limits and decoding, image and sampler handling, pipeline-cache snapshots, Vulkan validation output, audio queue latency, and gamepad-open failure handling.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to 22ffc

GPU data may become stale, Windows signal delivery can fail, and some resources or pipeline-cache progress may be lost. Resolve the material paths before merging; the malformed audio setting is a narrower issue.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 22ffc

A live guest stack can cause protection to be skipped for neighboring memory, and stack registrations can outlive or lose their owner. These conditions could undermine memory-change tracking. The review found no evidence of a host escape or broader security compromise.

Retained concerns

  • Medium · reliability · inferred: A stack overlap skips protection of the entire coalesced page range, potentially leaving adjacent tracked pages writable without updating the corresponding memory-change control.
  • Medium · reliability · inferred: Address-only stack registrations do not preserve fiber ownership: reinitializing a fiber can leave an old range exempt, while unregistering one of two users of an address removes both registrations.
Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is within one emulator process's guest memory tracking and GPU backing. The examined paths do not establish cross-tenant reachability or a host-code execution path.

Security Findings and Attack Paths

  • inferred — A caller-supplied fiber stack can influence which page-protection requests are skipped. Adjacent pages in the same request, or memory covered by a stale registration, may then evade the protection used for change tracking; no host escape is established.

Trust Boundaries and Controls

  • observed — The live-stack registry uses a mutex for lookup and mutation, but PageManager releases that lock before applying protection. Registration restores read/write access separately, so those operations do not form one atomic exclusion.

Resilience and Maintainability Implications

  • inferred — Normal cleanup reduces stale registrations, but address-only removal cannot distinguish separate owners of the same range, and fiber reinitialization does not enforce the preceding registration's termination.

Hardening Proposals

  • proposed — Apply protection separately to stack and non-stack page spans, and tie each exemption to an owner or registration handle with a defined reinitialization and cleanup transition.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 8.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 85 functions across 22 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main purpose: Windows stability fixes discovered while bringing up Tekken 8. It is concise and specific.
Description check ✅ Passed The description directly explains the Windows, GPU, shader, pipeline, audio, input, and validation changes. It also includes testing results and known limitations.
Full details: Docstring Coverage

Explanation

Docstring coverage is 8.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 85 functions across 22 files. (1 skipped: 1 too large.)


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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#issuecomment-5837460508) · edited 2026-09-25 18:30 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/833"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The changes add submitted-work GPU buffer readback, known-fill tracking, and limits on dirty-buffer downloads. Guest-stack tracking and Windows signal handling now account for stack ranges and the guest red zone. The red-zone patcher analyzes frame-pointer accesses and jump-table control flow. Other changes update shader limits and decoding, image and sampler handling, pipeline-cache snapshots, Vulkan validation output, audio queue latency, and gamepad-open failure handling. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"22ffc198027fd364405a0b174007f409d6d9f155" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `22ffc` <!-- final_review_risk_coverage:{"sourceCommitId":"22ffc198027fd364405a0b174007f409d6d9f155","coveredCommitId":"22ffc198027fd364405a0b174007f409d6d9f155","kind":"reviewed"} --> GPU data may become stale, Windows signal delivery can fail, and some resources or pipeline-cache progress may be lost. Resolve the material paths before merging; the malformed audio setting is a narrower issue. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `22ffc` A live guest stack can cause protection to be skipped for neighboring memory, and stack registrations can outlive or lose their owner. These conditions could undermine memory-change tracking. The review found no evidence of a host escape or broader security compromise. **Retained concerns** - **Medium · reliability · inferred:** A stack overlap skips protection of the entire coalesced page range, potentially leaving adjacent tracked pages writable without updating the corresponding memory-change control. - **Medium · reliability · inferred:** Address-only stack registrations do not preserve fiber ownership: reinitializing a fiber can leave an old range exempt, while unregistering one of two users of an address removes both registrations. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The demonstrated exposure is within one emulator process's guest memory tracking and GPU backing. The examined paths do not establish cross-tenant reachability or a host-code execution path. **Security Findings and Attack Paths** - _inferred_ — A caller-supplied fiber stack can influence which page-protection requests are skipped. Adjacent pages in the same request, or memory covered by a stale registration, may then evade the protection used for change tracking; no host escape is established. **Trust Boundaries and Controls** - _observed_ — The live-stack registry uses a mutex for lookup and mutation, but PageManager releases that lock before applying protection. Registration restores read/write access separately, so those operations do not form one atomic exclusion. **Resilience and Maintainability Implications** - _inferred_ — Normal cleanup reduces stale registrations, but address-only removal cannot distinguish separate owners of the same range, and fiber reinitialization does not enforce the preceding registration's termination. **Hardening Proposals** - _proposed_ — Apply protection separately to stack and non-stack page spans, and tie each exemption to an owner or registration handle with a defined reinitialization and cleanup transition. </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 8.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 85 functions across 22 files. (1 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Title check | ✅ Passed | The title clearly identifies the main purpose: Windows stability fixes discovered while bringing up Tekken 8. It is concise and specific. | | Description check | ✅ Passed | The description directly explains the Windows, GPU, shader, pipeline, audio, input, and validation changes. It also includes testing results and known limitations. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 8.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 85 functions across 22 files. (1 skipped: 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -194,0 +206,4 @@
std::fflush(stdout);
}
return;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original

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

Skip protection only for the part of the range that overlaps the stack.

UpdateRegionWatchers merges consecutive pages into one Protect call. That call can cover pages on both sides of a stack. The new check returns early when any part overlaps a live stack. The pages outside the stack then stay ReadWrite, while PageState records watchers for them. Guest writes to those pages do not fault, and the GPU cache misses the invalidation.

Protect the parts before and after the overlap. Repeat for other live stacks that overlap the remaining parts.

Proposed fix
 		if (mode != Common::VirtualMemory::Mode::ReadWrite &&
 		    Libs::LibKernel::FindLiveGuestStack(vaddr, size, &stack_start, &stack_end)) {
 			...log...
+			const uint64_t end = vaddr + size;
+			const uint64_t lo  = Common::AlignDown(stack_start, PAGE_SIZE);
+			const uint64_t hi  = Common::AlignUp(stack_end, PAGE_SIZE);
+			if (vaddr < lo) {
+				Protect(vaddr, lo - vaddr, mode);
+			}
+			if (hi < end) {
+				Protect(hi, end - hi, mode);
+			}
 			return;
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		if (mode != Common::VirtualMemory::Mode::ReadWrite &&
		    Libs::LibKernel::FindLiveGuestStack(vaddr, size, &stack_start, &stack_end)) {
			static std::atomic<uint32_t> reports {0};
			if (reports.fetch_add(1, std::memory_order_relaxed) < 16) {
				std::printf("PageManager: refusing to protect 0x%016" PRIx64 "+0x%" PRIx64
				            " (mode 0x%x): overlaps live guest stack 0x%016" PRIx64
				            "-0x%016" PRIx64 "\n",
				            vaddr, size, static_cast<uint32_t>(mode), stack_start, stack_end);
				std::fflush(stdout);
			}
			const uint64_t end = vaddr + size;
			const uint64_t lo  = Common::AlignDown(stack_start, PAGE_SIZE);
			const uint64_t hi  = Common::AlignUp(stack_end, PAGE_SIZE);
			if (vaddr < lo) {
				Protect(vaddr, lo - vaddr, mode);
			}
			if (hi < end) {
				Protect(hi, end - hi, mode);
			}
			return;
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#discussion_r4107461701) _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ **Skip protection only for the part of the range that overlaps the stack.** `UpdateRegionWatchers` merges consecutive pages into one `Protect` call. That call can cover pages on both sides of a stack. The new check returns early when any part overlaps a live stack. The pages outside the stack then stay `ReadWrite`, while `PageState` records watchers for them. Guest writes to those pages do not fault, and the GPU cache misses the invalidation. Protect the parts before and after the overlap. Repeat for other live stacks that overlap the remaining parts. <details> <summary>Proposed fix</summary> ```diff if (mode != Common::VirtualMemory::Mode::ReadWrite && Libs::LibKernel::FindLiveGuestStack(vaddr, size, &stack_start, &stack_end)) { ...log... + const uint64_t end = vaddr + size; + const uint64_t lo = Common::AlignDown(stack_start, PAGE_SIZE); + const uint64_t hi = Common::AlignUp(stack_end, PAGE_SIZE); + if (vaddr < lo) { + Protect(vaddr, lo - vaddr, mode); + } + if (hi < end) { + Protect(hi, end - hi, mode); + } return; } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (mode != Common::VirtualMemory::Mode::ReadWrite && Libs::LibKernel::FindLiveGuestStack(vaddr, size, &stack_start, &stack_end)) { static std::atomic<uint32_t> reports {0}; if (reports.fetch_add(1, std::memory_order_relaxed) < 16) { std::printf("PageManager: refusing to protect 0x%016" PRIx64 "+0x%" PRIx64 " (mode 0x%x): overlaps live guest stack 0x%016" PRIx64 "-0x%016" PRIx64 "\n", vaddr, size, static_cast<uint32_t>(mode), stack_start, stack_end); std::fflush(stdout); } const uint64_t end = vaddr + size; const uint64_t lo = Common::AlignDown(stack_start, PAGE_SIZE); const uint64_t hi = Common::AlignUp(stack_end, PAGE_SIZE); if (vaddr < lo) { Protect(vaddr, lo - vaddr, mode); } if (hi < end) { Protect(hi, end - hi, mode); } return; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:aebac7421511fdc7688b25ff --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -257,0 +416,4 @@
if (!slow_readback && buffer.last_gpu_write_tick < m_scheduler.CurrentTick()) {
if (ReadbackSubmitted(buffer, chunk, chunk_size)) {
m_memory_tracker.UnmarkRegionAsGpuModified(chunk, chunk_size);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C3 'last_gpu_write_tick|SynchronizeBufferFromImage\s*\(|m_gpu_modified_ranges\.Add' src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 5305


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- bufferCache outline ---'
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --view compact
printf '%s\n' '--- bufferCache relevant source ---'
sed -n '360,670p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- textureCache image synchronization ---'
sed -n '1710,1795p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- bound symbols and scheduler semantics ---'
rg -n -P -C4 'ReadbackSubmitted|SynchronizeBufferFromImage|SynchronizeBuffer\(|CurrentTick\(\)|Current\(\)|m_gpu_modified_ranges' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 332


🏁 Script executed:

#!/bin/bash
set -e
sed -n '370,455p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '500,650p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '1740,1790p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -P -C5 'ReadbackSubmitted|DownloadImage|TileImage|DownloadBufferMemory|UploadCopies|CurrentTick\(\)|class Scheduler|Current\(\)' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -n 600

Repository: KytyPS5/KytyPS5

Length of output: 42265


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- readback and download implementations ---'
rg -n -P -C8 'ReadbackSubmitted|DownloadBufferMemory|void Image::Download|Image::Download\(|TileImage\(' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer
printf '%s\n' '--- GPU modified range tracking ---'
rg -n -P -C6 'm_gpu_modified_ranges|IsRegionGpuModified|UnmarkRegionAsGpuModified|MarkRegionAsGpuModified|ForEach.*GpuModified|ReadMemory\(' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 42129


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact submitted readback ---'
sed -n '108,245p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- image and tiler symbol locations ---'
rg -n -g '*.h' -g '*.cpp' 'class Image|struct Image|Image::Download|TileImage\(' src/graphics
printf '%s\n' '--- scheduler-bearing implementations ---'
rg -n -P -C10 'void .*::Download\s*\(|void .*::TileImage\s*\(|class Tiler|struct Tiler' src/graphics

Repository: KytyPS5/KytyPS5

Length of output: 14052


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- ObtainBuffer call sites ---'
rg -n -P -C4 'ObtainBuffer\s*\(' src/graphics/host_gpu
printf '%s\n' '--- image download command recording ---'
sed -n '259,320p' src/graphics/host_gpu/renderer/image/image.cpp
sed -n '393,470p' src/graphics/host_gpu/renderer/image/tiler.cpp

Repository: KytyPS5/KytyPS5

Length of output: 16231


Track image-to-buffer writes in last_gpu_write_tick.

SynchronizeBufferFromImage queues DownloadImage in the current command buffer but does not update last_gpu_write_tick. If the range remains in m_gpu_modified_ranges, ReadMemory can select ReadbackSubmitted and copy data before the current image download executes. Update the tick after queueing the image download.

The is_written upload path already updates the tick in ObtainBuffer; no additional assignment is needed there.

🐛 Suggested fix
 m_texture_cache.DownloadImage(image, buffer, buf_offset, copy_size, std::move(transfer));
+buffer.last_gpu_write_tick = m_scheduler.CurrentTick();
 return true;
**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#discussion_r4107461733) _🗄️ Data Integrity & Integration_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C3 'last_gpu_write_tick|SynchronizeBufferFromImage\s*\(|m_gpu_modified_ranges\.Add' src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 5305 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- bufferCache outline ---' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --view compact printf '%s\n' '--- bufferCache relevant source ---' sed -n '360,670p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- textureCache image synchronization ---' sed -n '1710,1795p' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- bound symbols and scheduler semantics ---' rg -n -P -C4 'ReadbackSubmitted|SynchronizeBufferFromImage|SynchronizeBuffer\(|CurrentTick\(\)|Current\(\)|m_gpu_modified_ranges' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 332 --- 🏁 Script executed: ```bash #!/bin/bash set -e sed -n '370,455p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '500,650p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '1740,1790p' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -P -C5 'ReadbackSubmitted|DownloadImage|TileImage|DownloadBufferMemory|UploadCopies|CurrentTick\(\)|class Scheduler|Current\(\)' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -n 600 ``` Repository: KytyPS5/KytyPS5 Length of output: 42265 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- readback and download implementations ---' rg -n -P -C8 'ReadbackSubmitted|DownloadBufferMemory|void Image::Download|Image::Download\(|TileImage\(' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer printf '%s\n' '--- GPU modified range tracking ---' rg -n -P -C6 'm_gpu_modified_ranges|IsRegionGpuModified|UnmarkRegionAsGpuModified|MarkRegionAsGpuModified|ForEach.*GpuModified|ReadMemory\(' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 42129 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- exact submitted readback ---' sed -n '108,245p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- image and tiler symbol locations ---' rg -n -g '*.h' -g '*.cpp' 'class Image|struct Image|Image::Download|TileImage\(' src/graphics printf '%s\n' '--- scheduler-bearing implementations ---' rg -n -P -C10 'void .*::Download\s*\(|void .*::TileImage\s*\(|class Tiler|struct Tiler' src/graphics ``` Repository: KytyPS5/KytyPS5 Length of output: 14052 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- ObtainBuffer call sites ---' rg -n -P -C4 'ObtainBuffer\s*\(' src/graphics/host_gpu printf '%s\n' '--- image download command recording ---' sed -n '259,320p' src/graphics/host_gpu/renderer/image/image.cpp sed -n '393,470p' src/graphics/host_gpu/renderer/image/tiler.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 16231 --- </details> **Track image-to-buffer writes in `last_gpu_write_tick`.** `SynchronizeBufferFromImage` queues `DownloadImage` in the current command buffer but does not update `last_gpu_write_tick`. If the range remains in `m_gpu_modified_ranges`, `ReadMemory` can select `ReadbackSubmitted` and copy data before the current image download executes. Update the tick after queueing the image download. The `is_written` upload path already updates the tick in `ObtainBuffer`; no additional assignment is needed there. <details> <summary>🐛 Suggested fix</summary> ```diff m_texture_cache.DownloadImage(image, buffer, buf_offset, copy_size, std::move(transfer)); +buffer.last_gpu_write_tick = m_scheduler.CurrentTick(); return true; ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a648d6b5f2b4ffcbdf9c5267 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -606,0 +785,4 @@
if (buffer.Size() > DownloadBudget - download_bytes) {
return false;
}
download_bytes += buffer.Size();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '750,810p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n 'GarbageCollect|DownloadBufferMemory|AllocateBuffer|buffer_size|size_bytes' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 2955


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- buffer cache outline ---'
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- GC continuation ---'
sed -n '780,850p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- relevant definitions and calls ---'
rg -n -C 3 'BufferCache::(Allocate|Create|Insert|Delete|Download|ReadMemory|RunGarbageCollector)|RunGarbageCollector|DeleteBuffer|m_lru_cache|m_slot_buffers|Resize|size' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer -g '*.cpp' -g '*.h' | head -n 500
printf '%s\n' '--- tracked files ---'
git ls-files 'src/graphics/host_gpu/renderer/cache/*'

Repository: KytyPS5/KytyPS5

Length of output: 41887


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- buffer cache implementations ---'
sed -n '1,285p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '430,575p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- buffer cache declarations and members ---'
sed -n '1,180p' src/graphics/host_gpu/renderer/cache/bufferCache.h
printf '%s\n' '--- stream buffer construction ---'
sed -n '1,180p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
printf '%s\n' '--- GC and deletion references ---'
rg -n -C 4 'RunGarbageCollector|DeleteBuffer\\(|CreateBuffer\\(|m_lru_cache\\.(ForEachItemBelow|Erase|Insert|Touch|Add|Remove)|lru_id|m_slot_buffers\\.erase|Unregister\\(' src -g '*.cpp' -g '*.h'

Repository: KytyPS5/KytyPS5

Length of output: 32942


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- buffer cache control flow ---'
sed -n '286,449p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '575,755p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- LRU implementation ---'
rg -n -C 8 'class LeastRecentlyUsedCache|ForEachItemBelow|LeastRecentlyUsedCache' src/common src -g '*.h' -g '*.cpp'
printf '%s\n' '--- buffer-cache callers ---'
rg -n -C 3 'ObtainBuffer\\(|ObtainBufferForImage\\(|FindBuffer\\(|ReadMemory\\(|RunGarbageCollector\\(' src -g '*.cpp' -g '*.h'

Repository: KytyPS5/KytyPS5

Length of output: 25854


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- complete LRU implementation ---'
sed -n '1,130p' src/common/lruCache.h
printf '%s\n' '--- direct call sites ---'
rg -n -C 3 'RunGarbageCollector' src -g '*.cpp' -g '*.h' || true
rg -n -C 3 'ObtainBufferForImage' src -g '*.cpp' -g '*.h' || true
rg -n -C 3 'ObtainBuffer' src -g '*.cpp' -g '*.h' || true
rg -n -C 3 'ReadMemory' src -g '*.cpp' -g '*.h' || true
printf '%s\n' '--- buffer destruction and overlap callers ---'
rg -n -C 3 'DeleteBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h
rg -n -C 3 'JoinOverlap' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 29000


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- guest range and request-size bounds ---'
rg -n -C 8 'struct GuestRange|class GuestRange|GuestRange::Valid|RequestedSize\\(' src -g '*.h' -g '*.cpp'
printf '%s\n' '--- copy-buffer callers ---'
rg -n -C 4 'CopyBuffer\\(' src/graphics -g '*.cpp' -g '*.h'
printf '%s\n' '--- memory-pressure accounting ---'
sed -n '755,820p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -C 5 'm_total_used_memory|GetDeviceMemoryUsage' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/renderContext.cpp

Repository: KytyPS5/KytyPS5

Length of output: 326


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- GuestRange references ---'
rg -n -F -C 6 'GuestRange' src -g '*.h' -g '*.cpp' | head -n 160
printf '%s\n' '--- RequestedSize references ---'
rg -n -F -C 6 'RequestedSize' src -g '*.h' -g '*.cpp' | head -n 120
printf '%s\n' '--- accounting and GC ---'
sed -n '755,820p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -F -C 5 'm_total_used_memory' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 20199


Chunk oversized dirty buffers during garbage collection.

ObtainBuffer(..., true) can create a buffer for a valid guest range larger than 48 MiB. When that buffer becomes old and remains GPU-dirty, non-aggressive GC skips it, and aggressive GC also skips it because its size exceeds the entire DownloadBudget. The LRU traversal does not remove skipped items, so each eligible GC round repeats this.

ReadMemory can clear the dirty state, and an overlapping request can replace the buffer. Without either path, the device allocation remains cached and continues to consume memory. Reuse the existing 8 MiB readback chunking, with completion waits between chunks, before untracking and retiring an oversized buffer.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#discussion_r4107461740) _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '750,810p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n 'GarbageCollect|DownloadBufferMemory|AllocateBuffer|buffer_size|size_bytes' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 2955 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- buffer cache outline ---' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- GC continuation ---' sed -n '780,850p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- relevant definitions and calls ---' rg -n -C 3 'BufferCache::(Allocate|Create|Insert|Delete|Download|ReadMemory|RunGarbageCollector)|RunGarbageCollector|DeleteBuffer|m_lru_cache|m_slot_buffers|Resize|size' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer -g '*.cpp' -g '*.h' | head -n 500 printf '%s\n' '--- tracked files ---' git ls-files 'src/graphics/host_gpu/renderer/cache/*' ``` Repository: KytyPS5/KytyPS5 Length of output: 41887 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- buffer cache implementations ---' sed -n '1,285p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '430,575p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- buffer cache declarations and members ---' sed -n '1,180p' src/graphics/host_gpu/renderer/cache/bufferCache.h printf '%s\n' '--- stream buffer construction ---' sed -n '1,180p' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp printf '%s\n' '--- GC and deletion references ---' rg -n -C 4 'RunGarbageCollector|DeleteBuffer\\(|CreateBuffer\\(|m_lru_cache\\.(ForEachItemBelow|Erase|Insert|Touch|Add|Remove)|lru_id|m_slot_buffers\\.erase|Unregister\\(' src -g '*.cpp' -g '*.h' ``` Repository: KytyPS5/KytyPS5 Length of output: 32942 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- buffer cache control flow ---' sed -n '286,449p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '575,755p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- LRU implementation ---' rg -n -C 8 'class LeastRecentlyUsedCache|ForEachItemBelow|LeastRecentlyUsedCache' src/common src -g '*.h' -g '*.cpp' printf '%s\n' '--- buffer-cache callers ---' rg -n -C 3 'ObtainBuffer\\(|ObtainBufferForImage\\(|FindBuffer\\(|ReadMemory\\(|RunGarbageCollector\\(' src -g '*.cpp' -g '*.h' ``` Repository: KytyPS5/KytyPS5 Length of output: 25854 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- complete LRU implementation ---' sed -n '1,130p' src/common/lruCache.h printf '%s\n' '--- direct call sites ---' rg -n -C 3 'RunGarbageCollector' src -g '*.cpp' -g '*.h' || true rg -n -C 3 'ObtainBufferForImage' src -g '*.cpp' -g '*.h' || true rg -n -C 3 'ObtainBuffer' src -g '*.cpp' -g '*.h' || true rg -n -C 3 'ReadMemory' src -g '*.cpp' -g '*.h' || true printf '%s\n' '--- buffer destruction and overlap callers ---' rg -n -C 3 'DeleteBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h rg -n -C 3 'JoinOverlap' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 29000 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- guest range and request-size bounds ---' rg -n -C 8 'struct GuestRange|class GuestRange|GuestRange::Valid|RequestedSize\\(' src -g '*.h' -g '*.cpp' printf '%s\n' '--- copy-buffer callers ---' rg -n -C 4 'CopyBuffer\\(' src/graphics -g '*.cpp' -g '*.h' printf '%s\n' '--- memory-pressure accounting ---' sed -n '755,820p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -C 5 'm_total_used_memory|GetDeviceMemoryUsage' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/renderContext.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 326 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- GuestRange references ---' rg -n -F -C 6 'GuestRange' src -g '*.h' -g '*.cpp' | head -n 160 printf '%s\n' '--- RequestedSize references ---' rg -n -F -C 6 'RequestedSize' src -g '*.h' -g '*.cpp' | head -n 120 printf '%s\n' '--- accounting and GC ---' sed -n '755,820p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -F -C 5 'm_total_used_memory' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 20199 --- </details> **Chunk oversized dirty buffers during garbage collection.** `ObtainBuffer(..., true)` can create a buffer for a valid guest range larger than 48 MiB. When that buffer becomes old and remains GPU-dirty, non-aggressive GC skips it, and aggressive GC also skips it because its size exceeds the entire `DownloadBudget`. The LRU traversal does not remove skipped items, so each eligible GC round repeats this. `ReadMemory` can clear the dirty state, and an overlapping request can replace the buffer. Without either path, the device allocation remains cached and continues to consume memory. Reuse the existing 8 MiB readback chunking, with completion waits between chunks, before untracking and retiring an oversized buffer. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0b16651c2cb5d1af13fc5a65 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -521,0 +541,4 @@
if (m_driver_cache == nullptr || !m_snapshot_pending) {
return;
}
m_snapshot_pending = false;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep the snapshot pending until the write succeeds.

If a periodic getPipelineCacheData() or file operation fails, this line clears m_snapshot_pending before the failure. If no new pipeline is inserted, Save() then skips its final write and destroys the driver cache. Clear the flag only after the rename succeeds so the final save can retry.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#discussion_r4107461752) _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ **Keep the snapshot pending until the write succeeds.** If a periodic `getPipelineCacheData()` or file operation fails, this line clears `m_snapshot_pending` before the failure. If no new pipeline is inserted, `Save()` then skips its final write and destroys the driver cache. Clear the flag only after the rename succeeds so the final save can retry. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ff860d2aab71dc7fb0380a4f --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -367,0 +368,4 @@
// otherwise drain it and crackle. KYTY_AUDIO_LATENCY_MS overrides the 100 ms default.
static const uint64_t target_latency_us = [] {
const char* value = std::getenv("KYTY_AUDIO_LATENCY_MS");
const auto ms = value != nullptr ? std::strtoull(value, nullptr, 10) : 0;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject trailing text when parsing the latency setting.

Line 371 passes a null end pointer to std::strtoull, so it accepts a numeric prefix. For example, KYTY_AUDIO_LATENCY_MS=20junk selects 20 ms instead of the 100 ms fallback for invalid values. Require the parser to consume the full string before applying the range check.

Suggested fix
-			const auto  ms    = value != nullptr ? std::strtoull(value, nullptr, 10) : 0;
-			return (ms >= 10 && ms <= 1000 ? ms : 100) * 1000ull;
+			char*       end   = nullptr;
+			const auto  ms    = value != nullptr ? std::strtoull(value, &end, 10) : 0;
+			const bool  valid = value != nullptr && end != value && *end == '\0';
+			return (valid && ms >= 10 && ms <= 1000 ? ms : 100) * 1000ull;
**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#discussion_r4107461757) _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Reject trailing text when parsing the latency setting.** Line 371 passes a null end pointer to `std::strtoull`, so it accepts a numeric prefix. For example, `KYTY_AUDIO_LATENCY_MS=20junk` selects 20 ms instead of the 100 ms fallback for invalid values. Require the parser to consume the full string before applying the range check. <details> <summary>Suggested fix</summary> ```diff - const auto ms = value != nullptr ? std::strtoull(value, nullptr, 10) : 0; - return (ms >= 10 && ms <= 1000 ? ms : 100) * 1000ull; + char* end = nullptr; + const auto ms = value != nullptr ? std::strtoull(value, &end, 10) : 0; + const bool valid = value != nullptr && end != value && *end == '\0'; + return (valid && ms >= 10 && ms <= 1000 ? ms : 100) * 1000ull; ``` </details> <!-- fingerprinting:phantom:triton:serval --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1b2bfe60e9da936bbb3f12a1 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -2610,6 +2688,7 @@ int32_t KYTY_SYSV_ABI FiberFinalize(FiberObject* fiber) {
if (!FiberCompareExchangeState(fiber, FIBER_STATE_IDLE, FIBER_STATE_TERMINATED)) {
return FIBER_ERROR_STATE;
}
LibKernel::UnregisterLiveStack(fiber->addr_context);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 18:27 UTC · original

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

Unregister the fiber stack when the fiber terminates by returning from its entry.

FiberStartTrampoline sets the state to FIBER_STATE_TERMINATED when fiber->entry returns. After that, the FIBER_STATE_IDLE → FIBER_STATE_TERMINATED exchange in FiberFinalize fails. The function then returns FIBER_ERROR_STATE before it calls UnregisterLiveStack. The range stays in g_live_stacks forever.

This has two effects:

  • Each fiber that finishes normally adds one permanent entry.
  • If the guest frees that context memory and reuses it for GPU-visible data, PageManager::Protect refuses write protection for it. GPU tracking then misses guest writes to that memory.

Unregister the stack on every path that ends the fiber's registration. Also unregister any previous registration when FiberInitialize reinitializes the same addr_context.

Proposed fix
 	if (!FiberCompareExchangeState(fiber, FIBER_STATE_IDLE, FIBER_STATE_TERMINATED)) {
+		if (FiberLoadState(fiber) == FIBER_STATE_TERMINATED) {
+			LibKernel::UnregisterLiveStack(fiber->addr_context);
+		}
 		return FIBER_ERROR_STATE;
 	}
 	LibKernel::UnregisterLiveStack(fiber->addr_context);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#discussion_r4107461769) _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ **Unregister the fiber stack when the fiber terminates by returning from its entry.** `FiberStartTrampoline` sets the state to `FIBER_STATE_TERMINATED` when `fiber->entry` returns. After that, the `FIBER_STATE_IDLE` → `FIBER_STATE_TERMINATED` exchange in `FiberFinalize` fails. The function then returns `FIBER_ERROR_STATE` before it calls `UnregisterLiveStack`. The range stays in `g_live_stacks` forever. This has two effects: - Each fiber that finishes normally adds one permanent entry. - If the guest frees that context memory and reuses it for GPU-visible data, `PageManager::Protect` refuses write protection for it. GPU tracking then misses guest writes to that memory. Unregister the stack on every path that ends the fiber's registration. Also unregister any previous registration when `FiberInitialize` reinitializes the same `addr_context`. <details> <summary>Proposed fix</summary> ```diff if (!FiberCompareExchangeState(fiber, FIBER_STATE_IDLE, FIBER_STATE_TERMINATED)) { + if (FiberLoadState(fiber) == FIBER_STATE_TERMINATED) { + LibKernel::UnregisterLiveStack(fiber->addr_context); + } return FIBER_ERROR_STATE; } LibKernel::UnregisterLiveStack(fiber->addr_context); ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:72d80014dab5dbdef3945604 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 6

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Consume the pending signal before unparking its context. · libKernel.cpp:1098-1106

src/libs/libKernel.cpp:1098-1106
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Consume the pending signal before unparking its context.

The merge base already used the unsupported fourth argument in CreateSignalUcontext and ApplySignalUcontext, so this PR does not introduce that existing NtQueueApcThreadEx mismatch. However, this PR adds an unconditional UnparkSignalContext(context) call before PthreadTakePendingSignal.

Multiple APCs can be queued for one coalesced pending bit. A later APC can reach this new call after an earlier handler consumed the bit. Because NtQueueApcThreadEx does not provide PCONTEXT, this new path can dereference invalid memory before the existing early return.

Suggested fix
 static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
-	// Resume at the interrupted guest instruction, not the parking stub, and show the handler the
-	// real guest context.
-	UnparkSignalContext(context);
-
 	auto*      thread = static_cast<Pthread>(arg1);
 	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
 	if (!PthreadTakePendingSignal(thread, signum)) {
 		return;
 	}
 
+	// Resume at the interrupted guest instruction, not the parking stub, and show the handler the
+	// real guest context.
+	UnparkSignalContext(context);
+

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 7d2edbed-a44e-4353-9f02-3e5b9b98cc56

📥 Commits

Reviewing files that changed from the base of the PR and between 497166009c and 22ffc19802.

📒 Files selected for processing (23)
  • src/graphics/host_gpu/pageManager.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/samplerCache.cpp
  • src/graphics/host_gpu/renderer/cache/streamBuffer.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/presentation/window/window.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/kernel/pthread.cpp
  • src/kernel/pthread.h
  • src/libs/audio.cpp
  • src/libs/libKernel.cpp
  • src/loader/redZonePatcher.cpp
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/shaderCfgTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/833#pullrequestreview-5321231122) · **reviewed** **Actionable comments posted: 6** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟠 Major</em> · Consume the pending signal before unparking its context. · <code>libKernel.cpp:1098-1106</code></summary><blockquote> > > `src/libs/libKernel.cpp:1098-1106` > _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ > > **Consume the pending signal before unparking its context.** > > The merge base already used the unsupported fourth argument in `CreateSignalUcontext` and `ApplySignalUcontext`, so this PR does not introduce that existing `NtQueueApcThreadEx` mismatch. However, this PR adds an unconditional `UnparkSignalContext(context)` call before `PthreadTakePendingSignal`. > > Multiple APCs can be queued for one coalesced pending bit. A later APC can reach this new call after an earlier handler consumed the bit. Because `NtQueueApcThreadEx` does not provide `PCONTEXT`, this new path can dereference invalid memory before the existing early return. > > <details><summary>Suggested fix</summary> > > ```diff > static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { > - // Resume at the interrupted guest instruction, not the parking stub, and show the handler the > - // real guest context. > - UnparkSignalContext(context); > - > auto* thread = static_cast<Pthread>(arg1); > const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); > if (!PthreadTakePendingSignal(thread, signum)) { > return; > } > > + // Resume at the interrupted guest instruction, not the parking stub, and show the handler the > + // real guest context. > + UnparkSignalContext(context); > + > ``` > > </details> > > <!-- cr-comment:v1:4e573f3927bc0cf788ff67e8 --> > > </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**: `7d2edbed-a44e-4353-9f02-3e5b9b98cc56` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 497166009c8c0dd663fa1ffce3805a31bdc40d0e and 22ffc198027fd364405a0b174007f409d6d9f155. </details> <details> <summary>📒 Files selected for processing (23)</summary> * `src/graphics/host_gpu/pageManager.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/samplerCache.cpp` * `src/graphics/host_gpu/renderer/cache/streamBuffer.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/image/image.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/presentation/window/window.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` * `src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/kernel/pthread.cpp` * `src/kernel/pthread.h` * `src/libs/audio.cpp` * `src/libs/libKernel.cpp` * `src/loader/redZonePatcher.cpp` * `tests/VirtualMemoryAllocationTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This pull request has changes conflicting with the target branch.
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/samplerCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/presentation/window/window.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/libs/audio.cpp
  • src/loader/guestInstructionPatcher.cpp
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/shaderCfgTests.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

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

Merge

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