Boot Demon's Souls to its first level: AGC recorder driver, runtime, audio, Bink fixes #5
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/5"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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_INDIRECTsubmission, 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_*_saveexecoperand order (the aliaseds_and_saveexec_b64 vcc, vcccomputedexec & 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 secondarybuild_tools/CMake tree.This replaces upstream driver work
The driver commit removes the code of
5a280ce,7ed5a0b,46c799d,598caacand40df528(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 inShaderResources, the two-tierBufferPool, and write-watch tracking inGuestMemory. The fault-based tracking layer in libc (GuestMemoryTracking,GuestMemoryBacking,GuestHeapStorage,MemoryTracking*,MemoryBacking*) is replaced byGuestArena+GuestHeapbecause 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 satisfiesWAIT_REG_MEMfrom labels already recorded.Driver.cpp: one worker thread per PM4 queue;RELEASE_MEM/WRITE_DATAlabels andCOPY_DATA/DMA_DATA/DUMP_CONST_RAMstores are written by the GPU into the host import;DISPATCH_INDIRECTruns GPU-side; the title's buffer-fill kernel is replaced byvkCmdFillBuffer; 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-checkVirtualQuery; 64 KiB-block write generations fromGetWriteWatchwith a per-thread collect memo.GuestBufferMemory: registered allocations are imported withVK_EXT_external_memory_host(budgetAPS5_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_FRAMESreads frames back on the GPU.WAIT_REG_MEMheader at the intro cinematic).Recompiler (core/shader/recompiler)
sSaveexecreads 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=1restores the old order.APS5_NO_ATOMIC_ZERO_SKIP=1restores plain atomics.DescriptorBindingcarriesbufferWritten/bufferAtomic/imageWritten; results expose avariantId; SPIR-V is shared copy-on-write; source keys use a length plus 64-bit hash; captures can be reused for the compile.v_movrels/v_movreldlowering, 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 withMEM_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.mmap/mprotect/munmapon the arena, flexible memory budget, realsceKernelVirtualQuery; 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.EXTRQ/INSERTQemulation;%ls/%lc/%S/%Cwith the guest's 16-bitwchar_t; hand-writtensetjmp/longjmpfor the guest'sjmp_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)
sceAudioOutOutput(handle, NULL)drains instead of throwing.Libraries (libSceAgc and other prx)
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, unalignedACQUIRE_MEMranges), NOP fillers for LOD stats and wait-until-safe, aNotImplementedstub file in upstream's pattern.scePadRead), libSceFiber, offline behaviour for the network/NP modules, and new export-only modules libSceAmpr, libSceJpegEnc, libSceJson2, libSceMsgDialog.native, libSceNpCppWebApi, libSceNpUtility.Verification
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
docs/CONVENTIONS.mddoes not allow. I left them in so reviewers can read the mechanisms; I can strip them (or move the design into adocs/note) if that is preferred before merging.docs/TechnicalDebt.mdasks 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.DRAW_INDIRECTand siblings) are not implemented; the title's first level submission is rejected there.APS5_HOST_IMPORT_MIB=16384.Update 2026-09-26 (commits
af3c202,01c4e3e,29b4601): intro-video stage from ~15 fps to ~48 fps,--to-intelrelinker lowering, upstream fixesMeasured 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):
d677f97)29b4601)Driver (core/libs/prx/libSceAgcDriver)
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=1disables,APS5_VERIFY_DATA_HITS=1captures beside every hit and aborts on any disagreement (150 s run: 0 disagreements).APS5_NO_DISPATCH_RECIPE,APS5_NO_DRAW_RECIPE,APS5_NO_DRAW_KEY,APS5_VERIFY_RECIPE,APS5_VERIFY_DRAW_ENTRIES,APS5_VERIFY_DRAW_RECIPE.vkCmdUpdateBuffer, hashed,APS5_NO_TEMPLATE_DATA_REFRESH=1keys the words as before).APS5_BLOCK_WRITEBACK_WIDEN=1widens), windowed detile.DccKeyProof), per-class GPU timing ([gputime]), per-layer storage clears.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).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=1disables both).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 theNonUniformpath whenVK_EXT_descriptor_indexingis present. The per-frame skip of program0x1048947300is gone (skipped 0at the video stage);APS5_NO_BINDLESS_IMAGES=1restores the skip;[bindless]reports tables bound, slots, padded and rejected entries.APS5_WORKER_AFFINITY,APS5_JOB_AFFINITYopt in);APS5_NO_PAD_INPUT=1ignores host input for unattended measurements; per-draw log lines behindAPS5_TRACE_DRAWS.ShaderMemorybehind a BDA-miss dispatch's snapshot;UnchangedSinceCollectednow 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
popcntandint 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-lengthjmpinto 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 forPOPCNTand the0F 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/reallocheap slot swap,libSceRtcexport fixes with tests, the libc default terminate handler, theBTCdecoder case;guest_rtc_testsandapplication_heap_testswired 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_MEMon 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=1keeps 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
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.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
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).docs/CONVENTIONS.mdis 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.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

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-intelflag is present (but it is not connected correctly yet). The decoder has only been verified by Dreaming Sarah.Here's a table of substitutions.
Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-26T08:29:04Z.
Sounds good, I'll look into that.
Imported from boykopovar/AnyPS5. Originally posted by boykopovar on 2026-09-26T09:53:52Z.
--to-intelflag is now enabled and running relinker with it now causes instructions to be replaced (on main)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 (
af3c202runtime,01c4e3erelinker,29b4601driver + 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 onpopcnt/int 0x41, ~46K VEX RIP-relative operands and jump tables to adjust), so each SSE4a site is lowered in place to a same-lengthjmpinto an appended executable section with the SSE body and a jump back (same-length in-place forms where they exist). Decoder fixes forPOPCNTand0F BB, tests added. The runtime trap is now only a fallback.calloc/reallocheap slot swap,libSceRtcfixes with tests, the default terminate handler, theBTCdecoder case.🤖 Generated with Claude Code
https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
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.
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.
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
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.cppdescribePages: on Linux there is no page cache, so the fallback re-reads and parses/proc/self/mapson 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/GetWriteWatchare 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 onuserfaultfdasync write-protect plusPAGEMAP_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 existingAPS5_FLIP_QUEUE_WAITpath) fixes it.Looking forward to this landing. Happy to help with the conflicts if useful.
Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T17:46:49Z.
nuh it's all good my slopgent is on it
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?

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:
e764385); initialised mutexes and conditions no longer take the process-wide lock on every lock, unlock, signal and wait (7233620).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: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
Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T20:59:39Z.
I would really abstain from trying to get this to run currently
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?
Imported from boykopovar/AnyPS5. Originally posted by yumlevi on 2026-09-27T21:15:38Z.
sure, conflicts are resolved