Skip to content

fix(guest-arena): place guest address space in the PS5 window on Linux - #861

Merged
oneandonlydean merged 5 commits into
boykopovar:mainfrom
jeffrey12cali:fix/linux-guest-arena
Oct 10, 2026
Merged

oneandonlydean merged 5 commits into
boykopovar:mainfrom
jeffrey12cali:fix/linux-guest-arena

Conversation

@jeffrey12cali

@jeffrey12cali jeffrey12cali commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What

Guest address space on Linux is placed inside the PS5 window instead of wherever the kernel's top-down mmap happens to land, so a title's allocator accepts the mapping. sceKernelAllocateDirectMemory/sceKernelMapDirectMemory with addr == NULL now return addresses in [0x2_0000_0000, 0xFC_0000_0000), which is the bound sceLibcMspaceCreate enforces.

The arena reserves the free intervals of that window up front (PROT_NONE | MAP_NORESERVE, 1 GiB chunks), so no later host mapping - driver, library, hinted mmap - can appear inside it, and commit can keep MAP_FIXED semantics, which is what committing over the arena's own reservation requires.

Also in this change, from review:

  • A reservation chunk that fails with EEXIST is recorded as occupied, so the arena cannot hand it out. Any other failure throws, with the address and the size.
  • An in-arena unmap keeps the range reserved, through the same PROT_NONE replacement that GuestArenaReset uses.
  • A partial overlap between a commit and an already-used range throws instead of being overwritten, and the unwind releases only what the failing call marked.
  • An unmodelled protection value throws.
  • The tests cover the kernel API with addr == NULL, not only the arena entry points.
  • GuestArenaReset_nid_postfix no longer releases address-space accounting on Linux (@blawesom). The Linux variant released the range in addition to resetting the memory, while the Windows variant only resets and leaves accounting to the caller. Two call sites released again after the reset, and Contains is span-based, so both released twice under two separate lock acquisitions: a thread that allocated the range in between had its entry erased and the arena handed the range out twice. Every caller already releases explicitly, so the contract is restored rather than duplicated.
  • The fixed-mapping probe test is Linux-only (@blawesom). It used mmap, PROT_READ, PROT_WRITE, MAP_FIXED_NOREPLACE and EEXIST directly, which does not compile under MinGW.

Fixes #692.

Tested

Arch Linux, kernel 7.2.8-arch1-2, GCC, Release, cmake -DBUILD_TESTING=ON: ctest 491/491 on this head, rebased onto current main. The slowest test in the suite takes 4.19 s and the two tests added here take 0.01 s each, so nothing approaches the 30 s limit.

The Windows build cannot be compiled here (no MinGW). The guard was verified by tracking preprocessor nesting: before the change the probe body and its call site are outside every __linux__ block, after it both are inside. CI has to confirm the build itself.

The new kernel-API tests were verified to fail without the change. Making ArenaAvailable() return false gives 0% tests passed, 1 tests failed, and restoring it gives 100%.

Reservation feasibility was measured before adopting it. With an unlimited address space, 1000 GiB of the window reserves in 1 GiB PROT_NONE | MAP_NORESERVE | MAP_FIXED_NOREPLACE chunks, with zero failures on kernel 7.2.8-arch1-2. Under ulimit -v 67108864 (64 GiB) the arena aborts with guest arena: cannot reserve 0x19c0000000+0x40000000 (Cannot allocate memory) instead of passing in silence, and at 128 GiB it fails at 0x29c0000000.

The reservation does not reduce allocatable device memory. A probe that reserves the same 997 GiB window and then allocates VK_MEMORY_HEAP_DEVICE_LOCAL_BIT memory gives identical totals with and without the reservation: 22 GiB before VK_ERROR_OUT_OF_DEVICE_MEMORY on an RTX 4070 Laptop, and 4 GiB on the AMD 780M, at both 1 GiB and 256 MiB step sizes. This is reported against #861's head in the discussion below.

Title evidence (PPSA28997, native Linux relink): the window placement is what the boot stands on. sceKernelGetDirectMemorySize reports 0x360000000 on both platforms, and with the window in place the bundled player/JSON chain stops rejecting the address and the title reaches on-screen video.

Independent reports on other titles:

  • @alfalfa-star, PPSA14632: sceKernelMapNamedFlexibleMemory → sceLibcMspaceCreate now lands inside [0x400000, 0xFC00000001) and Common::initialize stops failing with 0x80553504.
  • @ghreprimand, PPSA01341: guest mappings move from host addresses such as 0x7fff94400000 into 0x200000000 / 0x200300000, and the title passes the allocator fault.
  • @fisherjoey, Demon's Souls (PPSA01341 v1.07, RTX 5070 Ti): without this PR the title SIGSEGVs under _dl_init in 2 of 2 runs; with head c2e15098 it boots, plays the attract movie at about 30 fps, and exits with code 0 in 2 of 2 runs.

#1370 (partly overlapped allocations) has since merged and this head is rebased on top of it. #1360 remains an alternative to the eager reservation; I will rebase onto it or drop the reservation on the maintainer's call.

Checklist

  • Based on current main (rebased; the head is 3c54adf0)
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw; no silent stubs added
  • No notes, investigation files or images added to the repository
  • No new third-party code
  • Generic behaviour, not specific to one title
  • Every test finishes well under 30 s, cold
  • Depends on: none
  • AI-assisted: yes

@alfalfa-star

alfalfa-star commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

@jeffrey12cali I don't have an arena PR in flight, so please keep #861. What I described in #692 was only a local experiment.

Tested #861 (c9ce0789) with LEGO Horizon Adventures (PPSA14632) on Linux (Arch, GCC 16.2, --to-intel), in place of that experiment. This title reaches the window through flexible memory: the bundled libSceNpCppWebApi.prx maps its 0x80000-byte heap with sceKernelMapNamedFlexibleMemory (prot 2, no address) and passes it to the bundled libc's sceLibcMspaceCreate, which only accepts [0x400000, 0xFC_0000_0001). With APS5_TRACE_MEMORY=1:

reserve    0x1000000000+0x8000000000
reserve    0x200000000+0x4000000
map anon   0x204000000+0x80000 prot=0x2
map direct 0x204080000+0x40000 ...
map direct 0x204200000+0x200000 ...

Every traced mapping is inside the window. Common::initialize no longer fails with 0x80553504, and the title runs past the online-subsystem segfault. With a separate fix for sceAudioOut2Set3DLatency(0xFF, 1) it continues to scePadReadState: invalid argument, which is unrelated. The test suite on that tree shows no new failures (only three RADV pixel tests fail, as without #861).

Edit: the first version of this comment showed a trace from a run where the patched prx in build/core/libs/libs were stale (I had built without the libs target), so it still used my local experiment. The trace above is from a rebuild with #861's libraries.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Thanks for testing on a second title — that is the strongest thing this PR could get, and the sceKernelMapNamedFlexibleMemory → sceLibcMspaceCreate route is a path I had not reproduced: my measurements came from sceKernelAllocateDirectMemory, same window, same [0x400000, 0xFC00000001) bound, and sceKernelGetDirectMemorySize reporting 0x360000000 on both targets.

On PPSA28997 this PR is what the boot stands on: with the window in place the title reaches on-screen video at about 60 FPS with the allocator counters matching the Windows reference built from the same commit; without it the bundled player/JSON chain asserts on the rejected address.

Good catch on the stale build/core/libs/libs trap, and worth writing down somewhere: our runner copies from exactly that directory, so a rebuild that skips the libs target silently tests the wrong binaries. If you agree it belongs in the contributor notes, I can send that as a small docs-only PR.

@fisherjoey

Copy link
Copy Markdown
Contributor

On NVIDIA (595.91), with #861, #864 and #732 merged, Demon's Souls reaches the main loop and renders, then every vkAllocateMemory returns VK_ERROR_OUT_OF_DEVICE_MEMORY with about 14 GB of VRAM free. Without #861 it segfaults during init.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Thank you for the data point, and sorry it is a mixed one. Reading it carefully: without #861 the title segfaults during init, and with it the title reaches the main loop and then fails at vkAllocateMemory - so this PR uncovers the NVIDIA failure rather than causing it, but that is no consolation if you want the title running, so here is what I can add.

First, a theory I tested and discarded, so nobody chases it: I suspected the arena size (sceKernelGetDirectMemorySize reports 0x360000000, 13824 MiB) of eating the card. It does not - the guest arena and direct memory are host anonymous mmap in this code path, not vkAllocateMemory-backed, so the window consumes address space and committed host pages, not VRAM. The size coincidence is still worth ruling in or out, but by the route below rather than by shrinking the arena.

What would actually pin it down:

  1. Is it literally every vkAllocateMemory, or the first large one and everything after it because the backend is wedged? "Every call fails with plenty free" usually means the memory-type/properties the backend selected are not satisfiable on that driver, not that the card is full.
  2. The failing allocationSize, memoryTypeIndex and memoryHeapIndex, plus the VkMemoryHeap sizes and flags the backend read at instance setup. If the title sizes its pools from a platform limit (the same family as 0x360000000) while ANV reports a smaller device-local heap, the request overshoots and the driver answers OUT_OF_DEVICE_MEMORY; on RADV the same request can be satisfied from a host-visible heap, which is exactly the asymmetry you would expect to see.
  3. Whether it reproduces with fix(guest-arena): place guest address space in the PS5 window on Linux #861 alone, without fix(module): resolve the default dlsym scope against the main program #864/fix(libs): keep a $ORIGIN runpath in the patched prx libraries #732 - if a combination matters, I would rather know which.

I can only test on AMD here (PPSA28997 on RADV: on-screen video at ~60 FPS with every mapping inside [0x400000, 0xFC00000001) and no allocator complaints), so I cannot reproduce the NVIDIA half myself. If those numbers are cheap to grab, post them here or in a new issue and I will work out whether the fix belongs in the placement (a reservation that can dodge driver-reserved ranges) or in the memory-type selection, and send a PR either way. If you would prefer I open the follow-up issue with your configuration quoted, say the word.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Two corrections, then measurements from an actual NVIDIA device, because it turns out I can test this half after all.

I was wrong twice in my previous comment. I wrote that I could only test on AMD. This machine has both GPUs, and the engine has always selected the discrete one - our own startup log says Selected GPU name=NVIDIA GeForce RTX 4070 Laptop GPU vendor=0x10de, driver 615.71.09, Memory heap 0 size=8188.0 MiB flags=0x1, Memory heap 1 size=23527.8 MiB flags=0x0. So "PPSA28997 on RADV" was an assumption I never checked. Second, my size-overshoot theory does not survive contact with the device either, and I would rather say so than leave it standing.

I wrote a small probe (vkCreateInstance -> select by device name -> vkAllocateMemory at fixed sizes, once on a device-local memory type and once on a host-visible coherent type, each freed immediately) and ran it on the idle card:

single allocation device-local type host-visible type
1, 64, 1024, 2048, 4096 MiB VK_SUCCESS VK_SUCCESS
6144 MiB VK_SUCCESS VK_SUCCESS
7168 MiB VK_SUCCESS VK_SUCCESS
0x360000000 = 13824 MiB VK_ERROR_OUT_OF_DEVICE_MEMORY (expected: that heap is 8188 MiB) not cleanly measured
1 TiB not attempted VK_ERROR_OUT_OF_DEVICE_MEMORY

The two results that actually matter for your report:

  1. A rejected request does not wedge the device. Immediately after the 0x360000000 failure, a 1 MiB allocation on the same device-local type returned VK_SUCCESS; same after the 1 TiB failure on the host-visible type. So "every vkAllocateMemory fails" cannot be explained by one early oversized call poisoning the allocator on this driver family. Either every request is independently too large for the budget its type is charged against, or the memory type the backend picks is not the one it believes it chose.
  2. The host-visible heap is system RAM, and its availability is not VRAM. An earlier run of the same probe, while other processes were active (~13 GiB of 30 GiB resident), failed at 6144 MiB and above on both types; minutes later, on a quiet machine, the identical binary succeeded at those sizes. So "~14 GB free" (of VRAM) does not describe what a host-visible allocation is charged against, and a repro that depends on machine load would look exactly like a driver bug.

What I would need to go further, and I think it is enough to settle it: for the failing calls, allocationSize, memoryTypeIndex, and that type's heapIndex with the heap size and property flags; plus, if it is cheap, VK_EXT_memory_budget's budget/usage per heap at that moment. If the failing sizes cluster around one value, the title is almost certainly computing them from a platform limit - our family reports 0x360000000 (13824 MiB) for direct memory, which is suspiciously close to a "one big allocation" - and the fix belongs in the reported limit, not in the placement change.

Two control tests worth running on your side: whether the failure persists with nothing else on the GPU, and whether it moves at all when the allocation is forced onto the host-visible type.

On my side, PPSA28997 with this arena in place is unaffected - the largest GPU-side block I can observe is 3407872 bytes, so this title never approaches the sizes in question, which is why I could not feel your failure from it. Nothing here makes me think #861 causes your problem, but I now have a probe that can test your exact numbers, and I will keep it pointed at this. Say the word and I will paste the whole ~130-line file into a comment, or add it to the repo under tools/ so anyone with an affected card can run it in one command (gcc -O2 vkprobe.c -o vkprobe -lvulkan).

@alfalfa-star

Copy link
Copy Markdown
Contributor

@jeffrey12cali Yes, please send the docs PR. The trap cost me one wrong comment here, so a line in the contributor notes would have saved it.

On the NVIDIA failure: @fisherjoey traced it in #1022, and #1051 is the fix. On NVIDIA, a refused VK_EXT_external_memory_host import of a read-only range (the relinked image's read-only sections) makes every later vkAllocateMemory on the device fail with -2. That fits "every allocation fails with 14 GB free" better than a size limit, and it would also explain why it only shows up once #861 gets the title far enough to import those ranges.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

That closes it, and #1022/#1051 explain what I could not: a refused VK_EXT_external_memory_host import of a read-only range poisoning the device allocation path is exactly the shape of "every vkAllocateMemory fails with plenty free", and your account also explains why it only surfaced once #861 got a title far enough to import those ranges at all.

For the record, the measurements I did get are consistent with that and rule the other theory out. On an idle NVIDIA device here (RTX 4070 Laptop, 6185 driver line, 8188 MiB device-local heap, 23528 MiB host heap): single vkAllocateMemory requests succeeded up to 7168 MiB and failed above the heap, and - the useful part - one rejected request did not wedge anything: the next 1 MiB allocation on the same memory type returned VK_SUCCESS, both on the device-local and on the host-visible type. So "every call fails" cannot come from an oversized allocation having been refused earlier; it needs a stateful failure like the refused import in #1022. My earlier size-overshoot guess was wrong and I have retracted it on this thread.

Docs PR for the stale build/core/libs/libs trap is on its way now - thanks for confirming where it belongs.

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Built and ran ctest on this PR merged onto current main (Linux, GCC): all green, guest_memory included. No CI ran on c9ce0789 (no checks on the head); the PR needs green CI, including the Windows/MinGW job, because the header moves the Commit/Reset declarations out of #ifdef _WIN32.

Before this can go in:

  • Code comments. GuestArena.cpp:291-297 (// PAGE_* on each case) and GuestMemory.cpp:452 (// PAGE_READWRITE). CONTRIBUTING says no code comments, and the description says there are none.
  • The TryMarkUsed result is ignored (GuestArena.cpp:318). If the range partly overlaps a used one, it returns true and the commit MAP_FIXEDs over it anyway, where MarkUsed would throw. That case should throw too. Also, on failure the catch at :322 releases the whole range, including the part the caller had already reserved with GuestArenaAllocate (the GuestHeap path).
  • MAP_FIXED on arena-chosen addresses (GuestArena.cpp:303, DirectMemory.cpp:406). The used map is seeded from /proc/self/maps once, on the first Arena() call. A host mapping created later inside the window (driver, another library, a hinted mmap) isn't in the map, so the arena can hand out its range and MAP_FIXED silently replaces it. The objection to MAP_FIXED_NOREPLACE was that it returns EEXIST on reserved space, but nothing is reserved up front anymore. For ranges the arena picked and for GuestMapNoOverwrite, MAP_FIXED_NOREPLACE turns that case into an error instead of corruption.
  • Eager reservation. You dropped the up-front PROT_NONE reservation because the kernel's top-down mmap "picks addresses just below the stack inside the range". On x86-64 with 47-bit user space, the stack and mmap_base sit near 0x7ff..., far above 0xFC_0000_0000. Could you share the failing case (kernel, ulimit -v, the /proc/self/maps at the failure)? If a MAP_NORESERVE reservation works, it also removes the seed race above.
  • Unknown protection becomes RW (GuestArena.cpp:298). Throw for values the switch doesn't model ("exact or throw").
  • Tests don't pin the fix itself. Both re-enabled checks map at fixed addresses. Nothing checks that a direct or flexible mapping with addr == NULL lands in [0x2_0000_0000, 0xFC_0000_0000), which is #692, or that munmap followed by a same-size map reuses the freed range (claimed under "Hole reuse"). Linux tests for both, plus the hinted path (addr != NULL without MAP_FIXED), would cover what the PR changes.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Thank you - the seed-race point is the important one and it changes the design, so I am taking it rather than defending it.

MAP_FIXED on arena-chosen addresses is wrong; switching to MAP_FIXED_NOREPLACE. You are right that the used map is seeded once from /proc/self/maps on the first Arena() call, so any host mapping created later inside the window - driver, another library, a hinted mmap - is invisible to the arena and MAP_FIXED silently replaces it. The original objection to MAP_FIXED_NOREPLACE was the up-front PROT_NONE reservation returning EEXIST, and that objection is gone now that nothing is reserved up front. I will use MAP_FIXED_NOREPLACE for arena-chosen ranges and for GuestMapNoOverwrite, and treat EEXIST as the retry/failure path rather than as corruption.

Eager reservation: I will re-measure and hand you the data. My note that top-down mmap picks addresses just below the stack inside the range was from a failing run, and your objection is reasonable - on 47-bit user space mmap_base sits far above 0xFC_0000_0000. I will re-test with a MAP_NORESERVE reservation and post the kernel version, ulimit -v, and the /proc/self/maps at the failure. If the reservation works, I would rather restore it, because it also removes the seed race above rather than mitigating it.

TryMarkUsed result ignored - agreed, it should throw. If the range partly overlaps a used one, returning true and then MAP_FIXED-ing over it is exactly the corruption case, and MarkUsed throws for it. I will make that path throw too. The second half of your point also stands: the catch currently releases the whole range, including the part the caller had already reserved through GuestArenaAllocate on the GuestHeap path - that has to unwind only what this call added.

Unknown protection becoming RW is wrong; it will throw. "Exact or throw" is the rule and I broke it.

Code comments removed - GuestArena.cpp:291-297 and GuestMemory.cpp:452. You are right that the description claimed there were none; that was wrong and the description will be corrected with the code.

Tests do not pin the fix - agreed, and this is the part I under-served. Both re-enabled checks map at fixed addresses, so neither would catch a regression of the actual bug. I will add Linux tests for: a direct and a flexible mapping with addr == NULL landing inside [0x2_0000_0000, 0xFC_0000_0000) (that is #692), munmap followed by a same-size map reusing the freed range (the "Hole reuse" claim, currently untested), and the hinted path (addr != NULL without MAP_FIXED) honouring or declining the hint explicitly.

CI. Noted on the missing checks for c9ce0789 and on the header moving Commit/Reset out of #ifdef _WIN32 - I will get the Windows/MinGW job green on the head before asking for another look, and will rebase onto current main as it moves.

@alfalfa-star

Copy link
Copy Markdown
Contributor

On current main (6cc3358), this branch (3c54adf) merges cleanly but breaks guest_mlock. That test came in with mlock/munlock (892aa8b, 1078608), after this branch's base, so CI here never ran it.

  • main alone: guest_mlock passes. main + this PR: it aborts.
  • The failing check is GuestMlock.cpp:118: after sceKernelMunmap(mapped, length), munlock(mapped, page) should return -1 with ENOMEM (12), but it returns 0. The mlock check just before it (line 116) still fails with ENOMEM as expected.
  • My reading: with the arena, an unmapped guest range stays host-reserved inside the window, so the host sees the same thing as a sceKernelReserveVirtualRange reservation. The test expects munlock on a reservation to succeed (line 110) and on a freed range to fail (line 118), and those two states now look the same to the host. So sceKernelMunlock probably needs to ask the guest mapping state, as msync does with RangeMapped, rather than the host.

Setup: Linux (Arch), GCC, Release. Found while rebuilding our PPSA14632 test branch on current main.

jeffrey12cali and others added 5 commits October 10, 2026 22:56
The arena constructor was Windows-only, so on Linux Available() was false: the guest heap fell back to the host allocator and direct memory landed wherever the kernel pleased. Titles that require a low virtual address rejected the mapping and re-issued the identical request, which surfaced as a start-up assert inside their own allocator.

Seed the window from the mappings that already exist instead of reserving it up front, because a PROT_NONE reservation of the whole range starves the kernel's own top-down mmap, which picks addresses just below the stack inside that range. Commit, reset and set-protection become portable so the arena owns its used ranges on both platforms, and fixed mappings are checked against the arena's used ranges rather than against EEXIST from a reservation.

The window-placement and no-overwrite checks in guest_memory were compiled only for Windows; they now run on Linux too, and the window check fails without this change.

Fixes boykopovar#692
The Linux implementation of GuestArenaReset released the range in addition to
resetting the memory, while the Windows implementation only resets the memory and
leaves accounting to the caller. Two call sites already release explicitly after a
reset, so every one of them released the same range twice: sceKernelMunmap through
ArenaForget, and GuestHeap::release through GuestArenaRelease.

The two releases acquire the arena lock separately. Contains is span-based, so the
second release still runs, and Release erases every overlapping entry. A thread that
allocates the range between the two calls therefore has its entry erased, and the arena
hands the same guest address range out twice.

Delete the release from the Linux reset so both platforms restore the documented
contract. Every existing caller already pairs the reset with an explicit release.
CheckUnmappedArenaRangeStaysReserved uses mmap, PROT_READ, PROT_WRITE,
MAP_FIXED_NOREPLACE and EEXIST directly, so the Windows build fails to compile it.
The probe exists to show that an unmapped arena range still rejects a hostile
MAP_FIXED_NOREPLACE mapping, which is Linux-specific behaviour.

Guard the function and its call site with __linux__. The other tests in the file
compile on both platforms.
An unmapped range inside the guest arena stays a PROT_NONE host
reservation, so host munlock succeeds on it. Check the guest mapping
state first, as msync does, and return ENOMEM for ranges the guest
has not mapped or reserved.
Throw when /proc/self/maps cannot be read or parsed, and when the kernel
places a reservation chunk at another address (MAP_FIXED_NOREPLACE
treated as a hint). Remove the unused PageSize and keep the POSIX-only
headers in the non-Windows block.
@oneandonlydean

Copy link
Copy Markdown
Collaborator

@jeffrey12cali @adriadam10 Rebased onto current main and pushed to the branch; your three commits are unchanged apart from the test-file conflict with CheckGuestModuleImageProtection (kept under #ifdef _WIN32). Two commits on top:

  • guest_mlock: an unmapped arena range stays a PROT_NONE reservation, so host munlock succeeded on it. On Linux sceKernelMunlock now checks the guest mapping state first, the same check msync uses (RangeMapped, moved to DirectMemory.hpp as GuestRangeMapped), and returns ENOMEM for ranges that are neither mapped nor reserved. mlock already returns ENOMEM there from the host.
  • Reservation: the arena throws when /proc/self/maps can't be read or parsed, and when the kernel places a chunk somewhere other than the requested address (kernels that treat MAP_FIXED_NOREPLACE as a hint). Also removed the unused PageSize() and moved <fstream>/<sstream> into the non-Windows block.

Linux, GCC, Release: ctest 694/695 on this head, guest_mlock and guest_memory included. The one failure, agc_driver_dcc_keys_first_write, fails the same way on main.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 10, 2026
@oneandonlydean
oneandonlydean dismissed stale reviews from adriadam10 and blawesom October 10, 2026 10:03

as per comment

@oneandonlydean
oneandonlydean merged commit b0cccf2 into boykopovar:main Oct 10, 2026
12 checks passed
@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Thank you for the rebase and for fixing guest_mlock rather than asking me to. The diagnosis matches what we
assumed when we wrote the reservation: an unmapped range inside the arena stays a host reservation, so a host
munlock on it succeeds while the guest contract says ENOMEM. Checking the guest mapping state first, the
same test msync uses, is the right shape, and exporting it as GuestRangeMapped is better than a second
copy of the logic.

Two notes from the far end of this change, on the title #692 was filed for (PPSA28997):

One process note against myself: the Windows sys/mman.h failure you caught is the second portability mistake
I have shipped in this area. I now guard every Linux-only include in the same #ifndef _WIN32 block as the
code that needs it, which is also what the fork change in #1791's shape should do.

For the maintainers coordinating the queue: with #861 merged, #1810 and #2660 are no longer blocked by the
empty arena span, and the branch referenced in #1791 can now store anything on Linux.

@EdouardSence

Copy link
Copy Markdown
Contributor

Ratchet & Clank: Rift Apart (PPSA01474) on Linux faults about 11 s in since this merged (3 of 3 runs on b5f5362d3, gone in 2 of 2 with only this PR reverted). The trace and the placement sequence are in #2704: an address-less 64 GiB reservation is now placed at the bottom of the arena and covers the addresses the title hints for its next direct maps.

Tested and written by Claude (AI assistant) on a contributor's machine.

jeffrey12cali added a commit to jeffrey12cali/SoS-PS5 that referenced this pull request Oct 10, 2026
…re-reading /proc/self/maps

describePages looks pages up in a per-span bitmap before it queries the kernel, and on
Linux two things stopped that bitmap from ever being filled.

First, PageStates::initialize asks GuestArenaRange for the guest window, but the Arena
constructor in libc is entirely inside #ifdef _WIN32, so the range comes back empty,
PageSpan::allocate returns false, and spanOf always answers null. The fix falls back to
the window libkernel actually reserves on Linux, 0x200000000 with a size of 0x400000000,
so the bitmap exists.

Second, the Linux branch queried mappings and stored nothing, while the Windows branch
stores its VirtualQuery results under an allocation-generation check. The fix stores the
same way, and invalidates the two munmap trims in DirectMemory that run outside any
GuestAllocations::Mutation, so no readable bit can outlive the mapping it came from.

Measured on this title: the map-parse path went from 1,172,045 parses per run to zero,
42,772 verifications now cost 0.1 s, forgets 715 covering 2377 MiB confirms invalidation
is live, and the CPU-bound frame rate went from 7.4 to 60.3 FPS with no fatal lines over
a 13 minute soak. Enabling the span also activates the invalidator, which was never
registered before because it is only installed when a span allocates.

The store-back half of this is already proposed upstream as boykopovar/AnyPS5#1810 for
boykopovar/AnyPS5#1791. The span fallback here is only needed while this tree predates
boykopovar/AnyPS5#861, which makes the span non-empty upstream; drop it once that lands.
@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Author of the arena here, and the bisect is right: this is my change, not something the title was already doing.

What I got wrong. #861 places an address-less reservation at the lowest free address of the arena. For
PPSA01474 that put a 64 GiB PROT_NONE reservation directly over the addresses the title then hints for its
next two direct maps, so the non-fixed maps were relocated above it while the title went on using the hinted
address. Before the arena, the reservation went to the host's top-down area and the hints were honoured by
accident. Placing at the bottom was chosen for contiguity and was never tested against a title that hints after
reserving.

Status, for anyone reading this later. The fix is already on main: PlaceHintInReservation in
core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (from #2667), which came through #2687; #2704 was
closed as a duplicate of it. Resolving it at map time rather than by moving the reservation is the right call,
and it is better than anything I would have proposed, because it leaves the placement policy alone.

The constraint from the other side, which the fix has to keep. PPSA28997 is a title that needs what #861
provides: with address-less mappings landing top-down it asserts at start-up, which is #692, and the low-window
arena is what lets it reach its main menu and hold 60 FPS. So the two titles pull in opposite directions - one
needs address-less reservations kept inside the low window, the other needs its hints to survive a reservation
that covers them. Honouring the hint at map time satisfies both, and I would not want a later simplification to
revert to "place address-less reservations high" just because that made the second case work.

What I can test, and what I cannot. I cannot run PPSA28997 on bare main today: our engine tree is a fork
pinned behind main, and main lacks the Umtx, Pthread and Exception shapes this title needs, plus the
bundled-libc.prx heap handshake still aborts at start-up there (see #693). So the honest test I can offer is
on our fork once it merges main: 15 minutes of scripted play with the mapping count and the start-up
milestones sampled, to confirm PlaceHintInReservation does not take the low window away from the titles that
need it. Say the word if that is worth having and I will run it and post the numbers here.

Thanks for the bisect and for writing it up with the trace - the hint= lines are what made this diagnosable
at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Linux: direct-memory mappings with addr == NULL get a top-down address, and titles that require the low window assert at start-up

9 participants