Skip to content

WIP: The Smurfs Dreams on Linux, first frames (stacked on #5) - #12

Closed
Pacuka wants to merge 19 commits into
boykopovar:mainfrom
Pacuka:wip/smurfs-on-pr5
Closed

Pacuka wants to merge 19 commits into
boykopovar:mainfrom
Pacuka:wip/smurfs-on-pr5

Conversation

@Pacuka

@Pacuka Pacuka commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Status

Draft: this is stacked on #5 (Demons Souls boot) and is not meant to be merged on its own yet. This branch is based on #5 (yumlevi:feat/demons-souls-boot) because its AGC driver is much further along than main. It also includes #14 (libstdc++ ABI interposition on Linux). Until #5 lands, the diff below also contains all of #5. The commits new in this PR are the 13 on top of it, listed below. When #5 is merged I will rebase, strip the explanatory comments (docs/CONVENTIONS.md) and split this into small PRs.

The goal is running The Smurfs Dreams (Unreal Engine, FMOD) on Linux. How far it gets:

  • It boots through engine init, file/pak loading (AMPR/APR), networking/NP init (offline console) and FMOD module loading.
  • The Vulkan device comes up and compute dispatches and draws run. The title renders into a 2848x1600 target, scales it to 3840x2160 and presents 4 frames.
  • After the 4th frame the render thread stops submitting, and the window then goes "not responding". The cause: UE waits for frame fences that are resolved from GPU end-of-pipe interrupts, with a predicated INDIRECT_BUFFER (fast clear eliminate) in between. The last commit fixes several parts of that path (see below); the frame loop is not yet continuous.

Commits on top of #5

Linux fixes that are also on main (#7) but missing from #5:

  • fix(build): bundled SDL2 without static executable linking; guest library tests linked dynamically
  • fix(videoout): no __stdcall on the window procedure
  • fix(libc): calloc/realloc replacement slots; register the main guest image on Linux
  • fix(kernel): map SCE protections to readable host pages

New:

  • fix(kernel): sceKernelVirtualQuery fallback through /proc/self/maps (Boot Demon's Souls to its first level: AGC recorder driver, runtime, audio, Bink fixes #5 only had VirtualQuery, so it did not build on Linux)
  • libc, host C++ exceptions on Linux: this branch first made the native __cxa_* aliases Windows-only. It now takes fix(exceptions): interpose libstdc++ ABI on Linux so the project's own unwinder drives it #14 instead, which fixes the same mixed-runtime problem the other way round (libc drives every host throw). With fix(exceptions): interpose libstdc++ ABI on Linux so the project's own unwinder drives it #14 Smurfs gets exactly as far (same 51 draws, 4 frames), and the GPU worker's catch now handles the VideoOut "window was closed" exception instead of terminating. The unhandled-throw log fix in Runtime.cpp stays.
  • libc: guest wchar_t is 16-bit. The wcs* functions in Boot Demon's Souls to its first level: AGC recorder driver, runtime, audio, Bink fixes #5 call the host std::wcs*, which uses 32-bit wchar_t on Linux. This branch keeps a UTF-16 implementation.
  • AGC driver:
    • end-of-pipe interrupt delivery (sceAgcDriverAddEqEvent registry, per queue id: 0 = graphics, 0x20+ = compute); interrupt RELEASE_MEM stores its label synchronously before the event
    • a retired compute submission raises its queue's end-of-pipe event
    • SET_PREDICATION (BOOL64/BOOL32)
    • INDIRECT_BUFFER: targets are copied into the submission at submit time. Without CHAIN it is a call with a return stack, with CHAIN a jump.
    • null sampled texture descriptors (format 0) bound as a zero 1x1 texture
    • 3D textures in 64 KiB XOR modes (use the SW_64KB_S order, which is exact only at the block origin; tech debt)
    • DMA_DATA cache policy bits; DX_LINEAR_ATTR_CLIP_ENA; CMASK FAST_CLEAR colour targets
  • libSceAgc:
    • sceAgcDcbJump: mode 0 = call, mode 1 = chain
    • sceAgcJumpPatchSetTarget, SetPredication, SetPacketPredication, SetRangePredication
    • shader half fusion: GetFusedShaderSize / FuseShaderHalves (VS front + GS back into the GS-stage pair the Boot Demon's Souls to its first level: AGC recorder driver, runtime, audio, Bink fixes #5 driver already draws)
    • the WRITE_DATA patch-address NID fPSCdQxgpSw
    • null placeholders for indirect register packets, plus Set*RegIndirectPatchSetNumRegisters
  • Runtime/libraries (from the Smurfs bring-up, merged with Boot Demon's Souls to its first level: AGC recorder driver, runtime, audio, Bink fixes #5 per file; the other side's missing exports were carried over):
    • Net/Http/Http2/NP*/Json2/AppContent/PlayGo/SystemService/UserService/pthreads
    • APR submit-and-get-result
    • the AMPR kernel-event-queue command
    • sceKernelLoadStartModule for relinked resident modules
    • IME keyboard without a device
    • an ErrorDialog state machine
    • pad output no-ops and trigger-effect state

Notes for #5

The 16-bit wcs* functions, the /proc/self/maps fallback and the per-queue interrupt delivery are independent of Smurfs and probably worth picking into #5 directly.

🤖 Generated with Claude Code

devilismyfriend and others added 19 commits September 25, 2026 16:27
- libc: reserve guest memory in one arena below the PS5 map limit with
  MEM_WRITE_WATCH (GuestArena) and a caching guest heap; the allocation
  registry gains a generation counter, an invalidator callback for the
  driver's page cache and a pin waiter for leased ranges. This replaces
  the fault-based GuestMemoryTracking/GuestMemoryBacking layer, whose
  files are removed.
- libkernel: mmap/mprotect/munmap on the arena, flexible memory budget,
  real sceKernelVirtualQuery; POSIX pthread layer, rwlocks, timed locks,
  TSD, event flags; 0.5 ms scheduler tick and high-resolution sleeps;
  TSC/clock/time functions; file APIs return SCE errno codes; the APR
  file-streaming API.
- libc: vectored crash reporter with backtraces for fatal exceptions,
  SIGABRT, UCRT invalid parameters and process exit; SSE4a EXTRQ/INSERTQ
  emulation for Intel hosts; %ls/%lc/%S/%C with the guest's 16-bit
  wchar_t; hand-written setjmp/longjmp for the guest jmp_buf; a path
  alias table for short save-data mount points; more string, stdio and
  math exports.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
- s_*_saveexec reads its source before writing the old EXEC into the
  destination, so the aliased form (vcc, vcc) computes exec & vcc; the
  per-lane exec bit comes from the lane's own bit. Every Bink 2 decoder
  kernel uses that form; this was the video corruption.
- buffer atomics add/sub/or/xor with a zero operand become an atomic
  load or nothing.
- DescriptorBinding carries bufferWritten/bufferAtomic/imageWritten;
  results expose a variantId and share SPIR-V copy-on-write; source
  keys use a length plus 64-bit hash; captures can be reused.
- wave-LDS ordering barriers, v_movrels/v_movreld lowering, SMEM with a
  VCC base, f16 conversion opcode fix, a per-function SPIRV-Tools pass
  list, env-gated IR dumps and probes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
Replaces the synchronous per-command execution model, and with it the
upstream render-target, pipeline-cache, tile-buffer, batched-draw and
memory-ownership commits (5a280ce, 7ed5a0b, 46c799d, 598caac, 40df528),
whose files are removed.

- Recorder: one open command buffer per device; dispatches, resident
  draws, uploads, write-backs, labels, fills and copies record into it;
  timeline-semaphore serials let drains wait without the GPU mutex;
  completions run in order at reap.
- one worker thread per PM4 queue; labels and stores written by the GPU
  into the host import; GPU-side DISPATCH_INDIRECT; the buffer-fill
  kernel replaced by vkCmdFillBuffer; a dispatch cache validated by
  write watch; filler packets tolerated; rejected submissions dumped.
- guest memory: page-state cache, 64 KiB write generations, host imports
  with VK_EXT_external_memory_host, persistent mirrors of the executable
  image, GPU copies of misaligned sub-ranges.
- textures: shader-written images stay resident with deferred
  write-back (adjacent-generation rule for packed video planes), sampled
  views of storage images, DCC key handling, addrlib swizzle equations,
  bidirectional detiler.
- draws: MRT, more formats, dynamic viewport/scissor, cached pipelines,
  resident 64 KiB targets, draws recorded into the recorder.
- ShaderResources: two-stage build, descriptor and sampler caches, a
  content-keyed resource cache; presentation from the resident image.
- a label deferred behind a completion is no longer re-stored by the
  CPU at reap time unless a write-back overwrote it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
…native

- AudioOut2: one SDL 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; ports are mixed per push with 7.1 folded to stereo.
- libSceAjm.native: instance and batch APIs; ATRAC9 decoding with
  variable-size frames inside superframes, padding, gapless parameters
  and handle re-creation on re-initialisation.
- AudioOut v1: sceAudioOutOutput(handle, NULL) drains instead of
  throwing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
- libSceAgc: SetIndexCount, SetBaseIndirectArgs, DispatchIndirect, wait
  and write-data patch functions, relaxed checks for what titles send,
  NOP fillers for LOD stats and wait-until-safe, NotImplemented stubs.
- libSceSaveData.native: short mount points, backup events, save-data
  memory slots.
- user/system service, store dialog, video-out flip modes and queue-full
  error, pad read, fibers, offline behaviour for network/NP modules, and
  new export-only modules Ampr, JpegEnc, Json2, MsgDialog.native,
  NpCppWebApi, NpUtility.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177gthrWEBBfBu5xJDXgBfo
Distributions without static X11 libraries (such as Arch-based ones) fail
SDL2's X11 feature checks because the global -static linker flag also
applies to its try_compile probes. Restore the flag after SDL2 is added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c6f2d98)
GCC on Linux rejects the attribute, which breaks the libs build since the
F11 fullscreen change. It has no effect on x86-64 Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a4273c1)
SceLibcMallocReplace lists calloc before realloc (malloc, free, calloc,
realloc, memalign, reallocalign, posix_memalign, ...), as the table in
retail titles shows. realloc therefore called the application's calloc
with the old pointer as the element count, and calloc called realloc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 998605f)
SCE_KERNEL_PROT_CPU_RW (0x02) and CPU_EXEC (0x04) include read access,
but were translated to write-only and execute-only host pages. GPU read
and write bits also need host access because the emulated GPU reads and
writes guest memory from the CPU. Write-only mappings made the AGC driver
reject guest data segments as unreadable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d15e936)
Guest mprotect calls on the executable's own segments failed with
"guest protection or unmap range is not registered" because only the
Windows build registered the main image. Register the PT_LOAD segments of
the main executable page by page, merging the protections of segments that
share a page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b98257b)
Tests in core/libs link against the prx shared libraries, which the
global -static flag rejects on Linux ("attempted static link of dynamic
object"). Drop -static in that directory on non-Windows hosts while
keeping the static GCC runtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 37074ab)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Takes PR boykopovar#5 as the base and ports the Smurfs bring-up (e43b43a): PR boykopovar#5 wins
AGC, guest memory, DirectMemory, AMPR/APR; ours wins network, NP, JSON, file,
app content and pthreads; the other side's extra exports are transplanted.
Adds APR submit-and-get-result, the AMPR kernel event queue command, EOP
interrupt delivery and keeps 16-bit guest wide-string functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…povar#5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed-throw log fix

SET_PREDICATION (BOOL64/BOOL32) and chained INDIRECT_BUFFER in the PR boykopovar#5 driver:
jump targets are appended to the submission at submit time, predicated packets
drain the queue before reading the label. libSceAgc emits SET_PREDICATION,
INDIRECT_BUFFER and packet/range predication. The unhandled-exception log no
longer walks frame pointers, which crashed for callers built without them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- libc: native __cxa_*/__gxx_personality_v0/_Unwind_Resume exports only on
  Windows; on Linux host code keeps libstdc++/libgcc (mixed runtimes lost every
  host catch). The libc unwinder also accepts the versioned libstdc++ personality.
- libkernel: sceKernelLoadStartModule hands out resident relinked modules.
- libSceAgc: shader half fusion (VS front + GS back), null indirect-register
  placeholders and SetNumRegisters patches.
- driver: 64 KiB XOR 3D textures (SW_64KB_S order, tech debt), null sampled
  texture descriptors, DMA_DATA cache policies, DX linear attribute clipping,
  CMASK fast-clear color targets.
- IME keyboard without a device, error dialog state machine, pad trigger state,
  Trophy2 game info with one output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…errupts

- sceAgcDcbJump mode 0 emits a returning INDIRECT_BUFFER, mode 1 a chained one;
  the driver keeps a return stack for calls.
- End-of-pipe events go only to the registration of the queue that raised them.
- A retired compute submission raises its queue's end-of-pipe event after its
  labels land.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…of Windows-only aliases

Replaces our Linux split-runtime workaround with boykopovar#14
(a4c519b, d01be2b). Smurfs reaches the same point (51 draws, 4 frames) and
the GPU worker now catches the VideoOut window-closed exception instead of
terminating.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Pacuka

Pacuka commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Closing: #5 has been merged, and this draft's work now lives on a local branch rebased onto main. The parts that are still relevant will come as small, separate PRs (some already did: #39, #40, #42). Thanks!

@Pacuka Pacuka closed this Sep 28, 2026
@boykopovar

Copy link
Copy Markdown
Owner

Closing: #5 has been merged, and this draft's work now lives on a local branch rebased onto main. The parts that are still relevant will come as small, separate PRs (some already did: #39, #40, #42). Thanks!

Does The Smurfs Dreams work on Linux (on main)?

@Pacuka

Pacuka commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Sorry for the late answer. Not on main yet. I checked today on main 5895ea7 (Linux 7.2, AMD): it doesn't load, because 23 imports have no export yet. The first one the loader hits is 3YQ1qY5ePUk (libSceAudioIn) from the bundled libfmod.prx. The others come from the eboot: libkernel (2), VideoOut (2), Net, NpManager, NpWebApi2, NpEntitlementAccess (4), Json2 (4), Http2, GameLiveStreaming (2), WebBrowserDialog (2), VoiceQoS and Acm.

On my local branch (an older main plus these exports and some AGC driver work that isn't upstream yet) it is playable but slow: the intro cinematic plays, the hub level loads and responds to the controller, at about 4–5 fps. The UI layers are never cleared, so they pile up on screen.

I'll send the missing exports as small PRs, one per library, after checking that no open PR already covers them, and then the driver parts one by one.

0xcrstn added a commit to 0xcrstn/AnyPS5 that referenced this pull request Oct 15, 2026
…residency is guarded

A slice of the versioned device-local execution design (boykopovar#12): GPU
outputs stay authoritative on the device until something reads them.

APS5_LAZY_STAGING_OUT (device-resident results of copied buffer
regions, instead of a copy-back after every use) was off. A CPU store
over such results reached ResidentStaging's "publish after a CPU store
of unknown extent" rejection. APS5_COHERENCE_RESIDENCY now guards those
pages, so a native access publishes the results first.

LazyStagingOut therefore defaults to on whenever residency protection
is active (the device installed the guards). The explicit value still
wins.

NoteDeviceResident keeps a result on the device only if its whole pages
are guarded. A range that is not page-aligned, or that the guards
refuse, is published at once through the active recorder (new site
"unprotected"), which is the copy-back it would have had. A device-only
result is therefore never unprotected, and the rejection path is not
reachable with the defaults.

agc_coherence_residency covers that fallback: an unaligned range is not
kept and its bytes land in place.

The measured staging-out share in A2 was 13.86 ms per present (review
section 6). The effect in game is unmeasured.

Built and tested in the worktree: 693 tests (agc_* and
guest_access_guards) pass with the usual exclusions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
hypermoist pushed a commit to hypermoist/AnyPS5 that referenced this pull request Oct 26, 2026
…kopovar#12)

* feat(bridge): carry peer-to-peer datagrams and session signaling kinds

The bridge now keeps the game traffic ports and stream key from welcome,
answers activate (0x0301), peer info (0x0304) and bind (0x0305), sends
deactivate (0x0302) and unbind (0x0306), keeps the peers each peer frame
(0x0303) reports per session, and sends binds and activations again after
a reconnect.

With the bridge on, SCE_NET_SOCK_DGRAM_P2P sockets run on a loopback UDP
socket: sceNetBind registers the sin_vport with the net service, and
sceNetSendto and sceNetRecvfrom carry each datagram through the net
service's UDP port with the 8-byte header. Stream peer-to-peer sockets
and the calls whose console behaviour is unknown throw.

* feat(bridge): carry peer-to-peer streams through the net service

With the bridge on, SCE_NET_SOCK_STREAM_P2P sockets run on loopback TCP.
sceNetListen registers the bound virtual port for streams, and
sceNetAccept takes only connections that start with the stream key and a
header naming that port, reporting the peer's virtual address.
sceNetConnect connects to the net service's stream port and sends the key
and a header naming the peer. Stream reads and writes pass through as they
are.

* docs(debt): keep the peer-to-peer socket entry under the length limit

* docs(debt): put the bridge's gaps first and keep the entry under the length limit

* docs(debt): keep the peer-to-peer datagram entry under the length limit

* fix(bridge): bound the peer-to-peer stream opening on every platform

receive_preamble and send_preamble now wait for the socket with the
time left before each read or write, so an accepted stream that sends
fewer than the 24 opening bytes is refused after 5 seconds on Linux too,
where the accepted socket blocks. TCP options are accepted on
SCE_NET_SOCK_STREAM_P2P sockets, which are TCP underneath.

* test(bridge): declare the peer-to-peer test's exports through the public header

* fix(bridge): keep the online-permission answer from main when merging the stream work

---------

Co-authored-by: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs rebase Conflicts with main, rebase needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants