Uncharted - LOFC boot to gameplay, fix rendering and frame rate #1430

Open
github-bot wants to merge 24 commits from github-bot/gh-1430 into main AGit
Owner

@⁠Almo7aya on GitHub · 2026-10-11 20:39 UTC · original
Almo7aya:fix/uncharted-cleanup → main · +6150 −694 · 65 files · 24 commits · open

Uncharted: Legacy of Thieves Collection (PPSA05389): boot to gameplay, fix rendering and frame rate

Game

Uncharted: Legacy of Thieves Collection (PPSA05389, 01.002.000).

Problem

On main the game does not reach gameplay:

  • At boot, the unresolved libSceVdecsw module asserts.
  • Resource tracking rejects compute shaders that pick their buffer or image through a key the GPU
    computes ("buffer descriptor is not a valid runtime value").
  • Unknown PM4 marker ids stop the emulator.
  • Specialization exits on stale descriptors read on paths the GPU does not take.
  • Boots fail intermittently because file reads into GPU-watched pages return zero bytes.

Past those, rendering is wrong:

  • glare, from CMASK fast clears of 11_11_10 targets that are dropped;
  • a flickering ocean, from device-address reads of unbacked ring pages;
  • stale stencil.

The frame rate is in single digits.

Result

  • The game boots reliably and plays: Continue loads the saved chapter, and gameplay renders
    correctly.
  • About 60 FPS in the menus and 20–40 FPS in gameplay.
  • No title-specific code: every change applies to any game.
    • The DMA shortcuts recognise memset and copy kernels from their IR and check them against the
      RDNA 2 buffer rules. They are not keyed on shader hashes.
    • Descriptor tables are handled by kind, not by title.

Commits

  1. libs: implement libSceVdecsw over the Videodec2 software decoder. The game imports
    libSceVdecsw for video playback and asserted on the unresolved module. Vdecsw shares
    Videodec2's ABI and drives the FFmpeg software decoder.
  2. memory: keep guest faults and page watches consistent across remapping. Windows remaps a
    guest view in several steps. Faults and GPU page watches during those steps were lost or handed
    to the wrong owner. Watches and protections now survive remapping, transient faults are
    retried, and code pages stay executable.
  3. shader: select descriptors through keys the GPU computes. Compute shaders that pick a
    descriptor by a GPU-computed key (a masked table byte, a bit scan, a counting loop) were
    rejected. The key's values are now enumerated from guest memory at dispatch, and the candidates
    are selected per lane.
  4. shader: treat stale data on untaken paths as null during specialization. Specialization
    reads descriptors on paths the GPU does not take with the current data. Unmapped memory and
    unmapped tables there now read as zero or null, instead of faulting or exiting.
  5. shader: specialize speculative descriptor tables on stable layouts. Over-approximated
    tables null the candidates an operation cannot use, including those of the wrong dimension, and
    get a canonical padded layout that grows in large steps. Changing table contents no longer
    recompiles shaders, which removes the compile stalls.
  6. gpu: ignore unknown PM4 marker ids. Marker 0x800 stopped the emulator. Unknown marker
    ids are skipped and reported once.
  7. renderer: decode register clears for 11_11_10 and 64-bit color targets. CMASK fast clears
    of these formats were dropped, so targets kept stale contents (the glare). Matching fill
    shaders run as image clears too.
  8. texture cache: download stencil planes to guest memory. Downloads only wrote the depth
    aspect, so guest copies of a depth buffer had stale stencil.
  9. renderer: back host-evaluable DMA bases before a dispatch. A per-frame ring read through
    device addresses returned zeros whenever it reached unbacked pages (the ocean flicker). Bases
    the host can evaluate are backed before the dispatch.
  10. renderer: name the shader and failing condition in fatal errors. Specialization failures
    and failed waits name the shader, resource and condition.
  11. shader: inline the IR value accessors and scalar resource reads. Per-draw resource
    evaluation was dominated by out-of-line one-line accessors.
  12. renderer: run proven memset and copy compute kernels as DMA. The game runs memset (CMASK
    clear) and copy kernels many times a frame. Their GPU-written results made CPU reads drain the
    GPU. Kernels proven from the IR to only fill or copy run as DMA fills and copies. They must
    pass the RDNA 2 format, DST_SEL, OOB_SELECT and overlap checks.
  13. renderer: cut the buffer-tracking work done per draw. The mapping query is cached per
    thread, and the device-address sweep before a draw covers only queued regions.
  14. renderer: collect cache garbage once per guest frame. The game submits dozens of times a
    frame, so the buffer and texture caches aged resources out almost immediately.
  15. shader: refresh flattened SRTs from a compiled tape. The per-draw SRT refresh was the
    command processor's largest cost. It now evaluates a precompiled tape.
  16. renderer: trim the per-draw state setup and checks. The per-draw state is no longer
    re-initialised for every draw, and the redundant pipeline bind and checks are skipped.
  17. renderer: remember texture and render-target resolution between draws. Texture and target
    descriptions and their texture-cache lookups are reused while the cache's lookup generation is
    unchanged.
  18. renderer: accept texture descriptors at the edges of the T# encoding. A MIN_LOD past
    LAST_LEVEL is clamped instead of exiting. A 256-bit T# with zero DWORDs 4–7 is read like a
    128-bit one.
  19. vulkan: report what the GPU was doing when the device is lost. On device loss, the
    VK_EXT_device_fault report is printed, along with the last draws and dispatches the GPU
    reached (NVIDIA checkpoints, always on, about 1% FPS).
  20. memory: keep guest write faults off the GPU thread's locks. Guest threads fault on tens of
    thousands of watched pages a second. Page-watch protection now takes the address-space lock
    shared.
  21. gpu: give the command processor thread a performance core of its own. On hybrid CPUs the
    GPU thread ran on efficiency cores and shared its core with spinning guest workers.
  22. renderer: shorten the GPU waits of CPU readbacks. A readback no longer waits for
    everything recorded so far, one page at a time. It downloads a 1 MiB window and submits sooner.
  23. kernel: read files into guest memory through a host buffer. A host read into a GPU-watched
    page fails and returned zero bytes without an error. This was the root cause of the
    intermittent boot failures and of corrupted data.
  24. shader: take runtime texel offsets on image samples. The latest main rejects
    non-constant sample offsets, and one of the game's shaders computes them per lane, so the game
    stopped at boot. With VK_KHR_maintenance8 the offset is emitted natively. Otherwise a
    level-zero sample moves its coordinates by the offset.

Testing

  • ctest: 53/54. The one failure, kernel_file_system's socket-options check, fails on main
    too.
  • New tests:
    • the copy proof, with a captured kernel;
    • the memset and copy RDNA 2 checks;
    • stable layouts that keep the specialization when table contents change;
    • a GPU-keyed table that drops wrong-dimension candidates;
    • runtime sample offsets on the GPU, plus the VK_KHR_maintenance8 path.
  • In game:
    • repeated batches of launches to the title screen without a failure;
    • played into gameplay and through the first areas, with FPS measured at the orphanage while
      standing and while moving.

AI use

This work was developed with AI assistance

**@⁠Almo7aya** on GitHub · 2026-10-11 20:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430) `Almo7aya:fix/uncharted-cleanup` → `main` · +6150 −694 · 65 files · 24 commits · open Uncharted: Legacy of Thieves Collection (PPSA05389): boot to gameplay, fix rendering and frame rate ## Game Uncharted: Legacy of Thieves Collection (PPSA05389, 01.002.000). ## Problem On `main` the game does not reach gameplay: - At boot, the unresolved `libSceVdecsw` module asserts. - Resource tracking rejects compute shaders that pick their buffer or image through a key the GPU\ computes ("buffer descriptor is not a valid runtime value"). - Unknown PM4 marker ids stop the emulator. - Specialization exits on stale descriptors read on paths the GPU does not take. - Boots fail intermittently because file reads into GPU-watched pages return zero bytes. Past those, rendering is wrong: - glare, from CMASK fast clears of 11\_11\_10 targets that are dropped; - a flickering ocean, from device-address reads of unbacked ring pages; - stale stencil. The frame rate is in single digits. ## Result - The game boots reliably and plays: Continue loads the saved chapter, and gameplay renders\ correctly. - About **60 FPS in the menus** and **20–40 FPS in gameplay**. - No title-specific code: every change applies to any game. - The DMA shortcuts recognise memset and copy kernels from their IR and check them against the\ RDNA 2 buffer rules. They are not keyed on shader hashes. - Descriptor tables are handled by kind, not by title. ## Commits 1. **libs: implement libSceVdecsw over the Videodec2 software decoder.** The game imports\ libSceVdecsw for video playback and asserted on the unresolved module. Vdecsw shares\ Videodec2's ABI and drives the FFmpeg software decoder. 2. **memory: keep guest faults and page watches consistent across remapping.** Windows remaps a\ guest view in several steps. Faults and GPU page watches during those steps were lost or handed\ to the wrong owner. Watches and protections now survive remapping, transient faults are\ retried, and code pages stay executable. 3. **shader: select descriptors through keys the GPU computes.** Compute shaders that pick a\ descriptor by a GPU-computed key (a masked table byte, a bit scan, a counting loop) were\ rejected. The key's values are now enumerated from guest memory at dispatch, and the candidates\ are selected per lane. 4. **shader: treat stale data on untaken paths as null during specialization.** Specialization\ reads descriptors on paths the GPU does not take with the current data. Unmapped memory and\ unmapped tables there now read as zero or null, instead of faulting or exiting. 5. **shader: specialize speculative descriptor tables on stable layouts.** Over-approximated\ tables null the candidates an operation cannot use, including those of the wrong dimension, and\ get a canonical padded layout that grows in large steps. Changing table contents no longer\ recompiles shaders, which removes the compile stalls. 6. **gpu: ignore unknown PM4 marker ids.** Marker `0x800` stopped the emulator. Unknown marker\ ids are skipped and reported once. 7. **renderer: decode register clears for 11\_11\_10 and 64-bit color targets.** CMASK fast clears\ of these formats were dropped, so targets kept stale contents (the glare). Matching fill\ shaders run as image clears too. 8. **texture cache: download stencil planes to guest memory.** Downloads only wrote the depth\ aspect, so guest copies of a depth buffer had stale stencil. 9. **renderer: back host-evaluable DMA bases before a dispatch.** A per-frame ring read through\ device addresses returned zeros whenever it reached unbacked pages (the ocean flicker). Bases\ the host can evaluate are backed before the dispatch. 10. **renderer: name the shader and failing condition in fatal errors.** Specialization failures\ and failed waits name the shader, resource and condition. 11. **shader: inline the IR value accessors and scalar resource reads.** Per-draw resource\ evaluation was dominated by out-of-line one-line accessors. 12. **renderer: run proven memset and copy compute kernels as DMA.** The game runs memset (CMASK\ clear) and copy kernels many times a frame. Their GPU-written results made CPU reads drain the\ GPU. Kernels proven from the IR to only fill or copy run as DMA fills and copies. They must\ pass the RDNA 2 format, `DST_SEL`, `OOB_SELECT` and overlap checks. 13. **renderer: cut the buffer-tracking work done per draw.** The mapping query is cached per\ thread, and the device-address sweep before a draw covers only queued regions. 14. **renderer: collect cache garbage once per guest frame.** The game submits dozens of times a\ frame, so the buffer and texture caches aged resources out almost immediately. 15. **shader: refresh flattened SRTs from a compiled tape.** The per-draw SRT refresh was the\ command processor's largest cost. It now evaluates a precompiled tape. 16. **renderer: trim the per-draw state setup and checks.** The per-draw state is no longer\ re-initialised for every draw, and the redundant pipeline bind and checks are skipped. 17. **renderer: remember texture and render-target resolution between draws.** Texture and target\ descriptions and their texture-cache lookups are reused while the cache's lookup generation is\ unchanged. 18. **renderer: accept texture descriptors at the edges of the T# encoding.** A `MIN_LOD` past\ `LAST_LEVEL` is clamped instead of exiting. A 256-bit T# with zero DWORDs 4–7 is read like a\ 128-bit one. 19. **vulkan: report what the GPU was doing when the device is lost.** On device loss, the\ `VK_EXT_device_fault` report is printed, along with the last draws and dispatches the GPU\ reached (NVIDIA checkpoints, always on, about 1% FPS). 20. **memory: keep guest write faults off the GPU thread's locks.** Guest threads fault on tens of\ thousands of watched pages a second. Page-watch protection now takes the address-space lock\ shared. 21. **gpu: give the command processor thread a performance core of its own.** On hybrid CPUs the\ GPU thread ran on efficiency cores and shared its core with spinning guest workers. 22. **renderer: shorten the GPU waits of CPU readbacks.** A readback no longer waits for\ everything recorded so far, one page at a time. It downloads a 1 MiB window and submits sooner. 23. **kernel: read files into guest memory through a host buffer.** A host read into a GPU-watched\ page fails and returned zero bytes without an error. This was the root cause of the\ intermittent boot failures and of corrupted data. 24. **shader: take runtime texel offsets on image samples.** The latest `main` rejects\ non-constant sample offsets, and one of the game's shaders computes them per lane, so the game\ stopped at boot. With `VK_KHR_maintenance8` the offset is emitted natively. Otherwise a\ level-zero sample moves its coordinates by the offset. ## Testing - `ctest`: 53/54. The one failure, `kernel_file_system`'s socket-options check, fails on `main`\ too. - New tests: - the copy proof, with a captured kernel; - the memset and copy RDNA 2 checks; - stable layouts that keep the specialization when table contents change; - a GPU-keyed table that drops wrong-dimension candidates; - runtime sample offsets on the GPU, plus the `VK_KHR_maintenance8` path. - In game: - repeated batches of launches to the title screen without a failure; - played into gameplay and through the first areas, with FPS measured at the orphanage while\ standing and while moving. ## AI use This work was developed with AI assistance
Titles that import libSceVdecsw for video playback assert when the
module is unresolved.

Vdecsw shares Videodec2's configuration, result and picture-info ABI,
so those move into videoDec2.h and both libraries use them. Each Vdecsw
decoder serializes its calls and drives the FFmpeg decoder for decode,
flush and drain. Drain ends the stream and returns the buffered
pictures one call at a time; the decoder keeps one picture of lookahead
so the last one can carry end_of_stream.
Windows changes a guest mapping in several steps. A view can only be
unmapped whole, so splitting one unmaps it and maps the surviving
fragments again, and a fixed mapping over live memory releases the old
views before it maps the new one. GPU page watches and guest
protections exist only as host page protections, and any fault in
GPU-visible memory was handed to the caches. Threads that touched a
range mid-transaction died on faults that were valid a moment later,
and splits silently dropped watches and protections.

- The render context claims a fault only when a page watch revoked the
  access. Other faults in GPU-visible memory no longer create cache
  state while no command buffer is recording.
- Backing reads and writes hold the address-space lock shared, so they
  see a mapping before or after a split, never a missing range.
- A fault the caches decline is resolved by the address space once the
  page permits the access again, waiting for a fixed replacement that
  covers it. In GPU-visible memory, where other threads lift and re-arm
  watches concurrently, a fault that belongs to neither owner is
  retried for up to 250 ms before it is reported.
- A split captures the protections of the whole view and reapplies
  them to the surviving fragments, or to the whole view when the split
  is rolled back.
- The address space remembers the ranges mapped or protected
  executable, and page watches keep execute on them. Guest code on a
  page a GPU resource covers no longer takes execute faults that no
  watcher claims; an execute fault on a watched page resolves like a
  read.

Tests that simulate a guest access through HandleFault now model it the
same way: the access faults only where a page watch revokes it.
Some compute shaders pick the buffer or image they access by a key
computed on the GPU: a masked byte of a guest lookup table indexed by
shared-memory results, an affine index, a bit scan or a counting loop.
Resource tracking rejected them with "buffer descriptor is not a valid
runtime value".

Such a key is now planned as an enumerated selector: the key value,
plus the ranges of the counting loops it depends on, proven by the
guards on the loop's other uses. At dispatch, KeySetEvaluator computes
every value the key can take. Host-evaluable operands are evaluated
exactly. A GPU-only operand is unknown, bounded by masks, extracts and
minimums, and a scalar read at an affine offset of it enumerates the
entries of the buffer it reads, plus zero for an out-of-bounds read.
The table entries at those keys become the candidates, and a key whose
entry is not in guest memory gets a null candidate.

A store destination must not be over-approximated, so an enumerated
buffer key needs a mask or a counting loop. Every store form (raw
DWORD, subword, formatted and wide) is emitted once per candidate
binding through ForEachStoreBinding, which skips null candidates. Each
candidate is bound with its own stride and bounds, so stores only
reject swizzled and add-TID addressing. Descriptor-table failures name
the shader and the table.

Keys that resource tracking used to reject for lack of a proven range
(an unguarded direct table, an unbounded image loop, a malformed
material waterfall) can now be planned as GPU-computed keys. Their
tests accept either outcome, but neither may claim the proven range.
Specialization evaluates descriptor reads on every path whose condition
depends on data the GPU computes, including paths the GPU does not take
with the current data. Pointers and descriptors there can be stale or
garbage, and the host faulted on non-canonical addresses or exited
with "the flattened SRT could not be read" or "unsupported descriptor
table V#".

- SRT reads of memory that is not GPU-mapped read zero: ordinary, raw
  and strict reads, and the specialization memory reader. A strict
  read of unmapped memory is not recorded as a specialization
  dependency, since it cannot be what the GPU reads.
- A bounded descriptor table whose V# does not point at mapped memory
  provides no descriptor, and its root binds null. Mapped table bytes
  that cannot be read still fail the specialization.
Candidates read from a descriptor table can over-approximate what the
GPU selects. A bounded table offers every DWORD offset, and a key the
GPU computes is enumerated as a superset of its values. When the host
cannot read the GPU-written data behind an image key, the first 1024
table entries are now scanned instead; buffer keys still fail, because
a store destination must not be over-approximated. Such speculative
candidates must not fail the draw or disturb the texture cache, and the
compiled shader must not follow the table's contents.

- An image candidate the operation cannot bind, or the texture cache
  cannot place (dimension, mip range, destination selects, mapping,
  tiling-block alignment), becomes null. An operation only samples an
  image of its own dimension, so a 2D sample drops cube maps and a 3D
  sample 2D images. Classification moves into ClassifyImage so it can
  be retried with a null descriptor. Only the largest group of mutually
  compatible images is kept. An enumerated buffer candidate whose
  memory is not mapped becomes null.
- A speculative table the shader only reads is laid out canonically:
  the root slot is null, candidates form one run per coordinate kind in
  a fixed order, and each run is padded to a power of four that never
  shrinks below the previous dispatch's layout, also when the kept
  class changes. The key mapping is rewritten to the new ordinals; its
  search depth grows two iterations at a time, and neither it nor its
  region shrinks, also when the table selects nothing, so later
  mappings keep their offsets. The previous class is kept while it
  still has entries. Every change of layout compiles a new permutation
  and stalls the frame, so layouts grow in few, large steps.
- A key set that selects nothing nulls the root instead of failing the
  key mapping.
- For the candidates of such a table the texture cache only reuses an
  image with the same backing or inserts one into an empty region
  (FindSpeculativeImage). Any other overlap, and an unsupported view of
  a depth target, binds a null texture, so stale entries cannot alias
  or reshape live images.

Keys read from a selector, counted keys, workgroup keys and finite
descriptor choices are all selected: they are validated strictly and
keep exact layouts. So does a table the shader writes through, because
a store target is never padded or selected through a root. A shader
without a stable table keeps its snapshot storage across dispatches.

Tests of bounded tables expect the padded layout. New tests check that
a table selecting fewer candidates, or none, keeps the shader's
specialization, and that a GPU-keyed 2D table drops cube-map entries.
A marker is a NOP packet: the GPU ignores its payload, and only the
flip and user-data ids carry work for the command processor. An
unknown id, such as 0x800, stopped the emulator with "unknown marker".
Other ids are now skipped by their length and reported once each.
CMASK fast clears of 11_11_10 float and 16_16_16_16 float targets were
dropped because the register-clear decoder knew neither format, so the
targets kept stale contents. Displacement maps cleared to 1.0 kept
zeros, and accumulation targets kept the previous frame.

The image metadata now carries both CB clear words, and the decoder
handles 11_11_10 unsigned floats and 64-bit RGBA16 and RG32 colors. A
DWORD fill of a 64-bit format repeats the word in both halves, so fill
shaders matched to these images also run as image clears. Targets whose
host format reverses the guest bit layout still refuse register clears,
since the clear word is in guest memory layout.
A depth/stencil image keeps its stencil plane in a separate guest
range, tracked by a stencil association record. Downloads only ever
wrote the depth aspect: FindImageFromRange mapped a request for the
stencil range to the depth owner, and SynchronizeBufferFromImage then
copied depth, or nothing. A guest copy of a depth buffer through memory
kept the right depth but stale stencil.

FindImageFromRange now returns the association itself, and
SynchronizeBufferFromImage downloads the owner's stencil aspect into
that range, mirroring how UploadImage uploads it. Compressed and
multisampled stencil planes are skipped, as they are on upload.
A DMA (buffer device address) read of guest memory that no cached
buffer covers returns zero. The miss only reaches the fault buffer,
which backs the page for later dispatches; the dispatch itself is never
replayed. A shader that reads per-frame data from a ring that moves
every frame therefore read zeros whenever the ring reached new pages.

Resource tracking records the base of each DMA address handle, the plan
keeps the bases the host can evaluate, and materialization reads them
with the plain runtime so they never feed specialization. Before a DMA
dispatch or draw, PrepareBda backs a 256 KiB window at each base,
clamped to GPU-mapped memory, and then synchronizes as before.
Several fatal paths reported only the condition that failed, which is
not enough to trace an intermittent failure.

- A failed resource materialization reports the shader hash and stage.
  Each failing path of MaterializeResources and
  MaterializeIndirectDescriptor goes through SpecializationFail, naming
  the resource and, for descriptor tables, the condition that failed.
- A failed timeline-semaphore wait reports the vk::Result and the tick
  instead of "Not implemented".
- The ADD_TID failure names the shader, stage, buffer and packed
  stride.
- The specialization-read overlap check names the shader, the read and
  the written range.
Draw-time resource evaluation walks the resource plan's value graph for
every draw, and Resolve, Arg, IsImmediate and the other one-line
accessors were out-of-line calls. They are now defined in the header.
Identity chains are followed in a loop, so Resolve and
ResolveInstruction inline rather than recurse, and the common opaque,
non-identity case of ResolveInstruction stays inline.

Scalar resource reads are almost always one DWORD but went through a
variable-size memcpy call; they now copy a constant four bytes.
Games run small memset and copy kernels many times a frame. Executed on
the GPU, they left their destinations GPU-written, and CPU reads and
the command processor's own resource reads then drained the GPU to read
them back.

- Memset kernels that store a 64-bit user-data value to index < count
  inside the compiler's EXEC skip were not recognized: the uniform-fill
  proof only took straight-line stores covering the whole dispatch. It
  now accepts a store guarded by a host-evaluable element count, and a
  branch that only skips the store when no lane passes that guard. A
  direct dispatch of such a fill over memory holding no cached image
  runs as a DMA fill, which fills guest memory on the CPU when the GPU
  has not written it.
- Copy kernels are proven from their IR. Every side effect must be a
  buffer store of what a load of the same width and form read at the
  same global index under the same guard, which may bound the index by
  a host-evaluable count. Other branches may only be EXEC tests that
  skip a store no lane performs, and one counted loop may surround the
  copies: its descriptors and counts are read from memory per
  iteration, with SrtWalker::Bind fixing the counter. Each dispatch
  evaluates its copies, and the renderer runs them through
  BufferCache::CopyBuffer.

Either runs as DMA only when that is exactly what the kernel's buffer
operations do under the RDNA 2 rules: unswizzled V#s whose stride is
the element size, raw DWORD access or 32-bit-per-component formats with
identity DST_SEL, lanes in range under OOB_SELECT 0-2 (stores past the
range are dropped), and for copies no write overlapping a read, another
write or the memory the copies were evaluated from. Fills consumed as
image clears get the same DST_SEL and range checks.
- Shader resource evaluation asks whether guest memory is mapped for
  nearly every word it reads, and each query took the shared
  mapped-range lock that faulting guest threads also contend. IsMapped
  now remembers the mapping a thread last found, invalidated by a
  generation that every map and unmap advances.
- Before each draw or dispatch that accesses memory through device
  addresses, every buffer in every mapped range was synchronized,
  though almost none had new CPU writes. The memory tracker now queues
  each 4 MiB tracker region once when pages there become CPU-modified
  (write faults, explicit marks, untracking, new regions), and buffer
  registration queues the regions a buffer covers. PrepareBda takes
  the queue and synchronizes only the buffers in those regions; a
  mapping change still sweeps everything. A region is dequeued before
  its buffers are uploaded, so writes during the sweep queue it again.
- ObtainBuffer's fast path for small read-only buffers asks the memory
  tracker for the range's CPU and GPU state in one walk instead of two.
The buffer and texture caches age their resources by collections, and
a collection ran after every guest submission. A title that submits
dozens of times a frame aged resources out within a fraction of a
second, so the buffer cache kept recreating and re-uploading buffers,
each a dedicated allocation, and textures were retired almost as soon
as they went unused. Collections now run once per guest frame.
Every draw refreshed each stage's flattened SRT by walking the plan's
value graph recursively and memoizing each node, which made the refresh
the largest single cost of the command processor.

The plan is now compiled once into a tape of nodes in the walker's own
depth-first order, and refreshes evaluate it in a loop.

- Clean reads, and everything they depend on, go through the clean
  walker's reader as before. A failure stops at the same read the
  walker would fail on, and the results seed both walkers' memos for
  the descriptor evaluation that follows.
- Plans with control flow keep the walker's block traversal and
  active-source bookkeeping. Each block lists the nodes its reads need;
  the walker evaluates the branch conditions and finds every node
  already computed.
- Nodes get their memo slots when the tape is compiled. Constant nodes
  are written once, when the value array is sized. A straight-line tape
  that opens the walkers' session skips the memo recall, which can
  never hit there.
- A plan without control flow maps each descriptor DWORD to the node
  computing it, and the walker reads those DWORDs straight from the
  tape's values.
- Each phi's invariant value is resolved once per plan instead of on
  every evaluation.

The tape was checked against the walker in game over millions of
refreshes and descriptor DWORDs without a mismatch.
- DrawRenderState holds three vertex input infos and a pixel input
  info with 32-entry resource arrays, and was value-initialized for
  every draw. One is now kept per executor and only its render-target
  fields are reset, and of the color targets only the slots the
  previous draw resolved; the shader input infos are reset by the code
  that fills them.
- A command buffer remembers the graphics pipeline it bound last and
  skips an identical bind. A new command buffer starts with none, and
  the blit helper, which binds its own pipeline, makes the next draw
  bind again.
- The check that a draw's specialization reads do not alias its writes
  looked up every bound image and written buffer again for each read.
  It now gathers the written image, attachment and buffer ranges once
  per draw, and tests the span of all reads before the pairs, since
  draws read their tables far from their targets.
Every bound texture, color target and depth target of every draw
rebuilt its image description and searched the texture cache, although
they rarely change from one draw to the next.

- A texture's description (tiling layout, mip view, DCC size, view
  info and validation) depends only on its T# and on how the shader
  uses the image. It is kept in a small direct-mapped cache, together
  with the image the texture cache found, the view it selected and the
  cache's lookup generation.
- Color targets are remembered by their registers, mask, slice offset
  and slot, and the depth target's description by its registers. The
  depth and stencil test state is still taken from the registers.
- While the lookup generation is unchanged, a remembered image is
  bound through TextureCache::ReuseImage, which touches it and
  materializes color clears as a lookup does.
- FindImage and the speculative overlap check keep a direct-mapped memo
  keyed by the exact requested image and view description. A result
  stays valid while the cache's structure generation is unchanged; it
  moves when an image is registered or unregistered, when a stencil
  association changes, and when a cached image's stencil plane or
  metadata kind or range changes.

Each memo was checked against the full lookup in game without a
difference.
- A T# MIN_LOD past LAST_LEVEL exited. The texture unit never selects a
  level past the resource's last one, so such a descriptor is legal
  and samples that level. MIN_LOD is clamped to the view's last level,
  which also keeps the min-LOD view within the range Vulkan requires.
- A 256-bit T# with DWORDs 4-7 all zero is a valid encoding (a zero
  PERF_MOD) that describes what a 128-bit T# does: one slice, no
  metadata, no mips past the last level. The storage encoding check
  rejected it. It now takes the 128-bit interpretation for that check
  and for the mip count, as r128 resources already did.
- A null or rejected texture always used a 2D view of a 1x1 2D image,
  so a shader declaring a 1D, 3D or arrayed image sampled a view of
  the wrong type (VUID-vkCmdDispatch-viewType-07752). Null descriptions
  take their image and view type from the resource's dimension, and
  the texture cache keeps one null image per format and image type.
A lost device only said which wait or submit noticed it.

- VK_EXT_device_fault is enabled where the driver offers it. On
  VK_ERROR_DEVICE_LOST the fault description, the faulting GPU
  addresses with their access type and the vendor fault codes are
  printed before exiting.
- Where VK_NV_device_diagnostic_checkpoints is available, every draw
  and dispatch records a checkpoint with its shader hash, and the
  report names the last checkpoints the GPU reached at the top and
  bottom of the pipe. Indirect dispatch arguments are copied into a
  host-visible ring just before each dispatch, so the report also
  shows the arguments the GPU read. Checkpoints are always on, so a
  device-lost report carries them without a rerun; they cost about one
  percent of the frame rate.
Guest threads fault on tens of thousands of watched pages a second,
almost all of them buffer pages, and each fault competed with the GPU
thread for two exclusive locks.

- Page-watch protection changes take the address-space lock shared.
  They only read the mapping tables, and the page manager already
  serializes the watches of each page; mapping changes still take it
  exclusively.
- The texture cache counts registered images per MiB of guest memory
  in a table read without its lock. Registration counts an image
  before its pages are watched or read, so a write fault on memory
  with no image returns without taking the cache lock the command
  processor's image lookups wait on.
The GPU thread bounds the frame rate in CPU-heavy titles, but Windows
scheduled it like any other thread. On a hybrid CPU it ran on
efficiency cores at times, and it shared its core with the guest's
spinning job workers.

With Windows CPU Sets, the thread now takes the fastest core the
scheduler prefers (by efficiency class, then scheduling class), and the
process's other threads default to the remaining cores. Systems with
fewer than eight cores are left alone, so the guest keeps the seven it
expects. Other platforms are unchanged.
A CPU read of GPU-written memory recorded its copy at the end of the
command buffer being recorded, submitted it and waited for everything
recorded so far, one page at a time.

- A readback downloads the GPU-modified data in the 1 MiB-aligned
  window of the buffer around the access, so the neighbouring pages a
  guest touches next are already resident. An unmap publishes only the
  range it removes; the rest of the buffer keeps its GPU data.
- A command buffer is submitted once it has recorded for a millisecond,
  checked between packets and before each draw and dispatch, so the
  GPU runs alongside the command processor instead of idling until a
  long guest submission ends.
- The buffer cache records, per MiB of guest memory, the tick of the
  last command buffer that wrote it on the GPU: shader writes, noted
  when the draw or dispatch is recorded, DMA copies and fills, buffer
  merges and image-to-buffer syncs. Shader address writes have no
  tracked range, so a global tick covers them.
- When every write to the downloaded ranges was submitted, a dedicated
  transfer queue copies them. It waits on the main timeline only for
  those writes, so the copy engines run beside 3D work, and the GPU
  thread polls briefly before blocking. Buffers use concurrent sharing
  across both queue families. Downloads whose writer is still
  recording, that have an unknown write, or that race an asynchronous
  publish keep the main-queue path. Without a transfer-only family, a
  second queue of the main family is used, and without that the old
  path.

Transfer-queue downloads were checked byte for byte against the
main-queue path.
The GPU caches watch guest pages with page protection. A host kernel
write into a watched page fails with ERROR_NOACCESS (EFAULT on Linux)
instead of raising a fault the handler could resolve, so ReadFile
straight into guest memory returned 0 bytes and no error. Calling
InvalidateMemory first is not enough: the GPU thread can watch the
pages again before the read lands. Games then used stale or zeroed
data, which surfaced intermittently as GPU hangs, zeroed shader
headers, unexpected shaders and unreadable SRT data.

read, pread and preadv now read into a 1 MiB host buffer and copy it
into guest memory. The copy is an ordinary CPU write that the fault
handler tracks.
RDNA 2 adds a VGPR texel offset to any image sample, and shaders compute
it per lane. The SPIR-V emitter now folds a sample offset to a constant
and stops the emulator when it cannot, so a compute shader that samples
neighbouring texels at offsets it loads stopped a game at boot.

- With VK_KHR_maintenance8, sampling instructions take a non-constant
  Offset image operand. The device capability reaches the emitter
  through CompileOptions::sample_offsets, and SPIR-V validation allows
  the operand.
- Without it, a level-zero sample moves its normalized coordinates by
  the offset over the size of level zero, which addresses the same
  texel. A sample that can filter other levels still stops: it would
  need the offset in each level's texels.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:56:34 +00:00
Author
Owner

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

Review in Change Stack →

📝 Walkthrough

Walkthrough

The changes add GPU command scheduling and diagnostics, update buffer and texture cache behavior, and add draw and compute execution paths. Shader resource analysis gains bounded descriptor enumeration, fill and copy recognition, and SRT evaluation support. Guest-memory fault handling now accounts for GPU page watches and mapping replacements. File reads use chunked transfers. A shared video-decoder ABI, decoder drain support, and a Vdecsw software-decoder API are added.

Suggested reviewers: nmzik


Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to db876

A memory remapping that overlaps GPU work can hang the emulator. On NVIDIA hardware, diagnostic markers that are always on can reduce performance. Descriptor evaluation and loop-bound handling in the shader paths can produce wrong results or exits in edge cases. Address these issues before merging.

Pre-merge checks | Passed 4 | Inconclusive 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 17.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 317 functions across 50 files. (15 skippe… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check Passed The description directly explains the boot, rendering, performance, memory, shader, Vulkan, and testing changes covered by the pull request.
Title check Passed The title clearly identifies the target game and the main outcomes: booting to gameplay, rendering fixes, and improved frame rate.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.

Full details: Docstring Coverage

Explanation

Docstring coverage is 17.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 317 functions across 50 files. (15 skipped: 1 unsupported, 14 over the file limit.)


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#issuecomment-6113581885) <!-- 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/1430?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough The changes add GPU command scheduling and diagnostics, update buffer and texture cache behavior, and add draw and compute execution paths. Shader resource analysis gains bounded descriptor enumeration, fill and copy recognition, and SRT evaluation support. Guest-memory fault handling now accounts for GPU page watches and mapping replacements. File reads use chunked transfers. A shared video-decoder ABI, decoder drain support, and a Vdecsw software-decoder API are added. **Suggested reviewers:** `nmzik` <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"db8760c7effaf15a91232fe11ffd72804c419996" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟡 Moderate** · up to `db876` <!-- final_review_risk_coverage:{"sourceCommitId":"db8760c7effaf15a91232fe11ffd72804c419996","coveredCommitId":"db8760c7effaf15a91232fe11ffd72804c419996","kind":"reviewed"} --> A memory remapping that overlaps GPU work can hang the emulator. On NVIDIA hardware, diagnostic markers that are always on can reduce performance. Descriptor evaluation and loop-bound handling in the shader paths can produce wrong results or exits in edge cases. Address these issues before merging. <!-- final_review_risk_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-v1.svg" width="14" height="17" align="middle" alt="Passed" title="Passed"></picture></sup> 4 | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v1.svg" width="14" height="17" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 17.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 317 functions across 50 files. (15 skippe… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the boot, rendering, performance, memory, shader, Vulkan, and testing changes covered by the pull request. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly identifies the target game and the main outcomes: booting to gameplay, rendering fixes, and improved frame rate. | | 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. | <hr> </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 17.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 317 functions across 50 files. (15 skipped: 1 unsupported, 14 over the file limit.) </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1430)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -140,0 +281,4 @@
}
(*chunk)[mib & ChunkMask] = tick;
}
}
Author
Owner

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard NoteWrite against a zero-size range.

If size == 0, vaddr + size - 1u evaluates to vaddr - 1. When vaddr is MiB-aligned, the loop then touches no MiB, which is harmless. When vaddr == 0, the expression wraps to UINT64_MAX. The loop then runs until the EXIT_IF bound check stops the process. The current callers pass nonzero sizes, so add an early return for size == 0 as a cheap safeguard for the new public API.

Proposed fix
--- "a/src/graphics/host_gpu/renderer/cache/bufferCache.cpp"
+++ "b/src/graphics/host_gpu/renderer/cache/bufferCache.cpp"
@@ -270,8 +270,11 @@
 	return m_scheduler.CurrentTick();
 }
 
 void BufferCache::NoteWrite(uint64_t vaddr, uint64_t size) {
+	if (size == 0) {
+		return;
+	}
 	constexpr uint64_t ChunkMask = (uint64_t {1} << WriteTickChunkBits) - 1u;
 	const auto         tick      = CurrentTick();
 	for (auto mib = vaddr >> 20u; mib <= (vaddr + size - 1u) >> 20u; ++mib) {
 		EXIT_IF((mib >> WriteTickChunkBits) >= m_write_ticks.size());
📝 Committable suggestion

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

void BufferCache::NoteWrite(uint64_t vaddr, uint64_t size) {
	if (size == 0) {
		return;
	}
	constexpr uint64_t ChunkMask = (uint64_t {1} << WriteTickChunkBits) - 1u;
	const auto         tick      = CurrentTick();
	for (auto mib = vaddr >> 20u; mib <= (vaddr + size - 1u) >> 20u; ++mib) {
		EXIT_IF((mib >> WriteTickChunkBits) >= m_write_ticks.size());
		auto& chunk = m_write_ticks[mib >> WriteTickChunkBits];
		if (chunk == nullptr) {
			chunk = std::make_unique<std::array<uint64_t, WriteTickChunkSize>>();
		}
		(*chunk)[mib & ChunkMask] = tick;
	}
}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#discussion_r4243161818) **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** **Guard `NoteWrite` against a zero-size range.** If `size == 0`, `vaddr + size - 1u` evaluates to `vaddr - 1`. When `vaddr` is MiB-aligned, the loop then touches no MiB, which is harmless. When `vaddr == 0`, the expression wraps to `UINT64_MAX`. The loop then runs until the `EXIT_IF` bound check stops the process. The current callers pass nonzero sizes, so add an early return for `size == 0` as a cheap safeguard for the new public API. <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/host_gpu/renderer/cache/bufferCache.cpp" +++ "b/src/graphics/host_gpu/renderer/cache/bufferCache.cpp" @@ -270,8 +270,11 @@ return m_scheduler.CurrentTick(); } void BufferCache::NoteWrite(uint64_t vaddr, uint64_t size) { + if (size == 0) { + return; + } constexpr uint64_t ChunkMask = (uint64_t {1} << WriteTickChunkBits) - 1u; const auto tick = CurrentTick(); for (auto mib = vaddr >> 20u; mib <= (vaddr + size - 1u) >> 20u; ++mib) { EXIT_IF((mib >> WriteTickChunkBits) >= m_write_ticks.size()); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion void BufferCache::NoteWrite(uint64_t vaddr, uint64_t size) { if (size == 0) { return; } constexpr uint64_t ChunkMask = (uint64_t {1} << WriteTickChunkBits) - 1u; const auto tick = CurrentTick(); for (auto mib = vaddr >> 20u; mib <= (vaddr + size - 1u) >> 20u; ++mib) { EXIT_IF((mib >> WriteTickChunkBits) >= m_write_ticks.size()); auto& chunk = m_write_ticks[mib >> WriteTickChunkBits]; if (chunk == nullptr) { chunk = std::make_unique<std::array<uint64_t, WriteTickChunkSize>>(); } (*chunk)[mib & ChunkMask] = tick; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e1c9413ca9cc5df6cb050808 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -55,0 +175,4 @@
}
VULKAN_HPP_DEFAULT_DISPATCHER.vkCmdSetCheckpointNV(
command, reinterpret_cast<const void*>(static_cast<uintptr_t>(sequence)));
}
Author
Owner

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

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Gate SetCheckpoint behind a debug option. Do not enable it on every device that has the extension.

checkpoints_enabled is set whenever the device advertises VK_NV_device_diagnostic_checkpoints. NVIDIA drivers generally advertise this extension. On those drivers, every draw and every dispatch records vkCmdSetCheckpointNV.

Every indirect dispatch also records two more commands:

  • an eAllCommands → eTransfer memory barrier
  • a copyBuffer into the host-visible args ring

That barrier drains all earlier GPU work before each indirect dispatch. This serializes compute work in normal gameplay on NVIDIA hardware, which works against the PR's frame-rate goal. The data serves only device-lost diagnostics.

Enable checkpoints only through an explicit config flag, such as an existing GPU debug option. As an alternative, keep the marker but skip the barrier and the args copy unless a debug flag is set.

Proposed gating in `src/graphics/presentation/window/vulkanWindow.cpp`
-		if (HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) {
+		if (Config::GraphicsDebugDumpEnabled() &&
+		    HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) {
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#discussion_r4243161837) **🚀 Performance & Scalability** | **🟠 Major** | **⚡ Quick win** **Gate `SetCheckpoint` behind a debug option. Do not enable it on every device that has the extension.** `checkpoints_enabled` is set whenever the device advertises `VK_NV_device_diagnostic_checkpoints`. NVIDIA drivers generally advertise this extension. On those drivers, every draw and every dispatch records `vkCmdSetCheckpointNV`. Every indirect dispatch also records two more commands: - an `eAllCommands` → `eTransfer` memory barrier - a `copyBuffer` into the host-visible args ring That barrier drains all earlier GPU work before each indirect dispatch. This serializes compute work in normal gameplay on NVIDIA hardware, which works against the PR's frame-rate goal. The data serves only device-lost diagnostics. Enable checkpoints only through an explicit config flag, such as an existing GPU debug option. As an alternative, keep the marker but skip the barrier and the args copy unless a debug flag is set. <details> <summary>Proposed gating in `src/graphics/presentation/window/vulkanWindow.cpp`</summary> ```diff - if (HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) { + if (Config::GraphicsDebugDumpEnabled() && + HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) { ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6cb689f53ad505e6e5ab5147 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1530,0 +1568,4 @@
(cop == ValueOpcode::ULessThan32 || cop == ValueOpcode::SLessThan32) &&
ValidateRuntimeValue(m_program, compare->Arg(1), RuntimeValueType::Integer)) {
range.begin = Value(start);
range.end = compare->Arg(1).Resolve();
Author
Owner

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

A signed ascending bound becomes an unsigned range, so a zero-trip loop can stop the emulator.

CountingLoopRange accepts both SLessThan32 and ULessThan32 as the bound. It stores the bound as [start, bound) and does not record which comparison it came from. KeySetEvaluator::Run (ResourceMaterialization.cpp Lines 226-239) evaluates begin and end as unsigned values.

Example: the guard is SLessThan32(counter, count) and count is negative at runtime, such as 0xFFFFFFFF.

  • On the GPU the loop runs zero times.
  • end - begin exceeds MaxValues, so Run returns false.
  • For an enumerated buffer table (dword_count != 8), MaterializeIndirectDescriptor then fails with "GPU-selected descriptor key has no bounded value set".
  • pipelineCache.cpp turns that failure into EXIT.
  • For image tables, the same input falls back to scanning 1024 keys when no keys can be selected.

Fix: record the comparison's signedness in InductionRange. In Run, treat a signed range whose signed end is at or below its signed begin as empty.

Proposed fix
 				} else if (ascending &&
 				           (cop == ValueOpcode::ULessThan32 || cop == ValueOpcode::SLessThan32) &&
 				           ValidateRuntimeValue(m_program, compare->Arg(1), RuntimeValueType::Integer)) {
 					range.begin = Value(start);
 					range.end   = compare->Arg(1).Resolve();
+					range.is_signed = cop == ValueOpcode::SLessThan32;

In KeySetEvaluator::Run:

-			if (begin < end) {
+			const bool empty = range.is_signed
+			    ? std::bit_cast<int32_t>(end) <= std::bit_cast<int32_t>(begin)
+			    : end <= begin;
+			if (!empty) {

Add bool is_signed = false; to DescriptorSource::IndirectDescriptor::InductionRange, and copy it in ExtractResourcePlan.

📝 Committable suggestion

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

				} else if (ascending &&
				           (cop == ValueOpcode::ULessThan32 || cop == ValueOpcode::SLessThan32) &&
				           ValidateRuntimeValue(m_program, compare->Arg(1), RuntimeValueType::Integer)) {
					range.begin = Value(start);
					range.end   = compare->Arg(1).Resolve();
					range.is_signed = cop == ValueOpcode::SLessThan32;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#discussion_r4243161843) **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** **A signed ascending bound becomes an unsigned range, so a zero-trip loop can stop the emulator.** `CountingLoopRange` accepts both `SLessThan32` and `ULessThan32` as the bound. It stores the bound as `[start, bound)` and does not record which comparison it came from. `KeySetEvaluator::Run` (ResourceMaterialization.cpp Lines 226-239) evaluates `begin` and `end` as unsigned values. Example: the guard is `SLessThan32(counter, count)` and `count` is negative at runtime, such as `0xFFFFFFFF`. - On the GPU the loop runs zero times. - `end - begin` exceeds `MaxValues`, so `Run` returns false. - For an enumerated buffer table (`dword_count != 8`), `MaterializeIndirectDescriptor` then fails with "GPU-selected descriptor key has no bounded value set". - `pipelineCache.cpp` turns that failure into `EXIT`. - For image tables, the same input falls back to scanning 1024 keys when no keys can be selected. Fix: record the comparison's signedness in `InductionRange`. In `Run`, treat a signed range whose signed `end` is at or below its signed `begin` as empty. <details> <summary>Proposed fix</summary> ```diff } else if (ascending && (cop == ValueOpcode::ULessThan32 || cop == ValueOpcode::SLessThan32) && ValidateRuntimeValue(m_program, compare->Arg(1), RuntimeValueType::Integer)) { range.begin = Value(start); range.end = compare->Arg(1).Resolve(); + range.is_signed = cop == ValueOpcode::SLessThan32; ``` In `KeySetEvaluator::Run`: ```diff - if (begin < end) { + const bool empty = range.is_signed + ? std::bit_cast<int32_t>(end) <= std::bit_cast<int32_t>(begin) + : end <= begin; + if (!empty) { ``` Add `bool is_signed = false;` to `DescriptorSource::IndirectDescriptor::InductionRange`, and copy it in `ExtractResourcePlan`. </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion } else if (ascending && (cop == ValueOpcode::ULessThan32 || cop == ValueOpcode::SLessThan32) && ValidateRuntimeValue(m_program, compare->Arg(1), RuntimeValueType::Integer)) { range.begin = Value(start); range.end = compare->Arg(1).Resolve(); range.is_signed = cop == ValueOpcode::SLessThan32; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8e280f7bb1d6b865ebfed0d7 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1070,0 +1502,4 @@
values[index] = tape->nodes[index].immediate;
}
}
}
Author
Owner

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

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Find callers that create SrtWalker sessions and call RefreshFlatBuffer / EvaluateDescriptor.
rg -nP --type=cpp -C4 '\bSrtWalker\s+\w+\s*\(|\.RefreshFlatBuffer\s*\(|\.EvaluateDescriptor\s*\('
rg -nP --type=cpp -C3 'srt_tape_values|evaluation_contexts|evaluation_depth'

Repository: KytyPS5/KytyPS5

Length of output: 42449


The shared srt_tape_values vector can be overwritten by another SrtWalker before the first walker calls EvaluateDescriptor. RefreshFlatBuffer writes this plan-level vector, while EvaluateDescriptor reads it without checking the walker context. Store tape values in EvaluationContext or otherwise prevent interleaved refreshes on the same plan.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#discussion_r4243161845) **🗄️ Data Integrity & Integration** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Find callers that create SrtWalker sessions and call RefreshFlatBuffer / EvaluateDescriptor. rg -nP --type=cpp -C4 '\bSrtWalker\s+\w+\s*\(|\.RefreshFlatBuffer\s*\(|\.EvaluateDescriptor\s*\(' rg -nP --type=cpp -C3 'srt_tape_values|evaluation_contexts|evaluation_depth' ``` Repository: KytyPS5/KytyPS5 Length of output: 42449 --- </details> The shared `srt_tape_values` vector can be overwritten by another `SrtWalker` before the first walker calls `EvaluateDescriptor`. `RefreshFlatBuffer` writes this plan-level vector, while `EvaluateDescriptor` reads it without checking the walker context. Store tape values in `EvaluationContext` or otherwise prevent interleaved refreshes on the same plan. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e511ee7ffa4cff8d9a018ff9 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -795,0 +929,4 @@
if (!replacing() && m_replacement_generation == generation) {
return false;
}
m_replacement_done.wait(lock, [&] { return !replacing(); });
Author
Owner

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C4 '\b(UnmapMemory|MapMemory|InvalidateMemory)\s*\(' src/graphics/host_gpu/renderer/renderContext.cpp
rg -nP -C3 'lock_guard|unique_lock|scoped_lock' src/graphics/host_gpu/renderer/cache/bufferCache.cpp | head -80

Repository: KytyPS5/KytyPS5

Length of output: 2619


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- memoryAddressSpace replacement and fault paths ---'
nl -ba src/kernel/memoryAddressSpace.inc | sed -n '820,1010p'
printf '%s\n' '--- replacement symbols and callers ---'
rg -n -F --glob '*.{cpp,h,hpp,inc}' -e 'BeginReplacement' -e 'EndReplacement' -e 'ReplacementWindow' -e 'ResolveTransientFault' -e 'HandleMemoryFault' src
printf '%s\n' '--- RenderContext mapping methods ---'
nl -ba src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,190p'
printf '%s\n' '--- cache methods and lock declarations ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'InvalidateMemory' -e 'UnmapMemory' -e 'ReadMemory' -e 'm_mutex' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer | head -180

Repository: KytyPS5/KytyPS5

Length of output: 25005


🏁 Script executed:

nl -ba src/kernel/memoryAddressSpace.inc | sed -n '880,970p'
printf '%s\n' '--- callers ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' --glob '*.inc' -e 'BeginReplacement' -e 'EndReplacement' -e 'ResolveTransientFault' -e 'HandleMemoryFault' -e 'ReplacementWindow' src || true

Repository: KytyPS5/KytyPS5

Length of output: 5640


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- fault handler and replacement owner ---'
nl -ba src/kernel/memory.cpp | sed -n '910,1070p'
printf '%s\n' '--- replacement call site 1 ---'
nl -ba src/kernel/memory.cpp | sed -n '2335,2395p'
printf '%s\n' '--- replacement call site 2 ---'
nl -ba src/kernel/memory.cpp | sed -n '3120,3180p'
printf '%s\n' '--- BufferCache fault-related methods ---'
nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '440,540p'
printf '%s\n' '--- TextureCache unmap method ---'
nl -ba src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '2025,2095p'

Repository: KytyPS5/KytyPS5

Length of output: 19407


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- replacement implementation and GPU unmap ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -e 'ReplaceFixedRangeWithReserved' -e 'UnmapGpuRange' src/kernel src/graphics
printf '%s\n' '--- definitions and surrounding blocks ---'
python3 - <<'PY'
from pathlib import Path
for p in [Path('src/kernel/memory.cpp'), Path('src/graphics/host_gpu/renderer/renderContext.cpp')]:
    lines = p.read_text().splitlines()
    for i, line in enumerate(lines):
        if 'ReplaceFixedRangeWithReserved' in line or 'UnmapGpuRange' in line:
            lo=max(0,i-12); hi=min(len(lines),i+45)
            print(f'--- {p}:{lo+1}-{hi} ---')
            for n in range(lo,hi):
                print(f'{n+1:5} {lines[n]}')
PY

Repository: KytyPS5/KytyPS5

Length of output: 42289


🏁 Script executed:

set -o pipefail
rg -n -F --glob '*.{cpp,h,hpp,inc}' -e 'SendCommandSync' -e 'void SendCommand' -e 'SendCommand(' src/graphics src

Repository: KytyPS5/KytyPS5

Length of output: 1741


🏁 Script executed:

nl -ba src/graphics/guest_gpu/graphicsRun.cpp | sed -n '80,145p'

Repository: KytyPS5/KytyPS5

Length of output: 2253


Bound the replacement wait in the fault handler.

When a transient fault reaches ResolveTransientFault during a fixed replacement, the resolver waits without a deadline. ReplaceFixedRangeWithReserved calls UnmapGpuRange while ReplacementWindow is active. From a non-GPU thread, SendCommandSync then waits for the GPU command to finish. If that command faults in the replacement range, its fault handler waits for EndReplacement, while the replacement thread waits for the command. This can deadlock. The 250 ms deadline in HandleMemoryFault is checked only after ResolveTransientFault returns.

Bound the condition-variable wait and return false when it expires.

Suggested bounded wait
-			m_replacement_done.wait(lock, [&] { return !replacing(); });
+			if (!m_replacement_done.wait_for(lock, std::chrono::milliseconds(250),
+			                                 [&] { return !replacing(); })) {
+				return false;
+			}
📝 Committable suggestion

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

			std::unique_lock lock(m_replacement_mutex);
			if (!replacing() && m_replacement_generation == generation) {
				return false;
			}
			if (!m_replacement_done.wait_for(lock, std::chrono::milliseconds(250),
			                                 [&] { return !replacing(); })) {
				return false;
			}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#discussion_r4243161847) **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C4 '\b(UnmapMemory|MapMemory|InvalidateMemory)\s*\(' src/graphics/host_gpu/renderer/renderContext.cpp rg -nP -C3 'lock_guard|unique_lock|scoped_lock' src/graphics/host_gpu/renderer/cache/bufferCache.cpp | head -80 ``` Repository: KytyPS5/KytyPS5 Length of output: 2619 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- memoryAddressSpace replacement and fault paths ---' nl -ba src/kernel/memoryAddressSpace.inc | sed -n '820,1010p' printf '%s\n' '--- replacement symbols and callers ---' rg -n -F --glob '*.{cpp,h,hpp,inc}' -e 'BeginReplacement' -e 'EndReplacement' -e 'ReplacementWindow' -e 'ResolveTransientFault' -e 'HandleMemoryFault' src printf '%s\n' '--- RenderContext mapping methods ---' nl -ba src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,190p' printf '%s\n' '--- cache methods and lock declarations ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'InvalidateMemory' -e 'UnmapMemory' -e 'ReadMemory' -e 'm_mutex' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer | head -180 ``` Repository: KytyPS5/KytyPS5 Length of output: 25005 --- 🏁 Script executed: ```bash nl -ba src/kernel/memoryAddressSpace.inc | sed -n '880,970p' printf '%s\n' '--- callers ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' --glob '*.inc' -e 'BeginReplacement' -e 'EndReplacement' -e 'ResolveTransientFault' -e 'HandleMemoryFault' -e 'ReplacementWindow' src || true ``` Repository: KytyPS5/KytyPS5 Length of output: 5640 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- fault handler and replacement owner ---' nl -ba src/kernel/memory.cpp | sed -n '910,1070p' printf '%s\n' '--- replacement call site 1 ---' nl -ba src/kernel/memory.cpp | sed -n '2335,2395p' printf '%s\n' '--- replacement call site 2 ---' nl -ba src/kernel/memory.cpp | sed -n '3120,3180p' printf '%s\n' '--- BufferCache fault-related methods ---' nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '440,540p' printf '%s\n' '--- TextureCache unmap method ---' nl -ba src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '2025,2095p' ``` Repository: KytyPS5/KytyPS5 Length of output: 19407 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- replacement implementation and GPU unmap ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -e 'ReplaceFixedRangeWithReserved' -e 'UnmapGpuRange' src/kernel src/graphics printf '%s\n' '--- definitions and surrounding blocks ---' python3 - <<'PY' from pathlib import Path for p in [Path('src/kernel/memory.cpp'), Path('src/graphics/host_gpu/renderer/renderContext.cpp')]: lines = p.read_text().splitlines() for i, line in enumerate(lines): if 'ReplaceFixedRangeWithReserved' in line or 'UnmapGpuRange' in line: lo=max(0,i-12); hi=min(len(lines),i+45) print(f'--- {p}:{lo+1}-{hi} ---') for n in range(lo,hi): print(f'{n+1:5} {lines[n]}') PY ``` Repository: KytyPS5/KytyPS5 Length of output: 42289 --- 🏁 Script executed: ```bash set -o pipefail rg -n -F --glob '*.{cpp,h,hpp,inc}' -e 'SendCommandSync' -e 'void SendCommand' -e 'SendCommand(' src/graphics src ``` Repository: KytyPS5/KytyPS5 Length of output: 1741 --- 🏁 Script executed: ```bash nl -ba src/graphics/guest_gpu/graphicsRun.cpp | sed -n '80,145p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2253 --- </details> **Bound the replacement wait in the fault handler.** When a transient fault reaches `ResolveTransientFault` during a fixed replacement, the resolver waits without a deadline. `ReplaceFixedRangeWithReserved` calls `UnmapGpuRange` while `ReplacementWindow` is active. From a non-GPU thread, `SendCommandSync` then waits for the GPU command to finish. If that command faults in the replacement range, its fault handler waits for `EndReplacement`, while the replacement thread waits for the command. This can deadlock. The 250 ms deadline in `HandleMemoryFault` is checked only after `ResolveTransientFault` returns. Bound the condition-variable wait and return `false` when it expires. <details> <summary>Suggested bounded wait</summary> ```diff - m_replacement_done.wait(lock, [&] { return !replacing(); }); + if (!m_replacement_done.wait_for(lock, std::chrono::milliseconds(250), + [&] { return !replacing(); })) { + return false; + } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion std::unique_lock lock(m_replacement_mutex); if (!replacing() && m_replacement_generation == generation) { return false; } if (!m_replacement_done.wait_for(lock, std::chrono::milliseconds(250), [&] { return !replacing(); })) { return false; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:383c0a4cb56d6ce0c2e2eaa3 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 5


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d06d07b2-3018-41eb-ae88-83d872870d9e
📥 Commits

Reviewing files that changed from the base of the PR and between e51de54ee4 and db8760c7ef.

📒 Files selected for processing (65)
  • src/common/threads.cpp
  • src/common/threads.h
  • src/graphics/guest_gpu/command_processor/pm4Handlers.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/pageManager.cpp
  • src/graphics/host_gpu/pageManager.h
  • src/graphics/host_gpu/rangeSet.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/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/colorRenderTarget.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.h
  • src/graphics/host_gpu/renderer/context.cpp
  • src/graphics/host_gpu/renderer/depthRenderTarget.cpp
  • src/graphics/host_gpu/renderer/image/blitHelper.cpp
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/masterSemaphore.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.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/vma.cpp
  • src/graphics/presentation/window/vulkanWindow.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/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/ir/ResourceSnapshot.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.cpp
  • src/graphics/shader/recompiler/ir/Value.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/kernel/fileSystem.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/libs/libVdecsw.cpp
  • src/libs/libVideoDec2.cpp
  • src/libs/libs.cpp
  • src/libs/videoDec2.h
  • src/libs/videoDec2Decoder.cpp
  • src/libs/videoDec2Decoder.h
  • src/loader/runtimeLinker.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/shaderCfgTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#pullrequestreview-5484891204) · **reviewed** **Actionable comments posted: 5** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `d06d07b2-3018-41eb-ae88-83d872870d9e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e51de54ee401df70f042103fb7c1c346ee4fdc23 and db8760c7effaf15a91232fe11ffd72804c419996. </details> <details> <summary>📒 Files selected for processing (65)</summary> * `src/common/threads.cpp` * `src/common/threads.h` * `src/graphics/guest_gpu/command_processor/pm4Handlers.cpp` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/memoryTracker.cpp` * `src/graphics/host_gpu/memoryTracker.h` * `src/graphics/host_gpu/pageManager.cpp` * `src/graphics/host_gpu/pageManager.h` * `src/graphics/host_gpu/rangeSet.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/streamBuffer.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/colorRenderTarget.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.h` * `src/graphics/host_gpu/renderer/context.cpp` * `src/graphics/host_gpu/renderer/depthRenderTarget.cpp` * `src/graphics/host_gpu/renderer/image/blitHelper.cpp` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/masterSemaphore.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.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/vma.cpp` * `src/graphics/presentation/window/vulkanWindow.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/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/ir/ResourceSnapshot.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/Value.cpp` * `src/graphics/shader/recompiler/ir/Value.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `src/kernel/fileSystem.cpp` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/libs/libVdecsw.cpp` * `src/libs/libVideoDec2.cpp` * `src/libs/libs.cpp` * `src/libs/videoDec2.h` * `src/libs/videoDec2Decoder.cpp` * `src/libs/videoDec2Decoder.h` * `src/loader/runtimeLinker.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/VirtualMemoryAllocationTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=505c98c1-ae0a-4ce0-9039-c3638c3f0c42 attempt=b13e9685-9721-46c3-a13a-419d0c566e3b batch=1/1 -->
Author
Owner

@⁠Crispy81 on GitHub · 2026-10-11 21:55 UTC · original

Look forward to this being merged.

**@⁠Crispy81** on GitHub · 2026-10-11 21:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#issuecomment-6114229493) Look forward to this being merged.
Author
Owner

@⁠Almo7aya on GitHub · 2026-10-16 14:00 UTC · original

@⁠Nmzik Hey, any chance we can get this commit into main? e9dbf19

Uncharted (PPSA05389) doesn't boot on current main without it, it dies at boot with condition (!Active()) is true in commandScheduler.cpp:325. I cherry-picked it on top of 9e41d83 and it applies clean and gets the game to the title screen.

The crash is because HandleFault sends every fault in GPU-visible memory to the caches, even ones no page watch caused (guest-protected pages, or pages that are briefly gone while Windows remaps a view), so the caches try to record before there's any command buffer. The commit makes the caches only take faults their own watches caused.

It also fixes a few related Windows remapping issues: faults that hit mid-remap get retried instead of killing the thread, view splits keep their page protections, backing reads/writes don't race splits, and watched code pages stay executable.

I know it touches a core part of the emulator but I tried to validate it as much as possible with all the games I have

**@⁠Almo7aya** on GitHub · 2026-10-16 14:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#issuecomment-6217148702) @⁠Nmzik Hey, any chance we can get this commit into main? [`e9dbf19`](https://git.gtahub.st/github/KytyPS5--KytyPS5/pulls/1430/commits/e9dbf19a73ab8904af83f17af2eabc2fe7f15829) Uncharted (PPSA05389) doesn't boot on current main without it, it dies at boot with `condition (!Active()) is true` in commandScheduler.cpp:325. I cherry-picked it on top of 9e41d83 and it applies clean and gets the game to the title screen. The crash is because HandleFault sends every fault in GPU-visible memory to the caches, even ones no page watch caused (guest-protected pages, or pages that are briefly gone while Windows remaps a view), so the caches try to record before there's any command buffer. The commit makes the caches only take faults their own watches caused. It also fixes a few related Windows remapping issues: faults that hit mid-remap get retried instead of killing the thread, view splits keep their page protections, backing reads/writes don't race splits, and watched code pages stay executable. I know it touches a core part of the emulator but I tried to validate it as much as possible with all the games I have
Author
Owner

@⁠Almo7aya on GitHub · 2026-10-24 16:41 UTC · original

@⁠Nmzik don't forget me :(, should I rebase this PR and drop the already implemented commits?

**@⁠Almo7aya** on GitHub · 2026-10-24 16:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1430#issuecomment-6386816769) @⁠Nmzik don't forget me :(, should I rebase this PR and drop the already implemented commits?
This pull request has changes conflicting with the target branch.
  • src/common/threads.cpp
  • src/common/threads.h
  • src/graphics/guest_gpu/command_processor/pm4Handlers.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.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/colorRenderTarget.cpp
  • 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/imageInfo.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.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/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/ir/ResourceSnapshot.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.cpp
  • src/graphics/shader/recompiler/ir/Value.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/kernel/fileSystem.cpp
  • src/kernel/memory.cpp
  • src/kernel/memoryAddressSpace.inc
  • src/libs/libVdecsw.cpp
  • src/libs/libVideoDec2.cpp
  • src/libs/videoDec2Decoder.cpp
  • src/loader/runtimeLinker.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/shaderCfgTests.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

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

Merge

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