Boot Demon's Souls to its first level: AGC recorder driver, runtime, audio, Bink fixes #5

Merged
yumlevi merged 15 commits from upstream-pr/5 into main 2026-09-27 21:40:25 +00:00
yumlevi commented 2026-09-25 23:28:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-25T23:28:17Z.


Summary

Boots Demon's Souls (PPSA01342) from the SIE logo through the Bink intro, the language menu, the title screen, the main menu and the in-engine intro cinematic, at roughly 11 fps at 4K on a 24-core Windows host with an NVIDIA GPU. The game then starts NEW GAME, shows its "Unable to connect to the server" dialog, and loads the first level until the first DRAW_INDIRECT submission, which the driver does not support yet (next item).

The work is in six areas, each its own commit (split by area for review; the tip builds cleanly from scratch, the intermediate commits are not guaranteed to build on their own):

  • perf(agc): the AGC driver's execution model changes from synchronous per-command GPU round trips to a batched recorder over host-imported guest memory with deferred write-back and content caches (13 s -> ~0.1 s per frame on this title).
  • fix(recompiler): s_*_saveexec operand order (the aliased s_and_saveexec_b64 vcc, vcc computed exec & exec; every Bink 2 decoder kernel uses that form), identity-operand buffer atomics, per-element write flags, cheaper cache keys.
  • feat(runtime): a reserved guest arena below the PS5 map limit with write watch, a caching guest heap, most of the pthread/event-flag/semaphore/file/time kernel APIs, SSE4a emulation on Intel hosts, crash and abort backtraces, wide printf conversions.
  • feat(audio): AudioOut2 on an SDL output queue with port mixing, an ATRAC9 decoder for libSceAjm.native on the existing libatrac9 submodule.
  • feat(libs): PM4 builders and patch functions in libSceAgc, save-data mounts/backup/memory, user/system service and store dialog behaviour for an offline console, six new export-only modules the title links.
  • chore(gitignore): ignore the secondary build_tools/ CMake tree.

Update 2026-09-26: the intro-video stage now runs at ~48 fps at 4K (from ~15 fps at the first push), --to-intel is implemented in the relinker as requested, and the recent upstream fixes are adopted; details in the last section.

This replaces upstream driver work

The driver commit removes the code of 5a280ce, 7ed5a0b, 46c799d, 598caac and 40df528 (render targets on the GPU across ACQUIRE_MEM, pipeline cache key, device-local tile buffers, batched draws with descriptor/sampler/buffer caches, fault-based guest memory ownership tracking). The same concerns are covered by the recorder, resident storage-texture targets, the pipeline cache keyed by recompile variant ids, the descriptor/sampler caches in ShaderResources, the two-tier BufferPool, and write-watch tracking in GuestMemory. The fault-based tracking layer in libc (GuestMemoryTracking, GuestMemoryBacking, GuestHeapStorage, MemoryTracking*, MemoryBacking*) is replaced by GuestArena + GuestHeap because guest code indexes tables by absolute address and corrupts memory when handed host addresses above 1 TiB, and page write watch was measured far cheaper than byte compares. The superseded files are deleted in this PR rather than left unbuilt.

Driver (core/libs/prx/libSceAgcDriver)

  • Graphics/Recorder: one open command buffer per device; dispatches, all-resident draws, texture uploads and write-backs, label stores, fills and copies record into it. Batches carry serials signalled on a timeline semaphore so drains wait without the GPU mutex; completions (CPU write-backs) run in order at reap; kept objects are released on a bounded thread after the unlock; a lock-free pending-write snapshot lets the guest-memory flush hook skip the mutex; a pending-label table satisfies WAIT_REG_MEM from labels already recorded.
  • Driver.cpp: one worker thread per PM4 queue; RELEASE_MEM/WRITE_DATA labels and COPY_DATA/DMA_DATA/DUMP_CONST_RAM stores are written by the GPU into the host import; DISPATCH_INDIRECT runs GPU-side; the title's buffer-fill kernel is replaced by vkCmdFillBuffer; a dispatch cache keyed by program, user data and SH registers reuses capture and recompile while the captured memory is unchanged; type-2 filler packets are tolerated; a rejected submission prints its packet summary and last packets (the binary dump is opt-in).
  • GuestMemory: the driver owns a recursive GPU mutex with per-site profiling; a page-state cache invalidated through libc replaces per-check VirtualQuery; 64 KiB-block write generations from GetWriteWatch with a per-thread collect memo.
  • GuestBufferMemory: registered allocations are imported with VK_EXT_external_memory_host (budget APS5_HOST_IMPORT_MIB, default 6 GiB; this title's later stages need 16 GiB); the executable image's ranges get persistent mirrors instead of per-build copies; misaligned descriptor sub-ranges inside imports are copied on the GPU; registry leases are released at batch completion.
  • Texture: shader-written images stay on the GPU with deferred write-back (blocks the CPU wrote since the last sync are kept; adjacent images sharing a 64 KiB stamp block are advanced together, which fixed the green blocks in Bink video); sampled textures over host-imported surfaces are views of the storage image; DCC fast-clear keys are honoured on reads and set to uncompressed after writes; addrlib GFX10 swizzle equations drive the detiler both ways.
  • Draw, Pipeline, State: MRT with per-slot blend state, more colour formats, dynamic viewport/scissor, pipelines cached by stage variant ids, 64 KiB tiled targets attached as resident images, all-resident draws recorded into the recorder.
  • ShaderResources: two-stage build (unlocked plan and descriptor set, locked image lookups and writes), per-device descriptor and sampler caches, a content-keyed resource cache shared by dispatches and draws, read-only V# elements skip write-back.
  • VulkanDevice, presentation: the GPU mutex is held only for the queue submit; flips present from the resident display image; APS5_DUMP_FRAMES reads frames back on the GPU.
  • One late label re-store was fixed on the way: a label deferred behind a completion was re-written by a CPU memcpy at reap time, which could land on memory the game had recycled for a new command buffer (it corrupted a WAIT_REG_MEM header at the intro cinematic).

Recompiler (core/shader/recompiler)

  • sSaveexec reads its source before writing the old EXEC into the destination; the per-lane exec bit comes from the lane's own bit. APS5_SAVEEXEC_WRITE_FIRST=1 restores the old order.
  • Buffer atomics add/sub/or/xor with a zero operand become an atomic load or nothing (two histogram kernels went from 29/24 ms to 1.3/0.5 ms per dispatch). APS5_NO_ATOMIC_ZERO_SKIP=1 restores plain atomics.
  • DescriptorBinding carries bufferWritten/bufferAtomic/imageWritten; results expose a variantId; SPIR-V is shared copy-on-write; source keys use a length plus 64-bit hash; captures can be reused for the compile.
  • Wave-LDS ordering barriers for compute programs that write LDS, v_movrels/v_movreld lowering, SMEM with VCC base, f16 conversion opcode fix, a hand-picked SPIRV-Tools pass list (APS5_SPIRV_OPT=full|none), and env-gated probes (APS5_DUMP_IR, APS5_PROBE, APS5_TRACE_BDA, APS5_LOOP_GUARD).

Runtime (core/libs/prx/libc, libkernel)

  • GuestArena: guest memory in one reserved arena from 0x10_0000_0000 with MEM_WRITE_WATCH; GuestHeap: size classes plus a bounded large-block cache (APS5_HEAP_CACHE_MIB); the allocation registry gains a generation counter, an invalidator callback for the driver's page cache, and a pin waiter instead of throwing on a leased range.
  • libkernel: mmap/mprotect/munmap on the arena, flexible memory budget, real sceKernelVirtualQuery; the POSIX pthread layer, rwlocks, timed locks, TSD, event flags; a 0.5 ms scheduler tick and high-resolution sleeps; TSC/clock/time functions; file APIs returning SCE errno codes; the APR file-streaming API shared with libSceAmpr.
  • libc: a vectored crash reporter with registers, frame chain and return-address candidates; SIGABRT, UCRT invalid-parameter and process-exit backtraces (abort and 0xC0000409 fast-fails were silent); SSE4a EXTRQ/INSERTQ emulation; %ls/%lc/%S/%C with the guest's 16-bit wchar_t; hand-written setjmp/longjmp for the guest's jmp_buf; a path-alias table so save-data mount points fit the 16-byte field; more string, stdio and math exports.

Audio (libSceAudioOut, libSceAjm.native)

  • AudioOut2: one SDL F32 stereo 48 kHz device per context; the hardware grain queue level is derived from the SDL queued bytes, so the title's poll-and-push loop runs at real time (it ran 4-5x too fast against the old "always empty" stub); ports are mixed per push with 7.1 folded to stereo. Object-port position attributes are ignored (unpanned).
  • libSceAjm.native: instance and batch APIs, ATRAC9 decoding with variable-size frames inside superframes, padding, gapless parameters and handle re-creation on re-initialisation. Other codecs are reported once and fail with a codec error.
  • AudioOut v1: sceAudioOutOutput(handle, NULL) drains instead of throwing.

Libraries (libSceAgc and other prx)

  • libSceAgc: SetIndexCount, SetBaseIndirectArgs, DispatchIndirect (both forms), wait/write-data patch functions, relaxed checks for what the title sends (null wait addresses filled later, 64-bit masks on 32-bit waits, unaligned ACQUIRE_MEM ranges), NOP fillers for LOD stats and wait-until-safe, a NotImplemented stub file in upstream's pattern.
  • libSceSaveData.native: short mount points through the libc alias table, backup events, save-data memory slots persisted per slot.
  • libSceUserService (login event, all-zero game presets), libSceSystemService (safe area, notice skip), libSceNpCommerce (store dialog finishes as user-cancelled), libSceVideoOut (all flip modes, queue-full error instead of throw, non-blocking presenter), libSceAcm, libScePad (scePadRead), libSceFiber, offline behaviour for the network/NP modules, and new export-only modules libSceAmpr, libSceJpegEnc, libSceJson2, libSceMsgDialog.native, libSceNpCppWebApi, libSceNpUtility.

Verification

  • Clean configure and build of the whole tree from scratch (all prx modules, tools and the relinker) with the WinLibs MinGW UCRT toolchain.
  • Runs of the title with frame dumps at every stage: the SIE and Bluepoint logos, the Bink intro (every frame decodes cleanly; the white/speckle and green-block corruption is gone with the saveexec and adjacent-generation fixes), the language menu, the title screen, the main menu (NEW GAME / SETTINGS over the Nexus statue video), and the in-engine intro cinematic (mountains, characters, fight scenes render correctly). Three consecutive runs through the cinematic start survived after the label re-store fix.
  • AudioOut2 pacing measured at 187.5 pushes/s with 104 s of cutscene audio in 103 s of wall time.

Switches

About 165 APS5_* environment variables were added: kill switches for each optimisation (APS5_NO_*), tracing (APS5_TRACE_*), profiling (APS5_PROFILE_DRAW, APS5_PROFILE_GPU), dumps (APS5_DUMP_FRAMES, APS5_DUMP_SHADERS, APS5_DUMP_REJECTED) and tuning (APS5_HOST_IMPORT_MIB, APS5_LABEL_FLUSH_US, APS5_HEAP_CACHE_MIB). Every one is read once at first use and has no effect when unset.

Known gaps and open items

  • Code comments: the changes add explanatory comments throughout, which docs/CONVENTIONS.md does not allow. I left them in so reviewers can read the mechanisms; I can strip them (or move the design into a docs/ note) if that is preferred before merging.
  • Silent stubs that docs/TechnicalDebt.md asks to list: the store dialog, share/gesture/json initialisers, NP web API setters, the unnamed libSceAgc NID -KRzWekV120, LOD-stats and wait-until-safe fillers, output gamma/latency calls.
  • Indirect draws (DRAW_INDIRECT and siblings) are not implemented; the title's first level submission is rejected there.
  • The default host-import budget (6 GiB) is too small for this title's later stages; runs use APS5_HOST_IMPORT_MIB=16384.
  • Object-port audio positions are ignored; other AJM codecs are not decoded.
  • Tests were not extended for the new driver code; two descriptor tests now only check that streaming-feedback and anisotropy fields decode instead of asserting rejection.

Update 2026-09-26 (commits af3c202, 01c4e3e, 29b4601): intro-video stage from ~15 fps to ~48 fps, --to-intel relinker lowering, upstream fixes

Measured at 4K on the same host, intro-video stage (SIE logo, Bink intro, in-engine cinematic), presents per 10 s over the last 60 s of a 150 s run (frames byte-identical to the previous build in every configuration):

Build presents / 10 s ms per frame
previous push (d677f97) 154 65
worker/job affinity off by default 165 61
dispatch variants + recipes + template data refresh 215 46
unit shadows (device-local slabs per host import) 240-250 41
CPU-side stages (counters, hook fix, T1 trim, BDA address space, dispatch/draw recipes, known-value copies) 267 37
plan-failure memo (one compute program fails its plan every frame) 385-417 25
data-only dispatch-cache hits + poisoned source memo 495-522 19.5
+ bindless image tables (the skipped per-frame program now runs; 29b4601) 476-495 20.8

Driver (core/libs/prx/libSceAgcDriver)

  • Dispatch cache: per-key value-set variants (k = 4), and data-only hits: a variant whose captured words differ from guest memory only at flat-SRT leaves the recompiler proves are pure data (IrResourcePlan::pureFlatSlots, never a descriptor source, condition, uniform-fill value or read address) is served without a capture, recompile or insert; the compiled result is patched and the resource template's data buffers are refreshed by words. APS5_NO_DATA_HITS=1 disables, APS5_VERIFY_DATA_HITS=1 captures beside every hit and aborts on any disagreement (150 s run: 0 disagreements).
  • Dispatch and draw recipes: a hit replays the previous prepare (template, pipeline objects, push bytes, presync surfaces) after a pre-check proof; draw entries keyed by the register banks and the registry before any decode. APS5_NO_DISPATCH_RECIPE, APS5_NO_DRAW_RECIPE, APS5_NO_DRAW_KEY, APS5_VERIFY_RECIPE, APS5_VERIFY_DRAW_ENTRIES, APS5_VERIFY_DRAW_RECIPE.
  • Resource templates refresh their data buffers in place when only flat-SRT / shader-data words differ (vkCmdUpdateBuffer, hashed, APS5_NO_TEMPLATE_DATA_REFRESH=1 keys the words as before).
  • Unit shadows: results of shader-written buffers live in device-local slabs per host import and are published before host-facing consumers; block-unit (64 KiB) storage tracking with per-piece write-back (APS5_BLOCK_WRITEBACK_WIDEN=1 widens), windowed detile.
  • DCC clear-key proofs (DccKeyProof), per-class GPU timing ([gputime]), per-layer storage clears.
  • Throughput: lazy completion counting, a rate-limited reap, a PFN table for page-state checks, epoch-gated revalidation, indirect template data refresh, a source-handle memo per shader snapshot, a draw pre-check.
  • CPU copy path with batch read tracking; present slot ring with early flip completion (APS5_FLIP_INFLIGHT); late label trust as an opt-in (APS5_LABEL_TRUST_LATE=1, off because the title recycles per-job label slots from the CPU).
  • A compute program whose resource plan fails is memoized in the recompiler (SourceEntry::planFailure) and its dispatches are skipped before the key, capture and lock (poisoned source-handle memo; [packets] skipped (memo) row; APS5_NO_FAILURE_MEMO=1 disables both).
  • Bindless image tables: a compute program that loads its T# from a descriptor table at a wave-uniform runtime index (T# = heap[material[readfirstlane(i) * stride + 4] * 32]) now compiles. The recompiler records the table read as a runtime-indexed image resource, the materializer reads a bounded candidate set on the CPU (the material records the dispatch can reach, or the whole table when it fits; APS5_BINDLESS_SLOTS, default 16), the driver binds them as consecutive elements of the image binding, and the shader selects the slot by a binary search over a (key, slot) block in the flattened SRT; keys with no valid entry sample zeros as the hardware does; a workgroup wider than one host subgroup takes the NonUniform path when VK_EXT_descriptor_indexing is present. The per-frame skip of program 0x1048947300 is gone (skipped 0 at the video stage); APS5_NO_BINDLESS_IMAGES=1 restores the skip; [bindless] reports tables bound, slots, padded and rejected entries.
  • Worker and job-thread CPU affinity default to off (APS5_WORKER_AFFINITY, APS5_JOB_AFFINITY opt in); APS5_NO_PAD_INPUT=1 ignores host input for unattended measurements; per-draw log lines behind APS5_TRACE_DRAWS.
  • Fixed on the way: a use-after-free of the ShaderMemory behind a BDA-miss dispatch's snapshot; UnchangedSinceCollected now stamps CPU-written blocks separately so a driver write-back cannot vouch for a CPU write.

Relinker (--to-intel)

As requested, AMD-only instructions are handled at relink time. The shifting rewriter was not used on this title's 32.6 MB text (decoder desyncs on popcnt and int 0x41, ~46K VEX RIP-relative operands and jump tables would need adjusting); instead each SSE4a site (EXTRQ, INSERTQ, MOVNTSS, MOVNTSD) is lowered in place to a same-length jmp into an appended executable section holding a scratch-free SSE body and a jump back (Sse4aLowering, Sse4aOperands, WindowsTrampolineBuilder), with same-length in-place forms where they exist. Decoder fixes for POPCNT and the 0F BB (BTC) opcode, tests for the lowering and the decoder. The runtime illegal-instruction trap stays as a fallback for anything the relinker did not rewrite. The title boots and runs from the converted executable.

Upstream fixes adopted

calloc/realloc heap slot swap, libSceRtc export fixes with tests, the libc default terminate handler, the BTC decoder case; guest_rtc_tests and application_heap_tests wired into the test build.

Stability

Under heavy CPU load (or rarely without it) the intro stage can enter a limping state where every GPU queue's WAIT_REG_MEM on the title's per-job labels times out after 1000 ms and continues: the CPU job graph waits on GPU-written fences the driver lands only when the recording batch is submitted and reaped, while queue 0 waits on a CPU-written label. Thread dumps at the wedge show all queue workers sleeping in their waits and the job workers idle, and the new timeout report shows the recorder holding nothing for the awaited labels. What distinguishes every wedged run from every clean one is a single skipped dispatch shortly before it: guest memory is not readable at 0x60, a compute program whose SRT pointer chain read a null pointer at capture time, i.e. the CPU-side walk read a pointer word before its producer had written it. The consumers of that dispatch's output then never signal. This is a capture-ordering race, not a label-table rule; it is the next item. Debug aids for it are in: APS5_FLIP_QUEUE_WAIT=1 keeps the process alive at a presenter stall, and every first wait timeout reports the recorder's view of the awaited range (table hit, open-batch overlap, pending completions, flush deadline).

Verification

  • Every configuration above measured on the same build with kill switches, frames 0-40 byte-identical between runs; verify modes (APS5_VERIFY_DATA_HITS, APS5_VERIFY_RECIPE, APS5_VERIFY_DRAW_ENTRIES, APS5_VERIFY_KNOWN_VALUES, APS5_VERIFY_SOURCE_HANDLE) ran full sessions without a disagreement.
  • Driver unit tests (agc_driver_recorder_tests, agc_shader_memory_tests) extended for the new paths; relinker codegen and elfpatcher tests added for --to-intel.

Open items added

  • The bindless table dispatch costs ~0.5 ms per frame (a 256-record material scan on the CPU plus 16 image lookups): 476-495 presents per 10 s with it, 501-518 with APS5_NO_BINDLESS_IMAGES=1. The draws that would composite its output are still skipped (depth, stencil or conditional color writes is unsupported, missing register at DWORD 0x1b3).
  • The capture-ordering race described under Stability.
  • Code comments: the new driver and recompiler code follows the same commenting style as the rest of the PR; stripping them to match docs/CONVENTIONS.md is still on offer.

Update 2026-09-27: merged with main

Update 2026-09-27: merged with main (9958d26), conflicts resolved; the maintainer's fix for cached textures on Vulkan device replacement is applied (1e4430e); main's scePthreadOnce stub that shadowed the implementation is removed, and initialised mutexes and conditions resolve without the global lock. Titles whose sce_module contains its own libc.prx (Demon's Souls) are relinked with --skip-sce-module. Demon's Souls reaches character creation at the same speed as before the merge (intro video about 430-440 presents per 10 s, main menu about 296, character creation about 72). Known open issue: the main menu loses its background on about 65% of presents (fast-cleared targets reused uncleared; clean with APS5_DRAW_DRAIN=1); the fix comes in the follow-up PR.

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4643586246 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-25T23:28:17Z. --- ## Summary Boots Demon's Souls (PPSA01342) from the SIE logo through the Bink intro, the language menu, the title screen, the main menu and the in-engine intro cinematic, at roughly 11 fps at 4K on a 24-core Windows host with an NVIDIA GPU. The game then starts NEW GAME, shows its "Unable to connect to the server" dialog, and loads the first level until the first `DRAW_INDIRECT` submission, which the driver does not support yet (next item). The work is in six areas, each its own commit (split by area for review; the tip builds cleanly from scratch, the intermediate commits are not guaranteed to build on their own): - `perf(agc)`: the AGC driver's execution model changes from synchronous per-command GPU round trips to a batched recorder over host-imported guest memory with deferred write-back and content caches (13 s -> ~0.1 s per frame on this title). - `fix(recompiler)`: `s_*_saveexec` operand order (the aliased `s_and_saveexec_b64 vcc, vcc` computed `exec & exec`; every Bink 2 decoder kernel uses that form), identity-operand buffer atomics, per-element write flags, cheaper cache keys. - `feat(runtime)`: a reserved guest arena below the PS5 map limit with write watch, a caching guest heap, most of the pthread/event-flag/semaphore/file/time kernel APIs, SSE4a emulation on Intel hosts, crash and abort backtraces, wide printf conversions. - `feat(audio)`: AudioOut2 on an SDL output queue with port mixing, an ATRAC9 decoder for libSceAjm.native on the existing libatrac9 submodule. - `feat(libs)`: PM4 builders and patch functions in libSceAgc, save-data mounts/backup/memory, user/system service and store dialog behaviour for an offline console, six new export-only modules the title links. - `chore(gitignore)`: ignore the secondary `build_tools/` CMake tree. > **Update 2026-09-26:** the intro-video stage now runs at ~48 fps at 4K (from ~15 fps at the first push), `--to-intel` is implemented in the relinker as requested, and the recent upstream fixes are adopted; details in the last section. ## This replaces upstream driver work The driver commit removes the code of 5a280ce, 7ed5a0b, 46c799d, 598caac and 40df528 (render targets on the GPU across ACQUIRE_MEM, pipeline cache key, device-local tile buffers, batched draws with descriptor/sampler/buffer caches, fault-based guest memory ownership tracking). The same concerns are covered by the recorder, resident storage-texture targets, the pipeline cache keyed by recompile variant ids, the descriptor/sampler caches in `ShaderResources`, the two-tier `BufferPool`, and write-watch tracking in `GuestMemory`. The fault-based tracking layer in libc (`GuestMemoryTracking`, `GuestMemoryBacking`, `GuestHeapStorage`, `MemoryTracking*`, `MemoryBacking*`) is replaced by `GuestArena` + `GuestHeap` because guest code indexes tables by absolute address and corrupts memory when handed host addresses above 1 TiB, and page write watch was measured far cheaper than byte compares. The superseded files are deleted in this PR rather than left unbuilt. ## Driver (core/libs/prx/libSceAgcDriver) - `Graphics/Recorder`: one open command buffer per device; dispatches, all-resident draws, texture uploads and write-backs, label stores, fills and copies record into it. Batches carry serials signalled on a timeline semaphore so drains wait without the GPU mutex; completions (CPU write-backs) run in order at reap; kept objects are released on a bounded thread after the unlock; a lock-free pending-write snapshot lets the guest-memory flush hook skip the mutex; a pending-label table satisfies `WAIT_REG_MEM` from labels already recorded. - `Driver.cpp`: one worker thread per PM4 queue; `RELEASE_MEM`/`WRITE_DATA` labels and `COPY_DATA`/`DMA_DATA`/`DUMP_CONST_RAM` stores are written by the GPU into the host import; `DISPATCH_INDIRECT` runs GPU-side; the title's buffer-fill kernel is replaced by `vkCmdFillBuffer`; a dispatch cache keyed by program, user data and SH registers reuses capture and recompile while the captured memory is unchanged; type-2 filler packets are tolerated; a rejected submission prints its packet summary and last packets (the binary dump is opt-in). - `GuestMemory`: the driver owns a recursive GPU mutex with per-site profiling; a page-state cache invalidated through libc replaces per-check `VirtualQuery`; 64 KiB-block write generations from `GetWriteWatch` with a per-thread collect memo. - `GuestBufferMemory`: registered allocations are imported with `VK_EXT_external_memory_host` (budget `APS5_HOST_IMPORT_MIB`, default 6 GiB; this title's later stages need 16 GiB); the executable image's ranges get persistent mirrors instead of per-build copies; misaligned descriptor sub-ranges inside imports are copied on the GPU; registry leases are released at batch completion. - `Texture`: shader-written images stay on the GPU with deferred write-back (blocks the CPU wrote since the last sync are kept; adjacent images sharing a 64 KiB stamp block are advanced together, which fixed the green blocks in Bink video); sampled textures over host-imported surfaces are views of the storage image; DCC fast-clear keys are honoured on reads and set to uncompressed after writes; addrlib GFX10 swizzle equations drive the detiler both ways. - `Draw`, `Pipeline`, `State`: MRT with per-slot blend state, more colour formats, dynamic viewport/scissor, pipelines cached by stage variant ids, 64 KiB tiled targets attached as resident images, all-resident draws recorded into the recorder. - `ShaderResources`: two-stage build (unlocked plan and descriptor set, locked image lookups and writes), per-device descriptor and sampler caches, a content-keyed resource cache shared by dispatches and draws, read-only V# elements skip write-back. - `VulkanDevice`, presentation: the GPU mutex is held only for the queue submit; flips present from the resident display image; `APS5_DUMP_FRAMES` reads frames back on the GPU. - One late label re-store was fixed on the way: a label deferred behind a completion was re-written by a CPU memcpy at reap time, which could land on memory the game had recycled for a new command buffer (it corrupted a `WAIT_REG_MEM` header at the intro cinematic). ## Recompiler (core/shader/recompiler) - `sSaveexec` reads its source before writing the old EXEC into the destination; the per-lane exec bit comes from the lane's own bit. `APS5_SAVEEXEC_WRITE_FIRST=1` restores the old order. - Buffer atomics add/sub/or/xor with a zero operand become an atomic load or nothing (two histogram kernels went from 29/24 ms to 1.3/0.5 ms per dispatch). `APS5_NO_ATOMIC_ZERO_SKIP=1` restores plain atomics. - `DescriptorBinding` carries `bufferWritten`/`bufferAtomic`/`imageWritten`; results expose a `variantId`; SPIR-V is shared copy-on-write; source keys use a length plus 64-bit hash; captures can be reused for the compile. - Wave-LDS ordering barriers for compute programs that write LDS, `v_movrels`/`v_movreld` lowering, SMEM with VCC base, f16 conversion opcode fix, a hand-picked SPIRV-Tools pass list (`APS5_SPIRV_OPT=full|none`), and env-gated probes (`APS5_DUMP_IR`, `APS5_PROBE`, `APS5_TRACE_BDA`, `APS5_LOOP_GUARD`). ## Runtime (core/libs/prx/libc, libkernel) - `GuestArena`: guest memory in one reserved arena from 0x10_0000_0000 with `MEM_WRITE_WATCH`; `GuestHeap`: size classes plus a bounded large-block cache (`APS5_HEAP_CACHE_MIB`); the allocation registry gains a generation counter, an invalidator callback for the driver's page cache, and a pin waiter instead of throwing on a leased range. - libkernel: `mmap`/`mprotect`/`munmap` on the arena, flexible memory budget, real `sceKernelVirtualQuery`; the POSIX pthread layer, rwlocks, timed locks, TSD, event flags; a 0.5 ms scheduler tick and high-resolution sleeps; TSC/clock/time functions; file APIs returning SCE errno codes; the APR file-streaming API shared with libSceAmpr. - libc: a vectored crash reporter with registers, frame chain and return-address candidates; SIGABRT, UCRT invalid-parameter and process-exit backtraces (abort and 0xC0000409 fast-fails were silent); SSE4a `EXTRQ`/`INSERTQ` emulation; `%ls`/`%lc`/`%S`/`%C` with the guest's 16-bit `wchar_t`; hand-written `setjmp`/`longjmp` for the guest's `jmp_buf`; a path-alias table so save-data mount points fit the 16-byte field; more string, stdio and math exports. ## Audio (libSceAudioOut, libSceAjm.native) - AudioOut2: one SDL F32 stereo 48 kHz device per context; the hardware grain queue level is derived from the SDL queued bytes, so the title's poll-and-push loop runs at real time (it ran 4-5x too fast against the old "always empty" stub); ports are mixed per push with 7.1 folded to stereo. Object-port position attributes are ignored (unpanned). - libSceAjm.native: instance and batch APIs, ATRAC9 decoding with variable-size frames inside superframes, padding, gapless parameters and handle re-creation on re-initialisation. Other codecs are reported once and fail with a codec error. - AudioOut v1: `sceAudioOutOutput(handle, NULL)` drains instead of throwing. ## Libraries (libSceAgc and other prx) - libSceAgc: `SetIndexCount`, `SetBaseIndirectArgs`, `DispatchIndirect` (both forms), wait/write-data patch functions, relaxed checks for what the title sends (null wait addresses filled later, 64-bit masks on 32-bit waits, unaligned `ACQUIRE_MEM` ranges), NOP fillers for LOD stats and wait-until-safe, a `NotImplemented` stub file in upstream's pattern. - libSceSaveData.native: short mount points through the libc alias table, backup events, save-data memory slots persisted per slot. - libSceUserService (login event, all-zero game presets), libSceSystemService (safe area, notice skip), libSceNpCommerce (store dialog finishes as user-cancelled), libSceVideoOut (all flip modes, queue-full error instead of throw, non-blocking presenter), libSceAcm, libScePad (`scePadRead`), libSceFiber, offline behaviour for the network/NP modules, and new export-only modules libSceAmpr, libSceJpegEnc, libSceJson2, libSceMsgDialog.native, libSceNpCppWebApi, libSceNpUtility. ## Verification - Clean configure and build of the whole tree from scratch (all prx modules, tools and the relinker) with the WinLibs MinGW UCRT toolchain. - Runs of the title with frame dumps at every stage: the SIE and Bluepoint logos, the Bink intro (every frame decodes cleanly; the white/speckle and green-block corruption is gone with the saveexec and adjacent-generation fixes), the language menu, the title screen, the main menu (NEW GAME / SETTINGS over the Nexus statue video), and the in-engine intro cinematic (mountains, characters, fight scenes render correctly). Three consecutive runs through the cinematic start survived after the label re-store fix. - AudioOut2 pacing measured at 187.5 pushes/s with 104 s of cutscene audio in 103 s of wall time. ## Switches About 165 `APS5_*` environment variables were added: kill switches for each optimisation (`APS5_NO_*`), tracing (`APS5_TRACE_*`), profiling (`APS5_PROFILE_DRAW`, `APS5_PROFILE_GPU`), dumps (`APS5_DUMP_FRAMES`, `APS5_DUMP_SHADERS`, `APS5_DUMP_REJECTED`) and tuning (`APS5_HOST_IMPORT_MIB`, `APS5_LABEL_FLUSH_US`, `APS5_HEAP_CACHE_MIB`). Every one is read once at first use and has no effect when unset. ## Known gaps and open items - Code comments: the changes add explanatory comments throughout, which `docs/CONVENTIONS.md` does not allow. I left them in so reviewers can read the mechanisms; I can strip them (or move the design into a `docs/` note) if that is preferred before merging. - Silent stubs that `docs/TechnicalDebt.md` asks to list: the store dialog, share/gesture/json initialisers, NP web API setters, the unnamed libSceAgc NID `-KRzWekV120`, LOD-stats and wait-until-safe fillers, output gamma/latency calls. - Indirect draws (`DRAW_INDIRECT` and siblings) are not implemented; the title's first level submission is rejected there. - The default host-import budget (6 GiB) is too small for this title's later stages; runs use `APS5_HOST_IMPORT_MIB=16384`. - Object-port audio positions are ignored; other AJM codecs are not decoded. - Tests were not extended for the new driver code; two descriptor tests now only check that streaming-feedback and anisotropy fields decode instead of asserting rejection. ## Update 2026-09-26 (commits af3c202, 01c4e3e, 29b4601): intro-video stage from ~15 fps to ~48 fps, `--to-intel` relinker lowering, upstream fixes Measured at 4K on the same host, intro-video stage (SIE logo, Bink intro, in-engine cinematic), presents per 10 s over the last 60 s of a 150 s run (frames byte-identical to the previous build in every configuration): | Build | presents / 10 s | ms per frame | |---|---|---| | previous push (d677f97) | 154 | 65 | | worker/job affinity off by default | 165 | 61 | | dispatch variants + recipes + template data refresh | 215 | 46 | | unit shadows (device-local slabs per host import) | 240-250 | 41 | | CPU-side stages (counters, hook fix, T1 trim, BDA address space, dispatch/draw recipes, known-value copies) | 267 | 37 | | plan-failure memo (one compute program fails its plan every frame) | 385-417 | 25 | | data-only dispatch-cache hits + poisoned source memo | 495-522 | 19.5 | | + bindless image tables (the skipped per-frame program now runs; 29b4601) | 476-495 | 20.8 | ### Driver (core/libs/prx/libSceAgcDriver) - Dispatch cache: per-key value-set variants (k = 4), and data-only hits: a variant whose captured words differ from guest memory only at flat-SRT leaves the recompiler proves are pure data (`IrResourcePlan::pureFlatSlots`, never a descriptor source, condition, uniform-fill value or read address) is served without a capture, recompile or insert; the compiled result is patched and the resource template's data buffers are refreshed by words. `APS5_NO_DATA_HITS=1` disables, `APS5_VERIFY_DATA_HITS=1` captures beside every hit and aborts on any disagreement (150 s run: 0 disagreements). - Dispatch and draw recipes: a hit replays the previous prepare (template, pipeline objects, push bytes, presync surfaces) after a pre-check proof; draw entries keyed by the register banks and the registry before any decode. `APS5_NO_DISPATCH_RECIPE`, `APS5_NO_DRAW_RECIPE`, `APS5_NO_DRAW_KEY`, `APS5_VERIFY_RECIPE`, `APS5_VERIFY_DRAW_ENTRIES`, `APS5_VERIFY_DRAW_RECIPE`. - Resource templates refresh their data buffers in place when only flat-SRT / shader-data words differ (`vkCmdUpdateBuffer`, hashed, `APS5_NO_TEMPLATE_DATA_REFRESH=1` keys the words as before). - Unit shadows: results of shader-written buffers live in device-local slabs per host import and are published before host-facing consumers; block-unit (64 KiB) storage tracking with per-piece write-back (`APS5_BLOCK_WRITEBACK_WIDEN=1` widens), windowed detile. - DCC clear-key proofs (`DccKeyProof`), per-class GPU timing (`[gputime]`), per-layer storage clears. - Throughput: lazy completion counting, a rate-limited reap, a PFN table for page-state checks, epoch-gated revalidation, indirect template data refresh, a source-handle memo per shader snapshot, a draw pre-check. - CPU copy path with batch read tracking; present slot ring with early flip completion (`APS5_FLIP_INFLIGHT`); late label trust as an opt-in (`APS5_LABEL_TRUST_LATE=1`, off because the title recycles per-job label slots from the CPU). - A compute program whose resource plan fails is memoized in the recompiler (`SourceEntry::planFailure`) and its dispatches are skipped before the key, capture and lock (poisoned source-handle memo; `[packets] skipped (memo)` row; `APS5_NO_FAILURE_MEMO=1` disables both). - Bindless image tables: a compute program that loads its T# from a descriptor table at a wave-uniform runtime index (`T# = heap[material[readfirstlane(i) * stride + 4] * 32]`) now compiles. The recompiler records the table read as a runtime-indexed image resource, the materializer reads a bounded candidate set on the CPU (the material records the dispatch can reach, or the whole table when it fits; `APS5_BINDLESS_SLOTS`, default 16), the driver binds them as consecutive elements of the image binding, and the shader selects the slot by a binary search over a (key, slot) block in the flattened SRT; keys with no valid entry sample zeros as the hardware does; a workgroup wider than one host subgroup takes the `NonUniform` path when `VK_EXT_descriptor_indexing` is present. The per-frame skip of program `0x1048947300` is gone (`skipped 0` at the video stage); `APS5_NO_BINDLESS_IMAGES=1` restores the skip; `[bindless]` reports tables bound, slots, padded and rejected entries. - Worker and job-thread CPU affinity default to off (`APS5_WORKER_AFFINITY`, `APS5_JOB_AFFINITY` opt in); `APS5_NO_PAD_INPUT=1` ignores host input for unattended measurements; per-draw log lines behind `APS5_TRACE_DRAWS`. - Fixed on the way: a use-after-free of the `ShaderMemory` behind a BDA-miss dispatch's snapshot; `UnchangedSinceCollected` now stamps CPU-written blocks separately so a driver write-back cannot vouch for a CPU write. ### Relinker (`--to-intel`) As requested, AMD-only instructions are handled at relink time. The shifting rewriter was not used on this title's 32.6 MB text (decoder desyncs on `popcnt` and `int 0x41`, ~46K VEX RIP-relative operands and jump tables would need adjusting); instead each SSE4a site (`EXTRQ`, `INSERTQ`, `MOVNTSS`, `MOVNTSD`) is lowered in place to a same-length `jmp` into an appended executable section holding a scratch-free SSE body and a jump back (`Sse4aLowering`, `Sse4aOperands`, `WindowsTrampolineBuilder`), with same-length in-place forms where they exist. Decoder fixes for `POPCNT` and the `0F BB` (`BTC`) opcode, tests for the lowering and the decoder. The runtime illegal-instruction trap stays as a fallback for anything the relinker did not rewrite. The title boots and runs from the converted executable. ### Upstream fixes adopted `calloc`/`realloc` heap slot swap, `libSceRtc` export fixes with tests, the libc default terminate handler, the `BTC` decoder case; `guest_rtc_tests` and `application_heap_tests` wired into the test build. ### Stability Under heavy CPU load (or rarely without it) the intro stage can enter a limping state where every GPU queue's `WAIT_REG_MEM` on the title's per-job labels times out after 1000 ms and continues: the CPU job graph waits on GPU-written fences the driver lands only when the recording batch is submitted and reaped, while queue 0 waits on a CPU-written label. Thread dumps at the wedge show all queue workers sleeping in their waits and the job workers idle, and the new timeout report shows the recorder holding nothing for the awaited labels. What distinguishes every wedged run from every clean one is a single skipped dispatch shortly before it: `guest memory is not readable at 0x60`, a compute program whose SRT pointer chain read a null pointer at capture time, i.e. the CPU-side walk read a pointer word before its producer had written it. The consumers of that dispatch's output then never signal. This is a capture-ordering race, not a label-table rule; it is the next item. Debug aids for it are in: `APS5_FLIP_QUEUE_WAIT=1` keeps the process alive at a presenter stall, and every first wait timeout reports the recorder's view of the awaited range (table hit, open-batch overlap, pending completions, flush deadline). ### Verification - Every configuration above measured on the same build with kill switches, frames 0-40 byte-identical between runs; verify modes (`APS5_VERIFY_DATA_HITS`, `APS5_VERIFY_RECIPE`, `APS5_VERIFY_DRAW_ENTRIES`, `APS5_VERIFY_KNOWN_VALUES`, `APS5_VERIFY_SOURCE_HANDLE`) ran full sessions without a disagreement. - Driver unit tests (`agc_driver_recorder_tests`, `agc_shader_memory_tests`) extended for the new paths; relinker codegen and elfpatcher tests added for `--to-intel`. ### Open items added - The bindless table dispatch costs ~0.5 ms per frame (a 256-record material scan on the CPU plus 16 image lookups): 476-495 presents per 10 s with it, 501-518 with `APS5_NO_BINDLESS_IMAGES=1`. The draws that would composite its output are still skipped (`depth, stencil or conditional color writes is unsupported`, `missing register at DWORD 0x1b3`). - The capture-ordering race described under Stability. - Code comments: the new driver and recompiler code follows the same commenting style as the rest of the PR; stripping them to match `docs/CONVENTIONS.md` is still on offer. ## Update 2026-09-27: merged with main Update 2026-09-27: merged with main (9958d26), conflicts resolved; the maintainer's fix for cached textures on Vulkan device replacement is applied (1e4430e); main's scePthreadOnce stub that shadowed the implementation is removed, and initialised mutexes and conditions resolve without the global lock. Titles whose sce_module contains its own libc.prx (Demon's Souls) are relinked with --skip-sce-module. Demon's Souls reaches character creation at the same speed as before the merge (intro video about 430-440 presents per 10 s, main menu about 296, character creation about 72). Known open issue: the main menu loses its background on about 65% of presents (fast-cleared targets reused uncleared; clean with APS5_DRAW_DRAIN=1); the fix comes in the follow-up PR.
yumlevi commented 2026-09-25 23:31:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-25T23:31:04Z.


This is a reference AI implementation trying to get DS to boot and play and fixing things along the way
image

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5841068695 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5841068695). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-25T23:31:04Z. --- This is a reference AI implementation trying to get DS to boot and play and fixing things along the way <img width="2212" height="1299" alt="image" src="https://github.com/user-attachments/assets/5df9f906-09f6-4760-8887-d7d4459451a1" />
boykopovar commented 2026-09-26 07:28:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by boykopovar on 2026-09-26T07:28:43Z.


Wow! A colossal amount of useful work has been done.

Regarding the emulation of instructions that are present on AMD Zen 2 (EXTRQ, INSERTQ, MOVNTSS, MOVNTSD, SHA-NI...) but absent on Intel, this issue must be resolved at the relinker stage to avoid CPU emulation on runtime. For this purpose, I prepared instruction decoder and rewriter.

The tool can replace an instruction with a sequence of instructions of a different length. This process should be started if the --to-intel flag is present (but it is not connected correctly yet). The decoder has only been verified by Dreaming Sarah.

Here's a table of substitutions.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5844264087 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5844264087). Originally posted by [boykopovar](https://github.com/boykopovar) on 2026-09-26T07:28:43Z. --- Wow! A colossal amount of useful work has been done. Regarding the emulation of instructions that are present on AMD Zen 2 (EXTRQ, INSERTQ, MOVNTSS, MOVNTSD, SHA-NI...) but absent on Intel, this issue must be resolved at the relinker stage to avoid CPU emulation on runtime. For this purpose, I prepared instruction [decoder](https://github.com/boykopovar/AnyPS5/tree/main/core/relinker/codegen/src/x86/X64InstructionDecoder.cpp) and [rewriter](https://github.com/boykopovar/AnyPS5/tree/main/core/relinker/codegen/src/x86/X64InstructionRewriter.cpp). The tool can replace an instruction with a sequence of instructions of a different length. This process should be started if the `--to-intel` flag is present (but it is not connected correctly yet). The decoder has only been verified by Dreaming Sarah. Here's a [table of substitutions](https://github.com/boykopovar/AnyPS5/tree/main/core/relinker/codegen/include/codegen/x86/Amd64OnlySubstitutionTable.hpp).
yumlevi commented 2026-09-26 08:29:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-26T08:29:04Z.


Sounds good, I'll look into that.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5844611349 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5844611349). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-26T08:29:04Z. --- Sounds good, I'll look into that.
boykopovar commented 2026-09-26 09:53:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by boykopovar on 2026-09-26T09:53:52Z.


--to-intel flag is now enabled and running relinker with it now causes instructions to be replaced (on main)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5845252929 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5845252929). Originally posted by [boykopovar](https://github.com/boykopovar) on 2026-09-26T09:53:52Z. --- `--to-intel` flag is now enabled and running relinker with it now causes instructions to be replaced (on main)
yumlevi commented 2026-09-27 02:01:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T02:01:22Z.


performance on the pre-gameplay portion is pushing around 50fps right now

Pushed three commits (af3c202 runtime, 01c4e3e relinker, 29b4601 driver + recompiler); the description has a new section with the details.

  • --to-intel: implemented as you asked, at relink time. On this title's 32.6 MB text the shifting rewriter was not safe (decoder desyncs on popcnt/int 0x41, ~46K VEX RIP-relative operands and jump tables to adjust), so each SSE4a site is lowered in place to a same-length jmp into an appended executable section with the SSE body and a jump back (same-length in-place forms where they exist). Decoder fixes for POPCNT and 0F BB, tests added. The runtime trap is now only a fallback.
  • Intro-video stage at 4K: 154 -> 476-495 presents per 10 s (65 -> ~21 ms per frame), frames byte-identical across configurations; the per-frame compute program that failed its resource plan (an image T# loaded from a descriptor table at a runtime index) now compiles through a bounded runtime-indexed descriptor array.
  • Adopted from main: the calloc/realloc heap slot swap, libSceRtc fixes with tests, the default terminate handler, the BTC decoder case.
  • Open: a capture-ordering race under CPU load (a dispatch skipped for reading a pointer before its producer wrote it; diagnostics are in, fix next), the bindless dispatch cost, and the items already listed.

🤖 Generated with Claude Code

https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5851815522 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5851815522). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-27T02:01:22Z. --- performance on the pre-gameplay portion is pushing around 50fps right now Pushed three commits (af3c202 runtime, 01c4e3e relinker, 29b4601 driver + recompiler); the description has a new section with the details. - `--to-intel`: implemented as you asked, at relink time. On this title's 32.6 MB text the shifting rewriter was not safe (decoder desyncs on `popcnt`/`int 0x41`, ~46K VEX RIP-relative operands and jump tables to adjust), so each SSE4a site is lowered in place to a same-length `jmp` into an appended executable section with the SSE body and a jump back (same-length in-place forms where they exist). Decoder fixes for `POPCNT` and `0F BB`, tests added. The runtime trap is now only a fallback. - Intro-video stage at 4K: 154 -> 476-495 presents per 10 s (65 -> ~21 ms per frame), frames byte-identical across configurations; the per-frame compute program that failed its resource plan (an image T# loaded from a descriptor table at a runtime index) now compiles through a bounded runtime-indexed descriptor array. - Adopted from main: the `calloc`/`realloc` heap slot swap, `libSceRtc` fixes with tests, the default terminate handler, the `BTC` decoder case. - Open: a capture-ordering race under CPU load (a dispatch skipped for reading a pointer before its producer wrote it; diagnostics are in, fix next), the bindless dispatch cost, and the items already listed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
boykopovar commented 2026-09-27 13:30:29 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by boykopovar on 2026-09-27T13:30:29Z.


I tried running your branch with Dreaming Sarah to check for regressions. I got an error when I started. worker failed: [gpu] worker failed: AGC graphics: missing Vulkan function: vkResetDescriptorPool.

Reason: When replacing a Vulkan device, old textures remained in global caches with a reference to a deleted TextureDetiler. A corrupted VkDevice was read from it, so vkResetDescriptorPool couldn't be found.

These changes fix-vulkan-texture-lifetime.patch helped fix this, and the app launched. Performance is significantly better than on the current main version. However, rendering bugs occasionally appeared, and frames would occasionally drop (the screen would flicker black).

PR #10 was merged into main, which added more conflicts to your branch. Now main uses prx from sce_module too.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5856292937 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5856292937). Originally posted by [boykopovar](https://github.com/boykopovar) on 2026-09-27T13:30:29Z. --- I tried running your branch with Dreaming Sarah to check for regressions. I got an error when I started. worker failed: `[gpu] worker failed: AGC graphics: missing Vulkan function: vkResetDescriptorPool`. Reason: When replacing a Vulkan device, old textures remained in global caches with a reference to a deleted TextureDetiler. A corrupted VkDevice was read from it, so vkResetDescriptorPool couldn't be found. These changes [fix-vulkan-texture-lifetime.patch](https://github.com/user-attachments/files/32700976/fix-vulkan-texture-lifetime.patch) helped fix this, and the app launched. Performance is significantly better than on the current main version. However, rendering bugs occasionally appeared, and frames would occasionally drop (the screen would flicker black). PR #10 was merged into main, which added more conflicts to your branch. Now main uses prx from sce_module too.
boykopovar commented 2026-09-27 13:31:26 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by boykopovar on 2026-09-27T13:31:26Z.


It's time to resolve the conflicts, perhaps further refine the current problems, and merge what's already there. New pull requests are already being opened that implement the PRX libraries you've already implemented in this pull request, which will generate further conflicts.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5856299367 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5856299367). Originally posted by [boykopovar](https://github.com/boykopovar) on 2026-09-27T13:31:26Z. --- It's time to resolve the conflicts, perhaps further refine the current problems, and merge what's already there. New pull requests are already being opened that implement the PRX libraries you've already implemented in this pull request, which will generate further conflicts.
yumlevi commented 2026-09-27 17:27:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T17:27:09Z.


alright I'll move the next batch of shaders/gbuffering to a new pr

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5858097440 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5858097440). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-27T17:27:09Z. --- alright I'll move the next batch of shaders/gbuffering to a new pr
Pacuka commented 2026-09-27 17:45:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Pacuka on 2026-09-27T17:45:52Z.


Tested this branch on Linux with The Smurfs Dreams (UE) and found three Linux-specific issues in the #5 code. I have fixes for them locally and will send them as small PRs once this is merged, so they don't add to the conflicts:

  • GuestMemory.cpp describePages: on Linux there is no page cache, so the fallback re-reads and parses /proc/self/maps on every query. In a 240 s run that took 219 s of CPU time. Caching the parsed maps (reloaded when the guest allocation generation changes or a lookup misses) took this title from ~6.8 s to ~1 s per frame.
  • GuestArena / GetWriteWatch are Windows-only, so on Linux there is no write tracking at all. Every storage texture counts as untracked and is re-uploaded, about 15 GB per 10 s here. A Linux counterpart could be built on userfaultfd async write-protect plus PAGEMAP_SCAN (kernel ≥ 6.7).
  • VideoOutDriver: a full flip queue throws "flip queue full" and kills the title once it renders faster than the presenter retires flips. Waiting (the existing APS5_FLIP_QUEUE_WAIT path) fixes it.

Looking forward to this landing. Happy to help with the conflicts if useful.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5858250671 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5858250671). Originally posted by [Pacuka](https://github.com/Pacuka) on 2026-09-27T17:45:52Z. --- Tested this branch on Linux with The Smurfs Dreams (UE) and found three Linux-specific issues in the #5 code. I have fixes for them locally and will send them as small PRs once this is merged, so they don't add to the conflicts: - `GuestMemory.cpp` `describePages`: on Linux there is no page cache, so the fallback re-reads and parses `/proc/self/maps` on every query. In a 240 s run that took 219 s of CPU time. Caching the parsed maps (reloaded when the guest allocation generation changes or a lookup misses) took this title from ~6.8 s to ~1 s per frame. - `GuestArena` / `GetWriteWatch` are Windows-only, so on Linux there is no write tracking at all. Every storage texture counts as untracked and is re-uploaded, about 15 GB per 10 s here. A Linux counterpart could be built on `userfaultfd` async write-protect plus `PAGEMAP_SCAN` (kernel ≥ 6.7). - `VideoOutDriver`: a full flip queue throws "flip queue full" and kills the title once it renders faster than the presenter retires flips. Waiting (the existing `APS5_FLIP_QUEUE_WAIT` path) fixes it. Looking forward to this landing. Happy to help with the conflicts if useful.
yumlevi commented 2026-09-27 17:46:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T17:46:49Z.


nuh it's all good my slopgent is on it

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5858258274 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5858258274). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-27T17:46:49Z. --- nuh it's all good my slopgent is on it
gatsuslayer commented 2026-09-27 19:32:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gatsuslayer on 2026-09-27T19:32:24Z.


@yumlevi I've tried to make it run with my own copy of the game (PPSA01341), and after testing various options, I still can't get text to display, I have intel and nvidia and used "--to-intel" flag, but it’s still not working. What am I missing?
dst

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5859120636 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5859120636). Originally posted by [gatsuslayer](https://github.com/gatsuslayer) on 2026-09-27T19:32:24Z. --- @yumlevi I've tried to make it run with my own copy of the game (PPSA01341), and after testing various options, I still can't get text to display, I have intel and nvidia and used "--to-intel" flag, but it’s still not working. What am I missing? <img width="1452" height="865" alt="dst" src="https://github.com/user-attachments/assets/80c26691-ca57-49f7-bc31-8cfae7b12850" />
yumlevi commented 2026-09-27 20:15:34 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T20:15:34Z.


Merged current main (9958d26) into the branch and resolved the conflicts. Your fix-vulkan-texture-lifetime patch is applied unchanged as its own commit (1e4430e, you as co-author).

Conflict resolution:

  • libc: main's working directory (chdir/getcwd), _Exit/exit structure, stream, format, string and math functions and bsearch are kept. The branch keeps its save-data path aliases (matched on the normalised guest path) and the Dinkumware locale layouts: guest code inlines them, so the objects handed to the guest keep the SDK layout (short ctype tables, the facet ids, the cout/cin storage the title imports). tests/GuestCharacter.cpp declares short tables again; guest_locale_tests and GuestLocale.hpp are restored.
  • libkernel: main's NativeStat helpers, POSIX wrappers, System/Process implementations and pthread structure (lazy static init, destroyed marker, MutexOperations, setprotocol) are kept. On top of them: SCE/FreeBSD error codes instead of exceptions (EDEADLK on an error-check relock, EPERM on unlock by a non-owner, EINVAL for a bad abstime), mutex type 4 as a normal mutex, timed waits through TimedWait, the condattr clock for absolute timeouts, adoption of Windows threads in scePthreadSelf, sceKernelUuidCreate returning EINVAL on null.
  • Found by running after the merge: main's NotImplemented scePthreadOnce_nid_postfix took the NID of the working export and the title aborted after 10 s (removed, e764385); initialised mutexes and conditions no longer take the process-wide lock on every lock, unlock, signal and wait (7233620).
  • AGC: Cb Sync uses main's check (gdsOffset == 0 && gdsSize <= 1). Main's rendering wait is ported into the branch's packet loop (the worker executes RenderingWaitPacketHeader and counts it as a wait).
  • relinker: main's guest modules and the --to-intel trampolines coexist; the trampolines are passed to Patch. GuestModuleBuilder now refuses --to-intel stubs inside a guest module instead of dropping them, since stub sections are not written for guest modules (listed in docs/TechnicalDebt.md).
  • CMake: main's registered tests are kept; the branch's duplicate guest_rtc target is dropped.

sce_module and Demon's Souls: the title ships sce_module/libc.prx and libSceNpCppWebApi.prx. With the default handling the relink with --lazy-binding stops with "Guest modules require eager binding"; relinked with eager binding, the title's libc.prx takes priority and the executable fails at startup with "unresolved ELF import 4h6F1LLbTiw" (sceKernelMapNamedFlexibleMemoryInternal, imported by that libc.prx), exit 0xc0000139. That libc would also replace the project's libc (guest arena below 1 TiB, heap, crash reporting). Demon's Souls is therefore relinked with --skip-sce-module, and the README says so for titles whose sce_module contains libc.prx. The default for other titles is unchanged.

Build and tests: clean configure and build on Windows (MinGW UCRT GCC, Ninja, Release, BUILD_TESTING=ON). exception_runtime_tests does not build on Windows (it includes sys/wait.h; same on main). ctest: 35 of 39 pass; agc_driver, agc_driver_flip and agc_driver_pm4 fail the same way on the branch before the merge, and agc_shader_memory is intermittent on both.

Demon's Souls, merged build against the branch before the merge (29b4601), same machine and session, relinked with --windows --windows-diagnostics unused-filter=0 --lazy-binding --to-intel --skip-sce-module, splash screens skipped:

  • intro video, presents per 10 s over the last 60 s of a 150 s run: 424-440 and 429-444 merged, 430-448 and 443-457 before (one window of the second run fell to 309-365);
  • main menu: about 296 merged, about 298 before;
  • character creation: about 72 merged, about 73 before;
  • the first 41 video-stage frames are byte-identical between the builds; character-creation frames differ only in the animated name highlight; no errors, no wait timeouts.

Black flicker: Demon's Souls shows it too, at the same rate on both builds. Over every dumped frame of a 45 s hold on the main menu, the background scene is present on 473 of 1334 presents (35.5%) after the merge and 458 of 1339 (34.2%) before it. The other presents show a black background with a large blurred white shape (53%), the menu text or highlight bar alone on black (5.5%), a fully black frame (5.7%), or a torn mix. Bad runs are 1-39 presents long. With APS5_DRAW_DRAIN=1 the same hold is clean on 1035 of 1035 presents.
The cause is fast-cleared transient render targets reused uncleared. The title clears them by filling only their DCC key bytes (a key fill recorded into the batch). The driver infers the clear state by reading those bytes, and its own 0xFF write-back key store for a larger image whose key range encloses the transient's, recorded after the title's fill, undoes the clear in program order. The target then keeps its previous content. The fix (a record-time ledger of every key write) is part of the next batch and will come as a separate PR; with it this menu is clean on every present.
The flicker in Dreaming Sarah is most likely the same defect, but I have not confirmed it. Could you attach the stderr log of a Dreaming Sarah run where the screen flickers, with APS5_PROFILE_DRAW=1 APS5_TRACE_DCC_KEYS=1 APS5_TRACE_UPLOAD=1 and APS5_DUMP_FRAMES= set to cover the flicker (frame_*.bmp are written next to the executable)? A second run with APS5_DRAW_DRAIN=1 that no longer flickers would confirm it.

🤖 Generated with Claude Code

https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5859457354 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5859457354). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-27T20:15:34Z. --- Merged current main (9958d26) into the branch and resolved the conflicts. Your fix-vulkan-texture-lifetime patch is applied unchanged as its own commit (1e4430e, you as co-author). Conflict resolution: - libc: main's working directory (chdir/getcwd), _Exit/exit structure, stream, format, string and math functions and bsearch are kept. The branch keeps its save-data path aliases (matched on the normalised guest path) and the Dinkumware locale layouts: guest code inlines them, so the objects handed to the guest keep the SDK layout (short ctype tables, the facet ids, the cout/cin storage the title imports). tests/GuestCharacter.cpp declares short tables again; guest_locale_tests and GuestLocale.hpp are restored. - libkernel: main's NativeStat helpers, POSIX wrappers, System/Process implementations and pthread structure (lazy static init, destroyed marker, MutexOperations, setprotocol) are kept. On top of them: SCE/FreeBSD error codes instead of exceptions (EDEADLK on an error-check relock, EPERM on unlock by a non-owner, EINVAL for a bad abstime), mutex type 4 as a normal mutex, timed waits through TimedWait, the condattr clock for absolute timeouts, adoption of Windows threads in scePthreadSelf, sceKernelUuidCreate returning EINVAL on null. - Found by running after the merge: main's NotImplemented scePthreadOnce_nid_postfix took the NID of the working export and the title aborted after 10 s (removed, e764385); initialised mutexes and conditions no longer take the process-wide lock on every lock, unlock, signal and wait (7233620). - AGC: Cb Sync uses main's check (gdsOffset == 0 && gdsSize <= 1). Main's rendering wait is ported into the branch's packet loop (the worker executes RenderingWaitPacketHeader and counts it as a wait). - relinker: main's guest modules and the --to-intel trampolines coexist; the trampolines are passed to Patch. GuestModuleBuilder now refuses --to-intel stubs inside a guest module instead of dropping them, since stub sections are not written for guest modules (listed in docs/TechnicalDebt.md). - CMake: main's registered tests are kept; the branch's duplicate guest_rtc target is dropped. sce_module and Demon's Souls: the title ships sce_module/libc.prx and libSceNpCppWebApi.prx. With the default handling the relink with --lazy-binding stops with "Guest modules require eager binding"; relinked with eager binding, the title's libc.prx takes priority and the executable fails at startup with "unresolved ELF import 4h6F1LLbTiw" (sceKernelMapNamedFlexibleMemoryInternal, imported by that libc.prx), exit 0xc0000139. That libc would also replace the project's libc (guest arena below 1 TiB, heap, crash reporting). Demon's Souls is therefore relinked with --skip-sce-module, and the README says so for titles whose sce_module contains libc.prx. The default for other titles is unchanged. Build and tests: clean configure and build on Windows (MinGW UCRT GCC, Ninja, Release, BUILD_TESTING=ON). exception_runtime_tests does not build on Windows (it includes sys/wait.h; same on main). ctest: 35 of 39 pass; agc_driver, agc_driver_flip and agc_driver_pm4 fail the same way on the branch before the merge, and agc_shader_memory is intermittent on both. Demon's Souls, merged build against the branch before the merge (29b4601), same machine and session, relinked with --windows --windows-diagnostics unused-filter=0 --lazy-binding --to-intel --skip-sce-module, splash screens skipped: - intro video, presents per 10 s over the last 60 s of a 150 s run: 424-440 and 429-444 merged, 430-448 and 443-457 before (one window of the second run fell to 309-365); - main menu: about 296 merged, about 298 before; - character creation: about 72 merged, about 73 before; - the first 41 video-stage frames are byte-identical between the builds; character-creation frames differ only in the animated name highlight; no errors, no wait timeouts. Black flicker: Demon's Souls shows it too, at the same rate on both builds. Over every dumped frame of a 45 s hold on the main menu, the background scene is present on 473 of 1334 presents (35.5%) after the merge and 458 of 1339 (34.2%) before it. The other presents show a black background with a large blurred white shape (53%), the menu text or highlight bar alone on black (5.5%), a fully black frame (5.7%), or a torn mix. Bad runs are 1-39 presents long. With APS5_DRAW_DRAIN=1 the same hold is clean on 1035 of 1035 presents. The cause is fast-cleared transient render targets reused uncleared. The title clears them by filling only their DCC key bytes (a key fill recorded into the batch). The driver infers the clear state by reading those bytes, and its own 0xFF write-back key store for a larger image whose key range encloses the transient's, recorded after the title's fill, undoes the clear in program order. The target then keeps its previous content. The fix (a record-time ledger of every key write) is part of the next batch and will come as a separate PR; with it this menu is clean on every present. The flicker in Dreaming Sarah is most likely the same defect, but I have not confirmed it. Could you attach the stderr log of a Dreaming Sarah run where the screen flickers, with APS5_PROFILE_DRAW=1 APS5_TRACE_DCC_KEYS=1 APS5_TRACE_UPLOAD=1 and APS5_DUMP_FRAMES=<n> set to cover the flicker (frame_*.bmp are written next to the executable)? A second run with APS5_DRAW_DRAIN=1 that no longer flickers would confirm it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
yumlevi commented 2026-09-27 20:59:39 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T20:59:39Z.


@yumlevi I've tried to make it run with my own copy of the game (PPSA01341), and after testing various options, I still can't get text to display, I have intel and nvidia and used "--to-intel" flag, but it’s still not working. What am I missing? dst

I would really abstain from trying to get this to run currently

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5859776613 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5859776613). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-27T20:59:39Z. --- > @yumlevi I've tried to make it run with my own copy of the game (PPSA01341), and after testing various options, I still can't get text to display, I have intel and nvidia and used "--to-intel" flag, but it’s still not working. What am I missing? <img alt="dst" width="1452" height="865" src="https://private-user-images.githubusercontent.com/30726623/659785554-80c26691-ca57-49f7-bc31-8cfae7b12850.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3OTA1NDI5OTAsIm5iZiI6MTc5MDU0MjY5MCwicGF0aCI6Ii8zMDcyNjYyMy82NTk3ODU1NTQtODBjMjY2OTEtY2E1Ny00OWY3LWJjMzEtOGNmYWU3YjEyODUwLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjA5MjclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwOTI3VDIwNTgxMFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTYzNDk2MGUxMWE4ODYyMzZmNTQ3NDU5Yzg2N2MxMzYyYjIwYjI2MjYwODczZWZhMDQ5YWI5ZDNiYTMxMmY3YjYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JnJlc3BvbnNlLWNvbnRlbnQtdHlwZT1pbWFnZSUyRnBuZyJ9.nWrb8ceKv17ltURyo4-0TZYGVddB7BI7GLFSr3SnKkw"> I would really abstain from trying to get this to run currently
boykopovar commented 2026-09-27 21:06:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by boykopovar on 2026-09-27T21:06:56Z.


It seems that with APS5_DRAW_DRAIN=1 the black flickering disappears. Is the branch ready to be removed from draft status, merged, and continued in other PRs?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5859830888 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5859830888). Originally posted by [boykopovar](https://github.com/boykopovar) on 2026-09-27T21:06:56Z. --- It seems that with APS5_DRAW_DRAIN=1 the black flickering disappears. Is the branch ready to be removed from draft status, merged, and continued in other PRs?
yumlevi commented 2026-09-27 21:15:38 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T21:15:38Z.


sure, conflicts are resolved

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5859893339 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5#issuecomment-5859893339). Originally posted by [yumlevi](https://github.com/yumlevi) on 2026-09-27T21:15:38Z. --- sure, conflicts are resolved
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!5
No description provided.