Consolidated Stability, Graphics, Audio and Memory Fixes (71 PRs) #2465

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

@⁠RecknockT on GitHub · 2026-11-20 17:37 UTC · original
RecknockT:master → main · +60637 −21340 · 198 files · 344 commits · closed without merging

Overview

This consolidated pull request bundles and resolves 71 open community improvements, bug fixes, and performance optimizations that have been vetted, conflict-resolved, and verified on modern Windows/Vulkan environments (including games like ASTRO BOT, GTA V, Demon's Souls, Uncharted, and Call of Duty: BO2).

All changes have been cleanly integrated into a single cohesive branch without regressions, adapting legacy PRs to the latest upstream codebase.


🎮 Major Subsystems & Highlights

1. Graphics, Shaders & Texture Cache

  • HTile & Depth Handling: Keep HTile clear state while its depth surface is bound (PPSA23566 / UFC 6) (#1743), recreate depth targets larger or narrower than cached images (#1748, #2417), handle in-place depth-to-color copies (#2455).
  • Texture Cache Performance: Copy evicted images without holding the cache lock to eliminate CPU-GPU thread stalls during texture GC (#1947). Fix corrupt textures when shorter mip chains reuse memory (#1781).
  • DCC & Bindless: Enlarge bindless array capacity to 1M descriptors (#2226), honour PS5 0x10 DCC register clears to fix black smoke in GTA V (#2394), disable DCC for block-compressed textures (#2006).
  • Formats & Views: Map RGB9E5 color buffers to renderable host formats (#2290), bind null textures for unmapped bytes (#2409), honour data format of LOAD_*_REG_INDEX lists (#2245).
  • Shader Recompiler: Derive barycentric X on NVIDIA GPUs to prevent pipeline compile crashes (#2415), order F32 min/max/MED3 by bits (#2096), fix V_CMP_CLASS range tests (#1554), bound waterfall image keys (#2278).

2. Kernel, Concurrencia & Memoria

  • ASTRO BOT & Protected Pages: Complete file reads that hit GPU-protected guest pages (#2141), lower Windows thread priority for Havok workers (#2022), retry guest address holes on concurrent allocation (#2143).
  • Windows Red-Zone & Call Stacks: Preserve Windows guest stack bounds (#2125), extend red-zone protection to functions missing from .eh_frame (#2099) and enable for CoD: BO2 (#2431).
  • Memory Stability: Retry guest accesses while mappings are briefly replaced (#2395), prefault large direct-memory mappings on Windows (#2284), staged memory reservations for DLSS initialization (#2443).

3. Audio & Video Playback

  • AvPlayer Video Decode: Multi-threaded video decode eliminating stutter and flickering in pre-rendered cutscenes (#2259).
  • AudioOut2 & NGS2: Return synchronous AudioOut2 pushes once the queue has room (#1872), hold audio while pipeline compiles block GPU (#1979), implement sampler voice peak meter for lip-sync (#1853), accept mastering control 2 (#2364).

4. Filesystem, Libs & OS Integration

  • Windows NTFS Character Encoding: Encode Windows-forbidden characters (:, <, >, etc.) in guest save filenames so games like Arcade Spirits can create and load save data (#907).
  • Paths & CJK Fonts: Support Windows host paths beyond MAX_PATH (#2305), fall back to host CJK font face for Chinese text (#1754).
  • Libc & Network: Implement guest getenv/setenv (#2452), getpeername/sceNetGetpeername (#2129), sceHttp2AbortRequest (#2139), and 14 Agc::GetSize entrypoints (#2441).

🧪 Verification

  • Compiled with MSVC / LLVM clang-cl (C++20) + Ninja on Windows 11.
  • Unit and recompiler tests passing.
  • Validated with game titles on Vulkan with RTX 5080.
**@⁠RecknockT** on GitHub · 2026-11-20 17:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465) `RecknockT:master` → `main` · +60637 −21340 · 198 files · 344 commits · closed without merging ## Overview This consolidated pull request bundles and resolves **71 open community improvements, bug fixes, and performance optimizations** that have been vetted, conflict-resolved, and verified on modern Windows/Vulkan environments (including games like ASTRO BOT, GTA V, Demon's Souls, Uncharted, and Call of Duty: BO2). All changes have been cleanly integrated into a single cohesive branch without regressions, adapting legacy PRs to the latest upstream codebase. --- ### 🎮 Major Subsystems & Highlights #### 1. Graphics, Shaders & Texture Cache - **HTile & Depth Handling:** Keep HTile clear state while its depth surface is bound (PPSA23566 / UFC 6) (#1743), recreate depth targets larger or narrower than cached images (#1748, #2417), handle in-place depth-to-color copies (#2455). - **Texture Cache Performance:** Copy evicted images without holding the cache lock to eliminate CPU-GPU thread stalls during texture GC (#1947). Fix corrupt textures when shorter mip chains reuse memory (#1781). - **DCC & Bindless:** Enlarge bindless array capacity to 1M descriptors (#2226), honour PS5 0x10 DCC register clears to fix black smoke in GTA V (#2394), disable DCC for block-compressed textures (#2006). - **Formats & Views:** Map RGB9E5 color buffers to renderable host formats (#2290), bind null textures for unmapped bytes (#2409), honour data format of LOAD_*_REG_INDEX lists (#2245). - **Shader Recompiler:** Derive barycentric X on NVIDIA GPUs to prevent pipeline compile crashes (#2415), order F32 min/max/MED3 by bits (#2096), fix V_CMP_CLASS range tests (#1554), bound waterfall image keys (#2278). #### 2. Kernel, Concurrencia & Memoria - **ASTRO BOT & Protected Pages:** Complete file reads that hit GPU-protected guest pages (#2141), lower Windows thread priority for Havok workers (#2022), retry guest address holes on concurrent allocation (#2143). - **Windows Red-Zone & Call Stacks:** Preserve Windows guest stack bounds (#2125), extend red-zone protection to functions missing from .eh_frame (#2099) and enable for CoD: BO2 (#2431). - **Memory Stability:** Retry guest accesses while mappings are briefly replaced (#2395), prefault large direct-memory mappings on Windows (#2284), staged memory reservations for DLSS initialization (#2443). #### 3. Audio & Video Playback - **AvPlayer Video Decode:** Multi-threaded video decode eliminating stutter and flickering in pre-rendered cutscenes (#2259). - **AudioOut2 & NGS2:** Return synchronous AudioOut2 pushes once the queue has room (#1872), hold audio while pipeline compiles block GPU (#1979), implement sampler voice peak meter for lip-sync (#1853), accept mastering control 2 (#2364). #### 4. Filesystem, Libs & OS Integration - **Windows NTFS Character Encoding:** Encode Windows-forbidden characters (`:`, `<`, `>`, etc.) in guest save filenames so games like *Arcade Spirits* can create and load save data (#907). - **Paths & CJK Fonts:** Support Windows host paths beyond MAX_PATH (#2305), fall back to host CJK font face for Chinese text (#1754). - **Libc & Network:** Implement guest `getenv`/`setenv` (#2452), `getpeername`/`sceNetGetpeername` (#2129), `sceHttp2AbortRequest` (#2139), and 14 `Agc::GetSize` entrypoints (#2441). --- ### 🧪 Verification - Compiled with MSVC / LLVM `clang-cl` (C++20) + Ninja on Windows 11. - Unit and recompiler tests passing. - Validated with game titles on Vulkan with RTX 5080.
Guest filenames may contain characters that NTFS rejects, such as ':' in
"rg_ac_Arcade Spirits: The New Challengers_0.dat". On Windows the save
could not be created, and the game crashed on the next boot when the
file was missing.

On Windows hosts, ResolvePath now stores < > : " | ? * and control
characters as %XX, and directory listings decode them back so the guest
sees its original names. '%' is not encoded, so every name that is
already valid keeps its existing host path. Archive mounts and non-Windows
hosts are unchanged.

Fixes #141
Review found two ways distinct guest names could share a host file:

- A literal "%3A" and a ':' both mapped to "%3A". A '%' is now stored
  as %25 when it would otherwise read as an escape (hex matched in
  either case, since NTFS ignores case).
- Windows strips a trailing '.' or ' ' from a path component, so
  "save:." aliased "save:". Those are now stored as %2E and %20, except
  in the "." and ".." components.

Names without these cases keep their existing host path. The tests add
both review examples and check that every short name over an alphabet
of escape fragments round-trips without sharing a host name.
sceRtcFormatRFC2822, sceRtcFormatRFC2822LocalTime and
sceRtcFormatRFC3339LocalTime were not registered. A game that calls one
of them hits the unresolved-import stub, which returns 0 and leaves the
caller's buffer untouched, so the game goes on to use whatever bytes
were already there as a date string. Teenage Mutant Ninja Turtles:
Splintered Fate (#908) calls sceRtcFormatRFC2822LocalTime twice in the
log attached to the issue.

The tick-to-calendar step that sceRtcFormatRFC3339 already did moves
into a shared helper. sceRtcFormatRFC2822 uses it and writes
"Wed, 07 Oct 2026 21:43:05 -0400": a 31-character date plus the
terminator, inside the same 32-byte bound sceRtcFormatRFC3339 uses.
A null buffer returns RTC_ERROR_INVALID_POINTER, a null tick formats
the current time, and an offset that moves the tick outside
0001..9999 returns RTC_ERROR_INVALID_VALUE without writing. The helper
now also rejects a positive offset that would wrap the tick, and the
RFC 3339 zone suffix negates the offset in 64 bits so INT_MIN is not
undefined behaviour.

The local-time variants use a zero offset. RtcConvertUtcToLocalTime
deliberately keeps RTC local time equal to UTC, and the formatters
follow it, so the string they produce still names the right instant.

tests/RtcFormatTests.cpp resolves the four formatters by NID through
InitRtc_1 and checks the output for several offsets, the first and
last representable days, the error codes and that nothing is written
past 32 bytes.
sceRtcFormatRFC2822 printed straight into the guest buffer with
snprintf(date_time, 32, ...) and returned OK whatever snprintf
returned. time_zone_minutes is not range-checked, so an offset of 6000
gives the zone "+10000" and a 32-character date: the guest got a
truncated string and OK. sceRtcFormatRFC3339 had the same unchecked
call, and its zone suffix was also truncated silently once the offset
reached 1000 hours.

Both formatters now build the string in a local 32-byte buffer, check
the snprintf result, and copy it to the guest only when it fits. A
string that does not fit, or a zone suffix that does not fit its own
buffer, returns RTC_ERROR_INVALID_VALUE and writes nothing. The
LocalTime variants go through the same code. Output for offsets that
fit is unchanged.

The tests cover the longest offsets that still fit (+-9959 for RFC 2822,
+999:59 for RFC 3339) and the first ones that do not, which must return
RTC_ERROR_INVALID_VALUE and leave the buffer untouched.
RFC 3339 allows only 00-23 for the offset hours, so sceRtcFormatRFC3339 and its LocalTime variant now return RTC_ERROR_INVALID_VALUE for an offset of 24 hours or more and leave the buffer untouched. The tests cover +/-23:59 and reject +/-24:00.
Only /app0/sce_module/libc.prx was loaded automatically. Other bundled
modules the executable imports from, such as libSceNpCppWebApi.prx in
Astro Bot (PPSA21564), were never loaded unless the game requested them,
so their functions were bound to stubs returning 0 ("Unresolved import
stub called: ...[NpCppWebApi_v1]").

Load sce_module/<module name>.prx for every module the executable imports,
next to libc, and start them after libc. A bundled PRX is named after the
module it exports (libc.prx exports libc, libSceNpCppWebApi.prx exports
libSceNpCppWebApi). HLE symbols still take precedence when resolving.
ProcessPm4 ends the run when a single dword is left in the buffer:
EXIT_NOT_IMPLEMENTED(remaining_dw < 2). One dword cannot be a packet at
all - a type-3 header with no body, or the type-2 filler word - and games
do leave one behind the last real packet. Gran Turismo 7 stops that way
after the session has already drawn: the fatal line arrives after 912
shader-counter lines, and in other runs the same buffer ends with a lone
0x00000000 dword at offset 0xc4.

Consume the word and let the buffer close normally instead of ending the
run. The offset is logged at most 16 times, since GT7 reaches it
repeatedly.
V_CMP_CLASS_F32/F16 and the CMPX forms built all ten class tests and OR-ed
them under the mask, about 70 SPIR-V instructions per compare.

For a register mask, compute the input's class index (0-9) from the
magnitude (zero, normal, infinity and NaN thresholds), the sign and the
quiet bit, and test that bit of the mask. For a literal mask, emit only the
selected classes as range tests on the magnitude bits; adjacent selected
classes share one test, and the sign test is skipped when the mask selects
both signs alike. The emitted code is integer-only.

The compute suite goes from 514,842 to 468,380 SPIR-V instructions
(FPCmpClass32 70 -> 17.5, FPCmpClass16 69 -> 19.3 per compare on average).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add KYTY_GUEST_STDOUT=1 to forward guest printf/vprintf to stderr with a prefix and immediate flush. Add synthetic regression tests and register them in CI.

Related to #1540, section 5 only. AI-assisted implementation and automated validation; human review is pending.
A guest sampler shared by an IMAGE_SAMPLE_C and a plain IMAGE_SAMPLE was one
sampler entry, and the materialization OR-ed depth_compare over its pairs. The
plain sample then got a comparison sampler over its colour view (R32_SFLOAT),
which hosts without depth comparison for that format reject
(VUID-vkCmdDispatch-None-06479) and which ends in a device loss on NVIDIA.

Classify depth-compare images as their own sampler class, so the plan creates a
compare variant that shares the guest descriptor, and pick indirect-image
variants with the same compare state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
EA SPORTS UFC 6 binds one depth surface alternately as D32 with one HTile and
as D32S8 with another, and fast-clears each HTile while the other variant is
bound. Every switch replaces the native depth image, and deleting the old image
erased its HTile clear state, so the guest clear found no metadata and was
dropped. The next binding loaded stale guest memory instead of clearing
(loadOp LOAD in RenderDoc), which tore the fighter depth and blacked out the
depth-tested lighting at fighter select.

Track the depth surface each HTile was bound with, and keep its clear state
while another native depth image of that surface is registered. A non-depth
replacement or the last depth image still drops it, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-ups for the UFC 6 (PPSA23566) HTile fix:
- Record the owning surface by the native image base, which DeleteImage
  compares against; a layered binding can start at a later slice.
- Only an HTile depth image keeps a surface's state alive, so cleanup still
  runs when that image is replaced by one without HTile.
- When an HTile is bound by another surface, start from that surface's own
  state instead of inheriting the previous surface's pending clear.
- Deleting a surface erases only the entries it owns, not an HTile another
  surface has rebound, and cleanup runs for every depth image deletion.

Tests cover the surface change, the rebinding owner surviving the old
surface, and retirement with the last depth image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
EA SPORTS UFC 6 (PPSA23566) loses the device on fighter select and in
fights. The NVIDIA driver reports "3D WIDTH ZT Violation" (Xid 13) and
Kyty exits in masterSemaphore.cpp. A depth target described as 128x32
(D32_SFLOAT_S8_UINT) was bound to a 32x32 cache image at the same
address, and the main fight depth target (3248x1824) to a 3240x1824
image. AcquireRenderTargets sets the render area from the description,
so depth was written past the image.

ResolveOverlap takes its equal-address branch when the pitch and height
match. Tiled depth pads the pitch, so a 32x32 and a 128x32 surface with
the same data size match there, and ResolveDepthOverlap returned the
cached image for a depth target unless depth, stencil, bytes per block,
levels or layers differed. It now also recreates when the requested
width or height exceeds the cached image; the existing recreate path
inserts the requested image and copies the cached contents into it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When ResolveDepthOverlap recreates a depth target because the requested
extent is larger than the cached image (EA SPORTS UFC 6, PPSA23566:
32x32 -> 128x32, 3240x1824 -> 3248x1824), it inserts the replacement
and copies the cached image into it. TextureCache::CopyImage marks the
destination current (PrepareImageCopy -> RefreshComplete) without
uploading it, so the part of the replacement outside the cached extent
was never filled from guest memory.

Refresh the replacement from guest memory before the copy when the
target grew. The copy then overlays the cached GPU contents on the old
extent.

Test: CheckUnifiedTextureCacheFlow (--htile-clear-only) writes 0.25 to
columns 0..31 and 0.5 to columns 32..127 of a 128-pitch depth surface,
clears the 32x32 image to 0.75, then requests 128x32. Without the fix
column 32 reads 0.0; with it, 0.75 in the old extent and 0.5 outside.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Draws write stencil into the depth image; the stencil association only
records which guest range it belongs to. When ResolveDepthOverlap
recreates a D32S8 depth target for a larger extent (EA SPORTS UFC 6,
PPSA23566: 32x32 -> 128x32 D32_SFLOAT_S8_UINT), Image::CopyImage copies
only the depth aspect and DeleteImage frees the cached image's stencil
associations. The replacement's first FindDepthTarget then created a new
association and uploaded the stale guest stencil over it.

For a same-format recreate with the same stencil range, associate the
stencil range with the replacement, upload it from guest memory (for the
grown region), and copy the cached stencil aspect over the old extent.
Image::CopyImage takes an opt-in stencil flag; its default is unchanged.
A GPU-modified association stays GPU-modified.

Test: CheckUnifiedTextureCacheFlow (--htile-clear-only) fills the guest
stencil with 0x11, binds a 32x32 D32S8 target, clears its stencil to
0x35 with a raw transfer clear (as a draw would, without marking the
association), then binds 128x32. Without the fix column 0 reads 0x11;
with it, 0x35 in the old extent and 0x11 outside.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
EA SPORTS UFC 6 (PPSA23566) exits with "condition (!is_allocated(id))
is true in slotVector.h:41" after a few minutes of menu navigation.

Small tiled depth and stencil planes are one 64 KiB block each, so the
game can place a 32x32 D32S8 target's stencil plane exactly on another
32x32 D32S8 surface. AssociateStencil reused any image with the same
range and extent, so it turned that depth image into an S8 stencil
record and kept the image's own stencil associations. DeleteImage frees
stencil_ids only for depth owners, so deleting the adopted image left
its old association registered with an erased depth_id, and the next
deletion of that association (overlap cleanup or unmap) indexed the
erased slot.

Logging in the game showed the adoption of a registered D32S8 image
with one association at the stencil range of another 32x32 target,
then the deletion of that association after its owner was erased,
then the exit. Never adopt a depth image; insert a separate
association instead.

The new UnifiedTextureCacheFlow check fails without this change, and
past it the same sequence ends in the same slotVector.h:41 exit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the console language set to Chinese, some in-game text showed up
as "??". This is not an encoding bug: libFont draws '?' on purpose for
any character it cannot find in the font.

Root cause:
- The game opens the PS5 system font sets (SC/TC/JP/KR) through
  FontOpenFontSet. Those fonts don't exist on the host, so libFont falls
  back to Roboto (3rdparty/tracy), which only has Latin glyphs.
- stb_supported_codepoint() replaced every code point missing from the
  font with '?'.
- The font format check only accepted .ttf/.otf, so TrueType
  collections (.ttc), which most Windows CJK fonts are (e.g. msyh.ttc),
  were rejected.
- FontGetKerning() returned FONT_ERROR_NO_SUPPORT_CODE for any
  character missing from the primary face, including CJK characters.

The system overlay already merges a per-language CJK font through
AddSystemFontFallbacks(), so it is not changed here.

Changes:
- Add Common::FindCjkFontFiles(locale) (src/common/systemFonts.{h,cpp}).
  It tries KYTY_CJK_FONT first, then the installed system CJK fonts,
  ordered by the console locale so shared Han characters use the
  regional glyph forms: zh-Hans prefers Microsoft YaHei, zh-Hant
  Microsoft JhengHei, ja-JP Yu Gothic/Meiryo, ko-KR Malgun Gothic.
  macOS (PingFang, Hiragino, Apple SD Gothic Neo) and Linux (Noto Sans
  CJK, WenQuanYi, Droid Sans Fallback) paths are included too.
- libFont: accept .ttc files and load face 0 through
  stbtt_GetFontOffsetForIndex().
- libFont: add resolve_stb_glyph(), which picks the face per character:
  the font's own face first, then the host CJK fallback, and '?' only if
  neither has the glyph. Glyph metrics and bitmaps are computed with the
  face that was actually picked, using its own em scale.
- libFont: FontGetKerning() returns OK with zero kerning when a
  character is drawn from the CJK fallback face, instead of
  FONT_ERROR_NO_SUPPORT_CODE.
- libFont: log which CJK fallback font is used, or warn when none is
  found.

Testing: this is the same change, on the same base commit (1a053f9e),
that was built successfully and verified in Astro Bot with the console
language set to Chinese: text that used to show as "??" renders
correctly. This checkout has not been built or tested separately.
Every shader that uses BDA synchronizes the pages queued since the
previous one. A write fault on a game thread queued its page at once,
so pages the game keeps writing for later frames were uploaded again
at nearly every BDA draw.

Queue BDA events from invalidations on threads other than the GPU
thread (game threads, file I/O and so on) separately. Promote them when
the command processor starts or resumes a submission, or reads a guest
value a game thread may have written after the data it guards. That
covers a passing WAIT_REG_MEM, COND_EXEC, BRANCH, a REWIND that is
already valid, SET_PREDICATION on a memory value, and a MEM_SEMAPHORE
wait that consumes a count. Promotion runs after the value is read,
behind an acquire fence, so it catches every event queued before the
write the command processor saw. GPU-thread writes still queue
immediately, since later draws of the same submission can read them.

Promotion runs at every submission slice and at each of those packets,
and usually finds nothing deferred. A flag set with each deferred event
lets it return without taking the lock. When the immediate set is empty,
the deferred set is swapped in whole.

New tests: Pm4ControlReadsPromoteBdaSync runs each of those packets and
checks it promotes a held-back event, and BdaSyncSubmissionPromotes
checks that starting a submission on the GPU thread does. The existing
CheckBdaSyncUploads writes from the test thread, which is now held back,
so it checks that and promotes the write before its existing checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
BdaSyncSubmissionPromotes polled a volatile marker that the GPU thread
writes, then checked TakeBdaSync. The marker shows the submission ran,
but it gives no ordering under the C++ memory model. Waiting for the GPU
thread to go idle orders its promotion before the check through the GPU
queue mutex. The bounded poll stays as the timeout, so the wait is only
reached once the marker has been seen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Count clean buffers released after going unbound, and released ranges
a shader then read again through BDA. Show both in the performance
overlay's GPU memory section, flagging any refaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Mesh shaders read the guest index buffer through BDA, and the draw only
registers it with FindBuffer, which deliberately doesn't count as a use.
So the garbage collector saw the buffer as unused while shaders kept
reading it. Add BufferCache::FindBufferForShaderRead, which finds or
creates the buffer and touches it, and use it for the mesh index buffer.
FindBuffer itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A cached buffer keeps its pages write-protected. Once a game reuses that
memory for other data, every CPU write there faults and is uploaded
again into a buffer nothing reads. In Octopath Traveler II about a third
of all write faults landed in buffers no binding had used for over 300
frames.

Every 60 garbage-collector ticks, release clean buffers that no binding
has used for 300 ticks, at most 128 per pass, through the same untrack
and delete path the memory-pressure collector uses. Buffers holding
GPU-written data are kept. That check is complete only because shaders
cannot write guest memory through BDA.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A buffer that shaders read only through BDA never counts as bound, so
stale release can drop it while it is still in use. The next read then
finds no buffer, reads zeros for a frame or so, and the fault path
creates it again.

Remember recently released ranges. When the fault path recreates one,
count a refault, log it, and protect that range from stale release
until it is unmapped. Protection is kept by address, so it carries over
when buffers merge. In Octopath Traveler II there were no refaults, so
this only guards engines that read buffers through BDA alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stale release and the memory-pressure garbage collector drop buffers the
GPU did not write without downloading them. That is safe only because
shaders cannot write guest memory through an address, which shader info
collection rejects, so only writes through bound buffers need tracking.
Say so where the rejection is, so whoever lifts it tracks those writes
first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Guest mip chains run backwards (smaller levels first), so a texture with
fewer mip levels keeps its base level at a different offset than a
texture with a longer chain at the same address. When an equal-address
request differed from a cached image only in its level count,
ResolveOverlap skipped the mip-layout comparison and reused the cached
image, so the request's base level was read from the wrong offset.

Octopath Traveler II streams one-level ground textures into memory that
an eight-level texture had used. The ground then showed half of the
streamed texture and half of whatever followed it in memory, a few
minutes into a session and differently each run.

Compare the levels both layouts share and treat any difference as a
separate guest layout, as an equal-count mismatch already was.

Adds a UnifiedTextureCacheFlow case: a one-level texture requested at
the address of a cached two-level image must get its own image and read
its base level from the start of the allocation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-ups for the mip-layout fix:

- FindImage accepted a cached image through SameBacking before
  ResolveOverlap ran. SameBacking allows a cached image with more levels
  and the same allocation size (common with padded tiled layouts), so a
  shorter-chain request could still read its base level from the wrong
  offset. Require the shared levels to be placed identically when the
  level counts differ.
- When a layout mismatch turns the request into a separate image, an
  idle cached image was freed even if the GPU had written it, dropping
  contents that were never downloaded. Retire it only when it mirrors
  guest memory; texture GC downloads GPU-written images before freeing.
- The shared-level comparison now only applies when the level counts
  differ, so equal-count lookups behave as before.

The regression test also requests a one-level texture with the same
allocation size as the cached two-level image, which exercised the
SameBacking path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a request's mip placement differs from a cached image at the same
address, the request becomes a separate image. Compare shared levels
whatever the layer counts are: guest mip layouts are per layer, so a
different layer count does not make mismatched levels compatible.

An idle cached image that was GPU-written was kept so its contents would
not be dropped, but then it coexisted with the new image: range lookups
could pick it and texture GC could later download its stale contents
over newer data. Retire it the way BC aliases are retired instead:
publish its contents to the buffer cache, from which the new image
uploads, and free it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build the clear as a vk::ClearValue (no converting constructors), and
look the range up without ensure_valid: the new image is not GPU-written,
so the default lookup would skip it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two-level chain keeps its 32-texel level 1 at offset 0, so a 64-texel
one-level texture over that row sees GPU-written data in its first half
and guest padding (preserved by the publish) in the second. The test
expected all 64 texels to hold the cleared value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The mip layout cases were linear with hand-built layouts. Add two cases
that use real UpdateSize() layouts of a 256x256 32-bit chain with
64 KiB tiling.

A one-level texture at the address of a 9-level tiled chain must get
its own image. Its first row reads the chain's mip tail block and
level 1, not the chain's base level. This is the Octopath Traveler II
ground texture case.

An 8-level request over a 9-level chain differs only inside the mip
tail. It must reuse the cached chain rather than create a second image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a request at the same address asks for another tile mode, the
cached image can't serve it. Upstream freed an idle cached image there,
which dropped anything the GPU had written to it. The branch now
publishes those contents to the buffer cache first, so the new image
starts from them.

Write a value into a linear 128x128 image on the GPU, leave it idle,
then request a 64 KiB tiled texture at the same address. The new image
must read the written value across the whole image, not the stale guest
memory, and the old image must be gone. At 128 texels both layouts have
the same pitch, so the request reaches the tile-mode check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ResolveOverlap asked ResolveDepthOverlap first, and that hands back a
cached depth image unchanged whenever it holds at least as many levels.
A depth request with a different level count could then get an image
whose shared levels sit somewhere else, the same bug this branch fixes
for color images.

Compute the shared-level check first. If the depth path would return the
cached image itself while the shared levels differ, fall through to the
separate-image branch instead. Its convert-and-copy result is kept, since
layered depth and color aliases rely on it.

Add a test where a one-level depth texture over a two-level depth chain
gets its own image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The GC holds m_lock for its whole pass and DownloadImageMemory copies
the guest bytes of each evicted image inside it, so guest write faults
spin in InvalidateMemory until the copy ends. Release the lock around
TryReadBacking on the GC path and look the image up again afterwards,
dropping the download if the image was freed, reused or dirtied
meanwhile.
Trails in the Sky 1st Chapter stopped at startup with "unsupported
sampler control: 0x10000009". That control is the sampler voice peak
meter (SamplerVoicePeakMeterParam {enableFlag, reserved}), which comes
after setup, waveform blocks/address/offset, exit loop, pitch,
envelope, distortion and user FX in the sampler control order; the
controls already handled (0, 1, 4, 5, 0xa) match that order.

While the meter is enabled, each render records the largest absolute
sample of the voice after its filters, and the sampler voice state
reports it as peak_height. It is 0 while the meter is off or the voice
renders nothing. The rack's peak-meter block count is not used: the
peak covers only the last render.

The game now runs past startup at a steady 60 fps in a 90-second run.
TestPeakMeter covers enabling, per-render peaks, running out of data
and disabling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A deferred sampler setup can leave an enabled voice without channels.
Its render then returned before clearing the peak, so the sampler voice
state kept reporting the peak of its last real render although the voice
rendered nothing. Clear the peak before that return.

TestPeakMeter now renders a voice without channels between two peaks. It
fails without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A killed or reset voice kept its last peak until it rendered again, so
a game reading it from another thread could see the previous sound's
level. Clear the peak on those events.

Sampler setup starts a new sound and already clears the voice's ports,
matrices and filters, so it now turns the peak meter off too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace the bare control number 9 and the hand-counted parameter size
with NGS2_SAMPLER_CONTROL_PEAK_METER and a typed
Ngs2SamplerPeakMeterParam, checked like the filter control's parameter.

The tests build the control from the same names, and the fixture's
setup moves into a Setup helper so the reset test can set a voice up
again without repeating it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the peak scan into Ngs2PeakHeight. It reads only the voice's own
output buffer and skips NaN and infinite samples, so a misbehaving
filter can't hand the game a peak it can't turn into a level. Levels
above full scale are kept.

Say at the call why the meter reads the voice after its filters and
before port volume, and that it should move after the envelope once
envelopes are implemented.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stereo voice whose right channel is louder must report the right
channel's peak, and reading the peak must not reset it.

The meter reads the voice after its filters. A Nyquist-rate signal
through a 100 Hz low-pass must report the small filtered level, not the
source's level. Also reword the meter field's comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Trails in the Sky 1st Chapter asks for one peak meter block on every
rack while metering up to 22 voices at once, so the count is not a cap
on metered voices. What a larger count means is unknown: a longer
window, sub-blocks of a grain or an allocation size would all fit. The
meter keeps reporting each grain's peak, which every reading agrees on
for one block.

Default the sampler rack to that one block instead of an invented 8,
and warn when a game asks for another count so the first such game
leaves evidence. Test that a paused voice reports 0 from its next
render and that the default is one block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the add/add conflict in tests/ResourceMaterializationTests.cpp by keeping both new tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Atelier Yumia builds some pipelines for up to 36 s on NVIDIA,
synchronously on the GPU command thread. Its frame loop waits on the
GPU, but its audio thread keeps pushing buffers, and the cutscene
follows the audio clock, so the scene skips ahead and is lost. A
throwaway build that held audio pushes during compiles kept the scene
in step.

GpuStall is the bookkeeping for that hold. The GPU command thread marks
the time it is blocked with a Scope, and guest audio entry points will
call WaitWhileStalled, which waits only while a Scope has lasted at
least 250 ms. Most cold compiles finish under that, and the host queue
hides about 50 ms, so holding for them would add dropouts to stalls
nobody notices. Each Scope keeps its own start time, so short compiles
one after another never add up to a hold. A thread that owns a Scope
never waits, and turning the module off releases every waiter. The
hold has no time limit, because a compile that never ends has already
frozen the game.

Nothing uses it yet and it starts disabled, so this commit changes no
behaviour. Tests cover the tracker against a fake clock, and threaded
release when a Scope ends or the module is turned off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GetGraphicsPipeline and GetComputePipeline build a missing pipeline
synchronously on the GPU command thread, and nothing the guest submits
runs until the driver returns. Wrapping that build in a GpuStall Scope
lets guest audio wait for it once it passes the hold threshold.

The Scope is only taken on the GPU command thread. A build on any other
thread leaves the game running, and holding audio for it would freeze
sound while the picture moves. A check skips the Scope there rather
than asserting, so a future caller on another thread keeps today's
behaviour instead of stopping the emulator. The boot-time warm up in
pipelineSerialization.cpp is not marked, since the guest has not
started. Storing the pipeline and checkpointing the driver cache stay
outside the Scope, so only the driver build counts toward the hold.

GpuStall is still disabled and nothing waits on it yet, so this commit
changes no behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The switch is off by default. Holding guest audio has only been tried
in Atelier Yumia, so it stays opt-in until more engines have been run
with it.

Config::Load pushes the setting into GpuStall rather than having the
audio code read the config, so audio tests keep working without one.
Shutdown turns it off, which lets any audio thread still held go.
There is no launcher option yet.

Nothing waits on GpuStall yet. The audio entry points follow in the
next commits, so this one changes no behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --audio-compile-hold, AudioOutOutput and AudioOutOutputs wait in
GpuStall while a pipeline compile has blocked the GPU command thread for
at least 250 ms. Atelier Yumia paces its cutscenes by the audio it
pushes here, so without the hold the scene ran ahead of its frozen
frames and was lost.

The wait is the first statement of each entry point, before the port
checks. A port closed while a submit is held is then reported as
invalid, instead of reaching the closed port further down. Port state
queries are not held, and nothing guest-visible is frozen. Once the
compile ends, the host queue has drained, so the next outputs prime it
again without pacing, as after any other long gap. That drain also
counts one AudioUnderruns per hold.

New AudioOutTimingTests cases run the compile on a stand-in GPU thread
and each submit on its own guest thread, since the thread that owns a
stall is never held. They check that single, batch and null-buffer
submits are held, that a held output only reaches the queue after
release and then re-primes, that a port closed during a hold reports an
invalid port, that port queries are not held, and that nothing is held
with the switch off. A wrongly held call hangs, so audio_out_timing now
has a 60 s ctest timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AudioOut2ContextPush looped until it found its context. A non-blocking
push gave up with NOT_READY, but a blocking push to a destroyed or
unknown context slept and retried forever, so the game's audio thread
never came back. A context destroyed while another thread pushes was a
narrow race before. The coming audio hold makes it likely, because a
push can wait out a long pipeline compile while the game tears the
context down.

A push to a missing context now returns NOT_READY in both modes. The
console's real error for this case is unknown, so this keeps the
result non-blocking pushes already gave rather than guessing a new one.

The test pushes to a destroyed and to a never-created context on a
thread with a time limit, so the old behaviour fails instead of hanging.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --audio-compile-hold, AudioOut2ContextPush waits in GpuStall while
a pipeline compile has blocked the GPU command thread for at least
250 ms, the same as AudioOut. Blocking and non-blocking pushes both
wait. Returning NOT_READY instead would contradict the queue level and
leave games that poll spinning.

The wait runs at the top of every pass of the push loop, not once on
entry. A blocking push already waiting for queue space would otherwise
slip through mid-compile once the modelled queue drains by wall-clock
time, and play one extra grain per stall. Waiting before the context
lookup also means a context destroyed during a hold is seen as missing,
so the held push returns NOT_READY. The console's real error for that
case is unknown.

Pushes reach the host through AudioInternal::AudioOutOutputs, not the
guest AudioOut entry points, so a push is never held twice.

Tests run the compile on a stand-in GPU thread and each push on its own
guest thread. They check that blocking, non-blocking and empty-context
pushes are held and then succeed, that a push already waiting for queue
space is held on its next pass, that queue queries are not held, that
a context destroyed during a hold gives NOT_READY, and that nothing is
held with the switch off. A wrongly held call hangs, so audio_out2_port
now has a 60 s ctest timeout. The missing-context helper now reports a
generic timeout message, since the new tests reuse it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --audio-compile-hold, Audio3dPortPush waits in GpuStall before
anything else while a pipeline compile has blocked the GPU command
thread for at least 250 ms, like AudioOut and AudioOut2. A game that
paces its scenes by Audio3d otherwise runs ahead of its frozen frames. Audio3d
playback is still simulated, so for now the hold only affects pacing,
not sound.

Audio3d ports are never closed, so a port cannot vanish while a push is
held. The wait after a blocking push only follows the emulator's own
playback thread, so it needs no hold of its own. Audio3d has no test
target, because its playback depends on kernel semaphores. The hold
logic itself is covered by the GpuStall, AudioOut and AudioOut2 tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A hold for a long pipeline compile lets the host audio queue run dry on
purpose. The first submit after it found an empty queue and counted an
AudioUnderruns, so every hold showed up as a dropout in the performance
panel.

WaitWhileStalled now records on its thread whether it waited, and
ResumedFromHold reports that. Every call sets it, so only the first
submit after a hold is exempt, and a real underrun on the same thread
later still counts. The thread that was held is the thread that submits
next, for AudioOut and for AudioOut2, which reaches the host on the
pushing thread. A per-thread flag therefore marks exactly the right
submit, where a global hold generation would excuse ports that were
never held. The queue still re-primes without pacing after a hold.

Tests check that a held submit counts no underrun, that a real underrun
on the same thread afterwards counts one, that an underrun with no hold
counts one, and that the flag is set only by the call that waited.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A new "Audio holds" row shows how many stalls held guest audio and for
how long in total, so a run with --audio-compile-hold can be measured.
It sits after "Audio underruns" and is not coloured, because a hold is
deliberate silence during a freeze the user already sees, not a fault.
It always shows, reading zero when the switch is off.

AudioHolds counts once per stall, not once per held thread, so a stall
that holds the AudioOut, AudioOut2 and Audio3d threads together counts
one. The held time runs from the first submit the stall held to the
end of the last overlapping Scope. A stall that held nothing is not
counted. Like every panel counter, these only collect while the panel
is open, so the "held N ms" log line stays for runs without it.

GpuStallTests check that one stall holding two threads counts once
with nonzero held time, that a stall holding nothing counts zero, and
that overlapping Scopes count as one stall only when the last ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Removing a level of nesting for the missing-context return left the
use_device_clock line at 102 columns, past the 100-column limit. It is
wrapped as it was before that change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
PthreadSetprio writes it while PthreadGetprio and the priority-ordered semaphore wait read it from other threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Guest reads of GPU-written pages fault into a blocking download. Pages the guest reads are remembered; later GPU writes to them are copied at ReleaseMem, BufferFlush and flips and written to guest memory once the GPU finished, so the next read needs no download. Newer GPU writes supersede a queued publish.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	.github/workflows/build.yml
Image writes through the texture cache now supersede queued publishes of the same memory. Ranges over the publish budget stay queued for the next batch, and nothing is dropped when the download buffer cannot be mapped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The priority mapping under test exists only on Windows; Linux and macOS no longer build a full-emulator test that runs no checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A buffer write over an image's memory marks the whole image, so its next
bind re-uploads all of it, even when the write covered a few bytes.
Image can now also hold a range mark, as a bounding range of the bytes
that were written. Later marks merge into the range that covers them,
a whole mark always wins, the range is clamped to the image, and marks
that fall outside the image are ignored. A range mark tells resident
image heaps to look at the image again, as a whole mark does. Nothing
records a range yet. The texture cache starts doing so behind an opt-in
flag in a later commit, and every existing caller keeps the whole mark.

The new checks in UnifiedTextureCacheFlow cover:
- the whole mark
- merging, in both orders
- a whole mark not being downgraded
- clearing
- clamping
- ignored marks, on a marked and a clean image
- heap notification, with ignored marks as the baseline
Each of 9 mutations failed its matching check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A compute dispatch that writes a storage buffer at an image's base
marks the whole image, and the image's next bind re-uploads all of it.
In LEGO Batman, 32 KB and 4-byte writes re-upload images of up to
33 MB, several GB every 2 s.

With --partial-buffer-refresh, InvalidateBufferWrite records the
written range on the image instead, and keeps the image's GPU-written
mark, because outside the range the image is newer than the buffer. A
range is recorded only on images whose bytes can be refreshed exactly
later, and only for writes up to half the image. Depth, volume, MSAA,
block-compressed, metadata, video-out, Fmask and colour-transform
images, and the kDepth tile mode, keep today's whole mark. DMA fills
and copies keep the whole mark. A copied image takes the source's mark
as a whole mark.

The upload is still a full refresh in this commit, so InitializeImage
drops the GPU-written mark first, and the result is exactly today's.
Later commits refresh only the recorded range. With the flag off, the
call forwards to the old path.

The new checks in UnifiedTextureCacheFlow compare the flag on and off,
and cover:
- the recorded range, and the GPU-written mark kept
- matching texels and state after the bind
- the half-image threshold, at and over the boundary
- each excluded image kind, one case per trait against a colour
  baseline
A CLI test covers the flag. Each of 20 mutations failed its matching
check, one per eligibility rule plus the flag, threshold, boundary,
range and fallback paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A partial refresh needs to know which texels a buffer write covered.
The new refreshRegions helpers turn a byte range of an image into
rectangles of elements, and the rectangles into buffer-to-image copies:
- Tiled images use the tiler's own block layout, so the touched blocks
  of each mip and layer become at most three rectangles, clipped to the
  mip. A mip-tail level shares one block, so it is refreshed whole.
- Linear images split each touched slice into a partial first row, the
  full rows between and a partial last row. Bytes in row padding map
  to no texels.
- Volumes return nothing, so they keep a full refresh.
Ranges are widened to whole elements and 32-bit words. Nothing calls
these yet.

The tests in shaderCfgTests check:
- that every texel whose tiled address is in a range lies in a region
- that every region covers only touched blocks, and that regions don't
  overlap
- exact results at block boundaries, across a block row, for mip tails,
  for array layers, and for linear rows with and without padding
The oracle mirrors TileManager::Prepare and the tiler shader. Each
mutation failed its check, except treating mip-tail levels as blocks,
which gives the same result because a tail fits in one block. A
precondition on the row splitter keeps a padding adjustment from being
dead code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --partial-buffer-refresh, a linear image whose recorded range is
pending now uploads only the texels that range covers, instead of the
whole image. The rest of the image keeps its own contents, which are
newer than the buffer there, so the image stays marked as GPU-written.
Today's full refresh overwrote them with stale buffer bytes.

The partial path runs only when all of these hold:
- the image is eligible
- it is not CPU-dirty
- it is linear
- the range is at most half the image
Anything else counts a fallback and takes the full upload. Tiled images
fall back until a later commit. Only the rounded range is fetched from
the buffer cache. New debug counters record partial refreshes, partial
upload bytes and fallbacks.

A readback that waits on an image with a pending range now stays
pending until the refresh, instead of being dropped.

The tests compare the flag on and off on R32 linear images. They cover:
- the written texel refreshed and every other texel kept
- upload bytes cut to the range
- a later download writing the refreshed and kept texels
- padded rows and a range split over three rectangles, with distinct
  guest words so a wrong row length shows
- fallbacks for an over-limit range, an ineligible image, a CPU-dirty
  image and a tiled image
- the kept readback
Each of 12 mutations failed its check. One commit-2 check that expected
the old full upload now checks the partial result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Prepare and Record were about 120 and 80 lines, and the next commit
needs to extend both for partial detiles. They are now split into
helpers of at most 50 lines, with no change in behaviour.

Prepare now runs, in the same order as before:
- ValidateImageForTiling
- a loop over BuildMip, which takes the mip size as a window that a
  later commit can narrow to a rectangle
- UploadParams

The per-mip checks keep their order, now split into CheckLinearSide and
CheckTiledSide, and the checked arithmetic lambdas become free
functions. Record now runs RecordBarriers, BindTilerDescriptors and
DispatchTexels, with the same barriers, stages, clear and dispatch
order. Shaders, the pipeline layout, spec constants and pipeline slots
are unchanged.

The full test suite passes apart from the known Windows
kernel_file_system failure, including the tiled round-trip and detile
tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A partial refresh of a tiled image has to detile only the blocks a
buffer write touched, and copy only the written bytes within them.
TileManager::DetileRegions does that for a list of element rectangles,
reading from a buffer that holds just the written byte window.

The tiler shaders gain a REGION specialization constant. With it set,
each record carries a rectangle origin and layer, and the shader skips
any element whose tiled byte offset is outside the window, using one
unsigned compare on a source base that may wrap by design. The region
data rides in the existing TilingInfo uniform: each mip record grows
to 64 bytes with the origin, and two spare header words hold the
window. The push constants and pipeline layout are unchanged.

Region pipelines are a third direction in the lazily built slot array.
The detile and tile slots keep their old numbers. With REGION at zero
the shaders compute exactly what they did before. The SPIR-V of every
family changes, but only the legacy behaviour after specialization is
claimed unchanged.

DetileRegions never clears the target, so texels outside the regions
keep their contents. It dispatches up to 16 regions at a time, counts
window texels, and rejects depth and volume images.

The tests compare against the tile tables, with sentinel targets and
misaligned sources. They cover:
- the mask inside a block
- rectangle origins
- a whole-mip rectangle with a narrow window
- several regions in one dispatch, and more than one dispatch
- an array layer
- the CPU-side records
- a sweep over every family a partial refresh reaches at every element
  size, each with legacy detile and tile, a full-window region and a
  partial misaligned region
GpuTilerCpuParity still passes. Every mutation failed, including
dropping the mask, the origin, the layer, the window bias and the
no-clear rule. The compact-buffer size check now expects 64-byte
records.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --partial-buffer-refresh, a tiled image whose recorded range is
pending now refreshes only the blocks the range touched. LEGO Batman's
32 KB writes over 4K render targets refresh one 64 KB block instead of
the whole image.

The refresh fetches only the written byte window from the buffer cache.
It then downloads the image's current texels for the touched block
rectangles into the linear scratch, detiles just the written elements
over them with the masked region detile, and uploads those rectangles
back. Texels in a touched block but outside the written bytes keep the
image's own values. The image stays marked as GPU-written. A write that
covers no texel, such as bytes of a mip-tail block that no level uses,
clears the mark with no upload.

The tiled path refuses, and the full upload runs instead, for:
- the Depth64KB family
- images too large for the tiler
- render targets that the full upload's own check would reject
That check is now one IsValidColorAttachmentUpload helper shared by
both paths, so they cannot drift apart.

The tests compare the flag on and off on tiled images:
- a 256x256 render target with a 32 KB base write, refreshing one block
  and keeping every other texel, with a check that uses distinct per-
  address words
- a range that starts inside the image
- a mipped Standard64KB texture where only tail texels change
- a later download writing the merged contents
- a pending readback kept until the refresh
The commit-4 placeholder that expected tiled images to fall back now
expects a partial refresh. Every mutation failed: skipping the
download, the detile or the upload, routing to the full upload,
dropping the window start, clearing the GPU-written mark, and planning
the whole image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Partial refresh excluded every image with metadata. In LEGO Batman that
left most of the remaining full re-uploads in place, because its 4K
colour render target carries DCC and gets hundreds of small storage
writes at its base every few seconds.

Colour DCC and CMASK images are now eligible. A storage write at the
image base lands on the image data, and the metadata lives at its own
address. The keys only matter to MaterializeColorClear, which runs
after the refresh and keeps its checked state. So a pending fast clear
still wins, exactly as with the full refresh. After a clear was
already applied, the partial refresh keeps the cleared texels outside
the written range, where the full refresh brought back stale guest
bytes. Eligibility is now a whitelist of no metadata, DCC and CMASK.
HTILE and any future kind stay on the full refresh, as do depth and
compressed images.

The tests use a real DCC descriptor, flag on and off. They cover:
- a pending clear winning over the refresh on the GPU path
- an applied and checked clear kept outside the written range, which
  the flag-off baseline loses
- the checked state kept across later binds
A real CMASK render target with a register clear pending takes exactly
one partial refresh, and the clear still wins at both corners.
Eligibility rows cover DCC, CMASK, HTILE on a colour image, and a
compression change between the mark and the refresh. Every mutation
failed its check, including refreshing after the clear, forgetting the
checked state, dropping CMASK and admitting every kind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a DMA fill or a memory-to-memory copy targets memory that is not
GPU modified, BufferCache writes it on the CPU and relied on the
resulting write faults to invalidate cached buffers, images and image
heaps one page at a time. In LEGO Batman: Legacy of the Dark Knight
(PPSA16833) the 160 KB and 288 KB DMA fills it issues before the title
screen caused about 7,500 such faults a second, all on the GPU command
thread.

FillBuffer and CopyBuffer now call RenderContext::InvalidateMemory for
the destination range first. That is the range form of the same three
invalidations a write fault runs, so the pages are already writable and
the CPU write no longer faults. The range is checked exactly, so an
image that starts partway into a page the write touches is marked CPU
dirty where a fault on that page might only have marked it maybe dirty.
A range that is not fully mapped is written as before.

The new test prepares identical clean cached ranges with an image over
each, and compares a plain host write, which faults once per page, with
FillBuffer and CopyBuffer, which must not fault and must leave the same
bytes, the range CPU modified, the image CPU dirty and untracked, and an
updated GPU copy. The test harness fault handler now counts GPU faults
the way the emulator does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the guest releases direct memory and then maps a fresh allocation
at the same address, the range is unmapped from the GPU side twice:
once by the release and again when the fixed map replaces the now empty
range. Buffers stay registered after an unmap, so the second unmap still
waits for the whole GPU queue to finish. LEGO Batman: Legacy of the Dark
Knight (PPSA16833) does this several times a second before its title
screen, and those repeat drains cost about 20 to 27 ms a second.

With the new --skip-redundant-unmap-drains option, an unmap skips the
queue drain when the range is no longer mapped, holds no images, has no
GPU-written data and no priority operation is pending anywhere. The
rest of the unmap still runs, so the range is still marked CPU modified
and queued for BDA sync. Every deferred operation that writes guest
memory is a priority operation, so the pending check covers them. A
deferred fault scan can now run after such an unmap, which can at most
register a buffer over the unmapped range without reading host memory.
The option is read once when the render context is created and is off
by default.

The new test counts queue submits with the option off and on. A mapped
range drains in both modes. A second unmap of the same range drains
only with the option off, and leaves the same state in both modes. An
unmapped range that still has an image, GPU-written bytes or a pending
priority operation drains with the option on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PageManager changes host page protection only when a page's watcher
count crosses zero, so the protection it set stays correct only while
the host view it applied it to stays mapped. A later change will keep
the GPU caches when direct memory is released and the same physical
memory is mapped back at the same address. The new view is mapped read
and write while the watcher counts are kept, so those pages would no
longer fault on the accesses the caches rely on.

ReapplyProtection walks a range and protects each run of pages to what
its current watcher counts require, using the existing per-page rule and
protect call, one call per run of equal protection. It leaves read and
write pages alone, never changes a count, skips tracking regions that
were never created, and takes each region's lock in the same order as
the watcher updates. Nothing calls it yet.

The tests start from a range made fully writable, the way a fresh view
is, and check that write-watched pages come back read-only, read-watched
pages no access and unwatched pages writable. They also check the exact
calls, including one call for two adjacent pages with the same
protection, a range that crosses a region boundary, and that the counts
are unchanged afterwards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A later change will let the kernel keep the GPU buffer cache when the
guest releases direct memory and then maps the same physical memory back
at the same address, instead of invalidating the range and uploading it
all again. This adds the GPU side of that. Nothing calls it yet apart
from a safety net in MapMemory.

SuspendMemory drains like UnmapMemory, publishes every GPU-written byte
in the range to guest memory while the view still exists, and then
treats the pages as clean rather than CPU modified. Textures and the
image heap are dropped as on any unmap. ResumeMemory, called once the
same memory is mapped again, adds the range back and re-arms page
protection with ReapplyProtection, so nothing is uploaded again.
CancelSuspendedMemory applies today's full invalidation to a suspended
range. MapMemory cancels any suspended overlap first and logs when it
has to, since the kernel is meant to cancel earlier. UnmapMemory now
also ends any suspension of its range, and a GPU that is stopping gets
a plain unmap instead of a suspension. UnmapMemory is otherwise
unchanged, moved onto two helpers shared with the new operations.

The tests release and remap a real view of direct memory. They compare
an unmap and map, which uploads the changed data, with a suspend and
resume, which keeps the cache, re-arms protection and uploads nothing.
They also check that a write after resume dirties only its page, that
GPU-written data reaches guest memory on suspend, that cancel and a map
over a suspended range both match the unmap and map baseline, and that
unmap, cancel, resume and a stopping GPU each end the suspension.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
LEGO Batman: Legacy of the Dark Knight (PPSA16833) releases a 685 MB
range of direct memory several times a second before its title screen,
allocates it again and maps it back at the same address with the same
physical offset every time. The kernel unmaps every GPU range on the
release and maps it as new on the remap, so the GPU caches are thrown
away and gigabytes are uploaded again even though Kyty keeps the bytes
in its shared backing and never zeroes direct memory.

With the new --keep-gpu-cache-on-reuse option, a release suspends each
mapped alias on the GPU side and records its address, size and physical
offset in a table of at most 32 entries. A later fixed read and write
MapDirectMemory of exactly the same address, size and offset resumes
the entry, so the GPU caches stay valid and nothing is uploaded. Every
other case cancels the entry first, which is today's full invalidation.
That covers a different offset or size, a read-only remap, any other
mapping at the address, any view of the same physical memory at another
address, any GPU map over the range, a failed remap after its view was
created, a full table, release rollback, teardown and turning the
option off. The redundant unmap from the fixed map is skipped only for
the exact candidate. With the option never turned on, the kernel takes
exactly the paths it takes today.

The tests check the exact order of suspend, resume, cancel, map and
unmap events. With the option off they match today's order. With it on
they cover the exact reuse, a different offset, a view of the same
physical memory at another address, flexible and private maps over the
address, a half-size remap, release rollback, a full table, teardown, a
PRT aperture over a suspended range, a read-only remap, a remap that
fails after its view exists, and two aliases of which only the exact
one resumes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The earlier tests checked the RenderContext and the kernel table apart.
These drive the real kernel calls with a real RenderContext installed,
so a release suspends through the GPU side and an exact remap resumes
it, as the game does.

With the option on, an exact release and remap keeps the same
registered buffer and leaves nothing to upload. With it off, every page
is queued again. Both end with the right data on the GPU, read from the
registered buffer rather than a streamed copy. Remapping a different
physical offset, and writing through the same physical memory mapped at
another address before the remap, both reach the GPU, so the cache is
never kept over changed bytes. A real write through the host view after
a resume dirties exactly its page, which needs the protection that
ReapplyProtection re-arms. Three cycles on one range check that a page
written but not yet uploaded at release is still uploaded after the
resume, and that a page which faulted in an earlier cycle is protected
again. A release while the GPU is stopping does not suspend. None of
these cases reaches the MapMemory safety net, which now counts how
often it fires so the tests can check it stays at zero.

Each guard was removed in turn and the matching case failed. Without
the offset compare or the physical overlap rule the GPU kept stale
data, without ReapplyProtection the write after resume was not seen,
and removing three cancel paths at once made the safety net fire.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The PRT aperture case of ReleaseRemapSuspension mapped its block at the
fixed address 0x1000000000, which is where Linux and Windows start their
user range. x86-64 macOS starts it at 0x7000000000 and owns nothing
between 0xfc0000000 and there, so the fixed map failed with ENOMEM
(0x8002000c) and the macOS job failed virtual_memory_allocation. The CI
runner is arm64, but it builds with CMAKE_OSX_ARCHITECTURES=x86_64, so
the x86-64 macOS layout applies.

The case now uses 0x7000000000. It is inside the PRT aperture range and a
user address on every platform, and ExtendedAndUserMappingsDoNotAlias
already maps there on all three. The other sub-cases only use addresses
from non-fixed maps, which are the same on every platform.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/graphics/guest_gpu/graphicsRun.cpp
#	src/graphics/host_gpu/renderer/renderCompute.cpp
# Conflicts:
#	src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
# Conflicts:
#	src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp
#	src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
Adds TryReadBackingStrided, which reads one byte at first + stride * i
for each of count addresses. It behaves like that many one-byte
TryReadBacking calls: the same up-front rejections plus count zero and
stride overflow, one shared lock, the backing-read test hook called once
inside it with the whole range, and false on a hole. Map entries are not
coalesced, so the entry found for one address is reused only while the
next address stays inside it.

Nothing calls it yet. The colour-clear check reads one code byte per
array slice, about 14 per call on the LEGO Batman menu, and will use it
next.

Tests compare it against single reads across adjacent entries, entry
ends, holes, an unmapped tail and edge counts, map three pages out of
order so a reader that skips the re-lookup reads the wrong page, assert
that rejected inputs never reach the lock, and add it to the
lock-exclusion test. Mutations caught: first byte for every address,
entry bound check skipped, lock dropped, hook called per byte or with
the wrong address, and each overflow check removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
MaterializeColorClear checks the first metadata byte of every viewed
slice for a fast-clear code. It read them with one TryReadBacking per
slice, each taking the guest memory lock and a map lookup, which made
the not-GPU-written path cost about 690 ns per call on the LEGO Batman
menu's array textures (about 14 slices each).

The codes are now read with one TryReadBackingStrided call into a small
helper (stack storage up to 128 slices, heap above), with the same exit
on a failed read. A slice whose code has any of its low five bits set is
skipped before decoding, because every code DecodeColorClear accepts
has them clear, so the consumed code 0xff, the steady state, skips the
decode. The full-slice check, the clear and the 0xff write-back are
unchanged. Reading every code first is safe because a clear writes only
its own slice and the GPU-written branch has already downloaded the
viewed range.

ColorClearCodeReads runs a 32-slice volume with four fixed clear codes,
a register clear with its own colour, near misses (0x21, 0x41, a 0x40
slice with one wrong byte) and consumed slices, plus a view starting at
slice 4, and checks every slice's texel and metadata against an explicit
table. The same test passes on the previous per-slice loop. Mutations
caught: slice 0's code for every slice, the read starting one slice
late or at the metadata base, the precheck on the high bits, and a 0x3f
mask. Dropping the precheck passes, as it only saves time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the colour-clear metadata range is GPU-written, MaterializeColorClear
asked whether every viewed slice was already checked, one
IsColorMetadataChecked per slice and per clear key, after decoding all 8
clear values into vk::ClearAttachment. On the LEGO Batman menu's array
textures (about 14 slices) that path cost about 900 ns per call.

When the slices sit back to back (mip size equals slice size) and there
are at least two, one lookup and one mark over the viewed range now
replace the per-slice loops. RangeSet::Add merges touching intervals and
Subtract never leaves touching pieces, so the range lookup equals the
AND of the per-slice lookups for every key set. Mipped views keep the
per-slice loops, because the gaps between slices are never marked. The
key mask is computed from DecodeColorClear's result alone, and the clear
values are built only on the conditional clear path that uses them.
DecodeColorClear and the key helper are declared in the header for the
tests, and the 5-bit key shift is a named constant.

Tests: an independent model of marks and byte-level forgets checks both
lookups through scripted steps and a seeded random walk that mixes
per-slice and range marks; a 4-layer GPU-written view checks that a
rebind adds no check and that rewriting one slice rechecks and clears
only it; the contiguity decision and a half-size mip are pinned; and a
key table over every metadata kind, binding, register, format and depth
combination plus all 256 codes. Mutations caught: range covering slice
0 only or one slice short, a range mark one slice short, a non-merging
Add, always taking the range path, wrong key shifts or a dropped
register key, and clear values built wrongly or never decoded. A mipped
view on the GPU path is covered only by the unit-level tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds the flag and caches it in BufferCache, read once because the fault
path is hot. Nothing reads it yet. A later commit makes a fault readback
that waits for the GPU also read back GPU-written bytes of recently
faulted buffers, so their next fault does not wait again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
DownloadBufferMemory was 83 lines. It is now four helpers and a short
composition, with a move-only PendingDownload that owns the copies, the
mapped download memory and any temporary buffer. Behaviour is unchanged:
the same copies, barriers, waits and publish order. The split lets a
later commit record downloads for several buffers and wait once.

Reserve and Record now check that they run once and in order, and the
64-byte copy alignment has a name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds HotReadbackTable, a capped table of buffer ranges that took a sync
readback recently, with the tick of each. With --batch-hot-readbacks,
ReadMemory notes the buffer after it downloads GPU-written bytes. Nothing
reads the table yet. A later commit downloads the hot buffers' GPU-dirty
bytes in the same wait.

Entries hold only an address range, never a buffer reference, so a
deleted or merged buffer cannot be reached through a stale entry. They
age out after HotReadbackTicks submits, and the table holds at most
MaxHotReadbackEntries.

Tests cover aging at the boundary, the entry cap, refresh without
duplicates, and recording through the real ReadMemory path: a clean
readback records nothing, a dirty one records the buffer start and the
readback tick with the flag on, and nothing with it off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --batch-hot-readbacks, a sync readback that has to wait for the GPU
also downloads the GPU-written bytes of buffers that took a sync readback
recently. Their next guest access then finds clean pages and does not wait
again. In LEGO Batman's main menu most fault readbacks are for writes that
had already finished by the previous wait.

Hot entries are resolved through the page table only, so a stale entry
never creates a buffer. The main buffer is skipped, duplicates are counted
once, and the extras stop at MaxHotReadbackBytes. The whole batch reserves
its download memory in one Map before anything is recorded, so a ring
wrap can never overwrite a download that is recorded but not yet
published. Extras are unmarked GPU-modified only after they are
published, and they are never marked CPU-modified. With the flag off the
readback path is unchanged.

Tests drive the real ReadMemory path against a flag-off baseline: one
shared wait, the age limit at its boundary, the byte cap, the main-buffer
skip, no CPU marking, a wrapped small ring, and a stale entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A batched extra download marked its whole buffer clean once published.
That was right while extras always collected whole buffers, but a later
commit adds extras that collect only part of a buffer. Unmarking the
whole buffer then would clear GPU-dirty pages that were never downloaded,
and the guest would read stale data without a fault.

Each batch entry now records the range it collected, and the unmark uses
that range. Hot buffers still collect and unmark their whole buffer, so
behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RecentGpuWriteRing remembers the spans of recent GPU writes of 64 KiB or
less, with the tick that submitted each one. A later step uses it to
co-download finished small writes in the same wait as a sync readback.

The walk goes newest first, rounds each span out to tracker pages and
flags whether the GPU has finished it. Pending entries are visited too,
so the caller can keep older finished writes under them out of a
download. The ring does not dedupe, because the caller's claimed range
set does that and also clips partial overlaps. Empty and oversized
writes are ignored, and a repeat of the newest span only refreshes its
tick.

Nothing uses the ring yet, so behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --batch-hot-readbacks, ObtainBuffer now notes each written span in
the recent write ring at the current tick. ObtainBuffer is the one place
that marks buffer memory GPU-dirty, so fills, copies, image publishes
and storage descriptors are all covered. The ring itself drops writes
over 64 KiB.

The tick is the one current when the buffer is bound, so it is a lower
bound for when the write lands.

Nothing reads the ring yet, so readbacks are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --batch-hot-readbacks, a sync readback now also downloads the
finished writes the recent write ring remembers, in the same GPU wait,
so their next fault costs no wait. LEGO Batman's main menu takes many
sync readbacks of buffers that never faulted before, which the hot
buffer table cannot predict.

The ring is walked newest first. Each finished span is clipped to what
the batch has not claimed yet, resolved through the page table without
creating a buffer, and unmarked exactly. Pending spans are claimed too,
so an older finished write under a newer pending one is held back. The
main window is claimed in whole tracker pages. Recent writes share the
4 MiB budget with the hot buffers.

A write counts as finished only once the tick after its own has
completed, because the recorded tick is the one current when the
buffer was bound.

The hot table aging test now clears the ring in its aged runs, so it
still tests the hot table alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two debug counters record the pieces of recent small GPU writes that a
sync readback downloads in its wait, and their bytes. Hot buffers are
not counted, so with both on the counters show what the recent write
ring adds over the hot table.

The GPU section of the performance overlay gains a "Co-downloaded GPU
writes" row with ranges per second and the byte rate. It shows while
--batch-hot-readbacks is on, even at zero, so a feature that never
fires stays visible.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
--batch-hot-readbacks now also reads back finished small GPU writes, so
its help text says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds the flag, its config field and accessor. Nothing reads it yet. A
later commit uses it to submit GPU work periodically while a long
command stream records, so the GPU starts on earlier work instead of
idling until the end of the slice.

A CLI test checks the flag is accepted, and a host test checks the
accessor returns its own field. The launcher toggle is left for the
release branch's Experiments tab.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
SubmitCadence decides when the GPU thread should submit the command
buffer it is recording. It holds no Vulkan state, so it is tested on a
fake clock without a device. Nothing uses it yet.

With the flag on, a submit comes due once 1 ms has passed since the
first draw or dispatch in the buffer, so idle time before the first
work does not count. A due submit is held back while the GPU still has
two submits running, because an extra one would only add buffers in
flight. Holding clears due but keeps the start time, so the next draw
re-arms it and the GPU lag is checked once per draw, not per packet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --gpu-submit-cadence, the GPU thread now submits the command buffer
it is recording once the submit cadence says so, so the GPU starts on
earlier work while the rest of a long command stream is still being
recorded. On the LEGO Batman menu the GPU otherwise sat idle while about
14 ms of work was recorded into one buffer.

The render scheduler owns the policy and resets it at every new command
buffer. Guest draws and dispatches, direct and indirect, note work. The
hook runs once at the end of each completed packet in ProcessPm4, never
inside a handler, and uses a plain Flush rather than BufferFlush, which
would publish occlusion queries and wait. The GPU lag is read only when
a submit is due, and a due submit is held back while two submits are
still running. The presenter's scheduler always passes false.

CadenceSubmits and CadenceHeldBack debug counters count both outcomes.
Draws are covered by the open-pass split test in the next commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Three tests show that splitting a command stream on the cadence changes
nothing a game can see.

- A read-modify-write compute shader run as eight dependent dispatches
  in one stream gives the same words with the flag on and off, and the
  on run really split between dependent dispatches.
- Two draws into opposite halves of their own target, split while the
  render pass is open, give the same pixels as one unsplit pass. This
  also covers the draw site of the cadence.
- A cadence submit leaves pending occlusion dumps unpublished and adds
  no GPU waits, because it uses a plain Flush.

A depth target with an HTILE meta clear is not split in a test. The
meta clear is consumed per draw before any pass begins and the pass
reopens with Load, so a split cannot change whether it is applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The texture cache protects a recently used image from being replaced or
freed by an overlapping request for 32 scheduler ticks. With
--gpu-submit-cadence submitting about every millisecond, 32 ticks
shrink from about two or three frames to about one, so turning the flag
on would also shorten that protection and cause extra re-uploads.

With the flag on, the age is now counted in texture cache collector
ticks, which advance once per frame at sceAgcSuspendPoint, and an image
is old after more than three of them. Both stamps are kept on every
access and heap release, so switching the flag never leaves a stale
age. With the flag off the comparison is unchanged.

A title that submits for a long time without a suspend point does not
age its images with the flag on. The LRU collector already stalls in
that case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
V_MIN/V_MAX_F32 compared the sources as floats, so on a host that flushes denormals in compares a denormal and a zero (or two denormals) compared equal and the result depended on the host. A signed compare of the raw bits, inverted when both signs are set, gives the guest's order for every non-NaN value, including -0 below +0, with one instruction less for V_MAX.
MED3 built MIN3, MAX3 and the median from five float min/max sequences and two float equality tests, so a host that flushes denormals in compares could pick another source. Signed integer keys of the source bits order every non-NaN value exactly, give NaN sources the highest keys, and need 35 instructions instead of 66 (55 with native min/max).
min2 and max2 compared host floats, so the expected bits of the denormal rows depended on the host CPU's float mode. A total-order key of the bits gives the same results without it.
--redzone only analyzed functions listed in .eh_frame, only recognized
RSP-relative red-zone operands, and dropped jump tables stored outside the
executable segment. Saros (PPSA07631) hits all three: leaf functions that are
not in .eh_frame keep locals below RSP, a Windows exception raised by a
tracked GPU write inside them overwrites those locals, and the game crashes
(a loop count turns into garbage and the loop runs past its buffer, or a
pointer reloads as null).

- Discover functions from the direct call targets of decoded code, to a
  fixpoint, so unlisted functions are analyzed instead of being decoded as
  the tail of the preceding function.
- Detect red-zone use through RBP in frame-pointer functions
  (push rbp; mov rbp, rsp; push/sub rsp) and protect such functions
  conservatively.
- Resolve jump tables that live anywhere in the loaded module (usually
  .rodata); targets are still required to be inside the function.
The bulk invalidation before a CPU fill or copy checked images against the exact written range.
A write that starts before a multi-page image and ends inside the image's first page therefore
marked the image CPU dirty, so its next use re-uploaded it from guest memory and lost anything
the GPU had written to it. The per-page faults it replaces only ever landed before such an image,
which untracks the image's head page and leaves the rest of the image alone.

The fill and copy now call RenderContext::InvalidateSequentialWrite, which invalidates buffers and
image heaps as before but marks an image CPU dirty only when a front-to-back write starts inside
it or crosses a page boundary inside it. Everything else takes the same head, tail and maybe-dirty
paths as a fault would. RenderContext::InvalidateMemory keeps its meaning for its other callers.
memcpy's write order is unspecified, so the copy is treated as front to back like the fill.

CheckBulkHeadPageFill puts a GPU-modified image partway into a page and fills up to a quarter
page into it, once with a plain host write and once with FillBuffer. The plain write must fault
and only untrack the head page. FillBuffer must not fault and must leave the image the same way.
Mutations caught: matching images by exact overlap again, and FillBuffer skipping the bulk
invalidation so it falls back to faulting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A submit only came due inside NoteWork, which runs once per draw or dispatch. A draw followed by a
long run of state or NOP packets therefore stayed unsubmitted past the interval until the next
draw, so the GPU sat idle on work that was ready.

The PM4 loop now asks SubmitCadence::DueAtBoundary at each packet boundary. Once the command
buffer holds work it also reads the clock there, once every SubmitCadenceBoundaryStride (32)
boundaries since state packets far outnumber draws, so the interval is honoured without another
draw and a due submit is at most 32 packets late. With the flag off no work is ever noted, so the
check reads nothing and is one branch.
After a submit is held back for GPU lag, only the next draw re-arms it as before, so a lagging
GPU is not polled at every packet.

CheckSubmitCadenceBoundary covers boundaries with no work, with the flag off, before and after
the interval without a draw (due exactly at the stride's clock read), and a hold at a boundary
that waits for the next draw. The wiring
check drives a real scheduler on the fake clock and expects a boundary to submit once the
interval passes with no further draw. Mutations caught: the boundary never reading the clock,
the boundary ignoring a hold, the stride being ignored, and the scheduler asking Due instead of
DueAtBoundary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Direct calls into the current function's range were recorded only as
callees. When --redzone is off (--amd-cpu or the TSC-only path),
AddDecodedCallees does not run, so the function is never split there and
the entry of an unlisted function could end up inside a relocated span.
Record the target as a branch target as well, as before.
SuspendMemory falls back to an unmap when the guest GPU is stopping, but shutdown could begin
after that check. RunMemoryOperation then ran the suspend body on the calling thread, which did
the suspend waits off the GPU thread and recorded a suspension during teardown. If shutdown had
already finished, the GPU was gone as well.

The suspend body is now RenderContext::SuspendNow, and it checks again when it runs. With the GPU
stopping or gone it unmaps through UnmapNow, the body UnmapMemory already uses, including the
drain upstream's own unmap runs on the calling thread at shutdown. The kernel records no
suspended entry in that case, because it asks the GPU side whether the range is suspended.

CheckSuspendBodyAtShutdown runs the suspend body on primed areas after the guest GPU stops and
again after RenderContext has released it. Each must end exactly like an unmap and stay
unsuspended. Mutations caught: no check in the body, no null check, and a null check alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Translating a new guest shader or creating a new pipeline on the render thread stops the emulated
GPU for the time it takes: tens of milliseconds for a translation, around a second for a large
pipeline. Whenever new content loads, the game freezes while shaders build.

Worker threads now do the three steps a draw needs: translate the guest shader, compile its SPIR-V
into a host module, and create the pipeline. The render thread keeps the program cache and the
pipeline map and applies what the workers finished at the start of each program lookup. A draw
whose shader or pipeline is not ready is skipped, so the frame it belonged to is incomplete; the
presenter holds the last complete frame (for at most 3 s) instead of showing it.

- Draws into small color targets (under 1024 pixels each way) are not skipped: such a target is
  often a cache the game fills once (glyphs, UI layers), so a skipped draw would be lost for good.
  They build synchronously, as before.
- Compute shaders still build synchronously.
- The driver pipeline cache is saved from a background thread every 5 minutes; the save at exit is
  still synchronous and waits for the background one.
- Workers translate and compile finished stages first (urgent queue), so a draw that is nearly
  ready does not wait behind translations of other shaders.
- --no-async-shader-compile restores the old behavior; --async-shader-compile is accepted too.

Known limitation: each step needs the same draw to come back, because compiling needs the
resources and push-data layout a draw supplies. A skipped draw that the game does not repeat is
never completed. Skipping only draws into targets the game redraws every frame is a follow-up.

Re-applied onto main 91c5820c. Merge conflicts: upstream removed the shader optimization setting
and the module-null check in CompileModule, so neither is carried over.

Tested: builds clean; a 130 s run reaches the game's menus with the workers running (8 threads),
with no crash and no GPU driver events. Not yet tested here: the License Center (this branch has
neither the depth cache fix nor the render-area guard) and frame rate.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The workers ran jobs first-come-first-served at normal priority. A pipeline a draw asks for every
frame then starved behind the new ones each frame brought, and eight compiles ran on the cores the
game's own threads use.

- The workers run at below-normal priority (new Common::Thread::LowerPriority: SetThreadPriority
  on Windows, a per-thread nice value on Linux, the utility QoS class on macOS; the last two are
  untested here).
- Each queued job records when a draw last asked for it. A draw that wants a job again, because
  the job is still running, refreshes that time. Within the urgent jobs and within the normal jobs
  a worker takes the one asked for last, the scene on screen; worker 0 takes the oldest, so a job
  asked for once is not left behind for good.
- Jobs no draw has asked for in 2 s are taken by the first two workers only, so work nobody sees
  any more does not take the other cores.
- While anything is pending, every 2 s the render thread prints one line: how many shaders are
  translating or compiling, how many translations are waiting for a draw to come back (and how
  long the oldest has waited), how many pipelines are being built, how many jobs are queued and
  how many draws were skipped. One more line says when everything is idle.

The scheduling follows the pipeline compiler in usa-ratt/KytyPS5-GT7.

Tested: builds clean; in a 100 s run the workers show as below-normal priority threads, the status
line prints, and there is no crash or GPU driver event. It also shows 126 translations still
waiting for a draw after 150 s, with no draws skipped: shaders whose first draw was skipped and
never came back. Skipping only draws into targets the game redraws every frame is the next change.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A draw whose shaders are still being built is skipped, so what it draws is missing from that
frame. That is harmless when the game draws the target again every frame, and lost for good when
it draws the target once and samples it for many frames (glyphs, UI layers, baked textures). The
test was only "not a small target", which skipped such draws.

- The renderer counts flips (one per FlipQueue::Prepare, in order with the draws) and keeps, for
  each render target address, in which of the last frames a draw went into it. A draw is skipped
  only if every color target it writes was drawn in at least three of the last six frames. A draw
  with no color target (a shadow map) goes by its depth buffer. Small targets (under 1024 pixels
  each way) still always wait for their shaders.
- A draw whose pipeline has a shader that writes buffers, images or memory through an address is
  never skipped at the pipeline step: other draws and dispatches may read what it writes.
- Draws that wait build their shaders on the render thread, as before, but now use a translation a
  worker already finished instead of translating again. Translations still waiting for a draw
  after a minute are dropped, since the scene they were for is gone.
- The 2 s status line on the console is shorter, ends in how many targets count as redrawn, and
  fits an ordinary console window.

The rule follows the redrawn-target logic of usa-ratt/KytyPS5-GT7, in a much simpler form.

Tested: builds clean; a 3 minute run to the first menu shows 50 of 69 targets counted as redrawn,
about 100 translations waiting (down from 250), no crash and no GPU driver events. Not tested:
the License Center, and frame rate.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
With async compile on, the render thread still built shaders and pipelines itself for every draw
that could not be skipped. How much was unknown. The 2 s status line now has a second line when it
spent 20 ms or more building: how long, the worst single build, and the time, shaders and pipelines
by reason: small targets, targets not yet seen redrawn, compute dispatches, and shaders that write
memory.

The first measurement (loading the first menus) showed the render thread building about 1,000
shaders and 870 pipelines in roughly 20 s, with 2 s windows that were 99% building. Small targets
were 10.6 s of it and targets not yet seen redrawn 8.8 s. Two changes to the rule for skipping:

- A small target is skipped like any other when the game redraws it every frame. The history of
  draws per target already tells a UI layer drawn every frame from a glyph cache drawn once, so the
  blanket "small targets wait" rule is gone. Small targets drawn once still wait.
- A G-buffer pass (two or more color targets of at least 256 pixels each way, depth tested and
  written) is skipped from its first frame instead of waiting for three frames of history.

The G-buffer test follows the pass detection in usa-ratt/KytyPS5-GT7.

Measured, same load: 1.8 s of building instead of 20.2 s (targets not yet redrawn 0.9 s, compute
0.9 s, small targets 0.03 s). In a 5.5 minute License Center run: 1.8 s in total, no crash, no GPU
driver events. The frame rate is unchanged; the stutter while shaders load is much smaller.
Compute dispatches are still built on the render thread.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A draw's render area comes from the guest's description of its render targets, while the
attachment is a view of a cache image. When that image is smaller than the guest extent (a depth
target asked for 512x512 over a 400x512 image, or a 4-layer shadow pass over fewer layers), the
draw writes past the image: the NVIDIA driver reports a "3D WIDTH ZT violation" and the GPU
times out, which ended the emulator in a GT7 race.

The render area is now bounded to the smaller of the cache's image extent and the extent that
was really allocated, and the layer count to the allocated layers. Each clamp is printed (the
first 32 of each kind), so a bounded target shows in the console.

From usa-ratt/KytyPS5-GT7 (15cddeb, "bound the render area to attachment images"), with the
real allocation's extent and the layer bound added.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Carry forward the local Pragmata thread-stack fix, the debug standard-library size check, and the normal-return regression test onto upstream a0268f1d.

Validated with a Windows Debug launcher build and GuestStackNormalReturn. PthreadExit coverage remains pending.
A vertex or mesh stage's push data started after the paired pixel shader's data, so the
same vertex program needed one module per pixel data size and FindModule missed. Place
vertex-pipeline stages top-down from a ceiling (32, then each pushing stage's start);
pixel and compute keep the bottom-up rule. A stage pushes exactly when it did before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Neither the POSIX getpeername (TXFFFiNldU8) nor sceNetGetpeername
(TCkRD0DWNLg) was registered. A call landed in the unresolved import
stub, which returns 0 without writing the address, so the caller read
whatever was in its buffer as the peer address.

007 First Light (PPSA11386, #1989) builds a socket pair over loopback
when it creates its "ZHttpManagerOrbisCurl" queue: socket 128 binds and
listens, socket 129 connects, accept returns 130. It then calls
getsockname on 129 and getpeername on 130, which hits the stub. Right
after that it closes all three sockets, and the log shows no other
socket for the rest of the run. It looks like the usual check that the
accepted end is the one it connected, which cannot pass on an unwritten
address.

Most other logs attached to recent game reports import getpeername as
well (Silent Hill f, Cronos, Hellblade, Star Wars Jedi, Sackboy, ...),
and Gran Turismo 7 and Star Wars Jedi Survivor import sceNetGetpeername.

Getpeername follows Getsockname: the host socket's peer address is
converted to the guest sockaddr, and errors (ENOTCONN, EBADF, EFAULT)
go through the same paths. The POSIX export returns -1 with errno, the
libSceNet export a SCE_NET error.

The kernel file system test checks both exports on a loopback TCP pair
and on a socket without a peer. It also runs with --network-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FreeBSD 9 (the PS4/PS5 kernel base) getpeername1()/kern_getpeername()
computes len = MIN(*alen, sa->sa_len), copies out len bytes only when
len != 0, and writes back *alen = len. Follow that: convert the peer to
the 16-byte guest sockaddr locally, copy min(*addrlen, 16) bytes and
store the truncated length instead of failing with EINVAL when the
caller's buffer is smaller than 16 bytes. A NULL addrlen is still
EFAULT, and a NULL addr is EFAULT only when bytes must be copied.

CheckSocketPeerName now covers a capacity of 8 (first 8 bytes copied,
size 8, the rest of the buffer untouched) and a capacity of 0 (size
stays 0, buffer untouched) for both the POSIX and the Net export.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Carmen Sandiego (PPSA25256) and Hot Wheels Infinite Rush (PPSA22408) both
stop at the logo on "Unresolved import stub called:
IZ-qjhRqvjk[Http2_v1][Http2_v1.1][Func]", which shadPS4 maps to
sceHttp2AbortRequest.

Requests stop at the send step here, so there is nothing to cancel. The
handler reports what the library does: an unknown id is rejected and a
known one succeeds, leaving DeleteRequest to free it.

The file was reformatted by the repository's clang-format hook, which the
existing file did not satisfy on main.
sceHttp2AbortRequest marks an unsent request, but Http2SendRequest then
overwrote the result with HTTP2_ERROR_TIMEOUT, so a title that aborted and
resubmitted saw a timeout instead of the abort. Track the aborted state on
the request and return the existing result from both send paths. Requests
that already reached the send step keep theirs.

Follow-up to 4e97990a.
The async abort test only looked at the response length. Read first so the
request carries event type 1, then confirm the aborted send resets it to 0
with the pre-send result, and that the caller's user event still fires on a
registered queue.

Follow-up to 0fa74931.
Host file reads write guest memory from kernel mode, which cannot raise the
emulator's fault handler. A ReadFile into a page the GPU tracker keeps
write-protected fails with ERROR_NOACCESS or ERROR_INVALID_USER_BUFFER and
the guest gets a short read; on Linux fread stops with EFAULT. ASTRO BOT
then asserts on a lost .odxb read.

Retry the failed bytes through a bounce buffer whose user-mode copy faults
into the normal handler, chunk by chunk, for destinations the guest may
write, and only for bytes the file still holds. Other destinations keep the
short read.

The probe hook and the Linux recovery come from #1165, the Windows bounce
from #838.

Co-authored-by: NeySlim <[email protected]>
Co-authored-by: ew-sudo <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ReserveGuestRegions queries a free hole and then reserves it at a fixed
base. Threads started before Memory (Tracy, Network) can allocate inside
the hole between the two calls; the fixed reservation then fails and
the emulator exits with "failed to reserve guest address space". Query
the same address again and reserve around the new block, up to 16
times per address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The protected-read case now also reads the fixture through KernelPread,
once into a fully GPU-mapped range (the pre-read invalidation unprotects
it) and once into a range whose first page is not GPU-mapped (the
invalidation skips it and the recovery delivers the bytes), and checks
the guest bytes, the CPU ownership and the next buffer lookup. Each
read starts from a cleared destination. The final seek of the Linux
recovery is dropped: the stream is already at start + w there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict only in the memory.cpp test globals: upstream dropped the backing-store
unmap failure hook; keep upstream's block and add the guest-reserve hook.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve DownloadBufferMemory against 96b251749: take the ring or temporary
destination from MapDownload and keep recording the copies through
RecordDownloadCopies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	tests/ShaderRecompilerComputeTests.cpp
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Removed tests for fragmented backing unmap rollback, flexible replacement rollback, and main entry checks.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	tests/shaderCfgTests.cpp
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A 16 KiB formatted read at the base of a 32 KiB GPU-written image, and a
16 KiB CopyBuffer from such an image, must return the image texels, not the
stale guest backing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A formatted read that starts at a GPU-written image now gets a cache buffer
that spans the whole image, so SynchronizeBufferFromImage can download
every level. Before, the buffer only spanned the read, and a read smaller
than the image's first level kept the stale guest bytes.

ObtainBuffer looks the image up once and passes it to
SynchronizeBufferFromImage, which no longer repeats the lookup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An image GPU write over a read-hot page with a queued publish keeps the page
GPU-dirty after the publish completes, and SupersedeAllPublishes keeps every
queued publish of two batches from cleaning its range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The vertex entry gave the guest the number of running subgroup lanes as its
vertex count. The NGG prologue turns that count into a prefix mask for EXEC,
so every later vector write is selected by the own-lane bit of that mask.

The count is now one past the highest running lane, capped at the wave size.
It equals the old value whenever running lanes are a dense prefix, and no
running lane falls outside the prefix otherwise. Constant propagation
evaluates a mask that depends only on this bound for every possible bound
and folds the own-lane bit to true when all of them cover it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Captured prologues build a first mask from the count in s3[15:8], through a
32-bit shift or a bit-field extract. Its own-lane bit kept the lane id and
the subgroup ballot alive in every vertex shader of the Demon's Souls run.
The projection now evaluates both forms, in one switch that reads operands
on demand.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Conflicts in bufferCache.cpp and bufferCache.h: upstream's UploadCopies and
SynchronizeBda structure is kept; SynchronizeBuffer still takes the image to
sync from, and SynchronizeBufferFromImage takes the image id.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Resource tracking does not assign a buffer to planning-only memory, so its
`resource` keeps the descriptor's SGPR quad index from translation. The
scalar empty-table fold and the zero-stride fold in
ApplyResourceSpecialization indexed the buffer specialization with it: past
the end of the buffers when the index is larger (an out-of-bounds read on
every compile of such a program), and an unrelated buffer when it is
smaller, which folds the planning reads through that buffer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Astro Bot's PlayStation Studios intro is a 3840x2160 H.264 video at
59.94 Hz. One emulated core decodes it at about 40 frames per second,
so the game finds no new frame 1-14 times per second and the video
falls up to ~575 ms behind its audio: the intro stutters.

Let FFmpeg decode video streams with frame and slice threads, one per
CPU. Its decoded frames do not depend on the thread count: for this
video, 510 frame MD5s from one thread and from automatic frame+slice
threads are identical (native FFmpeg, -f framemd5). In game, every
pull now gets a frame (0 misses) and the video stays 30-66 ms behind
its clock. AvPlayerFileTests passes.

Audio streams keep their single decoder thread.

Signed-off-by: Jonathan Goyvaerts <[email protected]>
Assisted-by: LLM
sceAvPlayerGetVideoData gave a frame's buffer back to the decoder as soon as
the guest took the next frame. The guest's GPU work can still read it then:
Astro Bot copies each intro frame into its own texture with a DMA that the
command processor runs one or two guest frames after the guest took the
frame. Once the decoder had refilled the buffer, that copy read a later
frame. The game's two textures then held frames from different points of the
video, so the intro flickered back and forth.

GuestGpu now numbers its submissions and tracks the ones not yet completed.
The guest gives a buffer back stamped with the work submitted until then
(GuestGpu::SubmittedWork). The decoder writes the buffer again only once the
command processor has completed all of that work (GuestGpu::WaitForWork).
The waiter is woken only when its marker is reached, and stop and seek still
cancel the wait.

Check: AvPlayerFileTests gains a case with a fake guest GPU. A buffer
returned with pending work is neither handed out again nor written until the
work completes, and is reused after it. The case fails without the wait. The
same change in a Jetsku-based build fixed the Astro Bot intro: a content hash
of the copied textures now matches the frame the guest was handed.

Signed-off-by: Jonathan Goyvaerts <[email protected]>
Assisted-by: LLM
The AMD instruction patch decoded every function of a module to find the
few instructions it rewrites. Astro Bot's 252 MB eboot.bin (312697
functions) took ~7-9 s at boot on one core.

Without red-zone protection only VRSQRTPS xmm, xmm, EXTRQ/INSERTQ, RDPID,
CLWB and, with a guest TSC rate, RDTSC/RDTSCP are rewritten. Each lies inside
its function, because decoding stops at the function's end, and contains
fixed bytes (MayContainAmdInstruction, MayReadTimeStampCounter). Modules with
at least 1024 functions are now scanned on one thread per CPU through those
byte filters. The workers decode the candidates at most 64 functions ahead
of the loading thread, which patches them in address order as before.
Patching a function writes only inside it and into the module's
trampolines. A function whose jump table lies outside its own bytes, where
an earlier function's patch may write, is decoded again on the loading
thread at its turn, so every decode sees the bytes a single-threaded pass
sees. Function and instruction counters, which only the red-zone report
prints, no longer count the skipped functions' instructions. With red-zone
protection every function is still decoded, on the workers.

The same change in a Jetsku-based build patches the eboot by 1.9-2.0 s after
launch instead of ~10 s, with identical patched code and trampolines (hash)
and counts (VRSQRTPS: native=10935, trapped=43).
guest_instruction_patch_scan_tests checks the filters on the rewritten
encodings and on similar ones that are not rewritten. It compares code,
trampolines and counters with a single-threaded pass at 2, 5 and 16 threads.
The modes are AMD only, AMD with RDTSC, RDTSC only, and red-zone protection.
The fixture includes a switch whose jump table lies in the next function.

Signed-off-by: Jonathan Goyvaerts <[email protected]>
Assisted-by: LLM
Reserve only fixed system ranges during memory setup, then reserve remaining guest regions after Vulkan/NGX initialization. This avoids host address-space conflicts while ensuring guest mappings are ready before driver startup.
A ReadFirstLane key takes its domain from a finite literal set or from the
context-free bits of the local value. A key clamped by UMin32 behind a select
whose condition the lane mask implies, as in SelectU32(c, UMin32(0x3fff, x), x)
read under a mask that implies c, therefore had no bound, and an address table
read with it failed with "GetImageResource dword 0 is not a valid runtime value"
(Warhammer Age of Sigmar Realms of Ruin, #774, pixel shader 0x8b06bb2656189c82).
The selected lane satisfies the mask, so the local value's maximum under that
mask bounds the key, as the ReadLane case already does for its equal local key.

IMAGE_GET_RESINFO and IMAGE_GET_LOD now carry their EXEC predicate like every
other image access. The tracker reads the last operand of an image access as
its EXEC; for the queries that operand was the image address, so a query-only
waterfall loop had no predicate to bound its key.

Packed material keys whose selector proof fails now keep their clamped table
domain instead of failing tracking; they still get no selector.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Hades II (PPSA36082) crashes about 3.8 s after launch on Windows while it
loads Content/Packages/1080p/Fx.pkg: a libc memcpy in the LoadTaskScheduler
thread writes a 16 MiB texture upload to address 0.

The game's own allocator returns an empty allocation because its 512 MiB
upload pool is full. Upload buffers are freed only after the streamer has
tiled the texture into the 6 GiB direct-memory pool, and every write into
never-touched memory of that pool takes a host page fault: a direct mapping
is a view of the backing section, and Windows gives its 4 KiB pages only on
first access. The streamer falls behind, the 16 MiB buffers pile up, and
the pool runs out. This is the race analysed for Linux in #1104.

MapDirectMemory now reads one byte per host page of every writable direct
mapping of 64 MiB or more before it publishes the range to the GPU. A read
is enough to make section pages resident, and it cannot race with writes
made through other views of the same memory. The cost moves to map time:
Hades II prefaults its 7.6 GiB of direct memory in 2.6 to 2.9 s at boot.
KYTY_NO_PREFAULT disables it. Linux and macOS code paths do not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
eE5B9G9R9UfloatPack32 cannot be used as a color attachment on NVIDIA,
and UFC 6 (PPSA23566) clears RGB9E5 targets, which fails device
creation or the render pass. Map k9_9_9_5Float to the renderable
eB10G11R11UfloatPack32 as a stand-in; guest RGB9E5 texels decode
wrong until a shader-side pack exists.
Reject inconsistent shader metadata before reading vertex table pointers and add regression coverage.\n\nCo-authored-by: Copilot <[email protected]>
graphics: validate vertex table SGPR ranges
A Game About Digging A Hole (PPSA30552) fails with "GEngineLoop.PreInit
Failed!" when its folder is nested deeply enough that the pak files end
up 260 or more characters from the drive root; Demon's Souls (PPSA01341)
reports hundreds of unresolved asset files in the same situation (#2296).
Shallow files such as eboot.bin still load, so the game starts and then
fails on its own missing-file path.

The Win32 calls in the host file layer were given plain paths, which are
limited to MAX_PATH unless long paths are enabled both system-wide and
in the application manifest. Pass paths of 248 characters or more (the
lower limit that applies to directories) in extended-length form
instead. Such paths are not parsed by Win32, so make them absolute and
normalized with GetFullPathNameW first; guest paths are appended to the
game folder with mixed separators.

Shorter paths are passed through unchanged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
get_bda_pointer narrowed the 64-bit page number to 32 bits and indexed the
page table and the fault bitmap with it unchecked. A guest address past the
end of the table indexed both out of bounds, and from a packed address of
2^46 on the page wrapped onto a lower one and returned that page's device
address. Such a page now reads as zero, like an unbacked page, and records
no fault.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Kyty does not draw message dialogs, so a game's error message stayed
invisible. Ghost of Yotei opens one ("Unable to launch: missing base
entitlement") and then waits behind its loading spinner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A guest thread loops on sceKernelUsleep while the main thread raises
signal 30 on it with sceKernelRaiseException. The handler holds until the
test releases it; the target must be the thread that runs the handler and
must make no progress meanwhile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sceKernelRaiseException queues a special user APC. When the APC found the
thread outside guest code, it ran the guest handler on a detached helper
thread posing as the target, and the target kept running guest code. Unity
stops its threads this way while its liveness pass tags class pointers, so
a thread that was in an HLE call or a wait read tagged pointers (#2197).

The APC now runs the handler only when the thread is in guest code and
otherwise leaves the signal pending. The thread takes it at its next wait
poll, or a later APC does: a redelivery thread queues the APC again every
millisecond while the signal is pending, with at most one APC outstanding.
Guest code is now every mapped module, [0x900000000, end of the last
module); the fixed end at 0x980000000 missed later modules. A new thread
starts with no pending signal, and an exiting one drops its pending ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Deleting or cancelling an event flag, and deleting a semaphore, waits in a
short sleep loop until the waiters have left. A waiter can be inside a
raised signal's handler, entered from its own wait poll; the deleting
thread then has to take its own signal in that loop, or a garbage
collector that stops both waits for it forever.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A signal raised while the target thread runs its handler waited for
nothing: a second special APC, or the wait poll inside the handler's own
waits, entered the handler again on the same thread. Linux installs the
host handler without SA_NODEFER, so there it stays blocked. Every dispatch
now claims the thread's dispatch flag and delivers pending signals in a
loop, so a signal raised during the handler runs after it returns; no APC
is queued while the flag is held, and the redelivery list keeps one entry
per thread and signal.

The guest-code bound now follows the address a module was mapped at, not
the address that was asked for, since the allocator can place a module
further up.

Tests: the signal reaches a target spinning in mapped guest code through
the APC, a second signal raised during the handler runs after it and not
inside it, and code mapped past an occupied module address is guest code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A signal raised on Linux or macOS after the dispatcher's last scan reached its
thread while the claim was still held: the host signal handler could not claim
the dispatch and returned, and nothing raised the signal again. The dispatcher
now claims again while signals are pending after it released the claim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The redelivery thread dropped a target when queueing the APC failed, while
the signal stayed pending, so a target that never reached a wait poll never
got it although sceKernelRaiseException had returned OK. A target now stays
on the list until its signal is taken; a thread that exits drops its
pending signals and leaves the list that way.

The cancel test also checks that the canceller's signal ran on the
canceller, and the nesting test reads the deepest nesting after both
handlers have finished.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The report of an unhandled host exception moves into
Loader::ReportUnhandledHostException, unchanged, so a test can run it.
FaultReportReachesTheLogFile runs the report in a child process that
logs to a file and checks the file for the error and the guest fault
context.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The context of an unhandled host exception (thread, registers, code
bytes and stack) was printed with std::printf. With file logging
std::printf reaches only the console, so _kyty.txt, the log attached to
reports, held the error line without the context. The report is now
built with the same formats and written with Log::WriteToConsoleAndLog,
as EXIT writes the error line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Windows CI runner cannot reserve the guest direct memory, so the
child's full subsystem start exited with 321 before file logging was
set up, and the test found an empty log file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A raise to a thread past CleanupThread set its pending bit after the
mask was cleared. PthreadTakePendingSignal refuses such a thread, so
the bit stayed: the dispatch loop could not end, and SignalRedelivery
requeued the target every millisecond until the join.

PthreadQueuePendingSignal now takes the bit back and fails when the
target is exiting or freed, and the raise returns ESRCH, as FreeBSD's
pthread_kill does for a dead thread, also when the dead target's host
thread id now belongs to the caller. CleanupThread marks the thread
before it clears the mask, so a raise racing it leaves no bit behind,
and PthreadJoin leaves the thread marked until PthreadCreate reuses it.
A signal APC that reaches another thread than its target, through a
reused host thread id, returns without running the handler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A depth target whose Z format is invalid has no Z surface: depth tests, depth
writes, depth bounds and depth clears cannot act on it, and its stencil plane is
the target's only memory. Bind such a target as a native S8 attachment over the
stencil range, keep its HTile metadata and compressed-stencil clears, and size it
with TileGetDepthSize, which now accepts a stencil-only surface.

Baldur's Gate 3 (#2334) binds a stencil-only target with HTile, an enabled depth
test with ZFUNC ALWAYS and a stencil clear; it stopped with
'Depth target fatal: unsupported depth register state'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stencil-only target consumed the whole HTile clear state of its
slice, so a later depth target over the same HTile lost its pending
depth clear. The clear state is now kept per aspect: a stencil-only
bind takes only the stencil clear, every other bind takes both as
before.

A stencil-only draw also stopped on distinct Z read and write
addresses that it does not use; that check now needs a Z surface. A
multisampled stencil-only target passed format selection but failed
cache validation; it now stops with its own message. The stencil-only
test cases run only where the host has an S8 depth/stencil attachment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A depth attachment takes the pending HTile clear aspects of the planes
it has: a depth-only bind leaves a pending stencil clear for a later
stencil bind over the same HTile, as a stencil-only bind leaves the
depth clear. A stencil plane without HTile stencil compression still
drops the stencil clear without applying it. IsMetaCleared keeps
main's meaning (pending depth clear).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Deleting the last image to bind an HTile range erased the range's clear
state while another image over the same HTile (a stencil-only image and
the depth image beside it) still used it: a pending depth clear was
lost, and the survivor's next bind re-created the state with both
clears set. An image that moved to another HTile, or a stencil-only
image adopted as a depth target's stencil plane, kept owning the old
range, so a new image over it skipped its initial clear. All three
paths now release the range through ReleaseHtileOwner, which passes it
to a live image with the same HTile range and erases it only when none
is left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Grand Theft Auto V (PPSA04263/PPSA04264) clears its R16_FLOAT particle
depth MRT to 65504 (CB_COLOR_CLEAR_WORD0 = 0x7bff7bff) with a DCC fast
clear whose metadata keys are 0x10. Only the GFX10 0x20 key was treated
as a clear-to-register, so the clear was dropped, the target kept zeros,
MIN blending kept 0, and depth of field drew cigar smoke and sky
particles as opaque black blobs (#979).

Treat 0x10 as a register clear in DecodeColorClear, and fold it into
0x20's slot in the native metadata check (gpu_tiler_color_clear.comp),
which required keys to be multiples of 0x20 and so never matched it.

Ported from TheCruZ's closed #1234, which only covered the CPU decode;
main has since gained the native GPU check, which needed the same key.

Co-authored-by: TheCruZ <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Grand Theft Auto V (PPSA04263) crashes about once every 100 sessions:
its "[RAGE] HDD Streamer" thread faults inside zlib inflate on a 64 KiB
direct-memory page that is mapped again a moment later. Two game
threads MAP_FIXED the same physical page at the same address; on the
console that is an atomic no-op, but the emulator replaces a mapping by
unmapping it and mapping it again (ReplaceFixedRangeWithReserved), so
the streamer's access lands in the gap. Windows has the same gap when
a partial unmap splits a file view: UnmapOne unmaps the whole view and
maps the survivors again.

Publish both gaps in a small lock-free table of transient-unmap
windows. The runtime linker's fault handler waits until the range is
mapped again and retries the access (after the GPU tracking had its
chance). A page that keeps faulting once its range is back is still
reported, so real access violations are not hidden. Only the survivors
of a view split are published, not the unmapped part.

Ported from TheCruZ's closed #1229 onto current main: main already
restores the survivors' protections in UnmapOne and keeps Linux
direct-over-direct replacements atomic, so only the retry windows are
taken over.

Co-authored-by: TheCruZ <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Grand Theft Auto V (PPSA04263) exits when SDL reports that a connected
gamepad was remapped: SDL_EVENT_GAMEPAD_REMAPPED reaches
GameEventController with `remapped` set, and the handler began with
EXIT_NOT_IMPLEMENTED(f.remapped).

A new mapping only changes how SDL translates the device's raw inputs;
the buttons and axes the emulator reads stay logical. SDL sends no
release or neutral-axis events for the old mapping, so reset the input
state of every player and keep running.

Based on TheCruZ's closed #1227, which reset only player 1's active
controller; main now supports up to four players.

Co-authored-by: TheCruZ <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2395:
- Open() picked s_windows[n % 16] without checking whether a Scope still
  held that entry, so enough concurrent replacements could overwrite an
  open range (and its Scope then closed the reused entry). Entries are
  now claimed atomically and only released by their Scope; when all 64
  are open, Open yields until one frees (scopes span a single remap).
- Run GPU fault tracking before waiting for a transient unmap, so a
  fault tracking can resolve does not wait for an unrelated remap.
- AccessDuringMappingReplacement starts replacing only once the worker
  has accessed both mappings, and checks that it made accesses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2396: Controller::ResetInputState() cannot reach the
gamepad touchpad state in hostInput.cpp. If Cross was held for drawing
when the remap arrived, `drawing` stayed true and PollGamepadTouchPad
kept sending a touch-down every poll; cached stick values could also
keep the cursor drifting.

HostInputResetGamepadTouchPad releases the contact at its position and
re-centres the cached stick values, keeping the touchpad mode and its
controller selected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2395: Wait read closed_ns a second time after the
spin loop. If the entry was reused for another range in between, that
read could return 0, the age check failed, and a fault on a mapping
that was already back was reported as fatal.

Wait now snapshots the entry's id with its range (rejecting a torn
read), keeps the closure time it observed, and treats a reused entry as
just closed, since reuse requires the original Scope to have closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on #2395: Wait skipped an entry whose id changed while
it read the range, so a window that reopened for a range holding the
fault address could be missed and the fault reported as fatal.

Open now publishes an entry as a seqlock: id 0 while the range is
written, then the new id. Wait re-reads the entry until its id and
range belong to one opening (spinning briefly while an owned entry is
being opened), so it never skips a reopened window and never pairs one
opening's id with another's range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AMD's Windows driver rejects any ray-query pipeline whose layout has
descriptor sets but no acceleration-structure binding, including empty
sets, sets of other descriptor types, and push-descriptor sets
(VK_ERROR_UNKNOWN from vkCreateComputePipelines). The TLAS is reached by
device address, so the layout never had one. Append one unused
acceleration-structure binding to layouts of shaders with ray_query and
give the descriptor pool matching capacity for layouts that do not use
push descriptors.
Uncharted: Legacy of Thieves Collection (#2385) binds a T# at 0x600, which is never mapped, and stopped at the texture alignment check. PS5 cannot read such a texture, and an unmapped image heap texture is already bound as null. The compute image fill, PSSR and the rebind of a released image now handle a binding without an image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ImageSubresources ordered {levels, layers} lexicographically, so the
texture cache treated 11 levels x 1 layer as covering 9 levels x 2 layers.
ResolveOverlap then skipped the growth branch and exited with
"unresolvable equal-address image overlap" (#774), and the depth overlap
and FindImage checks kept a backing that lacked a requested layer.
Replace the order with Contains, true only when both the level and the
layer counts cover the request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit f255e675bc2ed3372fdf4e943781dd1faab581ce)
(cherry picked from commit 4297034a5f4193d7305dd25568abb0db8f283d57)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
AssociateStencil can reuse any registered image whose range and extent
match the stencil memory, for example an R8 texture that a resident
image heap sampled before the depth image was associated. It rewrote
the record's info and depth_id without queuing a heap change, so the
heap kept sampling the old R8 backing while stencil writes went to the
depth image. The record's heap_refs still belong to the pinned image,
so calling HeapChanged() before the rewrite queues the change.

Fixes #2297.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
My First Gran Turismo (PPSA24156) crashes in-race on NVIDIA GPUs: the
driver's shader compiler (nvgpucomp64.dll, driver 621.24, RTX 5090) hits
an internal breakpoint in vkCreateGraphicsPipelines for a depth-only,
2x MSAA, sample-shaded pipeline. The fragment shader interpolates a
PerVertexKHR input by hand and reads BaryCoordKHR.x. The SPIR-V passes
spirv-val.

Replaying the captured pipeline showed it builds with 1 sample, without
sample shading, or with only the BaryCoordKHR.x read replaced. Add a
Spirv::Profile flag, set for NVIDIA (vendor 0x10DE), that makes
EmitPixelAttribute compute x as 1 - y - z.

Tested: the game builds the pipeline and continues; 32 CI regression
tests and shader_recompiler_compute_tests pass on the RTX 5090.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
My First Gran Turismo (PPSA24156) renders 4-, 13- and 26-wide (x512)
depth targets at one address. Their tiled pitch and footprint match, so
ResolveDepthOverlap returned the cached 4-wide image for the wider
targets while the render area used the requested width. NVIDIA reports
"3D WIDTH ZT Violation", resets the GPU, and the emulator stops on
device loss (masterSemaphore.cpp:54).

For depth targets, recreate the image when the request is wider or
taller than the cached one; the existing path copies the old contents.

Tested: no render area exceeds an attachment and no GPU fault in a
15-minute session through the tutorial; 32 CI regression tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a draw's attachments mix sample counts, PrepareDrawRenderState
drops the ones that differ from the raster count. Resolving had already
marked them with BindRenderTarget, so a stage sampling one of them later
expected an attachment layout that AcquireRenderTargets never set and
stopped at descriptors.cpp:978 (layout == eUndefined).

Clear is_target on dropped targets that no kept attachment uses.

Tested: My First Gran Turismo (PPSA24156) runs past the point where it
stopped (~162 s into the first race); 32 CI regression tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two gaps in the ResolveDepthOverlap replacement path, raised in review:

- CopyImage copies only the overlap with the cached extent and marks the
  replacement refreshed, so a wider or taller replacement exposed
  undefined texels. A larger replacement now loads the guest bytes first;
  the copy then fills the overlap.
- Freeing the cached image erased the HTile clear state it owned, so a
  pending fast clear never reached the next pass. When the replacement
  uses the same HTile range, it now takes ownership before the cached
  image is freed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
BO2 (PPSA34502) skins characters on the CPU. The 2-, 3- and 4-weight
blend functions keep a 1.0f vector and a mask below rsp, and their
output stores land on GPU-tracked pages. Windows builds the exception
frame for each tracking fault on the guest stack and overwrites those
slots, so blended vertices get garbage weights and characters explode
into spikes (#1752). --redzone fixes it, but nothing points users to it.

Turn red zone protection on for titles known to need it, starting with
PPSA34502, and log when it happens. The default for other titles is
unchanged.
Black Ops II (PPSA34502) on Monsoon issues a copy_depth_to_color draw
whose R32_FLOAT color target and D32_FLOAT depth target are the same
memory (both 0xc062200000, 0x280000 bytes). Finding the color target
replaces the depth image and finding the depth target replaces the
color image, so acquisition always found one of them stale and hit
"TextureCache: color target requires rediscovery before final
acquisition" on mission load.

When the two share an address, the guest is converting its depth
buffer into a color view in place. Finding the color image already
replaces the depth image with a copy of its data, so do that and skip
the copy.
init_env now seeds a guest-only environment from the entry envp.
getenv (smbQukfxYJM) reads it and setenv writes it, honouring
overwrite, instead of returning 0 without storing anything. The host
environment of the emulator is not touched.

Adds libc_environment_tests, which resolves the three exports by NID
and covers the entry environment, invalid names, overwrite and a null
entry. It fails on main (getenv is not registered) and passes with
this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Gears of War Reloaded calls two Ces imports that were unresolved:
NLW0QcvJY-E (sceCesRefersUcsProfileIso8859_15) and RO-MRURI76g
(sceCesMbcsStrToUtf16Str).

- Add the ISO-8859-15 single-byte profile. sceCesUtf8ToSbc and
  sceCesSbcToUtf8 now pick the code page from the profile they are given
  instead of always using CP1252. Unknown profiles keep the CP1252
  behaviour.
- Make the CP932 converter work for both UTF-8 and UTF-16LE output, and
  add sceCesMbcsStrToUtf16Str plus its measuring counterpart
  sceCesMbcsStrGetUtf16Len (KkcyBpHeV6Q). Lengths and buffer sizes are
  counted in 16-bit units, with the same partial-output and error rules
  as the UTF-8 variant.
- Extend ces_tests to cover UTF-16 mapping, measuring, partial output and
  errors, and both single-byte profiles.
Register zero-argument sceAgc*GetSize functions for packets whose
builders already exist: Acb EventWrite/DmaData/Rewind/DispatchIndirect,
Dcb SetShRegisterDirect/SetUcRegisterDirect/SetIndexSize/SetIndexBuffer/
SetIndexCount/DrawIndexIndirect/DrawIndirectMulti/DrawIndexIndirectMulti/
GetLodStats/StallCommandBufferParser. Sizes are derived from each
builder's AllocateDW count (dwords * 4 bytes). Without these, the
runtime linker patches unresolved imports to a stub returning 0, so a
game reserving command-buffer space gets a zero-sized reservation while
the builder writes a full packet.
Add Acb workload builders (SetWorkloadsActive/SetWorkloadComplete,
delegating to the existing Dcb builders, which emit the same 18/12-word
packets) and DcbMemSemaphore (delegating to AcbMemSemaphore). Register
zero-argument GetSize entry points sourced from AnyPS5's hardware-verified
implementations: AtomicMem 36, AtomicGds 44, PrimeUtcl2 20 bytes.
NID hash verification (AnyPS5 NidCompute scheme) showed jt3pl7EN17o is
sceAgcDcbPrimeUtcl2, not sceAgcDcbMemSemaphore (which hashes to
G0jrLdvEqDw). Register sceAgcAcbPrimeUtcl2 (szG7hz2yEhA) and
sceAgcDcbPrimeUtcl2 (jt3pl7EN17o) as 5-word NOP-payload packets matching
AnyPS5's layout and the 20-byte GetSize, and keep sceAgcDcbMemSemaphore
registered under its correct NID G0jrLdvEqDw.
Replace the compare-and-select chain over every candidate register with a
binary multiplexer on M0's bits: one test per bit and one select per
candidate, with O(log n) depth instead of O(n). M0 past the last register
still reads the base register.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pixel parameters read only flat or per-vertex often carry packed integer
words, some of which are NaN patterns as floats. Declare those locations as
uvec4 in both stages and bitcast at each end, so the words cross the stage
interface unchanged instead of relying on float varyings keeping NaN
payloads, which Metal does not guarantee.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Draws bind the same ranges again and again, unchanged. In a 60-frame
capture of the memory tracker calls in Demon's Souls' heaviest outdoor
area, the GPU thread made about 33,000 ForEachUploadRange calls a frame.
Most of them repeated an identical call with no state change in the
range's 4 MiB regions in between. One 112 MiB buffer that dispatches
bind as writable was marked GPU-dirty again about 1,700 times a frame,
each time walking 28 regions under their locks.

Each tracker region now counts the changes of its dirty bits (a
generation, bumped under its lock). ForEachUploadRange remembers per
thread the sum of its range's region generations as it leaves them. An
identical later call with the same sum would find nothing to upload and
change nothing, so it only runs the upload callback. Generations only
grow, so an equal sum means no region changed.

Replaying the capture against the tracker with real page protection and
upload copies (a replay tool kept out of this change), three runs of
each build on an i7-14700KF:

                              before          after
  GPU thread's tracker calls  2.83-2.87 ms    1.53-1.56 ms a frame
  whole replay                4.32-4.38 ms    2.97-3.05 ms a frame

Both builds upload the same 22.8 MiB a frame and make the same 2,769
protection calls a frame, with equal checksums over every upload range
and protection change. TestRepeatedUploadSkip covers CPU writes, GPU
unmarks, downloads and a new tracker over the same range; removing the
bump in ChangeState fails it.
# Conflicts:
#	CMakeLists.txt
#	src/common/emulatorConfig.cpp
#	src/common/emulatorConfig.h
#	src/graphics/host_gpu/pageManager.cpp
#	src/graphics/host_gpu/renderer/renderContext.cpp
#	src/graphics/host_gpu/renderer/renderContext.h
#	src/graphics/presentation/window/vulkanWindow.cpp
#	src/kernel/memory.cpp
#	src/kernel/memory.h
#	src/main.cpp
#	tests/ShaderRecompilerComputeTests.cpp
#	tests/VirtualMemoryAllocationTests.cpp
RelocateRecord wrote 8 bytes at r_offset + base without checking the
result against the module's mapped range, so a malformed ELF could
patch arbitrary guest memory. Exit with an error instead.

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

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original · edited 2026-11-21 00:01 UTC

Explain Change →

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
Walkthrough

The pull request updates build workflows and adds configuration options. It changes GPU submission, cache synchronization, image handling, shader compilation, memory mapping, and guest-library behavior. It also adds host file and font support, loader and pthread changes, and new tests across these areas.

Suggested reviewers: nmzik, mrbigbritches

Change: Bug fix

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title, "Consolidated Stability, Graphics, Audio and Memory Fixes (71 PRs)", is partially related to the changeset. It names real areas the changes touch: graphics, audio, memory, and stability fix…
Description check Passed The description lists the bundled improvements by subsystem, including HTile and depth handling, texture cache, shader recompiler, kernel and memory, AvPlayer video decode, AudioOut2 and NGS2, Windows…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title, "Consolidated Stability, Graphics, Audio and Memory Fixes (71 PRs)", is partially related to the changeset. It names real areas the changes touch: graphics, audio, memory, and stability fixes. It is overly broad, though. It does not name the main changes, and the changeset also covers filesystem, libc, network, shader recompiler, and kernel work. It does not describe a single primary change.

Full details: Description check

Explanation

The description lists the bundled improvements by subsystem, including HTile and depth handling, texture cache, shader recompiler, kernel and memory, AvPlayer video decode, AudioOut2 and NGS2, Windows filename encoding, CJK fonts, libc, network, and Agc entrypoints. These match the file changes in the raw summary. It also gives verification notes. The description is related to the changeset.

Warning

Review coverage is incomplete: 1 file could not be fully reviewed. Findings from completed review steps are included; see review info for details.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#issuecomment-7046808067) · edited 2026-11-21 00:01 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/2465?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-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" 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: 2577e26e25f245640d57e5fc3d5bdabef99b7f20 > - Latest commit, not reviewed: 52f20e9eaf27a8a3380e1b6e42e28164960199f0 > > 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 --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The pull request updates build workflows and adds configuration options. It changes GPU submission, cache synchronization, image handling, shader compilation, memory mapping, and guest-library behavior. It also adds host file and font support, loader and pthread changes, and new tests across these areas. **Suggested reviewers:** `nmzik`, `mrbigbritches` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"2577e26e25f245640d57e5fc3d5bdabef99b7f20" --> <!-- change_assessment_priority:{"version":1,"urgency":"p3","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title, "Consolidated Stability, Graphics, Audio and Memory Fixes (71 PRs)", is partially related to the changeset. It names real areas the changes touch: graphics, audio, memory, and stability fix… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description lists the bundled improvements by subsystem, including HTile and depth handling, texture cache, shader recompiler, kernel and memory, AvPlayer video decode, AudioOut2 and NGS2, Windows… | | 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. | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **Explanation** The title, "Consolidated Stability, Graphics, Audio and Memory Fixes (71 PRs)", is partially related to the changeset. It names real areas the changes touch: graphics, audio, memory, and stability fixes. It is overly broad, though. It does not name the main changes, and the changeset also covers filesystem, libc, network, shader recompiler, and kernel work. It does not describe a single primary change. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **Explanation** The description lists the bundled improvements by subsystem, including HTile and depth handling, texture cache, shader recompiler, kernel and memory, AvPlayer video decode, AudioOut2 and NGS2, Windows filename encoding, CJK fonts, libc, network, and Agc entrypoints. These match the file changes in the raw summary. It also gives verification notes. The description is related to the changeset. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- operational_warnings_start --> <!-- This is an auto-generated comment: resource warnings by coderabbit.ai --> > [!WARNING] > Review coverage is incomplete: 1 file could not be fully reviewed. Findings from completed review steps are included; see review info for details. <!-- end of auto-generated comment: resource warnings by coderabbit.ai --> <!-- operational_warnings_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2465)! 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> <br> - [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> <!-- tips_end -->
@ -357,2 +370,3 @@
const auto source_aspect =
FullAspectMask(source.backing.format) & ~vk::ImageAspectFlagBits::eStencil;
stencil ? vk::ImageAspectFlags {vk::ImageAspectFlagBits::eStencil}
: FullAspectMask(source.backing.format) & ~vk::ImageAspectFlagBits::eStencil;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Functional Correctness · Quick win

Preserve stencil in default copies of S8 images.

When both images use eS8Uint, TextureCache::CopyImage selects the direct path and calls this function with stencil=false. Lines 372 and 375 then remove the only available aspect. The copy regions select no stencil data, so the copy cannot preserve the image contents. Vulkan requires the regions to specify image aspects. (docs.vulkan.org)

Use PrimaryAspect for both default selectors. This preserves stencil-only copies and keeps the existing color and depth behavior.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899653) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Preserve stencil in default copies of S8 images.** When both images use `eS8Uint`, `TextureCache::CopyImage` selects the direct path and calls this function with `stencil=false`. Lines 372 and 375 then remove the only available aspect. The copy regions select no stencil data, so the copy cannot preserve the image contents. Vulkan requires the regions to specify image aspects. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/vkCmdCopyImage.html)) Use `PrimaryAspect` for both default selectors. This preserves stencil-only copies and keeps the existing color and depth behavior. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0225303ba35dc3fb5b915bff --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -76,0 +124,4 @@
::fflush(stdout);
if (window != nullptr) {
SDL_SetWindowTitle(window, ("Kyty - " + text).c_str());
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Quick win

Keep window-title updates on the main thread.

Both warm-up passes call ReportShaderProgress from helper threads. ParallelFor joins those helpers before returning. (raw.githubusercontent.com)

SDL requires SDL_SetWindowTitle to run on the main thread. (raw.githubusercontent.com) On Windows, the backend calls SetWindowText, which sends a synchronous window message. A helper can wait for the window thread while holding progress_mutex. If the main thread waits for that mutex or joins the helper, warm-up cannot finish. (raw.githubusercontent.com)

Keep helper progress updates console-only. Set the window title before and after the parallel passes, or update it through a main-thread progress loop.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899675) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Keep window-title updates on the main thread.** Both warm-up passes call `ReportShaderProgress` from helper threads. `ParallelFor` joins those helpers before returning. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/src/common/parallelFor.h)) SDL requires `SDL_SetWindowTitle` to run on the main thread. ([raw.githubusercontent.com](https://raw.githubusercontent.com/libsdl-org/SDL/release-3.4.x/include/SDL3/SDL_video.h)) On Windows, the backend calls `SetWindowText`, which sends a synchronous window message. A helper can wait for the window thread while holding `progress_mutex`. If the main thread waits for that mutex or joins the helper, warm-up cannot finish. ([raw.githubusercontent.com](https://raw.githubusercontent.com/libsdl-org/SDL/release-3.4.x/src/video/windows/SDL_windowswindow.c)) Keep helper progress updates console-only. Set the window title before and after the parallel passes, or update it through a main-thread progress loop. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0dc3a650a0a4c300c8319c40 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1005,1 +1088,4 @@
state.ps_input_info.ps_sample_mask_export_enable);
// In place: the guest converts its depth buffer into a color view of the same memory. Finding
// the color image replaces the depth image with a copy of its data, which is the whole copy.
if (color.desc.info.data.address == depth.desc.info.data.address) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Functional Correctness · Heavy lift

Check subresource identity before skipping the copy.

The same base address can contain different selected array layers. With depth layer 1 selected and color layer 0 selected, both one-layer views pass the guards above. FindImage preserves corresponding layers during replacement; it does not copy depth layer 1 into color layer 0. This branch then returns without that transfer. (raw.githubusercontent.com)

Limit this shortcut to the same physical subresource. For different layers, preserve the source and perform the selected-layer copy.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899681) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Check subresource identity before skipping the copy.** The same base address can contain different selected array layers. With depth layer 1 selected and color layer 0 selected, both one-layer views pass the guards above. `FindImage` preserves corresponding layers during replacement; it does not copy depth layer 1 into color layer 0. This branch then returns without that transfer. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/src/graphics/host_gpu/renderer/cache/textureCache.cpp)) Limit this shortcut to the same physical subresource. For different layers, preserve the source and perform the selected-layer copy. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a890b486c2106d31eb39ff21 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -79,1 +79,3 @@
{Prospero::BufferFormat::k9_9_9_5Float, vk::Format::eE5B9G9R9UfloatPack32},
// RGB9E5 is not renderable on NVIDIA; B10G11R11 is a renderable 32-bit HDR stand-in.
// Guest-uploaded RGB9E5 texel data will decode wrong; add a shader-side pack if colors break.
{Prospero::BufferFormat::k9_9_9_5Float, vk::Format::eB10G11R11UfloatPack32},
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Functional Correctness · Heavy lift

Guest RGB9E5 textures will sample with wrong colors.

The lookup maps k9_9_9_5Float to eB10G11R11UfloatPack32 for every caller. Guest RGB9E5 texel data is not converted, so it can be interpreted as B10G11R11 during sampling. This affects sampled-only textures, not only render targets. The code comment already states this decode mismatch.

Preserve the guest RGB9E5 meaning for uploads. Either convert the texel data to the host format before upload, or keep the native eE5B9G9R9UfloatPack32 format for guest uploads and use the B10G11R11 substitute only for render targets. The inspected source does not establish which option fits the renderer, so no code change is proposed here.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899689) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Guest RGB9E5 textures will sample with wrong colors.** The lookup maps `k9_9_9_5Float` to `eB10G11R11UfloatPack32` for every caller. Guest RGB9E5 texel data is not converted, so it can be interpreted as B10G11R11 during sampling. This affects sampled-only textures, not only render targets. The code comment already states this decode mismatch. Preserve the guest RGB9E5 meaning for uploads. Either convert the texel data to the host format before upload, or keep the native `eE5B9G9R9UfloatPack32` format for guest uploads and use the B10G11R11 substitute only for render targets. The inspected source does not establish which option fits the renderer, so no code change is proposed here. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d1cde9d3a8da3befeaa55d99 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -349,1 +347,3 @@
inline constexpr uint32_t ImageHeapKindShift = 20u;
inline constexpr uint32_t ImageHeapSet = 1u;
inline constexpr uint32_t ImageHeapKindShift = 20u;
inline constexpr uint32_t ImageHeapCapacity = 1u << ImageHeapKindShift;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Heavy lift

Keep heap descriptor capacity within device limits.

This changes the allocated heap from 65,536 to 1,048,576 descriptors. On a device with a 500,000-descriptor limit, ImageHeap now exits during unconditional RenderContext construction, before any guest image is allocated. The former capacity passed this check. Vulkan permits that device limit. (raw.githubusercontent.com)

Separate the resident descriptor capacity from the 20-bit encoding capacity. Use a device-supported capacity consistently for host allocation and emitted image arrays.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899699) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Keep heap descriptor capacity within device limits.** This changes the allocated heap from 65,536 to 1,048,576 descriptors. On a device with a 500,000-descriptor limit, `ImageHeap` now exits during unconditional `RenderContext` construction, before any guest image is allocated. The former capacity passed this check. Vulkan permits that device limit. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp)) Separate the resident descriptor capacity from the 20-bit encoding capacity. Use a device-supported capacity consistently for host allocation and emitted image arrays. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f55ded1c62957e30156b66f6 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -229,6 +294,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) {
while (m_waiting_threads > 0) {
m_mutex.Unlock();
Common::Thread::SleepMicro(10);
LibKernel::KernelDispatchPendingSignalForCurrentThread();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Heavy lift

Nested Set or Clear from a signal handler can deadlock Cancel.

Cancel sets the flag to Canceled and then dispatches pending signals on its own thread (line 297). A guest handler that calls Set or Clear on the same flag waits at line 246 until the status returns to Set. Cancel restores that status only after the handler returns (line 301). Releasing m_mutex does not break this cycle, and the cycle does not depend on the waiter count. The waiting thread can exit, and Cancel still never returns.

The fix must preserve one of these behaviors: Cancel must not run guest handlers while the flag is Canceled, or a reentrant Set or Clear from the canceling thread must not block on the Canceled state. The choice between these options is left to the author.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899705) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Nested `Set` or `Clear` from a signal handler can deadlock `Cancel`.** `Cancel` sets the flag to `Canceled` and then dispatches pending signals on its own thread (line 297). A guest handler that calls `Set` or `Clear` on the same flag waits at line 246 until the status returns to `Set`. `Cancel` restores that status only after the handler returns (line 301). Releasing `m_mutex` does not break this cycle, and the cycle does not depend on the waiter count. The waiting thread can exit, and `Cancel` still never returns. The fix must preserve one of these behaviors: `Cancel` must not run guest handlers while the flag is `Canceled`, or a reentrant `Set` or `Clear` from the canceling thread must not block on the `Canceled` state. The choice between these options is left to the author. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:62fa275da2c87fc4382858e5 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -405,3 +497,1 @@
static_cast<int>(mounted_name.size()), mounted_name.data());
}
return p.dir / native_rel_path;
return p.dir / Common::PathFromUtf8(EncodeHostFilename(rel_path));
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Data Integrity & Integration · Heavy lift

Preserve existing Windows files with literal percent escapes.

Before this change, a guest could open an existing save%3A.dat by that name. The new resolver looks for save%253A.dat and returns ENOENT if it is absent. The directory listing also reports the original file as save:.dat.

Add a migration or a per-directory mapping that preserves the identity of existing files. Test a directory containing both spellings. An encoded-first lookup with a literal fallback cannot disambiguate both files on its own.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899719) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** **Preserve existing Windows files with literal percent escapes.** Before this change, a guest could open an existing `save%3A.dat` by that name. The new resolver looks for `save%253A.dat` and returns `ENOENT` if it is absent. The directory listing also reports the original file as `save:.dat`. Add a migration or a per-directory mapping that preserves the identity of existing files. Test a directory containing both spellings. An encoded-first lookup with a literal fallback cannot disambiguate both files on its own. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:446557bc15ae3bb902e411fb --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -861,0 +1162,4 @@
const auto end = addr + size;
while (addr < end) {
VirtualRanges::Range range {};
if (!g_virtual_ranges->Query(addr, 0, &range)) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Quick win

Take the state lock shared inside the recoverable-destination probe.

The probe walks g_virtual_ranges through Query without holding g_memory_state_mutex. Mapping writers modify that tree under the exclusive state lock, for example in the Add, Remove, and ReplaceSpan paths. The probe runs on the file-read path after a partial read fault. Such a fault can occur during a mapping replacement, so the traversal can race with node insertion, erase, or rebalancing. Rebalancing can affect nodes outside the read destination, so a non-overlapping edit does not prevent the race.

The lock policy at src/kernel/memory.cpp:196-198 requires readers outside a memory operation to take the state lock shared. ClampRangeSize already follows this pattern. Take the same lock in the probe for the duration of its traversal:

Suggested fix

 		probe = [](const void* data, uint64_t size) {
+			std::shared_lock state(g_memory_state_mutex);
 			if (g_virtual_ranges == nullptr) {
 				return false;
 			}
**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899728) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Take the state lock shared inside the recoverable-destination probe.** The probe walks `g_virtual_ranges` through `Query` without holding `g_memory_state_mutex`. Mapping writers modify that tree under the exclusive state lock, for example in the `Add`, `Remove`, and `ReplaceSpan` paths. The probe runs on the file-read path after a partial read fault. Such a fault can occur during a mapping replacement, so the traversal can race with node insertion, erase, or rebalancing. Rebalancing can affect nodes outside the read destination, so a non-overlapping edit does not prevent the race. The lock policy at `src/kernel/memory.cpp:196-198` requires readers outside a memory operation to take the state lock shared. `ClampRangeSize` already follows this pattern. Take the same lock in the probe for the duration of its traversal: <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff probe = [](const void* data, uint64_t size) { + std::shared_lock state(g_memory_state_mutex); if (g_virtual_ranges == nullptr) { return false; } ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c67755cc983a111c457b4245 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -902,10 +1250,20 @@ private:
if (info.State == MEM_FREE && reserve_end > reserve_start &&
reserve_end - reserve_start > MinimumRegionSize) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Quick win

Reject an empty required region on Windows.

If Region 2 contains only free gaps of 16 MiB or less, the loop reserves nothing and still completes. ReserveRemainingGuestRegions marks phase two complete. The self-tests can pass using Regions 0 and 1, but extended-memory mappings later fail the ownership check.

Track successful reservations per region and fail phase two if a required region has none. The POSIX paths already reject this condition. Preserve the existing success path when every region has usable reserved space.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899741) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Reject an empty required region on Windows.** If Region 2 contains only free gaps of 16 MiB or less, the loop reserves nothing and still completes. `ReserveRemainingGuestRegions` marks phase two complete. The self-tests can pass using Regions 0 and 1, but extended-memory mappings later fail the ownership check. Track successful reservations per region and fail phase two if a required region has none. The POSIX paths already reject this condition. Preserve the existing success path when every region has usable reserved space. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:35baaae6d5912ddf652b16df --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -3108,0 +3336,4 @@
const auto mask = 1ull << static_cast<uint32_t>(signum);
thread->pending_signal_mask.fetch_or(mask);
if (thread->almost_done || thread->free) {
thread->pending_signal_mask.fetch_and(~mask);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Heavy lift

Prevent a rejected signal from clearing a new thread's pending signal.

A sender can set signal 30 for thread A, see almost_done, and pause before clearing the bit. If A joins and its record is reused for B, a second sender can successfully queue signal 30 for B. The first sender then clears B's signal before B takes it.

Make the lifecycle check and pending-mask update atomic with respect to record recycling. A rejected send must leave the new worker's mask unchanged. A send to a live worker must still set its pending bit.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899752) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Prevent a rejected signal from clearing a new thread's pending signal.** A sender can set signal 30 for thread A, see `almost_done`, and pause before clearing the bit. If A joins and its record is reused for B, a second sender can successfully queue signal 30 for B. The first sender then clears B's signal before B takes it. Make the lifecycle check and pending-mask update atomic with respect to record recycling. A rejected send must leave the new worker's mask unchanged. A send to a live worker must still set its pending bit. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1150287696aeff42f6da9e1a --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -766,0 +776,4 @@
}
// TrueType collections (.ttc) store a table of faces; use the first one.
const int offset = stbtt_GetFontOffsetForIndex(data, 0);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Quick win

Require the full collection header before reading the first face offset.

init_stb_info accepts a 12-byte ttcf buffer. stbtt_GetFontOffsetForIndex then reads the face-0 offset at bytes 12 to 15 without a length check. For a collection with at least one face, that read exceeds the buffer. The offset >= size check runs too late to prevent it. Require 16 bytes for collections before calling the helper. Plain-font input keeps its current path.

Suggested fix

--- "a/src/libs/libFont.cpp"
+++ "b/src/libs/libFont.cpp"
@@ -775,8 +775,11 @@
 		return false;
 	}
 
 	// TrueType collections (.ttc) store a table of faces; use the first one.
+	if (size < 16 && data[0] == 't' && data[1] == 't' && data[2] == 'c' && data[3] == 'f') {
+		return false;
+	}
 	const int offset = stbtt_GetFontOffsetForIndex(data, 0);
 	if (offset < 0 || static_cast<uint32_t>(offset) >= size) {
 		return false;
 	}
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

	if (size < 16 && data[0] == 't' && data[1] == 't' && data[2] == 'c' && data[3] == 'f') {
		return false;
	}
	const int offset = stbtt_GetFontOffsetForIndex(data, 0);
**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899765) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Require the full collection header before reading the first face offset.** `init_stb_info` accepts a 12-byte `ttcf` buffer. `stbtt_GetFontOffsetForIndex` then reads the face-0 offset at bytes 12 to 15 without a length check. For a collection with at least one face, that read exceeds the buffer. The `offset >= size` check runs too late to prevent it. Require 16 bytes for collections before calling the helper. Plain-font input keeps its current path. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff --- "a/src/libs/libFont.cpp" +++ "b/src/libs/libFont.cpp" @@ -775,8 +775,11 @@ return false; } // TrueType collections (.ttc) store a table of faces; use the first one. + if (size < 16 && data[0] == 't' && data[1] == 't' && data[2] == 'c' && data[3] == 'f') { + return false; + } const int offset = stbtt_GetFontOffsetForIndex(data, 0); if (offset < 0 || static_cast<uint32_t>(offset) >= size) { return false; } ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> <br> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Review the replacement and indentation, then test before committing. ```suggestion if (size < 16 && data[0] == 't' && data[1] == 't' && data[2] == 'c' && data[3] == 'f') { return false; } const int offset = stbtt_GetFontOffsetForIndex(data, 0); ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e55b7061a5db8572d8c3319a --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -665,0 +754,4 @@
AudioOut2::AudioOut2PortHandle port = 0;
Check(AudioOut2::AudioOut2PortCreate(context, AsParam(&param), &port) == OK,
"port create failed");
uint32_t pcm[512]{};
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original

Major · Stability & Availability · Quick win

Allocate a complete stereo PCM grain.

When device is true, SetPcm copies 4096 bytes for 512 stereo float frames. This array contains only 2048 bytes. The copy reads beyond the stack array and can fail under a memory sanitizer. Use float pcm[512 * 2]{} to preserve the intended silent input. (raw.githubusercontent.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899868) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Allocate a complete stereo PCM grain.** When `device` is true, `SetPcm` copies 4096 bytes for 512 stereo float frames. This array contains only 2048 bytes. The copy reads beyond the stack array and can fail under a memory sanitizer. Use `float pcm[512 * 2]{}` to preserve the intended silent input. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/src/libs/libAudio2.cpp)) <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c11272e5c98926711d065b46 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +133,4 @@
Common::Singleton<Loader::RuntimeLinker>::Instance();
Libs::LibKernel::Initialize();
Libs::LibKernel::PthreadInitSelfForMainThread();
TestPriorities();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 17:58 UTC · original · edited 2026-11-20 21:30 UTC

Major · Stability & Availability · Quick win

Initialize the guest memory lifecycle in this test entrypoint.

main initializes configuration and logging, but not Libs::LibKernel::Memory::Lifecycle. Each worker calls CreateThreadTls in RunThread before it runs guest code. That path calls AllocateRuntimeMemory, which uses memory globals created only during Memory::Initialize. The new test can therefore fail when it creates its workers. Initialize the lifecycle after logging and before the runtime linker. The sibling tests use the same order.

Suggested fix

   subsystems.Initialize<Log::Lifecycle>();
+  subsystems.Initialize<Libs::LibKernel::Memory::Lifecycle>();
   Common::Singleton<Loader::RuntimeLinker>::Instance();

✅ Addressed in commits d6dc67d to 2577e26

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4645899874) · edited 2026-11-20 21:30 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Initialize the guest memory lifecycle in this test entrypoint.** `main` initializes configuration and logging, but not `Libs::LibKernel::Memory::Lifecycle`. Each worker calls `CreateThreadTls` in `RunThread` before it runs guest code. That path calls `AllocateRuntimeMemory`, which uses memory globals created only during `Memory::Initialize`. The new test can therefore fail when it creates its workers. Initialize the lifecycle after logging and before the runtime linker. The sibling tests use the same order. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff subsystems.Initialize<Log::Lifecycle>(); + subsystems.Initialize<Libs::LibKernel::Memory::Lifecycle>(); Common::Singleton<Loader::RuntimeLinker>::Instance(); ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fbd9798f021ee4c3b7ff2fbf --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits d6dc67d to 2577e26
Author
Owner

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

Actionable comments posted: 15

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

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

⚠️ Outside diff range comments (1)

Minor · Accept the trailing word that ProcessPm4 now accepts. · pm4.cpp:105-106

src/graphics/guest_gpu/pm4.cpp:105-106
Minor · Functional Correctness · Quick win

Accept the trailing word that ProcessPm4 now accepts.

If a command buffer ends with 0xc0001000, ProcessPm4 now consumes that trailing word. With command-buffer dumping enabled, GraphicsDbgDumpDcb calls this function before submission. This check still terminates the emulator when only that word remains.

Print and consume the trailing word here too. Keep validation for complete packets.

Minor comments: 15

tests/SaveDataDialogTests.cpp: 1

153-153: Minor · Data Integrity & Integration · Quick win

Pass the production parameter types to UserMessageText.

The nonempty case passes a MsgParam that the reader accesses as MsgDialogParam. The reader also accesses MsgUserMessage as MsgDialogUserMessageParam. Equal offsets do not make those accesses valid C++20. Put the production declarations in a shared internal header and construct those types in the test. The same four cases can then test the reader without relying on undefined behavior. (timsong-cpp.github.io)

tests/VirtualMemoryAllocationTests.cpp: 8

3153-3156: Minor · Stability & Availability · Quick win

Stop and join the replacement worker on failure.

If a partial KernelMunmap fails after an earlier split succeeds, CheckOk throws before the worker reaches join(). Destruction of the joinable std::thread terminates the process before RunTest can catch the failure. The fixed-map checks have the same path. Use a scope guard that requests worker stop, joins it, and removes the exception handler on both success and failure. (timsong-cpp.github.io)


3172-3173: Minor · Functional Correctness · Heavy lift

Require the replacement test to exercise a transient retry.

The worker can publish started after its first access and then remain paused through every replacement. The test passes with one access and zero retries. Use a rendezvous that makes the worker access a page during a known replacement window. Then assert that the retry succeeded and the access completed.


931-931: Minor · Functional Correctness · Quick win

Synchronize a sparse read with the middle-chunk commits.

The reader signals started before its first read. If the mapper finishes before the reader runs again, the reader sees stop and exits with reads == 0. The test reports a backing failure although no read ran. A read completed before the first commit can also satisfy the count. Use an explicit checkpoint during the commit sequence and wait for the reader's observation before stopping it.

Also applies to: 961-963


625-625: Minor · Stability & Availability · Quick win

Do not replace an existing host mapping in this fixture.

If the build lacks MAP_FIXED_NOREPLACE, MAP_FIXED discards any mapping already at foreign_addr. The exact-address check then passes, although the fixture has overwritten memory before the reservation code runs. Use a nonfixed hint on that branch. If it returns another address, unmap that result and report that the fixture could not be placed. (man7.org)


7697-7699: Minor · Functional Correctness · Quick win

Wait for thread exit before testing ESRCH.

ReturnAtOnce publishes progress before it returns. If the target is paused at that point for more than 100 ms, the test raises against a live thread and can reject a correct result. Synchronize with the actual exit transition while keeping the handle valid for the raise. Join only after checking the result and pending state.


7108-7114: Minor · Functional Correctness · Quick win

Measure the TSC rate over the same interval in both clocks.

If the test thread pauses for 20 ms between KernelReadTsc() and the first steady_clock sample, the tick delta covers about 70 ms while the time delta covers about 50 ms. The 10% tolerance then rejects a correct counter. Bracket the counter reads with clock samples and retry if an endpoint gap is too large.


424-425: Minor · Functional Correctness · Quick win

Distinguish write protection from a failed probe.

On Linux, this assertion accepts any process_vm_writev failure. If a sandbox rejects the syscall with EPERM, the check passes even when the target page is writable. Use a writable control to establish that the probe works, and require the expected address fault for the read-only page. (github.com)


4731-4733: Minor · Stability & Availability · Quick win

The AMM fixture advertises 64 bytes of capacity over 24 bytes of storage.

The constructor passes sizeof(data) (64 bytes) as the capacity for abandoned.header, which holds only 24 bytes. The two appends in this test write 16 bytes, so they stay in bounds. A longer command sequence on the same storage can write past abandoned.header. Pass a capacity that does not exceed the storage the fixture supplies.

src/graphics/presentation/window/window.cpp: 1

323-323: Minor · Functional Correctness · Quick win

Clear the remapped controller's trigger latches too.

With Pad:Cross=LeftTrigger, an old trigger press leaves g_pad_trigger_pressed[f.id] set. This reset clears touchpad drawing but preserves that latch. If the new mapping supplies no old release, the next trigger press computes down == state in HostInputPadTrigger and never reaches ApplyPadControl. The user must release and press again.

Add a host-input reset that also erases this controller's trigger latches. Clear the latches even when gamepad touchpad mode is disabled.

src/kernel/fileSystem.cpp: 1

446-449: Minor · Functional Correctness · Quick win

Account for the host component limit after encoding.

A guest filename containing 86 colons becomes one 258-character host component. A Windows volume with a 255-character component limit rejects it. Extended-length paths lift the total path limit, not the component limit. (learn.microsoft.com)

Use a bounded storage representation for names that do not fit, or detect the overflow and return ENAMETOOLONG instead of letting it appear as a generic open or create failure. Keep the existing representation for names that fit.

src/kernel/memoryAddressSpace.inc: 1

197-199: Minor · Functional Correctness · Quick win

Match the close timestamp to the window ID.

Wait can read the bounds of an expired window, then read the close timestamp of a replacement window in the same slot. If the replacement covers a different address and closed recently, Wait still returns the expired window's ID. The loader retries and logs a fault that did not occur during a matching remap.

Validate the ID with the close timestamp before applying the age check. If the slot changed, rescan it instead of using the new timestamp with the old bounds. Keep accepting recently closed windows when the ID still matches.

src/kernel/pthread.cpp: 1

3393-3396: Minor · Functional Correctness · Quick win

Classify one snapshot of guest_priority.

If the priority changes from 478 to 733 between the two loads, both comparisons fail and this function returns 700. Neither priority maps to 700. Load guest_priority once and use that value for both comparisons. This preserves the existing thresholds.

src/libs/libAudio2.cpp: 1

641-644: Minor · Performance & Scalability · Quick win

Use the same clock unit for the queue deadline.

last_update and audioout2_clock() use sixth-microsecond ticks. audioout2_grain_micros() returns microseconds, and SleepMicro consumes microseconds.

With num_grains=256, a full queue needs 32000 ticks to drain one grain. If this helper first checks after 1000 microseconds, it treats the deadline as expired and repeatedly requests one-microsecond sleeps for approximately 4333 more microseconds. This adds repeated polling to blocking pushes without a queueable device.

Calculate next with uint64_t{state->num_grains} * 125. Convert the remaining ticks to microseconds, rounded up, before sleeping. Keep the immediate return when the queue has room.

src/libs/ngs2.cpp: 1

3043-3043: Minor · Stability & Availability · Quick win

Synchronize the shared warning flag across systems.

If two threads send mastering control 2 to different NGS2 systems, each thread holds a different ngs->mutex. Both threads can read and write the same static warned flag without synchronization. This creates a data race.

Use an atomic exchange or a process-wide once guard. Keep the control accepted after the warning.

Based on learnings, shared non-atomic fields need synchronization across all accessing threads.

Source: Learnings

Nitpick comments: 4

.github/workflows/build.yml: 1

140-140: Trivial · Maintainability & Code Quality · Quick win

Add the new stdout and GPU-stall tests to CI.

guest_printf_tests and gpu_stall_tests use EXCLUDE_FROM_ALL. None of the platform build lists or CTest filters includes them. Adding them to kyty_tests does not cover this workflow because it never builds that target. (raw.githubusercontent.com)

Add both targets and their CTest names (guest_printf, guest_printf_disabled, guest_printf_default, guest_printf_invalid, and gpu_stall) to the applicable platform lists. This gives the new forwarding and wake-up checks automatic regression coverage.

Also applies to: 151-151

tests/AudioOut2PortTests.cpp: 1

758-760: Trivial · Maintainability & Code Quality · Quick win

Supply PCM before each device-paced push.

The first push consumes the PCM. The next two pushes therefore use the no-PCM path, even when device is true. Move this conditional SetPcm call inside the push loop to cover repeated device-paced pushes. (raw.githubusercontent.com)

tests/ShaderVertexMetadataTests.cpp: 1

95-98: Trivial · Maintainability & Code Quality · Quick win

Test the last valid SGPR pair at the hardware limit.

The new cases reject index 31 with a limit of 32. The successful cases use 64 and never try index 30. Add a success case at SGPRS_MAX - 2 with the same hardware limit. Derive the rejected index from SGPRS_MAX - 1 so the cases continue to test adjacent values if the limit changes.

Also applies to: 101-102, 104-105

src/loader/guestInstructionPatcher.cpp: 1

1758-1762: Trivial · Performance & Scalability · Heavy lift

Reuse the callee-discovery decode, or run it in parallel.

AddDecodedCallees runs DecodeFunction on every known function start, on one thread, before the parallel scan starts. When protect_memory is true, the parallel scan then calls analyze on every function again, and candidate functions are decoded a third time in the windowed decode pass. The comment at Line 1834 says the full decode takes about 9 s for Astro Bot on one core. Red-zone protection enabled therefore keeps one full single-threaded decode on the boot path, and the parallel scan cannot remove it. This applies to the Call of Duty: Black Ops II configuration that enables red-zone protection.

Options:

  • Run the fixpoint passes over pending with the same worker pool. Merge the newly found callees after each pass.
  • Keep the decoded results from AddDecodedCallees for functions whose range did not change, and skip the scan decode for them.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a1fc5ae438 and 135901b88c.

Files selected for processing: 139

  • .github/workflows/build.yml
  • CMakeLists.txt
  • src/common/debugCounters.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/gpuStall.cpp
  • src/common/gpuStall.h
  • src/common/parallelFor.h
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/common/systemFonts.cpp
  • src/common/systemFonts.h
  • src/common/threads.cpp
  • src/common/threads.h
  • src/emulator.cpp
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/command_processor/pm4Handlers.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/guest_gpu/graphicsRun.h
  • src/graphics/guest_gpu/pm4.cpp
  • src/graphics/guest_gpu/pm4.h
  • src/graphics/guest_gpu/tile.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/rangeSet.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.h
  • src/graphics/host_gpu/renderer/depthRenderTarget.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/image/imageView.cpp
  • src/graphics/host_gpu/renderer/image/tiler.cpp
  • src/graphics/host_gpu/renderer/image/tiler.h
  • src/graphics/host_gpu/renderer/meshSlices.h
  • src/graphics/host_gpu/renderer/pipeline/descriptorHeap.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptorHeap.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/rayTracing.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderContext.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/renderer/renderPssr.cpp
  • src/graphics/host_gpu/shaders/gpu_mesh_indirect.task
  • src/graphics/host_gpu/shaders/gpu_tiler_color_clear.comp
  • src/graphics/host_gpu/vulkanCommon.cpp
  • src/graphics/presentation/performanceOverlay.cpp
  • src/graphics/presentation/window/hostInput.cpp
  • src/graphics/presentation/window/hostInput.h
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/presentation/window/window.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.h
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/ir/Serialize.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.h
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/shader.cpp
  • src/kernel/eventFlag.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/kernel/pthread.cpp
  • src/kernel/pthread.h
  • src/kernel/semaphore.cpp
  • src/libs/agc.cpp
  • src/libs/agc.h
  • src/libs/audio.cpp
  • src/libs/audio3d.cpp
  • src/libs/avPlayer.cpp
  • src/libs/dialog.cpp
  • src/libs/dialog.h
  • src/libs/guestPrintf.cpp
  • src/libs/libAgcDriver.cpp
  • src/libs/libAudio2.cpp
  • src/libs/libC.cpp
  • src/libs/libCes.cpp
  • src/libs/libFont.cpp
  • src/libs/libKernel.cpp
  • src/libs/libNet.cpp
  • src/libs/libRtc.cpp
  • src/libs/network.cpp
  • src/libs/network.h
  • src/libs/ngs2.cpp
  • src/loader/guestInstructionPatcher.cpp
  • src/loader/guestInstructionPatcher.h
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • src/main.cpp
  • tests/ArchiveFileTests.cpp
  • tests/AudioOut2PortTests.cpp
  • tests/AudioOutTimingTests.cpp
  • tests/AvPlayerFileTests.cpp
  • tests/CesTests.cpp
  • tests/GpuStallTests.cpp
  • tests/GuestInstructionPatchScanTests.cpp
  • tests/GuestPrintfTests.cpp
  • tests/Http2AbortRequestTests.cpp
  • tests/KernelFileSystemTests.cpp
  • tests/LibCEnvironmentTests.cpp
  • tests/Ngs2SamplerTests.cpp
  • tests/PthreadPriorityTests.cpp
  • tests/ResourceMaterializationTests.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/RtcFormatTests.cpp
  • tests/SaveDataDialogTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/ShaderVertexMetadataTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/shaderCfgTests.cpp
Files not fully reviewed because they exceed a per-file size limit: 1

  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#pullrequestreview-5997168261) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 15** > [!NOTE] > Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments. > [!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><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Accept the trailing word that <code>ProcessPm4</code> now accepts. · <code>pm4.cpp:105-106</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/graphics/guest_gpu/pm4.cpp:105-106` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Accept the trailing word that `ProcessPm4` now accepts.** > > If a command buffer ends with `0xc0001000`, `ProcessPm4` now consumes that trailing word. With command-buffer dumping enabled, `GraphicsDbgDumpDcb` calls this function before submission. This check still terminates the emulator when only that word remains. > > Print and consume the trailing word here too. Keep validation for complete packets. > > <!-- cr-comment:v1:058bdbf02010f81a395869cd --> > > </dd> > </dl> > </blockquote></details> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor comments: 15</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/SaveDataDialogTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `153-153`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Pass the production parameter types to `UserMessageText`.** The nonempty case passes a `MsgParam` that the reader accesses as `MsgDialogParam`. The reader also accesses `MsgUserMessage` as `MsgDialogUserMessageParam`. Equal offsets do not make those accesses valid C++20. Put the production declarations in a shared internal header and construct those types in the test. The same four cases can then test the reader without relying on undefined behavior. ([timsong-cpp.github.io](https://timsong-cpp.github.io/cppwp/n4861/basic.lval)) <!-- cr-comment:v1:029d169be9247e303be0cbf1 --> </dd> </dl> </blockquote></details> <details> <summary>tests/VirtualMemoryAllocationTests.cpp: 8</summary><blockquote> <dl> <dd> <br> `3153-3156`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Stop and join the replacement worker on failure.** If a partial `KernelMunmap` fails after an earlier split succeeds, `CheckOk` throws before the worker reaches `join()`. Destruction of the joinable `std::thread` terminates the process before `RunTest` can catch the failure. The fixed-map checks have the same path. Use a scope guard that requests worker stop, joins it, and removes the exception handler on both success and failure. ([timsong-cpp.github.io](https://timsong-cpp.github.io/cppwp/n4861/thread.thread.destr)) <!-- cr-comment:v1:a7d3790b2a22d8a853958fc1 --> --- `3172-3173`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Heavy lift** **Require the replacement test to exercise a transient retry.** The worker can publish `started` after its first access and then remain paused through every replacement. The test passes with one access and zero retries. Use a rendezvous that makes the worker access a page during a known replacement window. Then assert that the retry succeeded and the access completed. <!-- cr-comment:v1:a2f16580656c81b69b8808ca --> --- `931-931`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Synchronize a sparse read with the middle-chunk commits.** The reader signals `started` before its first read. If the mapper finishes before the reader runs again, the reader sees `stop` and exits with `reads == 0`. The test reports a backing failure although no read ran. A read completed before the first commit can also satisfy the count. Use an explicit checkpoint during the commit sequence and wait for the reader's observation before stopping it. Also applies to: 961-963 <!-- cr-comment:v1:0dfbe8b42e9fbfd31e961d57 --> --- `625-625`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Do not replace an existing host mapping in this fixture.** If the build lacks `MAP_FIXED_NOREPLACE`, `MAP_FIXED` discards any mapping already at `foreign_addr`. The exact-address check then passes, although the fixture has overwritten memory before the reservation code runs. Use a nonfixed hint on that branch. If it returns another address, unmap that result and report that the fixture could not be placed. ([man7.org](https://www.man7.org/linux/man-pages/man3/mmap.3p.html?utm_source=openai)) <!-- cr-comment:v1:e8765bebf3ac438696f6144b --> --- `7697-7699`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Wait for thread exit before testing `ESRCH`.** `ReturnAtOnce` publishes progress before it returns. If the target is paused at that point for more than 100 ms, the test raises against a live thread and can reject a correct result. Synchronize with the actual exit transition while keeping the handle valid for the raise. Join only after checking the result and pending state. <!-- cr-comment:v1:ce0b095f341ccc59f486cbf8 --> --- `7108-7114`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Measure the TSC rate over the same interval in both clocks.** If the test thread pauses for 20 ms between `KernelReadTsc()` and the first `steady_clock` sample, the tick delta covers about 70 ms while the time delta covers about 50 ms. The 10% tolerance then rejects a correct counter. Bracket the counter reads with clock samples and retry if an endpoint gap is too large. <!-- cr-comment:v1:555b581f4353aa98f280bfec --> --- `424-425`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Distinguish write protection from a failed probe.** On Linux, this assertion accepts any `process_vm_writev` failure. If a sandbox rejects the syscall with `EPERM`, the check passes even when the target page is writable. Use a writable control to establish that the probe works, and require the expected address fault for the read-only page. ([github.com](https://github.com/torvalds/linux/blob/master/mm/process_vm_access.c?utm_source=openai)) <!-- cr-comment:v1:48433995c88c3ae414ff3e3e --> --- `4731-4733`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **The AMM fixture advertises 64 bytes of capacity over 24 bytes of storage.** The constructor passes `sizeof(data)` (64 bytes) as the capacity for `abandoned.header`, which holds only 24 bytes. The two appends in this test write 16 bytes, so they stay in bounds. A longer command sequence on the same storage can write past `abandoned.header`. Pass a capacity that does not exceed the storage the fixture supplies. <!-- cr-comment:v1:6fcbaccc18d10797cba5dda2 --> </dd> </dl> </blockquote></details> <details> <summary>src/graphics/presentation/window/window.cpp: 1</summary><blockquote> <dl> <dd> <br> `323-323`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Clear the remapped controller's trigger latches too.** With `Pad:Cross=LeftTrigger`, an old trigger press leaves `g_pad_trigger_pressed[f.id]` set. This reset clears touchpad drawing but preserves that latch. If the new mapping supplies no old release, the next trigger press computes `down == state` in `HostInputPadTrigger` and never reaches `ApplyPadControl`. The user must release and press again. Add a host-input reset that also erases this controller's trigger latches. Clear the latches even when gamepad touchpad mode is disabled. <!-- cr-comment:v1:d46bc3276f94b42d352463f3 --> </dd> </dl> </blockquote></details> <details> <summary>src/kernel/fileSystem.cpp: 1</summary><blockquote> <dl> <dd> <br> `446-449`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Account for the host component limit after encoding.** A guest filename containing 86 colons becomes one 258-character host component. A Windows volume with a 255-character component limit rejects it. Extended-length paths lift the total path limit, not the component limit. ([learn.microsoft.com](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry%29%3A&utm_source=openai)) Use a bounded storage representation for names that do not fit, or detect the overflow and return `ENAMETOOLONG` instead of letting it appear as a generic open or create failure. Keep the existing representation for names that fit. <!-- cr-comment:v1:ba56fc419279ab81f836e6ce --> </dd> </dl> </blockquote></details> <details> <summary>src/kernel/memoryAddressSpace.inc: 1</summary><blockquote> <dl> <dd> <br> `197-199`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Match the close timestamp to the window ID.** `Wait` can read the bounds of an expired window, then read the close timestamp of a replacement window in the same slot. If the replacement covers a different address and closed recently, `Wait` still returns the expired window's ID. The loader retries and logs a fault that did not occur during a matching remap. Validate the ID with the close timestamp before applying the age check. If the slot changed, rescan it instead of using the new timestamp with the old bounds. Keep accepting recently closed windows when the ID still matches. <!-- cr-comment:v1:ab7521b50c9c732ef03e28a2 --> </dd> </dl> </blockquote></details> <details> <summary>src/kernel/pthread.cpp: 1</summary><blockquote> <dl> <dd> <br> `3393-3396`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Classify one snapshot of `guest_priority`.** If the priority changes from `478` to `733` between the two loads, both comparisons fail and this function returns `700`. Neither priority maps to `700`. Load `guest_priority` once and use that value for both comparisons. This preserves the existing thresholds. <!-- cr-comment:v1:4cfc05ca3c136aec8459f8f2 --> </dd> </dl> </blockquote></details> <details> <summary>src/libs/libAudio2.cpp: 1</summary><blockquote> <dl> <dd> <br> `641-644`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Performance & Scalability** · **Quick win** **Use the same clock unit for the queue deadline.** `last_update` and `audioout2_clock()` use sixth-microsecond ticks. `audioout2_grain_micros()` returns microseconds, and `SleepMicro` consumes microseconds. With `num_grains=256`, a full queue needs 32000 ticks to drain one grain. If this helper first checks after 1000 microseconds, it treats the deadline as expired and repeatedly requests one-microsecond sleeps for approximately 4333 more microseconds. This adds repeated polling to blocking pushes without a queueable device. Calculate `next` with `uint64_t{state->num_grains} * 125`. Convert the remaining ticks to microseconds, rounded up, before sleeping. Keep the immediate return when the queue has room. <!-- cr-comment:v1:cb725ffa68581a88861d7dd6 --> </dd> </dl> </blockquote></details> <details> <summary>src/libs/ngs2.cpp: 1</summary><blockquote> <dl> <dd> <br> `3043-3043`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Synchronize the shared warning flag across systems.** If two threads send mastering control 2 to different NGS2 systems, each thread holds a different `ngs->mutex`. Both threads can read and write the same static `warned` flag without synchronization. This creates a data race. Use an atomic exchange or a process-wide once guard. Keep the control accepted after the warning. Based on learnings, shared non-atomic fields need synchronization across all accessing threads. <!-- coderabbit-global-learning v1 gid=857d9c615d003aba scope=lang --> <!-- cr-comment:v1:fb797e030ced1c6971f59a7f --> _Source: Learnings_ </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 4</summary><blockquote> <dl> <dd> <br> <details> <summary>.github/workflows/build.yml: 1</summary><blockquote> <dl> <dd> <br> `140-140`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Add the new stdout and GPU-stall tests to CI.** `guest_printf_tests` and `gpu_stall_tests` use `EXCLUDE_FROM_ALL`. None of the platform build lists or CTest filters includes them. Adding them to `kyty_tests` does not cover this workflow because it never builds that target. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/CMakeLists.txt)) Add both targets and their CTest names (`guest_printf`, `guest_printf_disabled`, `guest_printf_default`, `guest_printf_invalid`, and `gpu_stall`) to the applicable platform lists. This gives the new forwarding and wake-up checks automatic regression coverage. Also applies to: 151-151 <!-- cr-comment:v1:a18aaea45129365656328784 --> </dd> </dl> </blockquote></details> <details> <summary>tests/AudioOut2PortTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `758-760`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Supply PCM before each device-paced push.** The first push consumes the PCM. The next two pushes therefore use the no-PCM path, even when `device` is true. Move this conditional `SetPcm` call inside the push loop to cover repeated device-paced pushes. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/src/libs/libAudio2.cpp)) <!-- cr-comment:v1:43ee122ef0d11c278e5725ae --> </dd> </dl> </blockquote></details> <details> <summary>tests/ShaderVertexMetadataTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `95-98`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Test the last valid SGPR pair at the hardware limit.** The new cases reject index 31 with a limit of 32. The successful cases use 64 and never try index 30. Add a success case at `SGPRS_MAX - 2` with the same hardware limit. Derive the rejected index from `SGPRS_MAX - 1` so the cases continue to test adjacent values if the limit changes. Also applies to: 101-102, 104-105 <!-- cr-comment:v1:01f05003ca95da63a2993cf5 --> </dd> </dl> </blockquote></details> <details> <summary>src/loader/guestInstructionPatcher.cpp: 1</summary><blockquote> <dl> <dd> <br> `1758-1762`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Performance & Scalability** · **Heavy lift** **Reuse the callee-discovery decode, or run it in parallel.** `AddDecodedCallees` runs `DecodeFunction` on every known function start, on one thread, before the parallel scan starts. When `protect_memory` is true, the parallel scan then calls `analyze` on every function again, and candidate functions are decoded a third time in the windowed decode pass. The comment at Line 1834 says the full decode takes about 9 s for Astro Bot on one core. Red-zone protection enabled therefore keeps one full single-threaded decode on the boot path, and the parallel scan cannot remove it. This applies to the Call of Duty: Black Ops II configuration that enables red-zone protection. Options: - Run the fixpoint passes over `pending` with the same worker pool. Merge the newly found callees after each pass. - Keep the decoded results from `AddDecodedCallees` for functions whose range did not change, and skip the scan decode for them. <!-- cr-comment:v1:b579310c5b3c7bc9573485fc --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a1fc5ae438ea343480c9850f585d8c0afed06241/.coderabbit.yaml>) - **Commit**: [a1fc5ae](<https://github.com/KytyPS5/KytyPS5/commit/a1fc5ae438ea343480c9850f585d8c0afed06241>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `0f7a734b-55a5-4c54-9b6e-a1adbcc899e3` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between a1fc5ae438ea343480c9850f585d8c0afed06241 and 135901b88cbcfb7156d7fffe6d53b7c366236caa. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 139</summary> <dl> <dd> <br> * `.github/workflows/build.yml` * `CMakeLists.txt` * `src/common/debugCounters.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/common/gpuStall.cpp` * `src/common/gpuStall.h` * `src/common/parallelFor.h` * `src/common/platform/sysFileIO.h` * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/common/systemFonts.cpp` * `src/common/systemFonts.h` * `src/common/threads.cpp` * `src/common/threads.h` * `src/emulator.cpp` * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/command_processor/pm4Handlers.cpp` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/guest_gpu/graphicsRun.h` * `src/graphics/guest_gpu/pm4.cpp` * `src/graphics/guest_gpu/pm4.h` * `src/graphics/guest_gpu/tile.cpp` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/rangeSet.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/streamBuffer.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.h` * `src/graphics/host_gpu/renderer/depthRenderTarget.cpp` * `src/graphics/host_gpu/renderer/image/image.cpp` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/image/imageView.cpp` * `src/graphics/host_gpu/renderer/image/tiler.cpp` * `src/graphics/host_gpu/renderer/image/tiler.h` * `src/graphics/host_gpu/renderer/meshSlices.h` * `src/graphics/host_gpu/renderer/pipeline/descriptorHeap.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptorHeap.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp` * `src/graphics/host_gpu/renderer/pipeline/shaders.cpp` * `src/graphics/host_gpu/renderer/rayTracing.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `src/graphics/host_gpu/renderer/renderContext.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/host_gpu/renderer/renderPssr.cpp` * `src/graphics/host_gpu/shaders/gpu_mesh_indirect.task` * `src/graphics/host_gpu/shaders/gpu_tiler_color_clear.comp` * `src/graphics/host_gpu/vulkanCommon.cpp` * `src/graphics/presentation/performanceOverlay.cpp` * `src/graphics/presentation/window/hostInput.cpp` * `src/graphics/presentation/window/hostInput.h` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/presentation/window/window.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.h` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/ir/Serialize.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/Value.h` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/shader.cpp` * `src/kernel/eventFlag.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/kernel/pthread.cpp` * `src/kernel/pthread.h` * `src/kernel/semaphore.cpp` * `src/libs/agc.cpp` * `src/libs/agc.h` * `src/libs/audio.cpp` * `src/libs/audio3d.cpp` * `src/libs/avPlayer.cpp` * `src/libs/dialog.cpp` * `src/libs/dialog.h` * `src/libs/guestPrintf.cpp` * `src/libs/libAgcDriver.cpp` * `src/libs/libAudio2.cpp` * `src/libs/libC.cpp` * `src/libs/libCes.cpp` * `src/libs/libFont.cpp` * `src/libs/libKernel.cpp` * `src/libs/libNet.cpp` * `src/libs/libRtc.cpp` * `src/libs/network.cpp` * `src/libs/network.h` * `src/libs/ngs2.cpp` * `src/loader/guestInstructionPatcher.cpp` * `src/loader/guestInstructionPatcher.h` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `src/main.cpp` * `tests/ArchiveFileTests.cpp` * `tests/AudioOut2PortTests.cpp` * `tests/AudioOutTimingTests.cpp` * `tests/AvPlayerFileTests.cpp` * `tests/CesTests.cpp` * `tests/GpuStallTests.cpp` * `tests/GuestInstructionPatchScanTests.cpp` * `tests/GuestPrintfTests.cpp` * `tests/Http2AbortRequestTests.cpp` * `tests/KernelFileSystemTests.cpp` * `tests/LibCEnvironmentTests.cpp` * `tests/Ngs2SamplerTests.cpp` * `tests/PthreadPriorityTests.cpp` * `tests/ResourceMaterializationTests.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/RtcFormatTests.cpp` * `tests/SaveDataDialogTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/ShaderVertexMetadataTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` * `tests/shaderCfgTests.cpp` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files not fully reviewed because they exceed a per-file size limit: 1</summary> <dl> <dd> <br> * tests/ShaderRecompilerComputeTests.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

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

Actionable comments posted: 13

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

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

⚠️ Outside diff range comments (3)

Major · Remove the 50 ms limit from the functional signal test. · KernelFileSystemTests.cpp:305-306

tests/KernelFileSystemTests.cpp:305-306
Major · Functional Correctness · Quick win

Remove the 50 ms limit from the functional signal test.

If the host deschedules this thread for 50 ms, the test aborts even when dispatched_signals == 1. Slow or instrumented builds can also fail this condition without a dispatch defect. This affects both the normal and --mutex-only runs.

Keep the exact delivery-count assertion. Measure idle-dispatch performance in a separate benchmark that controls scheduling noise.

Major · Dispatch --fault-report before initializing guest… · VirtualMemoryAllocationTests.cpp:7863

tests/VirtualMemoryAllocationTests.cpp:7863
Major · Functional Correctness · Quick win

Dispatch --fault-report before initializing guest memory.

RunFaultReportChild starts this executable with --fault-report <log path>. With argc == 3, main skips every option handler and starts the full suite instead of calling ReportFaultTo. If the child reaches the same fault-report test, it starts another child. Handle this invocation before InitSubsystems() and call ReportFaultTo(argv[2]). Keep the no-argument invocation on the full-suite path.

Minor · Accept the trailing word that ProcessPm4 now accepts. · pm4.cpp:105-106

src/graphics/guest_gpu/pm4.cpp:105-106
Minor · Functional Correctness · Quick win

Accept the trailing word that ProcessPm4 now accepts.

If a command buffer ends with 0xc0001000, ProcessPm4 now consumes that trailing word. With command-buffer dumping enabled, GraphicsDbgDumpDcb calls this function before submission. This check still terminates the emulator when only that word remains.

Print and consume the trailing word here too. Keep validation for complete packets.

Minor comments: 15

tests/SaveDataDialogTests.cpp: 1

153-153: Minor · Data Integrity & Integration · Quick win

Pass the production parameter types to UserMessageText.

The nonempty case passes a MsgParam that the reader accesses as MsgDialogParam. The reader also accesses MsgUserMessage as MsgDialogUserMessageParam. Equal offsets do not make those accesses valid C++20. Put the production declarations in a shared internal header and construct those types in the test. The same four cases can then test the reader without relying on undefined behavior. (timsong-cpp.github.io)

tests/VirtualMemoryAllocationTests.cpp: 8

3153-3156: Minor · Stability & Availability · Quick win

Stop and join the replacement worker on failure.

If a partial KernelMunmap fails after an earlier split succeeds, CheckOk throws before the worker reaches join(). Destruction of the joinable std::thread terminates the process before RunTest can catch the failure. The fixed-map checks have the same path. Use a scope guard that requests worker stop, joins it, and removes the exception handler on both success and failure. (timsong-cpp.github.io)


3172-3173: Minor · Functional Correctness · Heavy lift

Require the replacement test to exercise a transient retry.

The worker can publish started after its first access and then remain paused through every replacement. The test passes with one access and zero retries. Use a rendezvous that makes the worker access a page during a known replacement window. Then assert that the retry succeeded and the access completed.


931-931: Minor · Functional Correctness · Quick win

Synchronize a sparse read with the middle-chunk commits.

The reader signals started before its first read. If the mapper finishes before the reader runs again, the reader sees stop and exits with reads == 0. The test reports a backing failure although no read ran. A read completed before the first commit can also satisfy the count. Use an explicit checkpoint during the commit sequence and wait for the reader's observation before stopping it.

Also applies to: 961-963


625-625: Minor · Stability & Availability · Quick win

Do not replace an existing host mapping in this fixture.

If the build lacks MAP_FIXED_NOREPLACE, MAP_FIXED discards any mapping already at foreign_addr. The exact-address check then passes, although the fixture has overwritten memory before the reservation code runs. Use a nonfixed hint on that branch. If it returns another address, unmap that result and report that the fixture could not be placed. (man7.org)


7697-7699: Minor · Functional Correctness · Quick win

Wait for thread exit before testing ESRCH.

ReturnAtOnce publishes progress before it returns. If the target is paused at that point for more than 100 ms, the test raises against a live thread and can reject a correct result. Synchronize with the actual exit transition while keeping the handle valid for the raise. Join only after checking the result and pending state.


7108-7114: Minor · Functional Correctness · Quick win

Measure the TSC rate over the same interval in both clocks.

If the test thread pauses for 20 ms between KernelReadTsc() and the first steady_clock sample, the tick delta covers about 70 ms while the time delta covers about 50 ms. The 10% tolerance then rejects a correct counter. Bracket the counter reads with clock samples and retry if an endpoint gap is too large.


424-425: Minor · Functional Correctness · Quick win

Distinguish write protection from a failed probe.

On Linux, this assertion accepts any process_vm_writev failure. If a sandbox rejects the syscall with EPERM, the check passes even when the target page is writable. Use a writable control to establish that the probe works, and require the expected address fault for the read-only page. (github.com)


4731-4733: Minor · Stability & Availability · Quick win

The AMM fixture advertises 64 bytes of capacity over 24 bytes of storage.

The constructor passes sizeof(data) (64 bytes) as the capacity for abandoned.header, which holds only 24 bytes. The two appends in this test write 16 bytes, so they stay in bounds. A longer command sequence on the same storage can write past abandoned.header. Pass a capacity that does not exceed the storage the fixture supplies.

src/graphics/presentation/window/window.cpp: 1

323-323: Minor · Functional Correctness · Quick win

Clear the remapped controller's trigger latches too.

With Pad:Cross=LeftTrigger, an old trigger press leaves g_pad_trigger_pressed[f.id] set. This reset clears touchpad drawing but preserves that latch. If the new mapping supplies no old release, the next trigger press computes down == state in HostInputPadTrigger and never reaches ApplyPadControl. The user must release and press again.

Add a host-input reset that also erases this controller's trigger latches. Clear the latches even when gamepad touchpad mode is disabled.

src/kernel/fileSystem.cpp: 1

446-449: Minor · Functional Correctness · Quick win

Account for the host component limit after encoding.

A guest filename containing 86 colons becomes one 258-character host component. A Windows volume with a 255-character component limit rejects it. Extended-length paths lift the total path limit, not the component limit. (learn.microsoft.com)

Use a bounded storage representation for names that do not fit, or detect the overflow and return ENAMETOOLONG instead of letting it appear as a generic open or create failure. Keep the existing representation for names that fit.

src/kernel/memoryAddressSpace.inc: 1

197-199: Minor · Functional Correctness · Quick win

Match the close timestamp to the window ID.

Wait can read the bounds of an expired window, then read the close timestamp of a replacement window in the same slot. If the replacement covers a different address and closed recently, Wait still returns the expired window's ID. The loader retries and logs a fault that did not occur during a matching remap.

Validate the ID with the close timestamp before applying the age check. If the slot changed, rescan it instead of using the new timestamp with the old bounds. Keep accepting recently closed windows when the ID still matches.

src/kernel/pthread.cpp: 1

3393-3396: Minor · Functional Correctness · Quick win

Classify one snapshot of guest_priority.

If the priority changes from 478 to 733 between the two loads, both comparisons fail and this function returns 700. Neither priority maps to 700. Load guest_priority once and use that value for both comparisons. This preserves the existing thresholds.

src/libs/libAudio2.cpp: 1

641-644: Minor · Performance & Scalability · Quick win

Use the same clock unit for the queue deadline.

last_update and audioout2_clock() use sixth-microsecond ticks. audioout2_grain_micros() returns microseconds, and SleepMicro consumes microseconds.

With num_grains=256, a full queue needs 32000 ticks to drain one grain. If this helper first checks after 1000 microseconds, it treats the deadline as expired and repeatedly requests one-microsecond sleeps for approximately 4333 more microseconds. This adds repeated polling to blocking pushes without a queueable device.

Calculate next with uint64_t{state->num_grains} * 125. Convert the remaining ticks to microseconds, rounded up, before sleeping. Keep the immediate return when the queue has room.

src/libs/ngs2.cpp: 1

3043-3043: Minor · Stability & Availability · Quick win

Synchronize the shared warning flag across systems.

If two threads send mastering control 2 to different NGS2 systems, each thread holds a different ngs->mutex. Both threads can read and write the same static warned flag without synchronization. This creates a data race.

Use an atomic exchange or a process-wide once guard. Keep the control accepted after the warning.

Based on learnings, shared non-atomic fields need synchronization across all accessing threads.

Source: Learnings

Nitpick comments: 4

.github/workflows/build.yml: 1

140-140: Trivial · Maintainability & Code Quality · Quick win

Add the new stdout and GPU-stall tests to CI.

guest_printf_tests and gpu_stall_tests use EXCLUDE_FROM_ALL. None of the platform build lists or CTest filters includes them. Adding them to kyty_tests does not cover this workflow because it never builds that target. (raw.githubusercontent.com)

Add both targets and their CTest names (guest_printf, guest_printf_disabled, guest_printf_default, guest_printf_invalid, and gpu_stall) to the applicable platform lists. This gives the new forwarding and wake-up checks automatic regression coverage.

Also applies to: 151-151

tests/AudioOut2PortTests.cpp: 1

758-760: Trivial · Maintainability & Code Quality · Quick win

Supply PCM before each device-paced push.

The first push consumes the PCM. The next two pushes therefore use the no-PCM path, even when device is true. Move this conditional SetPcm call inside the push loop to cover repeated device-paced pushes. (raw.githubusercontent.com)

tests/ShaderVertexMetadataTests.cpp: 1

95-98: Trivial · Maintainability & Code Quality · Quick win

Test the last valid SGPR pair at the hardware limit.

The new cases reject index 31 with a limit of 32. The successful cases use 64 and never try index 30. Add a success case at SGPRS_MAX - 2 with the same hardware limit. Derive the rejected index from SGPRS_MAX - 1 so the cases continue to test adjacent values if the limit changes.

Also applies to: 101-102, 104-105

src/loader/guestInstructionPatcher.cpp: 1

1758-1762: Trivial · Performance & Scalability · Heavy lift

Reuse the callee-discovery decode, or run it in parallel.

AddDecodedCallees runs DecodeFunction on every known function start, on one thread, before the parallel scan starts. When protect_memory is true, the parallel scan then calls analyze on every function again, and candidate functions are decoded a third time in the windowed decode pass. The comment at Line 1834 says the full decode takes about 9 s for Astro Bot on one core. Red-zone protection enabled therefore keeps one full single-threaded decode on the boot path, and the parallel scan cannot remove it. This applies to the Call of Duty: Black Ops II configuration that enables red-zone protection.

Options:

  • Run the fixpoint passes over pending with the same worker pool. Merge the newly found callees after each pass.
  • Keep the decoded results from AddDecodedCallees for functions whose range did not change, and skip the scan decode for them.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a1fc5ae438 and 135901b88c.

Files selected for processing: 139

  • .github/workflows/build.yml
  • CMakeLists.txt
  • src/common/debugCounters.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/gpuStall.cpp
  • src/common/gpuStall.h
  • src/common/parallelFor.h
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/common/systemFonts.cpp
  • src/common/systemFonts.h
  • src/common/threads.cpp
  • src/common/threads.h
  • src/emulator.cpp
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/command_processor/pm4Handlers.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/guest_gpu/graphicsRun.h
  • src/graphics/guest_gpu/pm4.cpp
  • src/graphics/guest_gpu/pm4.h
  • src/graphics/guest_gpu/tile.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/rangeSet.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.h
  • src/graphics/host_gpu/renderer/depthRenderTarget.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/image/imageView.cpp
  • src/graphics/host_gpu/renderer/image/tiler.cpp
  • src/graphics/host_gpu/renderer/image/tiler.h
  • src/graphics/host_gpu/renderer/meshSlices.h
  • src/graphics/host_gpu/renderer/pipeline/descriptorHeap.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptorHeap.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/rayTracing.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderContext.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/renderer/renderPssr.cpp
  • src/graphics/host_gpu/shaders/gpu_mesh_indirect.task
  • src/graphics/host_gpu/shaders/gpu_tiler_color_clear.comp
  • src/graphics/host_gpu/vulkanCommon.cpp
  • src/graphics/presentation/performanceOverlay.cpp
  • src/graphics/presentation/window/hostInput.cpp
  • src/graphics/presentation/window/hostInput.h
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/presentation/window/window.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.h
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/ir/Serialize.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.h
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/shader.cpp
  • src/kernel/eventFlag.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/kernel/pthread.cpp
  • src/kernel/pthread.h
  • src/kernel/semaphore.cpp
  • src/libs/agc.cpp
  • src/libs/agc.h
  • src/libs/audio.cpp
  • src/libs/audio3d.cpp
  • src/libs/avPlayer.cpp
  • src/libs/dialog.cpp
  • src/libs/dialog.h
  • src/libs/guestPrintf.cpp
  • src/libs/libAgcDriver.cpp
  • src/libs/libAudio2.cpp
  • src/libs/libC.cpp
  • src/libs/libCes.cpp
  • src/libs/libFont.cpp
  • src/libs/libKernel.cpp
  • src/libs/libNet.cpp
  • src/libs/libRtc.cpp
  • src/libs/network.cpp
  • src/libs/network.h
  • src/libs/ngs2.cpp
  • src/loader/guestInstructionPatcher.cpp
  • src/loader/guestInstructionPatcher.h
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • src/main.cpp
  • tests/ArchiveFileTests.cpp
  • tests/AudioOut2PortTests.cpp
  • tests/AudioOutTimingTests.cpp
  • tests/AvPlayerFileTests.cpp
  • tests/CesTests.cpp
  • tests/GpuStallTests.cpp
  • tests/GuestInstructionPatchScanTests.cpp
  • tests/GuestPrintfTests.cpp
  • tests/Http2AbortRequestTests.cpp
  • tests/KernelFileSystemTests.cpp
  • tests/LibCEnvironmentTests.cpp
  • tests/Ngs2SamplerTests.cpp
  • tests/PthreadPriorityTests.cpp
  • tests/ResourceMaterializationTests.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/RtcFormatTests.cpp
  • tests/SaveDataDialogTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/ShaderVertexMetadataTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/shaderCfgTests.cpp
Files not fully reviewed because they exceed a per-file size limit: 1

  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 17:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#pullrequestreview-5997173179) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 13** > [!NOTE] > Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments. > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (3)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Remove the 50 ms limit from the functional signal test. · <code>KernelFileSystemTests.cpp:305-306</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/KernelFileSystemTests.cpp:305-306` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** > > **Remove the 50 ms limit from the functional signal test.** > > If the host deschedules this thread for 50 ms, the test aborts even when `dispatched_signals == 1`. Slow or instrumented builds can also fail this condition without a dispatch defect. This affects both the normal and `--mutex-only` runs. > > Keep the exact delivery-count assertion. Measure idle-dispatch performance in a separate benchmark that controls scheduling noise. > > <!-- cr-comment:v1:fbfca216ba29e054f0941574 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Dispatch <code>--fault-report</code> before initializing guest… · <code>VirtualMemoryAllocationTests.cpp:7863</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/VirtualMemoryAllocationTests.cpp:7863` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** > > **Dispatch `--fault-report` before initializing guest memory.** > > `RunFaultReportChild` starts this executable with `--fault-report <log path>`. With `argc == 3`, `main` skips every option handler and starts the full suite instead of calling `ReportFaultTo`. If the child reaches the same fault-report test, it starts another child. Handle this invocation before `InitSubsystems()` and call `ReportFaultTo(argv[2])`. Keep the no-argument invocation on the full-suite path. > > <!-- cr-comment:v1:c39ce3bfe7d407c7795e9c72 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Accept the trailing word that <code>ProcessPm4</code> now accepts. · <code>pm4.cpp:105-106</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/graphics/guest_gpu/pm4.cpp:105-106` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Accept the trailing word that `ProcessPm4` now accepts.** > > If a command buffer ends with `0xc0001000`, `ProcessPm4` now consumes that trailing word. With command-buffer dumping enabled, `GraphicsDbgDumpDcb` calls this function before submission. This check still terminates the emulator when only that word remains. > > Print and consume the trailing word here too. Keep validation for complete packets. > > <!-- cr-comment:v1:058bdbf02010f81a395869cd --> > > </dd> > </dl> > </blockquote></details> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor comments: 15</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/SaveDataDialogTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `153-153`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Pass the production parameter types to `UserMessageText`.** The nonempty case passes a `MsgParam` that the reader accesses as `MsgDialogParam`. The reader also accesses `MsgUserMessage` as `MsgDialogUserMessageParam`. Equal offsets do not make those accesses valid C++20. Put the production declarations in a shared internal header and construct those types in the test. The same four cases can then test the reader without relying on undefined behavior. ([timsong-cpp.github.io](https://timsong-cpp.github.io/cppwp/n4861/basic.lval)) <!-- cr-comment:v1:029d169be9247e303be0cbf1 --> </dd> </dl> </blockquote></details> <details> <summary>tests/VirtualMemoryAllocationTests.cpp: 8</summary><blockquote> <dl> <dd> <br> `3153-3156`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Stop and join the replacement worker on failure.** If a partial `KernelMunmap` fails after an earlier split succeeds, `CheckOk` throws before the worker reaches `join()`. Destruction of the joinable `std::thread` terminates the process before `RunTest` can catch the failure. The fixed-map checks have the same path. Use a scope guard that requests worker stop, joins it, and removes the exception handler on both success and failure. ([timsong-cpp.github.io](https://timsong-cpp.github.io/cppwp/n4861/thread.thread.destr)) <!-- cr-comment:v1:a7d3790b2a22d8a853958fc1 --> --- `3172-3173`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Heavy lift** **Require the replacement test to exercise a transient retry.** The worker can publish `started` after its first access and then remain paused through every replacement. The test passes with one access and zero retries. Use a rendezvous that makes the worker access a page during a known replacement window. Then assert that the retry succeeded and the access completed. <!-- cr-comment:v1:a2f16580656c81b69b8808ca --> --- `931-931`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Synchronize a sparse read with the middle-chunk commits.** The reader signals `started` before its first read. If the mapper finishes before the reader runs again, the reader sees `stop` and exits with `reads == 0`. The test reports a backing failure although no read ran. A read completed before the first commit can also satisfy the count. Use an explicit checkpoint during the commit sequence and wait for the reader's observation before stopping it. Also applies to: 961-963 <!-- cr-comment:v1:0dfbe8b42e9fbfd31e961d57 --> --- `625-625`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Do not replace an existing host mapping in this fixture.** If the build lacks `MAP_FIXED_NOREPLACE`, `MAP_FIXED` discards any mapping already at `foreign_addr`. The exact-address check then passes, although the fixture has overwritten memory before the reservation code runs. Use a nonfixed hint on that branch. If it returns another address, unmap that result and report that the fixture could not be placed. ([man7.org](https://www.man7.org/linux/man-pages/man3/mmap.3p.html?utm_source=openai)) <!-- cr-comment:v1:e8765bebf3ac438696f6144b --> --- `7697-7699`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Wait for thread exit before testing `ESRCH`.** `ReturnAtOnce` publishes progress before it returns. If the target is paused at that point for more than 100 ms, the test raises against a live thread and can reject a correct result. Synchronize with the actual exit transition while keeping the handle valid for the raise. Join only after checking the result and pending state. <!-- cr-comment:v1:ce0b095f341ccc59f486cbf8 --> --- `7108-7114`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Measure the TSC rate over the same interval in both clocks.** If the test thread pauses for 20 ms between `KernelReadTsc()` and the first `steady_clock` sample, the tick delta covers about 70 ms while the time delta covers about 50 ms. The 10% tolerance then rejects a correct counter. Bracket the counter reads with clock samples and retry if an endpoint gap is too large. <!-- cr-comment:v1:555b581f4353aa98f280bfec --> --- `424-425`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Distinguish write protection from a failed probe.** On Linux, this assertion accepts any `process_vm_writev` failure. If a sandbox rejects the syscall with `EPERM`, the check passes even when the target page is writable. Use a writable control to establish that the probe works, and require the expected address fault for the read-only page. ([github.com](https://github.com/torvalds/linux/blob/master/mm/process_vm_access.c?utm_source=openai)) <!-- cr-comment:v1:48433995c88c3ae414ff3e3e --> --- `4731-4733`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **The AMM fixture advertises 64 bytes of capacity over 24 bytes of storage.** The constructor passes `sizeof(data)` (64 bytes) as the capacity for `abandoned.header`, which holds only 24 bytes. The two appends in this test write 16 bytes, so they stay in bounds. A longer command sequence on the same storage can write past `abandoned.header`. Pass a capacity that does not exceed the storage the fixture supplies. <!-- cr-comment:v1:6fcbaccc18d10797cba5dda2 --> </dd> </dl> </blockquote></details> <details> <summary>src/graphics/presentation/window/window.cpp: 1</summary><blockquote> <dl> <dd> <br> `323-323`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Clear the remapped controller's trigger latches too.** With `Pad:Cross=LeftTrigger`, an old trigger press leaves `g_pad_trigger_pressed[f.id]` set. This reset clears touchpad drawing but preserves that latch. If the new mapping supplies no old release, the next trigger press computes `down == state` in `HostInputPadTrigger` and never reaches `ApplyPadControl`. The user must release and press again. Add a host-input reset that also erases this controller's trigger latches. Clear the latches even when gamepad touchpad mode is disabled. <!-- cr-comment:v1:d46bc3276f94b42d352463f3 --> </dd> </dl> </blockquote></details> <details> <summary>src/kernel/fileSystem.cpp: 1</summary><blockquote> <dl> <dd> <br> `446-449`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Account for the host component limit after encoding.** A guest filename containing 86 colons becomes one 258-character host component. A Windows volume with a 255-character component limit rejects it. Extended-length paths lift the total path limit, not the component limit. ([learn.microsoft.com](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry%29%3A&utm_source=openai)) Use a bounded storage representation for names that do not fit, or detect the overflow and return `ENAMETOOLONG` instead of letting it appear as a generic open or create failure. Keep the existing representation for names that fit. <!-- cr-comment:v1:ba56fc419279ab81f836e6ce --> </dd> </dl> </blockquote></details> <details> <summary>src/kernel/memoryAddressSpace.inc: 1</summary><blockquote> <dl> <dd> <br> `197-199`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Match the close timestamp to the window ID.** `Wait` can read the bounds of an expired window, then read the close timestamp of a replacement window in the same slot. If the replacement covers a different address and closed recently, `Wait` still returns the expired window's ID. The loader retries and logs a fault that did not occur during a matching remap. Validate the ID with the close timestamp before applying the age check. If the slot changed, rescan it instead of using the new timestamp with the old bounds. Keep accepting recently closed windows when the ID still matches. <!-- cr-comment:v1:ab7521b50c9c732ef03e28a2 --> </dd> </dl> </blockquote></details> <details> <summary>src/kernel/pthread.cpp: 1</summary><blockquote> <dl> <dd> <br> `3393-3396`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Classify one snapshot of `guest_priority`.** If the priority changes from `478` to `733` between the two loads, both comparisons fail and this function returns `700`. Neither priority maps to `700`. Load `guest_priority` once and use that value for both comparisons. This preserves the existing thresholds. <!-- cr-comment:v1:4cfc05ca3c136aec8459f8f2 --> </dd> </dl> </blockquote></details> <details> <summary>src/libs/libAudio2.cpp: 1</summary><blockquote> <dl> <dd> <br> `641-644`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Performance & Scalability** · **Quick win** **Use the same clock unit for the queue deadline.** `last_update` and `audioout2_clock()` use sixth-microsecond ticks. `audioout2_grain_micros()` returns microseconds, and `SleepMicro` consumes microseconds. With `num_grains=256`, a full queue needs 32000 ticks to drain one grain. If this helper first checks after 1000 microseconds, it treats the deadline as expired and repeatedly requests one-microsecond sleeps for approximately 4333 more microseconds. This adds repeated polling to blocking pushes without a queueable device. Calculate `next` with `uint64_t{state->num_grains} * 125`. Convert the remaining ticks to microseconds, rounded up, before sleeping. Keep the immediate return when the queue has room. <!-- cr-comment:v1:cb725ffa68581a88861d7dd6 --> </dd> </dl> </blockquote></details> <details> <summary>src/libs/ngs2.cpp: 1</summary><blockquote> <dl> <dd> <br> `3043-3043`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Synchronize the shared warning flag across systems.** If two threads send mastering control 2 to different NGS2 systems, each thread holds a different `ngs->mutex`. Both threads can read and write the same static `warned` flag without synchronization. This creates a data race. Use an atomic exchange or a process-wide once guard. Keep the control accepted after the warning. Based on learnings, shared non-atomic fields need synchronization across all accessing threads. <!-- coderabbit-global-learning v1 gid=857d9c615d003aba scope=lang --> <!-- cr-comment:v1:fb797e030ced1c6971f59a7f --> _Source: Learnings_ </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 4</summary><blockquote> <dl> <dd> <br> <details> <summary>.github/workflows/build.yml: 1</summary><blockquote> <dl> <dd> <br> `140-140`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Add the new stdout and GPU-stall tests to CI.** `guest_printf_tests` and `gpu_stall_tests` use `EXCLUDE_FROM_ALL`. None of the platform build lists or CTest filters includes them. Adding them to `kyty_tests` does not cover this workflow because it never builds that target. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/CMakeLists.txt)) Add both targets and their CTest names (`guest_printf`, `guest_printf_disabled`, `guest_printf_default`, `guest_printf_invalid`, and `gpu_stall`) to the applicable platform lists. This gives the new forwarding and wake-up checks automatic regression coverage. Also applies to: 151-151 <!-- cr-comment:v1:a18aaea45129365656328784 --> </dd> </dl> </blockquote></details> <details> <summary>tests/AudioOut2PortTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `758-760`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Supply PCM before each device-paced push.** The first push consumes the PCM. The next two pushes therefore use the no-PCM path, even when `device` is true. Move this conditional `SetPcm` call inside the push loop to cover repeated device-paced pushes. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/135901b88cbcfb7156d7fffe6d53b7c366236caa/src/libs/libAudio2.cpp)) <!-- cr-comment:v1:43ee122ef0d11c278e5725ae --> </dd> </dl> </blockquote></details> <details> <summary>tests/ShaderVertexMetadataTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `95-98`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Test the last valid SGPR pair at the hardware limit.** The new cases reject index 31 with a limit of 32. The successful cases use 64 and never try index 30. Add a success case at `SGPRS_MAX - 2` with the same hardware limit. Derive the rejected index from `SGPRS_MAX - 1` so the cases continue to test adjacent values if the limit changes. Also applies to: 101-102, 104-105 <!-- cr-comment:v1:01f05003ca95da63a2993cf5 --> </dd> </dl> </blockquote></details> <details> <summary>src/loader/guestInstructionPatcher.cpp: 1</summary><blockquote> <dl> <dd> <br> `1758-1762`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Performance & Scalability** · **Heavy lift** **Reuse the callee-discovery decode, or run it in parallel.** `AddDecodedCallees` runs `DecodeFunction` on every known function start, on one thread, before the parallel scan starts. When `protect_memory` is true, the parallel scan then calls `analyze` on every function again, and candidate functions are decoded a third time in the windowed decode pass. The comment at Line 1834 says the full decode takes about 9 s for Astro Bot on one core. Red-zone protection enabled therefore keeps one full single-threaded decode on the boot path, and the parallel scan cannot remove it. This applies to the Call of Duty: Black Ops II configuration that enables red-zone protection. Options: - Run the fixpoint passes over `pending` with the same worker pool. Merge the newly found callees after each pass. - Keep the decoded results from `AddDecodedCallees` for functions whose range did not change, and skip the scan decode for them. <!-- cr-comment:v1:b579310c5b3c7bc9573485fc --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a1fc5ae438ea343480c9850f585d8c0afed06241/.coderabbit.yaml>) - **Commit**: [a1fc5ae](<https://github.com/KytyPS5/KytyPS5/commit/a1fc5ae438ea343480c9850f585d8c0afed06241>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `0f7a734b-55a5-4c54-9b6e-a1adbcc899e3` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between a1fc5ae438ea343480c9850f585d8c0afed06241 and 135901b88cbcfb7156d7fffe6d53b7c366236caa. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 139</summary> <dl> <dd> <br> * `.github/workflows/build.yml` * `CMakeLists.txt` * `src/common/debugCounters.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/common/gpuStall.cpp` * `src/common/gpuStall.h` * `src/common/parallelFor.h` * `src/common/platform/sysFileIO.h` * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/common/systemFonts.cpp` * `src/common/systemFonts.h` * `src/common/threads.cpp` * `src/common/threads.h` * `src/emulator.cpp` * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/command_processor/pm4Handlers.cpp` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/guest_gpu/graphicsRun.h` * `src/graphics/guest_gpu/pm4.cpp` * `src/graphics/guest_gpu/pm4.h` * `src/graphics/guest_gpu/tile.cpp` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/rangeSet.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/streamBuffer.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.h` * `src/graphics/host_gpu/renderer/depthRenderTarget.cpp` * `src/graphics/host_gpu/renderer/image/image.cpp` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/image/imageView.cpp` * `src/graphics/host_gpu/renderer/image/tiler.cpp` * `src/graphics/host_gpu/renderer/image/tiler.h` * `src/graphics/host_gpu/renderer/meshSlices.h` * `src/graphics/host_gpu/renderer/pipeline/descriptorHeap.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptorHeap.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp` * `src/graphics/host_gpu/renderer/pipeline/shaders.cpp` * `src/graphics/host_gpu/renderer/rayTracing.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `src/graphics/host_gpu/renderer/renderContext.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/host_gpu/renderer/renderPssr.cpp` * `src/graphics/host_gpu/shaders/gpu_mesh_indirect.task` * `src/graphics/host_gpu/shaders/gpu_tiler_color_clear.comp` * `src/graphics/host_gpu/vulkanCommon.cpp` * `src/graphics/presentation/performanceOverlay.cpp` * `src/graphics/presentation/window/hostInput.cpp` * `src/graphics/presentation/window/hostInput.h` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/presentation/window/window.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.h` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/ir/Serialize.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/Value.h` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/shader.cpp` * `src/kernel/eventFlag.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/kernel/pthread.cpp` * `src/kernel/pthread.h` * `src/kernel/semaphore.cpp` * `src/libs/agc.cpp` * `src/libs/agc.h` * `src/libs/audio.cpp` * `src/libs/audio3d.cpp` * `src/libs/avPlayer.cpp` * `src/libs/dialog.cpp` * `src/libs/dialog.h` * `src/libs/guestPrintf.cpp` * `src/libs/libAgcDriver.cpp` * `src/libs/libAudio2.cpp` * `src/libs/libC.cpp` * `src/libs/libCes.cpp` * `src/libs/libFont.cpp` * `src/libs/libKernel.cpp` * `src/libs/libNet.cpp` * `src/libs/libRtc.cpp` * `src/libs/network.cpp` * `src/libs/network.h` * `src/libs/ngs2.cpp` * `src/loader/guestInstructionPatcher.cpp` * `src/loader/guestInstructionPatcher.h` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `src/main.cpp` * `tests/ArchiveFileTests.cpp` * `tests/AudioOut2PortTests.cpp` * `tests/AudioOutTimingTests.cpp` * `tests/AvPlayerFileTests.cpp` * `tests/CesTests.cpp` * `tests/GpuStallTests.cpp` * `tests/GuestInstructionPatchScanTests.cpp` * `tests/GuestPrintfTests.cpp` * `tests/Http2AbortRequestTests.cpp` * `tests/KernelFileSystemTests.cpp` * `tests/LibCEnvironmentTests.cpp` * `tests/Ngs2SamplerTests.cpp` * `tests/PthreadPriorityTests.cpp` * `tests/ResourceMaterializationTests.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/RtcFormatTests.cpp` * `tests/SaveDataDialogTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/ShaderVertexMetadataTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` * `tests/shaderCfgTests.cpp` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files not fully reviewed because they exceed a per-file size limit: 1</summary> <dl> <dd> <br> * tests/ShaderRecompilerComputeTests.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -45,0 +55,4 @@
m_owner.store(std::this_thread::get_id(), std::memory_order_relaxed);
}
void Unlock() {
m_owner.store({}, std::memory_order_relaxed);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:15 UTC · original

Minor · Stability & Availability · Quick win

Keep the owner until the final recursive unlock.

Mutex explicitly supports recursive locking. With Lock(); TryLock(); Unlock();, the thread still owns one level of the underlying mutex, but this store clears m_owner. IsHeldByCurrentThread() then incorrectly returns false. Recursive ownership ends only after all acquisition levels are released. (ece.uvic.ca)

This can bypass the supplied EmergencyShutdown same-thread guard. Track recursion depth for successful Lock and TryLock calls. Clear m_owner only when the depth reaches zero. Preserve the existing single-acquisition behavior.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646643276) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Keep the owner until the final recursive unlock.** `Mutex` explicitly supports recursive locking. With `Lock(); TryLock(); Unlock();`, the thread still owns one level of the underlying mutex, but this store clears `m_owner`. `IsHeldByCurrentThread()` then incorrectly returns false. Recursive ownership ends only after all acquisition levels are released. ([ece.uvic.ca](https://www.ece.uvic.ca/~frodo/cppbook/cppdraft/n4861/thread.mutex.recursive)) This can bypass the supplied `EmergencyShutdown` same-thread guard. Track recursion depth for successful `Lock` and `TryLock` calls. Clear `m_owner` only when the depth reaches zero. Preserve the existing single-acquisition behavior. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:467f9fc3a4f9add791d6f39c --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -77,2 +92,4 @@
uint64_t generations = 0;
Iterate<true>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) {
if (!is_written && !manager->IsModified<DirtySource::Cpu>(offset, bytes)) {
generations += manager->Generation();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:15 UTC · original

Major · Data Integrity & Integration · Quick win

Capture the clean state and generation under the same lock.

If a CPU invalidation occurs after Line 94 reads a clean page but before Line 95 reads its generation, this branch records the new generation without processing the dirty page. CPU invalidation can change that state under the region lock. (raw.githubusercontent.com)

The next identical call then matches the memo and skips the required upload. Without memoization, that call would detect the dirty page.

Hold manager->lock across the clean-state check and generation capture. This preserves the unchanged-page result and prevents a concurrent invalidation from being recorded as already processed.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646643285) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Quick win** **Capture the clean state and generation under the same lock.** If a CPU invalidation occurs after Line 94 reads a clean page but before Line 95 reads its generation, this branch records the new generation without processing the dirty page. CPU invalidation can change that state under the region lock. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/7d2b333b010751005297d315ac93a707cf6e1679/src/graphics/host_gpu/memoryTracker.cpp)) The next identical call then matches the memo and skips the required upload. Without memoization, that call would detect the dirty page. Hold `manager->lock` across the clean-state check and generation capture. This preserves the unchanged-page result and prevents a concurrent invalidation from being recorded as already processed. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:102652a368a2b8cb65cfcd03 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:15 UTC · original · edited 2026-11-20 19:40 UTC
On tests/MemoryTrackerTests.cpp line 429 (outdated):

@@ -406,6 +406,75 @@ void TestCpuDirtyUpload() {
   Release(memory);
 }
 
+// A repeated ForEachUploadRange is skipped only while its regions are
+// unchanged: a CPU write, a GPU unmark or a download in between makes the next
+// identical call run again, and a new tracker does not take an old one's skip.
+void TestRepeatedUploadSkip() {
+  uint8_t *memory = nullptr;
+  uint64_t address = 0;
+  uint64_t page_size = 0;
+  uint32_t ranges = 0;
+  uint32_t uploads = 0;
+  const auto upload = [&](MemoryTracker &tracker, bool written) {
+    ranges = 0;
+    tracker.ForEachUploadRange(
+        address, page_size, written,
+        [&](uint64_t, uint64_t) noexcept { ranges++; },
+        [&]() noexcept { uploads++; });
+  };
+  {
+    TrackerHarness harness;
+    auto &tracker = harness.tracker;
+    page_size = harness.page_manager.GetPageSize();
+    memory = Allocate(harness.page_manager, 2);

Major · Functional Correctness · Quick win

Use the supplied Allocate signature.

Line 429 passes two arguments, but the local helper at Line 263 accepts only uint64_t pages. This prevents the test executable from compiling against the supplied interface. Use Allocate(2), as the neighboring tests do.

✅ Addressed in commits 8fc3ff3 to b56e901

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646643289) · edited 2026-11-20 19:40 UTC On `tests/MemoryTrackerTests.cpp` line 429 (outdated): ```diff @@ -406,6 +406,75 @@ void TestCpuDirtyUpload() { Release(memory); } +// A repeated ForEachUploadRange is skipped only while its regions are +// unchanged: a CPU write, a GPU unmark or a download in between makes the next +// identical call run again, and a new tracker does not take an old one's skip. +void TestRepeatedUploadSkip() { + uint8_t *memory = nullptr; + uint64_t address = 0; + uint64_t page_size = 0; + uint32_t ranges = 0; + uint32_t uploads = 0; + const auto upload = [&](MemoryTracker &tracker, bool written) { + ranges = 0; + tracker.ForEachUploadRange( + address, page_size, written, + [&](uint64_t, uint64_t) noexcept { ranges++; }, + [&]() noexcept { uploads++; }); + }; + { + TrackerHarness harness; + auto &tracker = harness.tracker; + page_size = harness.page_manager.GetPageSize(); + memory = Allocate(harness.page_manager, 2); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Use the supplied Allocate signature.** Line 429 passes two arguments, but the local helper at Line 263 accepts only `uint64_t pages`. This prevents the test executable from compiling against the supplied interface. Use `Allocate(2)`, as the neighboring tests do. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2006df1902fd3f8b9a9b642e --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 8fc3ff3 to b56e901
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:15 UTC · original · reviewed

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)

Minor · Update mutex ownership across both condition-variable waits. · threads.cpp:150

src/common/threads.cpp:150
Minor · Stability & Availability · Quick win

Update mutex ownership across both condition-variable waits.

Both non-Windows waits pass m_mutex directly. condition_variable_any therefore releases and reacquires that object without calling Mutex::Unlock or Mutex::Lock. (ece.uvic.ca)

If thread B acquires and releases the mutex while thread A waits, B clears m_owner. After A resumes, A holds the mutex but IsHeldByCurrentThread() returns false. This also defeats the supplied EmergencyShutdown same-thread guard if invoked in that state.

Use a BasicLockable adapter that calls the ownership-tracking wrappers for both waits. Preserve notification and timeout behavior.

Also applies to: 169-169

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 8958064dad and 7d2b333b010751005297d315ac93a707cf6e1679.

Files selected for processing: 16

  • CMakeLists.txt
  • src/common/threads.cpp
  • src/common/threads.h
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/regionManager.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/libs/agc.cpp
  • src/libs/agc.h
  • tests/MemoryTrackerTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
Files not fully reviewed because they exceed a per-file size limit: 1

  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#pullrequestreview-5998079973) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 3** > [!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><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Update mutex ownership across both condition-variable waits. · <code>threads.cpp:150</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/common/threads.cpp:150` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** > > **Update mutex ownership across both condition-variable waits.** > > Both non-Windows waits pass `m_mutex` directly. `condition_variable_any` therefore releases and reacquires that object without calling `Mutex::Unlock` or `Mutex::Lock`. ([ece.uvic.ca](https://www.ece.uvic.ca/~frodo/cppbook/cppdraft/n4861/thread.condvarany.wait)) > > If thread B acquires and releases the mutex while thread A waits, B clears `m_owner`. After A resumes, A holds the mutex but `IsHeldByCurrentThread()` returns false. This also defeats the supplied `EmergencyShutdown` same-thread guard if invoked in that state. > > Use a BasicLockable adapter that calls the ownership-tracking wrappers for both waits. Preserve notification and timeout behavior. > > > > > > > Also applies to: 169-169 > > <!-- cr-comment:v1:a7d9c8b1745e268bfcbc4c81 --> > > </dd> > </dl> > </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a1fc5ae438ea343480c9850f585d8c0afed06241/.coderabbit.yaml>) - **Commit**: [a1fc5ae](<https://github.com/KytyPS5/KytyPS5/commit/a1fc5ae438ea343480c9850f585d8c0afed06241>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `721c94b2-2ee2-4ea1-a1e3-56049d84aec3` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 8958064dad8711894ed50e3f7438bf5674424def and 7d2b333b010751005297d315ac93a707cf6e1679. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 16</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/common/threads.cpp` * `src/common/threads.h` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/memoryTracker.h` * `src/graphics/host_gpu/regionManager.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/libs/agc.cpp` * `src/libs/agc.h` * `tests/MemoryTrackerTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files not fully reviewed because they exceed a per-file size limit: 1</summary> <dl> <dd> <br> * tests/ShaderRecompilerComputeTests.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=bb2328e1-b2db-49f1-b4d3-3313ec114717 attempt=a42839dd-a660-4764-a0ca-5bb2779d6f9f batch=1/1 -->
@ -274,6 +323,14 @@ PageManager::PageManager(): m_impl(std::make_unique<Impl>()) {}
PageManager::~PageManager() = default;
uint64_t PageManager::GetPageSize() const {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original · edited 2026-11-20 21:30 UTC

Critical · Functional Correctness · Quick win

Declare GetPageSize in PageManager, or remove its definition.

PageManager in src/graphics/host_gpu/pageManager.h does not declare GetPageSize. The out-of-class definition at src/graphics/host_gpu/pageManager.cpp:326 therefore names a member that does not exist. The compiler rejects this in every build that compiles pageManager.cpp.

Add uint64_t GetPageSize() const; to the public section of PageManager. If the method is not needed, remove the definition at pageManager.cpp:326 instead.

✅ Addressed in commits d6dc67d to 2577e26

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991047) · edited 2026-11-20 21:30 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/critical-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Critical** · **Functional Correctness** · **Quick win** **Declare `GetPageSize` in `PageManager`, or remove its definition.** `PageManager` in `src/graphics/host_gpu/pageManager.h` does not declare `GetPageSize`. The out-of-class definition at `src/graphics/host_gpu/pageManager.cpp:326` therefore names a member that does not exist. The compiler rejects this in every build that compiles `pageManager.cpp`. Add `uint64_t GetPageSize() const;` to the public section of `PageManager`. If the method is not needed, remove the definition at `pageManager.cpp:326` instead. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b59e882f2f64e92289ac0b97 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits d6dc67d to 2577e26
@ -119,0 +248,4 @@
return address < end;
}
const auto first_boundary = Common::AlignUp(begin, TRACKER_PAGE_SIZE);
return first_boundary < end && first_boundary < address + size;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original

Minor · Data Integrity & Integration · Quick win

Dirty the image when a sequential write overwrites its head bytes.

SequentialWriteReachesImage returns false for a write that starts before the image and ends inside the image's first tracker page. The bytes from the image start through the write end are still overwritten. InvalidateCpuAliases then untracks the image head without marking the image CPU dirty. The fill and copy paths in bufferCache.cpp write the new bytes to guest memory without updating the native image. Sampling that GPU-written image can return the old texels for those bytes.

The sequential path must mark the image CPU dirty when the write overlaps any image byte. The ordinary Overlaps path already does this. Apply the same rule here, or update the native image from the written bytes. Keep the other sequential cases unchanged.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991055) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Dirty the image when a sequential write overwrites its head bytes.** `SequentialWriteReachesImage` returns `false` for a write that starts before the image and ends inside the image's first tracker page. The bytes from the image start through the write end are still overwritten. `InvalidateCpuAliases` then untracks the image head without marking the image CPU dirty. The fill and copy paths in `bufferCache.cpp` write the new bytes to guest memory without updating the native image. Sampling that GPU-written image can return the old texels for those bytes. The sequential path must mark the image CPU dirty when the write overlaps any image byte. The ordinary `Overlaps` path already does this. Apply the same rule here, or update the native image from the written bytes. Keep the other sequential cases unchanged. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2f687ded4dd7bfa80ecd8a83 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -71,0 +92,4 @@
// Suspends a range, or unmaps it like UnmapNow once shutdown has begun.
void SuspendNow(uint64_t vaddr, uint64_t size);
[[nodiscard]] bool NeedsUnmapDrain(uint64_t vaddr, uint64_t size);
[[nodiscard]] bool IsUnmapDrainRedundant(uint64_t vaddr, uint64_t size);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original · edited 2026-11-20 21:30 UTC

Critical · Functional Correctness · Quick win

Restore the WaitWriteBacks member declaration.

renderContext.cpp defines RenderContext::WaitWriteBacks at Line 87. HandleFault and InvalidateMemory still call it. The class no longer declares the member, so this translation unit cannot compile. Restore [[nodiscard]] bool WaitWriteBacks(uint64_t vaddr, uint64_t size); in the private section.

✅ Addressed in commits d6dc67d to 2577e26

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991060) · edited 2026-11-20 21:30 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/critical-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Critical** · **Functional Correctness** · **Quick win** **Restore the `WaitWriteBacks` member declaration.** `renderContext.cpp` defines `RenderContext::WaitWriteBacks` at Line 87. `HandleFault` and `InvalidateMemory` still call it. The class no longer declares the member, so this translation unit cannot compile. Restore `[[nodiscard]] bool WaitWriteBacks(uint64_t vaddr, uint64_t size);` in the private section. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:390ca08cfcf4e43e8fc34eee --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits d6dc67d to 2577e26
@ -1190,0 +1560,4 @@
#if defined(KYTY_VIRTUAL_MEMORY_ALLOCATION_TESTS)
if (g_test_fail_next_physical_memory_map) {
g_test_fail_next_physical_memory_map = false;
return false;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original

Major · Stability & Availability · Heavy lift

Return a recoverable error for the injected map failure.

RunRemapFailedAfterView expects the map to return an error and leave the address usable for a retry. This hook returns false after the host view is installed, but the check at Line 2741 terminates instead of returning to the test. Roll back the new view and preserve the prior reservation before returning an error. Let ResumeCandidateScope cancel the exposed candidate so the next map uses the normal path.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991066) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Return a recoverable error for the injected map failure.** `RunRemapFailedAfterView` expects the map to return an error and leave the address usable for a retry. This hook returns `false` after the host view is installed, but the check at Line 2741 terminates instead of returning to the test. Roll back the new view and preserve the prior reservation before returning an error. Let `ResumeCandidateScope` cancel the exposed candidate so the next map uses the normal path. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:64819052df4ffdd5c9bec771 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original
On src/kernel/memory.cpp line 1564 (outdated):

@@ -1187,6 +1555,13 @@ bool PhysicalMemory::Release(uint64_t start, size_t len) {
 }
 
 bool PhysicalMemory::Map(uint64_t vaddr, uint64_t phys_addr, size_t len) {
+#if defined(KYTY_VIRTUAL_MEMORY_ALLOCATION_TESTS)
+	if (g_test_fail_next_physical_memory_map) {
+		g_test_fail_next_physical_memory_map = false;
+		return false;
+	}
+#endif
+	Common::LockGuard lock(m_mutex);

Critical · Functional Correctness · Quick win

Declare or remove m_mutex in PhysicalMemory::Map. The identifier does not resolve.

PhysicalMemory declares no m_mutex member, and it has no base class that could provide one. memory.h and memoryAddressSpace.inc declare no such member either. The Common::LockGuard lock(m_mutex); at line 1564 therefore fails to compile in any build that includes this file.

Fix this in one of two ways:

  • Declare the intended lock as a member of PhysicalMemory and use it for m_mappings and m_physical.
  • Remove the line if the lock that governs these structures is already held by callers of Map.

Before you choose, confirm which lock protects these structures. Do not acquire a lock that the caller already holds, because a non-recursive mutex deadlocks when acquired twice.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991072) On `src/kernel/memory.cpp` line 1564 (outdated): ```diff @@ -1187,6 +1555,13 @@ bool PhysicalMemory::Release(uint64_t start, size_t len) { } bool PhysicalMemory::Map(uint64_t vaddr, uint64_t phys_addr, size_t len) { +#if defined(KYTY_VIRTUAL_MEMORY_ALLOCATION_TESTS) + if (g_test_fail_next_physical_memory_map) { + g_test_fail_next_physical_memory_map = false; + return false; + } +#endif + Common::LockGuard lock(m_mutex); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/critical-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Critical** · **Functional Correctness** · **Quick win** **Declare or remove `m_mutex` in `PhysicalMemory::Map`. The identifier does not resolve.** `PhysicalMemory` declares no `m_mutex` member, and it has no base class that could provide one. `memory.h` and `memoryAddressSpace.inc` declare no such member either. The `Common::LockGuard lock(m_mutex);` at line 1564 therefore fails to compile in any build that includes this file. Fix this in one of two ways: - Declare the intended lock as a member of `PhysicalMemory` and use it for `m_mappings` and `m_physical`. - Remove the line if the lock that governs these structures is already held by callers of `Map`. Before you choose, confirm which lock protects these structures. Do not acquire a lock that the caller already holds, because a non-recursive mutex deadlocks when acquired twice. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b1d3e3b5c777cc0a26bed94a --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original · edited 2026-11-20 21:30 UTC
On src/kernel/memory.cpp line 2182 (outdated):

@@ -1789,18 +2179,19 @@ static void UnmapMemoryOwner(const VirtualRanges::Range& range, bool keep_pool_r
 		EXIT("failed to unmap guest memory: addr=0x%016" PRIx64 " size=0x%016" PRIx64 "\n", vaddr,
 		     len);
 	}
+}

Critical · Functional Correctness · Quick win

Keep the unmap bookkeeping inside UnmapMemoryOwner.

This brace ends the function before g_virtual_ranges->Remove. The remaining statements are at namespace scope and cannot use vaddr, len, or range. Remove the extra brace so a successful unmap updates the virtual range and pool accounting before the function returns.

✅ Addressed in commits d6dc67d to 2577e26

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991078) · edited 2026-11-20 21:30 UTC On `src/kernel/memory.cpp` line 2182 (outdated): ```diff @@ -1789,18 +2179,19 @@ static void UnmapMemoryOwner(const VirtualRanges::Range& range, bool keep_pool_r EXIT("failed to unmap guest memory: addr=0x%016" PRIx64 " size=0x%016" PRIx64 "\n", vaddr, len); } +} ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/critical-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Critical** · **Functional Correctness** · **Quick win** **Keep the unmap bookkeeping inside `UnmapMemoryOwner`.** This brace ends the function before `g_virtual_ranges->Remove`. The remaining statements are at namespace scope and cannot use `vaddr`, `len`, or `range`. Remove the extra brace so a successful unmap updates the virtual range and pool accounting before the function returns. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:292bdf033c197e944b92e161 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits d6dc67d to 2577e26
@ -2285,3 +2727,1 @@
if (g_guest_address_space->MapBacking(target, len, direct_memory_start, mode,
&shared_failure)) {
out_addr = target;
if (MapBackingForGuest(target, len, direct_memory_start, mode, &shared_failure)) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original

Major · Stability & Availability · Heavy lift

Do not wait for GPU cache cancels while g_memory_state_mutex is held exclusively.

MapBackingForGuest runs under the exclusive g_memory_state_mutex lock (src/kernel/memory.cpp:2729-2737). When a new physical mapping overlaps a suspended entry, that entry's cancel runs through CancelSuspendedWhere and CancelGpuRange (memory.cpp:1028-1041, 255). RenderContext::CancelSuspendedMemory requires the GPU thread (renderContext.cpp:150-152). The guest thread therefore waits on the GPU thread while it holds the lock.

The GPU thread can reach ClampRangeSize while it records a draw (renderDraw.cpp:715, descriptors.cpp:844). When a request misses the lock-free fast path, ClampRangeSize takes a shared lock on g_memory_state_mutex (memory.cpp:1104). If the guest thread holds that lock exclusively, neither thread can proceed. The guest thread waits for the cancel, and the GPU thread waits for the lock.

The stated lock contract at memory.cpp:430-432 forbids a graphics call under this lock. Cancels that a map triggers must run after the state lock is released. The change must keep the table and virtual-range state consistent while the GPU cache cancel runs outside the lock. The exact split is not prescribed here.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991084) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Do not wait for GPU cache cancels while `g_memory_state_mutex` is held exclusively.** `MapBackingForGuest` runs under the exclusive `g_memory_state_mutex` lock (`src/kernel/memory.cpp:2729-2737`). When a new physical mapping overlaps a suspended entry, that entry's cancel runs through `CancelSuspendedWhere` and `CancelGpuRange` (`memory.cpp:1028-1041`, `255`). `RenderContext::CancelSuspendedMemory` requires the GPU thread (`renderContext.cpp:150-152`). The guest thread therefore waits on the GPU thread while it holds the lock. The GPU thread can reach `ClampRangeSize` while it records a draw (`renderDraw.cpp:715`, `descriptors.cpp:844`). When a request misses the lock-free fast path, `ClampRangeSize` takes a shared lock on `g_memory_state_mutex` (`memory.cpp:1104`). If the guest thread holds that lock exclusively, neither thread can proceed. The guest thread waits for the cancel, and the GPU thread waits for the lock. The stated lock contract at `memory.cpp:430-432` forbids a graphics call under this lock. Cancels that a map triggers must run after the state lock is released. The change must keep the table and virtual-range state consistent while the GPU cache cancel runs outside the lock. The exact split is not prescribed here. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6c64498cad8723ad99289756 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -2323,0 +2765,4 @@
// Resuming happens here, after the view exists and before the guest call returns. Between the
// view and this point watched pages are not protected, which is why it must not be later.
if (!ResumeSuspendedGpuRange(out_addr, len, static_cast<uint64_t>(direct_memory_start))) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original

Major · Data Integrity & Integration · Heavy lift

Protect retained cache entries before exposing a writable remap.

A second guest thread can store through the fresh view after MapBackingForGuest succeeds but before ResumeMemory restores page protection. The store does not fault, so the GPU can reuse buffer bytes from before the store. Returning from the mapping call only after protection is restored does not protect other threads during that interval. Either expose the view with the required tracking protection already in place or invalidate retained bytes for remaps that expose an untracked writable view.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991097) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** **Protect retained cache entries before exposing a writable remap.** A second guest thread can store through the fresh view after `MapBackingForGuest` succeeds but before `ResumeMemory` restores page protection. The store does not fault, so the GPU can reuse buffer bytes from before the store. Returning from the mapping call only after protection is restored does not protect other threads during that interval. Either expose the view with the required tracking protection already in place or invalidate retained bytes for remaps that expose an untracked writable view. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e77ff8eb06d4808d69b6e9bb --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original · edited 2026-11-20 21:31 UTC
On src/kernel/memory.cpp line 3723 (outdated):

@@ -3205,31 +3719,33 @@ int KYTY_SYSV_ABI KernelMemoryPoolCommit(void* addr, size_t len, int type, int p
 		if (!g_pooled_memory->Allocate(vaddr, len, &mappings)) {
 			return KERNEL_ERROR_ENOMEM;
 		}
-		// Validation precedes the first backing map; failing after it is an emulator fault.
-		for (const auto& mapping: mappings) {
-			auto failure_reason = GuestBackingStore::FailureReason::None;
-			if (!g_guest_address_space->MapBacking(mapping.vaddr, mapping.size, mapping.phys_addr,
-			                                       mode, &failure_reason)) {
-				EXIT("failed to map pooled memory: %s\n",
-				     GuestBackingStore::GetFailureReasonName(failure_reason));
-			}
-		}
-		for (const auto& range: ranges) {
-			EXIT_IF(!g_virtual_ranges->ReplaceSpan(range.start, range.size,
-			                                       VirtualRangeType::PoolReserved, 0, prot, type,
-			                                       VirtualRangeType::Pooled, range.name));
+		return KERNEL_ERROR_ENOMEM;
+	}

Critical · Functional Correctness · Quick win

Keep the pool commit in scope and return ENOMEM only on allocation failure.

The closing brace puts mappings out of scope before the backing-map loop, so the code cannot compile. The extra return also exits after a successful Allocate, which has already recorded ownership. Remove the extra return and keep the mapping and virtual-range updates inside the state-lock block. Leave GPU notification and callbacks outside that block.

✅ Addressed in commits d6dc67d to 2577e26

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991106) · edited 2026-11-20 21:31 UTC On `src/kernel/memory.cpp` line 3723 (outdated): ```diff @@ -3205,31 +3719,33 @@ int KYTY_SYSV_ABI KernelMemoryPoolCommit(void* addr, size_t len, int type, int p if (!g_pooled_memory->Allocate(vaddr, len, &mappings)) { return KERNEL_ERROR_ENOMEM; } - // Validation precedes the first backing map; failing after it is an emulator fault. - for (const auto& mapping: mappings) { - auto failure_reason = GuestBackingStore::FailureReason::None; - if (!g_guest_address_space->MapBacking(mapping.vaddr, mapping.size, mapping.phys_addr, - mode, &failure_reason)) { - EXIT("failed to map pooled memory: %s\n", - GuestBackingStore::GetFailureReasonName(failure_reason)); - } - } - for (const auto& range: ranges) { - EXIT_IF(!g_virtual_ranges->ReplaceSpan(range.start, range.size, - VirtualRangeType::PoolReserved, 0, prot, type, - VirtualRangeType::Pooled, range.name)); + return KERNEL_ERROR_ENOMEM; + } ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/critical-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Critical** · **Functional Correctness** · **Quick win** **Keep the pool commit in scope and return `ENOMEM` only on allocation failure.** The closing brace puts `mappings` out of scope before the backing-map loop, so the code cannot compile. The extra return also exits after a successful `Allocate`, which has already recorded ownership. Remove the extra return and keep the mapping and virtual-range updates inside the state-lock block. Leave GPU notification and callbacks outside that block. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:81d78e8bdbb511b68d208f38 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits d6dc67d to 2577e26
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original · edited 2026-11-20 21:31 UTC
On src/kernel/memory.cpp line 3728 (outdated):

@@ -3205,31 +3719,33 @@ int KYTY_SYSV_ABI KernelMemoryPoolCommit(void* addr, size_t len, int type, int p
 		if (!g_pooled_memory->Allocate(vaddr, len, &mappings)) {
 			return KERNEL_ERROR_ENOMEM;
 		}
-		// Validation precedes the first backing map; failing after it is an emulator fault.
-		for (const auto& mapping: mappings) {
-			auto failure_reason = GuestBackingStore::FailureReason::None;
-			if (!g_guest_address_space->MapBacking(mapping.vaddr, mapping.size, mapping.phys_addr,
-			                                       mode, &failure_reason)) {
-				EXIT("failed to map pooled memory: %s\n",
-				     GuestBackingStore::GetFailureReasonName(failure_reason));
-			}
-		}
-		for (const auto& range: ranges) {
-			EXIT_IF(!g_virtual_ranges->ReplaceSpan(range.start, range.size,
-			                                       VirtualRangeType::PoolReserved, 0, prot, type,
-			                                       VirtualRangeType::Pooled, range.name));
+		return KERNEL_ERROR_ENOMEM;
+	}
+	// Validation precedes the first backing map; failing after it is an emulator fault.
+	for (const auto& mapping: mappings) {
+		auto failure_reason = GuestBackingStore::FailureReason::None;
+		if (!g_guest_address_space->MapBacking(mapping.vaddr, mapping.size, mapping.phys_addr, mode,
+		                                       &failure_reason)) {

Major · Data Integrity & Integration · Heavy lift

Cancel suspended GPU caches before pool commit maps physical pages.

The pool commit maps each allocated fragment with a direct MapBacking call. Unlike MapBackingForGuest, this path does not cancel suspended GPU entries whose physical range overlaps the new view. After a direct allocation is released, its physical blocks return to the physical allocator, but its suspended entry still records the old physical offset. Pool allocation can then return those pages. A CPU write through the pooled view can change them. Releasing the pool and remapping the original direct range exactly can then resume the cache with stale bytes.

Route the pool commit through the same physical-overlap cancellation that MapBackingForGuest performs, before the new view is exposed. The MapBackingForGuest comment states that cancellation runs while no address-space lock is held, because it can wait on the GPU. Keep the pool path consistent with that, so the cancellation does not run under g_memory_state_mutex.

✅ Addressed in commits d6dc67d to 2577e26

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991109) · edited 2026-11-20 21:31 UTC On `src/kernel/memory.cpp` line 3728 (outdated): ```diff @@ -3205,31 +3719,33 @@ int KYTY_SYSV_ABI KernelMemoryPoolCommit(void* addr, size_t len, int type, int p if (!g_pooled_memory->Allocate(vaddr, len, &mappings)) { return KERNEL_ERROR_ENOMEM; } - // Validation precedes the first backing map; failing after it is an emulator fault. - for (const auto& mapping: mappings) { - auto failure_reason = GuestBackingStore::FailureReason::None; - if (!g_guest_address_space->MapBacking(mapping.vaddr, mapping.size, mapping.phys_addr, - mode, &failure_reason)) { - EXIT("failed to map pooled memory: %s\n", - GuestBackingStore::GetFailureReasonName(failure_reason)); - } - } - for (const auto& range: ranges) { - EXIT_IF(!g_virtual_ranges->ReplaceSpan(range.start, range.size, - VirtualRangeType::PoolReserved, 0, prot, type, - VirtualRangeType::Pooled, range.name)); + return KERNEL_ERROR_ENOMEM; + } + // Validation precedes the first backing map; failing after it is an emulator fault. + for (const auto& mapping: mappings) { + auto failure_reason = GuestBackingStore::FailureReason::None; + if (!g_guest_address_space->MapBacking(mapping.vaddr, mapping.size, mapping.phys_addr, mode, + &failure_reason)) { ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** **Cancel suspended GPU caches before pool commit maps physical pages.** The pool commit maps each allocated fragment with a direct `MapBacking` call. Unlike `MapBackingForGuest`, this path does not cancel suspended GPU entries whose physical range overlaps the new view. After a direct allocation is released, its physical blocks return to the physical allocator, but its suspended entry still records the old physical offset. Pool allocation can then return those pages. A CPU write through the pooled view can change them. Releasing the pool and remapping the original direct range exactly can then resume the cache with stale bytes. Route the pool commit through the same physical-overlap cancellation that `MapBackingForGuest` performs, before the new view is exposed. The `MapBackingForGuest` comment states that cancellation runs while no address-space lock is held, because it can wait on the GPU. Keep the pool path consistent with that, so the cancellation does not run under `g_memory_state_mutex`. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e3b4441ebaafc8b239f21be3 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits d6dc67d to 2577e26
@ -3413,0 +4786,4 @@
TestFailNextPhysicalMemoryUnmap();
} else {
TestFailGuestBackingStoreUnmapAfter(0);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original

Major · Functional Correctness · Heavy lift

Connect the release failure hooks to the unmap operations.

TestFailGuestBackingStoreUnmapAfter(0) and TestFailNextPhysicalMemoryUnmap() set injection state, but neither unmap implementation reads it. The checked release therefore returns OK for this valid mapping. CheckFailed stops the suite before it checks cancellation or restored data. Connect each hook at its intended stage and make the checked release return an error after restoring any view it already removed. Keep the release without injection successful. (raw.githubusercontent.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4646991117) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Connect the release failure hooks to the unmap operations.** `TestFailGuestBackingStoreUnmapAfter(0)` and `TestFailNextPhysicalMemoryUnmap()` set injection state, but neither unmap implementation reads it. The checked release therefore returns `OK` for this valid mapping. `CheckFailed` stops the suite before it checks cancellation or restored data. Connect each hook at its intended stage and make the checked release return an error after restoring any view it already removed. Keep the release without injection successful. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/b56e9015c74b275912ab8237091f01d3ddcda726/src/kernel/memory.cpp)) <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d3235655b713940c329b3708 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 19:52 UTC · original · reviewed

Actionable comments posted: 11

Caution

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

⚠️ Outside diff range comments (4)

Major · Preserve batched GPU unmaps when cache reuse is off. · memory.cpp:2348

src/kernel/memory.cpp:2348
Major · Functional Correctness · Quick win

Preserve batched GPU unmaps when cache reuse is off.

Releasing two adjacent direct views now calls SuspendOrUnmapGpuRange once per view. With reuse off, that emits two unmap events. TestDirectReleaseUnmapsGpuRuns requires one event covering the combined span, so the full test run stops before the new remap cases. Use the existing contiguous-run unmap path when reuse is off. Keep per-view suspension when reuse is on so each alias retains its own remap identity. (raw.githubusercontent.com)

Minor · Check that synchronization uploads only the written page. · ShaderRecompilerComputeTests.cpp:7404

tests/ShaderRecompilerComputeTests.cpp:7404
Minor · Functional Correctness · Quick win

Check that synchronization uploads only the written page.

The dirty-mask assertion runs before synchronization. If synchronization uploads all four pages, the three unchanged pages still contain the expected words and RequireNativePages passes. Enable BufferUploadBytes for this probe and assert that the counter increases by kSuspendPageSize across the synchronization. Keep the native-word checks to verify the uploaded data. (raw.githubusercontent.com)

Minor · Keep the GPU object installed during the stopping-state… · ShaderRecompilerComputeTests.cpp:7870

tests/ShaderRecompilerComputeTests.cpp:7870
Minor · Functional Correctness · Quick win

Keep the GPU object installed during the stopping-state release.

ShutdownGpu() resets the GPU pointer before KeepRelease runs. The test therefore exercises the absent-GPU fallback, not the stopping-GPU fallback. If SuspendMemory stops checking IsStopping() but still handles a null GPU pointer, this test passes. Call rig.context.GetGpu().Shutdown() before the release and remap, as the suspend fixture does, then call ShutdownGpu() after the checks. (raw.githubusercontent.com)

Minor · Make the baseline write order explicit instead of… · ShaderRecompilerComputeTests.cpp:3806-3807

tests/ShaderRecompilerComputeTests.cpp:3806-3807
Minor · Functional Correctness · Quick win

Make the baseline write order explicit instead of relying on std::fill_n.

std::fill_n specifies the values written, not the order of the stores. At lines 3806-3807, the baseline therefore depends on an unspecified order. The image starts at slot + 1.5 pages, and the fill ends at slot + 1.75 pages. The second protected page contains bytes before and inside the image. If a build stores to an in-image address first, the first fault on that page lands inside the image. The check at lines 3817-3820 then fails because the baseline image is CPU-dirty. That failure reflects store order, not the bulk invalidation under test.

The baseline must write each protected page in ascending address order, and the test should enforce that order. For example, use ascending volatile stores. Keep the existing fault-count and head-page assertions.

Nitpick comments: 1

tests/MemoryTrackerTests.cpp: 1

472-472: Trivial · Maintainability & Code Quality · Quick win

Make the fresh-tracker check distinguish tracker identity from generation.

The check at Line 471 still passes if ForEachUploadRange stops comparing tracker IDs. The fresh tracker has no region, so its generation lookup returns zero. The previous tracker records a nonzero generation. Prepare the second tracker by uploading the neighboring page in the same region. Leave the target page dirty and match the memo's address, size, write mode, and generation before testing the upload. (raw.githubusercontent.com)

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7d2b333b010751005297d315ac93a707cf6e1679 and b56e9015c74b275912ab8237091f01d3ddcda726.

Files selected for processing: 20

  • CMakeLists.txt
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/threads.h
  • src/graphics/host_gpu/pageManager.cpp
  • src/graphics/host_gpu/pageManager.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • 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/renderContext.h
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/main.cpp
  • tests/MemoryTrackerTests.cpp
  • tests/PageManagerTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp
Files not fully reviewed because they exceed a per-file size limit: 1

  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#pullrequestreview-5998515336) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 11** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (4)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Preserve batched GPU unmaps when cache reuse is off. · <code>memory.cpp:2348</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/kernel/memory.cpp:2348` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** > > **Preserve batched GPU unmaps when cache reuse is off.** > > Releasing two adjacent direct views now calls `SuspendOrUnmapGpuRange` once per view. With reuse off, that emits two unmap events. `TestDirectReleaseUnmapsGpuRuns` requires one event covering the combined span, so the full test run stops before the new remap cases. Use the existing contiguous-run unmap path when reuse is off. Keep per-view suspension when reuse is on so each alias retains its own remap identity. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/b56e9015c74b275912ab8237091f01d3ddcda726/src/kernel/memory.cpp)) > > <!-- cr-comment:v1:31cc3c3a5b6c0ef8a94d484e --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Check that synchronization uploads only the written page. · <code>ShaderRecompilerComputeTests.cpp:7404</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:7404` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Check that synchronization uploads only the written page.** > > The dirty-mask assertion runs before synchronization. If synchronization uploads all four pages, the three unchanged pages still contain the expected words and `RequireNativePages` passes. Enable `BufferUploadBytes` for this probe and assert that the counter increases by `kSuspendPageSize` across the synchronization. Keep the native-word checks to verify the uploaded data. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/b56e9015c74b275912ab8237091f01d3ddcda726/src/graphics/host_gpu/renderer/cache/bufferCache.cpp)) > > <!-- cr-comment:v1:7e642efaff6757077392b304 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Keep the GPU object installed during the stopping-state… · <code>ShaderRecompilerComputeTests.cpp:7870</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:7870` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Keep the GPU object installed during the stopping-state release.** > > `ShutdownGpu()` resets the GPU pointer before `KeepRelease` runs. The test therefore exercises the absent-GPU fallback, not the stopping-GPU fallback. If `SuspendMemory` stops checking `IsStopping()` but still handles a null GPU pointer, this test passes. Call `rig.context.GetGpu().Shutdown()` before the release and remap, as the suspend fixture does, then call `ShutdownGpu()` after the checks. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/b56e9015c74b275912ab8237091f01d3ddcda726/src/graphics/host_gpu/renderer/renderContext.cpp)) > > <!-- cr-comment:v1:ec13e5007df7268629e37cd2 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Make the baseline write order explicit instead of… · <code>ShaderRecompilerComputeTests.cpp:3806-3807</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:3806-3807` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Make the baseline write order explicit instead of relying on `std::fill_n`.** > > `std::fill_n` specifies the values written, not the order of the stores. At lines 3806-3807, the baseline therefore depends on an unspecified order. The image starts at `slot + 1.5` pages, and the fill ends at `slot + 1.75` pages. The second protected page contains bytes before and inside the image. If a build stores to an in-image address first, the first fault on that page lands inside the image. The check at lines 3817-3820 then fails because the baseline image is CPU-dirty. That failure reflects store order, not the bulk invalidation under test. > > The baseline must write each protected page in ascending address order, and the test should enforce that order. For example, use ascending `volatile` stores. Keep the existing fault-count and head-page assertions. > > <!-- cr-comment:v1:cf0a2da0fb73e9c5c273480f --> > > </dd> > </dl> > </blockquote></details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/MemoryTrackerTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `472-472`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Make the fresh-tracker check distinguish tracker identity from generation.** The check at Line 471 still passes if `ForEachUploadRange` stops comparing tracker IDs. The fresh tracker has no region, so its generation lookup returns zero. The previous tracker records a nonzero generation. Prepare the second tracker by uploading the neighboring page in the same region. Leave the target page dirty and match the memo's address, size, write mode, and generation before testing the upload. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/b56e9015c74b275912ab8237091f01d3ddcda726/src/graphics/host_gpu/memoryTracker.h)) <!-- cr-comment:v1:93d13d9e1e7eb0359391e651 --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a1fc5ae438ea343480c9850f585d8c0afed06241/.coderabbit.yaml>) - **Commit**: [a1fc5ae](<https://github.com/KytyPS5/KytyPS5/commit/a1fc5ae438ea343480c9850f585d8c0afed06241>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `a705a295-e41b-4323-8b89-144463633f2c` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 7d2b333b010751005297d315ac93a707cf6e1679 and b56e9015c74b275912ab8237091f01d3ddcda726. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 20</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/common/threads.h` * `src/graphics/host_gpu/pageManager.cpp` * `src/graphics/host_gpu/pageManager.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `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/renderContext.h` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/main.cpp` * `tests/MemoryTrackerTests.cpp` * `tests/PageManagerTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files not fully reviewed because they exceed a per-file size limit: 1</summary> <dl> <dd> <br> * tests/ShaderRecompilerComputeTests.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=d94f04e2-2378-4cf4-aea9-245b59b45387 attempt=6564057a-ca35-417a-9bf3-834af4565f27 batch=1/1 -->
@ -39,0 +46,4 @@
// A clear code is key << ColorClearKeyShift, so the code bits below the shift are always clear
// in the DCC (0x00, 0x20, 0x40, 0x80 and 0xc0) and CMask (0x00) codes DecodeColorClear accepts.
// The steady state code 0xff has them set, so it skips the decode.
constexpr uint32_t ColorClearKeyShift = 5;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 21:45 UTC · original

Major · Functional Correctness · Quick win

Admit 0x10 before the low-bit rejection in the CPU color-clear filter.

MaterializeColorClear skips any code with low bits set, so a slice filled with the accepted 0x10 register-clear code never clears. The GPU predicate path already maps 0x10 to the 0x20 slot, so only the CPU filter needs the change. The byte comparison must still use the original code value.

Suggested fix

 		const auto code    = codes[slice];
-		if ((code & ColorClearCodeLowBits) != 0) {
+		if ((code & ColorClearCodeLowBits) != 0 && code != 0x10) {
 			continue;
 		}
**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 21:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4648072956) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Admit `0x10` before the low-bit rejection in the CPU color-clear filter.** `MaterializeColorClear` skips any code with low bits set, so a slice filled with the accepted `0x10` register-clear code never clears. The GPU predicate path already maps `0x10` to the `0x20` slot, so only the CPU filter needs the change. The byte comparison must still use the original `code` value. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff const auto code = codes[slice]; - if ((code & ColorClearCodeLowBits) != 0) { + if ((code & ColorClearCodeLowBits) != 0 && code != 0x10) { continue; } ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7bacc39d3e2164a7a41ce4c6 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -952,0 +1318,4 @@
namespace Counters = Common::DebugCounters;
const auto& info = image.info;
const auto first = range.address - info.data.address;
const auto rounded = RoundRefreshRange(info, first, first + range.size);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 21:45 UTC · original

Minor · Functional Correctness · Quick win

Keep the linear partial refresh from overwriting image texels outside the marked buffer range.

RoundRefreshRange widens the marked range to 4-byte boundaries. For a sub-word storage-buffer write, the widened window includes bytes that the buffer write did not mark. The image still owns those texels: InvalidateBufferWrite keeps gpu_mod set and documents the image as newer outside the range. RefreshLinearRange then copies buffer or guest bytes over them. An R8 image with a one-byte marked range at its base can have three neighboring texels replaced with stale data.

The linear path must copy only the marked bytes, at the granularity the upload permits, or otherwise keep the neighboring image texels unchanged. The tiled path in PlanTiledRefresh uses the same rounding and can carry the widened window into its merge. Choose the granularity change in one place so both paths share the rule.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 21:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4648072969) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Keep the linear partial refresh from overwriting image texels outside the marked buffer range.** `RoundRefreshRange` widens the marked range to 4-byte boundaries. For a sub-word storage-buffer write, the widened window includes bytes that the buffer write did not mark. The image still owns those texels: `InvalidateBufferWrite` keeps `gpu_mod` set and documents the image as newer outside the range. `RefreshLinearRange` then copies buffer or guest bytes over them. An R8 image with a one-byte marked range at its base can have three neighboring texels replaced with stale data. The linear path must copy only the marked bytes, at the granularity the upload permits, or otherwise keep the neighboring image texels unchanged. The tiled path in `PlanTiledRefresh` uses the same rounding and can carry the widened window into its merge. Choose the granularity change in one place so both paths share the rule. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:427cbb5b00cf276f29f5b318 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -3216,0 +3704,4 @@
// Validation precedes the first backing map; failing after it is an emulator fault.
for (const auto& mapping: mappings) {
auto failure_reason = GuestBackingStore::FailureReason::None;
if (!MapBackingForGuest(mapping.vaddr, mapping.size, mapping.phys_addr, mode,
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 21:45 UTC · original

Major · Stability & Availability · Heavy lift

Hold the state lock while installing pooled backing views.

MapBackingForGuest reaches GuestAddressSpace::MapBacking without g_memory_state_mutex. A GPU thread in ProtectTransient can hold the shared lock and traverse m_mapped while the pool commit inserts into that tree. The operation lock does not protect that reader.

Cancel suspended overlaps before taking the exclusive state lock. Then hold the state lock across the backing maps and virtual-range publication.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 21:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4648072974) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Hold the state lock while installing pooled backing views.** `MapBackingForGuest` reaches `GuestAddressSpace::MapBacking` without `g_memory_state_mutex`. A GPU thread in `ProtectTransient` can hold the shared lock and traverse `m_mapped` while the pool commit inserts into that tree. The operation lock does not protect that reader. Cancel suspended overlaps before taking the exclusive state lock. Then hold the state lock across the backing maps and virtual-range publication. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:979abd435baef372b9d8530f --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -141,0 +143,4 @@
int UnmapAmmMemory(uint64_t vaddr, size_t size);
bool TryWriteBacking(uint64_t vaddr, const void* data, uint64_t size);
bool TryReadBacking(uint64_t vaddr, void* data, uint64_t size);
// Reads one byte from each of count addresses spaced stride apart under one lock. Returns
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 21:45 UTC · original

Minor · Functional Correctness · Quick win

Hold the state lock across the strided read so one sample sees one mapping generation.

TryReadBackingStrided reads each entry with a separate LoadPage call and takes no lock. StorePages writes entries without a lock. If a mapping is replaced between two samples, the call can return true with bytes from two backing generations. The header at src/kernel/memory.h:146 says the read happens under one lock, but the implementation does not take one.

Take the shared state lock once in the free-function forwarder, so the lock covers the whole loop. Writers that hold the exclusive lock then block until the read finishes. Take the lock in one place only, because nested shared locks on the same mutex can deadlock. Confirm that no caller already holds g_memory_state_mutex when it reaches this function.

Suggested fix

 bool TryReadBackingStrided(uint64_t first, uint64_t stride, uint32_t count, uint8_t* out) {
+	std::shared_lock state(g_memory_state_mutex);
 	return g_guest_address_space->TryReadBackingStrided(first, stride, count, out);
 }
**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 21:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#discussion_r4648072986) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Hold the state lock across the strided read so one sample sees one mapping generation.** `TryReadBackingStrided` reads each entry with a separate `LoadPage` call and takes no lock. `StorePages` writes entries without a lock. If a mapping is replaced between two samples, the call can return `true` with bytes from two backing generations. The header at `src/kernel/memory.h:146` says the read happens under one lock, but the implementation does not take one. Take the shared state lock once in the free-function forwarder, so the lock covers the whole loop. Writers that hold the exclusive lock then block until the read finishes. Take the lock in one place only, because nested shared locks on the same mutex can deadlock. Confirm that no caller already holds `g_memory_state_mutex` when it reaches this function. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff bool TryReadBackingStrided(uint64_t first, uint64_t stride, uint32_t count, uint8_t* out) { + std::shared_lock state(g_memory_state_mutex); return g_guest_address_space->TryReadBackingStrided(first, stride, count, out); } ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5b414fb24e850a217226dc06 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-20 21:45 UTC · original · reviewed

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (10)

Major · Apply the requested depth clear before the in-place color view reads the… · renderDraw.cpp:1033

src/graphics/host_gpu/renderer/renderDraw.cpp:1033
Major · Functional Correctness · Heavy lift

Apply the requested depth clear before the in-place color view reads the depth memory.

When copy_depth_to_color is set and the color and depth addresses match, CopyDepthToColor returns at lines 1033-1038 before AcquireRenderTargets runs. The requested depth clear (depth.depth_clear_enable) is consumed only in AcquireRenderTargets and then applied by BeginRendering. FindImage does not receive or apply that state. The color view can therefore read the old depth values instead of the cleared value.

The same early return also skips TakeMetaClear. A pending HTile clear stays set and can apply to a later, unrelated draw.

Before the in-place conversion, the clear that AcquireRenderTargets would apply must be executed on the depth image. Handle the pending metadata clear on this path as well, or state why it must remain pending.

Major · Gate video-buffer reuse on host-GPU completion, not command consumption. · graphicsRun.cpp:553

src/graphics/guest_gpu/graphicsRun.cpp:553
Major · Stability & Availability · Heavy lift

Gate video-buffer reuse on host-GPU completion, not command consumption.

WaitForWork returns when the command processor consumes the submissions up to the marker. For query-free work, the path through BufferFlush submits to the scheduler and does not wait on the host GPU. The marker in ThreadRun therefore advances before the submitted copy finishes. The avPlayer reuse gate in src/libs/avPlayer.cpp:1428-1434 then releases the buffer on that marker. The decoder can overwrite a frame that the host GPU still reads, which can produce corrupted video.

The reuse gate must wait until the host GPU completes all work submitted up to the marker. The fix can either track host-GPU completion in the marker or add a separate completion wait. The WaitForWork contract and its caller must agree on which completion they guarantee.

Major · Keep recent fault windows available when the registry wraps. · memoryAddressSpace.inc:232

src/kernel/memoryAddressSpace.inc:232
Major · Stability & Availability · Heavy lift

Keep recent fault windows available when the registry wraps.

If a worker faults while range A is unmapped, its handler can run after A is restored. If 64 replacements at other addresses open before the handler scans the registry, they can overwrite A's record even within the one-second retry interval. Wait then returns zero, and the runtime linker reports an unhandled fault on an address that is mapped again.

Keep recent completions separately from active slots, or provide another way to confirm recovery after a slot is reused. Add a regression case that delays fault handling until the active registry wraps.

Major · Restore phase two after resetting the Windows fixture. · VirtualMemoryAllocationTests.cpp:714

tests/VirtualMemoryAllocationTests.cpp:714
Major · Functional Correctness · Quick win

Restore phase two after resetting the Windows fixture.

The full suite reserves all three guest regions before this test. The final Shutdown() and Initialize() leave only Region 0 reserved. The later pool fixture searches from 0x1000000000, where no guest space remains reserved, so its allocation fails and RunTest skips the remaining cases.

Call ReserveGuestAddressSpace() after the final Initialize(). Leave the initial setup unchanged so the blocker still exercises the reservation race.

Major · Skip the cadence draw test when rasterization support… · ShaderRecompilerComputeTests.cpp:18982

tests/ShaderRecompilerComputeTests.cpp:18982
Major · Functional Correctness · Quick win

Skip the cadence draw test when rasterization support is unavailable.

The harness lets compute tests run without the production rasterization extensions. This call bypasses that guard in both the default suite and --submit-cadence-gpu-only. If the device lacks VK_EXT_depth_clip_control, the draw still enters production pipeline creation, which attaches the extension's viewport state. That makes the pipeline creation invalid before the remaining compute cadence checks run. Guard only CheckCadenceRenderPass with RasterizationSupported(). (raw.githubusercontent.com)

Minor · Pass --no-shader-cache when the launcher option is unchecked. · emulatorConfig.h:84

src/common/emulatorConfig.h:84
Minor · Functional Correctness · Quick win

Pass --no-shader-cache when the launcher option is unchecked.

The emulator default for shader_cache_enabled changed from false to true. CreateEmulatorArgs passes --shader-cache only when the checkbox is set. When the checkbox is cleared, the emulator starts with caching enabled, and pipeline caching then persists shaders between boots. Emit the explicit disable flag so an unchecked option keeps caching off:

Suggested fix

-	AddFlag(args, info.shader_cache_enabled, "--shader-cache");
+	args << (info.shader_cache_enabled ? "--shader-cache" : "--no-shader-cache");
Minor · Disarm the gate watchdog before waiting on the… · ShaderRecompilerComputeTests.cpp:18434-18435

tests/ShaderRecompilerComputeTests.cpp:18434-18435
Minor · Stability & Availability · Quick win

Disarm the gate watchdog before waiting on the open gate.

If RunCadenceStream returns just before the watchdog deadline and the following timeline wait succeeds just after it, the watchdog still sets timed_out. The test reports a hang even though it opened the gate and the GPU finished within the host wait's own timeout. Signal and join the watchdog when the gated stream returns, before WaitForTimelineOnHost. Keep the watchdog armed while the stream can still block on the closed gate.

Minor · Make adjacent 64 KiB blocks contain different test data. · ShaderRecompilerComputeTests.cpp:30903

tests/ShaderRecompilerComputeTests.cpp:30903
Minor · Functional Correctness · Quick win

Make adjacent 64 KiB blocks contain different test data.

RegionPatternByte(a) equals RegionPatternByte(a + 0x10000) for every a. In the four-region full-window case, a detiler that selects the next source block but preserves the in-block offset can return identical bytes. Mix the block index into the pattern before truncating to uint8_t, and keep the sentinel excluded.

Minor · Exercise the 0x10 register clear through the… · ShaderRecompilerComputeTests.cpp:17087

tests/ShaderRecompilerComputeTests.cpp:17087
Minor · Functional Correctness · Quick win

Exercise the 0x10 register clear through the CPU-backed path.

The script tests 0x20, and the host mask check maps 0x10 to the same slot as 0x20. Neither exposes the CPU materializer's raw low-bit check: it skips a uniform 0x10 slice before DecodeColorClear, leaving the painted texel and metadata unchanged. The GPU path accepts that same slice. Add a separate uniform 0x10 slice that must produce the register color and consumed metadata. In the CPU path, admit the alias before the low-bit rejection, but compare the metadata bytes against the original 0x10. Keep the near-miss cases rejected. (raw.githubusercontent.com)

Minor · Require a whole refresh in the flag-off CMASK case. · ShaderRecompilerComputeTests.cpp:20701

tests/ShaderRecompilerComputeTests.cpp:20701
Minor · Functional Correctness · Quick win

Require a whole refresh in the flag-off CMASK case.

If flag-off invalidation drops the buffer write, the CMASK clear can still produce the expected corners. The partial-refresh and fallback counters also stay at zero, so the case passes without testing whether the clear wins after a whole refresh. Assert that the preexisting image has a whole mark before acquisition and that acquisition performs a full upload. Keep the partial-refresh assertion for the enabled case. (raw.githubusercontent.com)

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b56e9015c74b275912ab8237091f01d3ddcda726 and 2577e26e25.

Files selected for processing: 43

  • CMakeLists.txt
  • src/common/debugCounters.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/pageManager.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.h
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/refreshRegions.cpp
  • src/graphics/host_gpu/renderer/image/refreshRegions.h
  • src/graphics/host_gpu/renderer/image/tiler.cpp
  • src/graphics/host_gpu/renderer/image/tiler.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderContext.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/renderer/submitCadence.h
  • src/graphics/host_gpu/shaders/gpu_tiler_common.inc
  • src/graphics/host_gpu/shaders/gpu_tiler_depth.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_prt.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_prt_3d.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_render_target.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_standard256.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_standard4.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_standard4_3d.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_standard64.comp
  • src/graphics/host_gpu/shaders/gpu_tiler_standard64_3d.comp
  • src/graphics/presentation/window/swapchain.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/main.cpp
  • tests/PthreadPriorityTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/shaderCfgTests.cpp
Files not fully reviewed because they exceed a per-file size limit: 1

  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-20 21:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2465#pullrequestreview-5999811602) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 4** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (10)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Apply the requested depth clear before the in-place color view reads the… · <code>renderDraw.cpp:1033</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/graphics/host_gpu/renderer/renderDraw.cpp:1033` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** > > **Apply the requested depth clear before the in-place color view reads the depth memory.** > > When `copy_depth_to_color` is set and the color and depth addresses match, `CopyDepthToColor` returns at lines 1033-1038 before `AcquireRenderTargets` runs. The requested depth clear (`depth.depth_clear_enable`) is consumed only in `AcquireRenderTargets` and then applied by `BeginRendering`. `FindImage` does not receive or apply that state. The color view can therefore read the old depth values instead of the cleared value. > > The same early return also skips `TakeMetaClear`. A pending HTile clear stays set and can apply to a later, unrelated draw. > > Before the in-place conversion, the clear that `AcquireRenderTargets` would apply must be executed on the depth image. Handle the pending metadata clear on this path as well, or state why it must remain pending. > > <!-- cr-comment:v1:d3438df851d3b66d062da2b9 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Gate video-buffer reuse on host-GPU completion, not command consumption. · <code>graphicsRun.cpp:553</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/graphics/guest_gpu/graphicsRun.cpp:553` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** > > **Gate video-buffer reuse on host-GPU completion, not command consumption.** > > `WaitForWork` returns when the command processor consumes the submissions up to the marker. For query-free work, the path through `BufferFlush` submits to the scheduler and does not wait on the host GPU. The marker in `ThreadRun` therefore advances before the submitted copy finishes. The `avPlayer` reuse gate in `src/libs/avPlayer.cpp:1428-1434` then releases the buffer on that marker. The decoder can overwrite a frame that the host GPU still reads, which can produce corrupted video. > > The reuse gate must wait until the host GPU completes all work submitted up to the marker. The fix can either track host-GPU completion in the marker or add a separate completion wait. The `WaitForWork` contract and its caller must agree on which completion they guarantee. > > <!-- cr-comment:v1:ee46e963b495e1f4cd4e256f --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Keep recent fault windows available when the registry wraps. · <code>memoryAddressSpace.inc:232</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/kernel/memoryAddressSpace.inc:232` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** > > **Keep recent fault windows available when the registry wraps.** > > If a worker faults while range A is unmapped, its handler can run after A is restored. If 64 replacements at other addresses open before the handler scans the registry, they can overwrite A's record even within the one-second retry interval. `Wait` then returns zero, and the runtime linker reports an unhandled fault on an address that is mapped again. > > Keep recent completions separately from active slots, or provide another way to confirm recovery after a slot is reused. Add a regression case that delays fault handling until the active registry wraps. > > <!-- cr-comment:v1:2772696cc4cb03d99bb91e02 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Restore phase two after resetting the Windows fixture. · <code>VirtualMemoryAllocationTests.cpp:714</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/VirtualMemoryAllocationTests.cpp:714` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** > > **Restore phase two after resetting the Windows fixture.** > > The full suite reserves all three guest regions before this test. The final `Shutdown()` and `Initialize()` leave only Region 0 reserved. The later pool fixture searches from `0x1000000000`, where no guest space remains reserved, so its allocation fails and `RunTest` skips the remaining cases. > > Call `ReserveGuestAddressSpace()` after the final `Initialize()`. Leave the initial setup unchanged so the blocker still exercises the reservation race. > > <!-- cr-comment:v1:3cdc787dc2e5893f114731e7 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Skip the cadence draw test when rasterization support… · <code>ShaderRecompilerComputeTests.cpp:18982</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:18982` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** > > **Skip the cadence draw test when rasterization support is unavailable.** > > The harness lets compute tests run without the production rasterization extensions. This call bypasses that guard in both the default suite and `--submit-cadence-gpu-only`. If the device lacks `VK_EXT_depth_clip_control`, the draw still enters production pipeline creation, which attaches the extension's viewport state. That makes the pipeline creation invalid before the remaining compute cadence checks run. Guard only `CheckCadenceRenderPass` with `RasterizationSupported()`. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/2577e26e25f245640d57e5fc3d5bdabef99b7f20/tests/ShaderRecompilerComputeTests.cpp)) > > <!-- cr-comment:v1:57418d2ae7247ccd1fc75402 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Pass <code>--no-shader-cache</code> when the launcher option is unchecked. · <code>emulatorConfig.h:84</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/common/emulatorConfig.h:84` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Pass `--no-shader-cache` when the launcher option is unchecked.** > > The emulator default for `shader_cache_enabled` changed from `false` to `true`. `CreateEmulatorArgs` passes `--shader-cache` only when the checkbox is set. When the checkbox is cleared, the emulator starts with caching enabled, and pipeline caching then persists shaders between boots. Emit the explicit disable flag so an unchecked option keeps caching off: > > <details> > <summary>Suggested fix</summary> > <dl> > <dd> > <br> > > ```diff > - AddFlag(args, info.shader_cache_enabled, "--shader-cache"); > + args << (info.shader_cache_enabled ? "--shader-cache" : "--no-shader-cache"); > ``` > > </dd> > </dl> > </details> > > <!-- cr-comment:v1:9547e524bcd57a9b8f788306 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Disarm the gate watchdog before waiting on the… · <code>ShaderRecompilerComputeTests.cpp:18434-18435</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:18434-18435` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** > > **Disarm the gate watchdog before waiting on the open gate.** > > If `RunCadenceStream` returns just before the watchdog deadline and the following timeline wait succeeds just after it, the watchdog still sets `timed_out`. The test reports a hang even though it opened the gate and the GPU finished within the host wait's own timeout. Signal and join the watchdog when the gated stream returns, before `WaitForTimelineOnHost`. Keep the watchdog armed while the stream can still block on the closed gate. > > <!-- cr-comment:v1:5020a6906c8638551de402f9 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Make adjacent 64 KiB blocks contain different test data. · <code>ShaderRecompilerComputeTests.cpp:30903</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:30903` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Make adjacent 64 KiB blocks contain different test data.** > > `RegionPatternByte(a)` equals `RegionPatternByte(a + 0x10000)` for every `a`. In the four-region full-window case, a detiler that selects the next source block but preserves the in-block offset can return identical bytes. Mix the block index into the pattern before truncating to `uint8_t`, and keep the sentinel excluded. > > <!-- cr-comment:v1:7bd0096be1743f9922fd57e2 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Exercise the <code>0x10</code> register clear through the… · <code>ShaderRecompilerComputeTests.cpp:17087</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:17087` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Exercise the `0x10` register clear through the CPU-backed path.** > > The script tests `0x20`, and the host mask check maps `0x10` to the same slot as `0x20`. Neither exposes the CPU materializer's raw low-bit check: it skips a uniform `0x10` slice before `DecodeColorClear`, leaving the painted texel and metadata unchanged. The GPU path accepts that same slice. Add a separate uniform `0x10` slice that must produce the register color and consumed metadata. In the CPU path, admit the alias before the low-bit rejection, but compare the metadata bytes against the original `0x10`. Keep the near-miss cases rejected. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/2577e26e25f245640d57e5fc3d5bdabef99b7f20/src/graphics/host_gpu/renderer/cache/textureCache.cpp)) > > <!-- cr-comment:v1:31cd6dd63ef502e60f688da9 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Require a whole refresh in the flag-off CMASK case. · <code>ShaderRecompilerComputeTests.cpp:20701</code></summary><blockquote> > <dl> > <dd> > <br> > > `tests/ShaderRecompilerComputeTests.cpp:20701` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Require a whole refresh in the flag-off CMASK case.** > > If flag-off invalidation drops the buffer write, the CMASK clear can still produce the expected corners. The partial-refresh and fallback counters also stay at zero, so the case passes without testing whether the clear wins after a whole refresh. Assert that the preexisting image has a whole mark before acquisition and that acquisition performs a full upload. Keep the partial-refresh assertion for the enabled case. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/2577e26e25f245640d57e5fc3d5bdabef99b7f20/src/graphics/host_gpu/renderer/cache/textureCache.cpp)) > > <!-- cr-comment:v1:92c60c8a0fba7790aaa2ff45 --> > > </dd> > </dl> > </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/a21fd80c8e570ebcde9248deec9c711c252ebc77/.coderabbit.yaml>) - **Commit**: [a21fd80](<https://github.com/KytyPS5/KytyPS5/commit/a21fd80c8e570ebcde9248deec9c711c252ebc77>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `2cc2351d-4f96-4e97-b66a-e975ddc9e3e4` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between b56e9015c74b275912ab8237091f01d3ddcda726 and 2577e26e25f245640d57e5fc3d5bdabef99b7f20. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 43</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/common/debugCounters.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/pageManager.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.h` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/refreshRegions.cpp` * `src/graphics/host_gpu/renderer/image/refreshRegions.h` * `src/graphics/host_gpu/renderer/image/tiler.cpp` * `src/graphics/host_gpu/renderer/image/tiler.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/imageHeap.cpp` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `src/graphics/host_gpu/renderer/renderContext.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/host_gpu/renderer/submitCadence.h` * `src/graphics/host_gpu/shaders/gpu_tiler_common.inc` * `src/graphics/host_gpu/shaders/gpu_tiler_depth.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_prt.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_prt_3d.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_render_target.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_standard256.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_standard4.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_standard4_3d.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_standard64.comp` * `src/graphics/host_gpu/shaders/gpu_tiler_standard64_3d.comp` * `src/graphics/presentation/window/swapchain.cpp` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/main.cpp` * `tests/PthreadPriorityTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` * `tests/shaderCfgTests.cpp` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-too-large.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files not fully reviewed because they exceed a per-file size limit: 1</summary> <dl> <dd> <br> * tests/ShaderRecompilerComputeTests.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=e914fc3f-fde8-4b3e-a804-dcf75b40c8d8 attempt=1a457a87-2d84-4d10-8931-33d86fbd3cda batch=1/1 -->

Pull request closed

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