fix(libkernel): unmap released direct memory views before freeing the physical range #7448
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/7448"
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 Tamalero on 2026-10-18T07:00:28Z.
What
sceKernelReleaseDirectMemoryandsceKernelCheckedReleaseDirectMemoryreturned the range to the physical allocator (DirectMemoryFree/DirectMemoryCheckedFree) before they unmapped its views (UnmapDirectMemoryViews). The unmap waits inGuestAllocationsRequireUnpinneduntil GPU leases on the view are gone, and that wait can be long (#7408). Meanwhile another allocation can take the freed pages and map them, while the old view is still mapped and host-imported. GPU writes through the old view then land in the new owner's memory.LEGO Batman: Legacy of the Dark Knight (PPSA16833) hits this on almost every boot when its files load fast. It releases a slice of its render-target block, then allocates the same physical pages for its command-buffer heap during the wait. A host import of the old render-target block is created again before the unmap ends. The title then stops on its own command buffers, now holding image rows where packets should be:
AGC driver: unsupported PM4 packet type,truncated PM4 packet, orsceAgcSetShRegIndirectPatchSetAddress: unexpected packet type, size or flags. #7408 has the memory and import trace of one such boot.Fix: both calls unmap the views first and free the range afterwards. The checked call still returns
SCE_KERNEL_ERROR_ENOENTfor a range that is not fully allocated, before it touches any view. For that check, the pool gets a non-destructiveDirectMemoryAllocated, which tests the same pagesCheckedFreewould.This conflicts textually with #7105, which edits the same lines to return
EACCES. Whichever lands second keeps the order: unmap, then free.Tested
CheckReleaseKeepsPhysicalUntilViewsUnmappedinguest_memory_tests, for both release calls. A lease holds the mapping while another thread releases the range. While that release still waits, the physical range must not be allocatable again. After the lease is dropped, the release finishes and the same range can be allocated.guest_memory,guest_memory_lifetimeandguest_memory_pool_statspass (guest_memory0.6 s).Export.cpprestored tomain, the new test fails. It stops at the check that the range cannot be allocated again during the wait (GuestMemory.cpp:1589): onmainthe pages are handed out while the view is still pinned.python3 tools/check_conventions.py --base origin/main: passes.5d9dcc42dto2626e5ee7. With the change: 2 of 2 runs passed the menu, and one of them went on into gameplay. Blocky rendering corruption remains on parts of the menu scene; I have not established whether it predates this change, and it is not a stop. With the files on an HDD the stop was rarer (0 of 2 runs tonight, none in about 20 earlier runs), which fits a race that depends on how soon the pages are allocated again.Checklist
main; no other open PR implements the same functions (#7105 touches the same lines for a different change)NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Tested and written by Claude (AI assistant) on a contributor's machine.
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-18T07:14:12Z.
Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.
main)core/libs/tests/GuestMemory.cppL2894core/libs/tests/GuestMemory.cppL1572, L2893-2894Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
core/libs/tests/GuestMemory.cppcore/libs/prx/libkernel/DirectMemory/Export.cppcore/libs/tests/GuestMemory.cppcore/libs/tests/GuestMemory.cppcore/libs/tests/GuestMemory.cppcore/libs/tests/GuestMemory.cppcore/libs/prx/libkernel/DirectMemory/DirectMemory.hppcore/libs/prx/libkernel/DirectMemory/Export.cppcore/libs/prx/libkernel/DirectMemory/MemoryPool.cppcore/libs/tests/GuestMemory.cppcore/libs/prx/libkernel/DirectMemory/DirectMemory.hppcore/libs/prx/libkernel/DirectMemory/Export.cppcore/libs/prx/libkernel/DirectMemory/Export.cppcore/libs/tests/GuestMemory.cppcore/libs/tests/GuestMemory.cppImported from boykopovar/AnyPS5. Originally posted by Bonjourcestmatt on 2026-10-18T07:25:59Z.
Independent Windows build of this PR (head
268e96df8b224c2a09385e9c2b975e2bfbfdea18) merged ontoorigin/main1c523bdb48f724c06d0f526ddfbcd4c3a22bbea0.Setup: Windows 11, WinLibs GCC 15.2.0 UCRT, Ninja, Release,
BUILD_TESTING=ON.guest_memory_testsguest_memoryThe error is in the new test,
core/libs/tests/GuestMemory.cpp:2867and:2868:CheckReleaseKeepsPhysicalUntilViewsUnmappedtakes a plainint (*)(std::int64_t, std::size_t), butsceKernelReleaseDirectMemoryandsceKernelCheckedReleaseDirectMemoryare declaredsysv_abi, so the pointer types differ on Windows. Declaring the parameter asint (__attribute__((sysv_abi)) *release)(std::int64_t, std::size_t)(or a small alias for it) should fix it; I did not try that, so I do not know whether the rest of the new test passes on Windows.Not checked: Linux/macOS, the non-GPU suite, and the behaviour of the fix itself.
Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by Tamalero on 2026-10-18T07:57:03Z.
@Bonjourcestmatt thanks for the Windows build. You're right: the test took a plain function pointer, and the release calls are declared
sysv_abi. Pushed a follow-up commit that declares the parameter asdecltype(&sceKernelReleaseDirectMemory), so it carries the calling convention on every platform.guest_memory_testsstill passes on Linux. I can't build on Windows here, so a rerun on your side would confirm the rest of the test.Tested and written by Claude (AI assistant) on a contributor's machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T15:04:53Z.
Review: APPROVED
Reviewed the release ordering and checked-release prevalidation. Keeping the physical pages allocated while UnmapDirectMemoryViews waits prevents another allocation from reusing the range before the old views are gone; DirectMemoryAllocated also preserves the ENOENT no-side-effect path. The regression test exercises both release APIs while a guest allocation lease is held. I reviewed the patch and CI results but did not rerun the platform/game tests locally.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T19:04:03Z.
I checked the updated calling-convention pattern with the MinGW compiler available in this Linux environment (GCC 12): a minimal Windows-targeted translation unit declaring
sceKernelReleaseDirectMemorywithAPS5_VABIand passing it throughdecltype(&sceKernelReleaseDirectMemory)compiles successfully.This only validates the function-pointer type pattern. It is not a build of
guest_memory_testsor a runtime test, and this GCC version is older than the repository's supported MinGW GCC 15.2. A full Windows build/test is still needed.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T20:01:37Z.
Review: COMMENTED
One concurrency case to clarify around the new
DirectMemoryAllocatedprecheck: it releases the pool mutex beforeUnmapDirectMemoryViewswaits for leases, so two concurrentsceKernelCheckedReleaseDirectMemory(start, len)calls can both observe the range as allocated and snapshot the same views. After the first unmaps and frees the range, the second still proceeds with its stale view snapshot beforeDirectMemoryCheckedFreereturnsENOENT. Could another thread map a new allocation at one of those virtual addresses in that interval, letting the second call unmap the new view? If concurrent release is excluded by an API/caller invariant, please point to it; otherwise a concurrent checked-release/remap regression would clarify that the second call returnsENOENTwithout affecting a new mapping.Imported from boykopovar/AnyPS5. Originally posted by Tamalero on 2026-10-19T00:16:32Z.
Title check on a longer session: LEGO Batman: Legacy of the Dark Knight (PPSA16833), with the game's files on an NVMe SSD, where the corruption showed up on almost every boot.
mainfb9a1eb8f+ this PR (both commits) + #6182 + the localAPS5_PIN_DIAGcounters from #7408.fb9a1eb8fpredates #6270, which stops this title at boot (#7678).unsupported PM4 packet type,truncated PM4 packet,sceAgcSetShRegIndirectPatchSetAddress: unexpected packet type), no Oodle shader-group failure and no RenderThread timeout. Exit code 0.sceKernelReleaseDirectMemoryunmaps finished. Their lease waits had a median of 2 ms, a 99th percentile of 123 ms and a maximum of 1.5 s.For comparison: without this change, the same scene (the animated main menu) stopped on a corrupted command buffer in 8 of 9 SSD boots, on builds from
5d9dcc42dto2626e5ee7. I didn't rerun a no-PR control onfb9a1eb8fitself, so this session shows the title running cleanly with the change, not a fresh A/B on this base.Tested and written by Claude (AI assistant) on a contributor's machine.
Examples of INGAME for LEGO BATMAN:
https://youtu.be/C04JePxxcOs
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-19T00:26:57Z.
Review: COMMENTED
Linux run of
9f5efd4f9, with a probe for @MarcZX10's question about two concurrent checked releases. On this head the second release terminates the process. Onmainit returnsENOENT.Machine: Linux x86_64, i7-8700, Ubuntu 26.04, GCC 15.2, Release,
BUILD_TESTING=ON, full build.Head
9f5efd4f9merged ontomain84c1a4d9a(clean merge).Builds. The memory tests (
ctest -R guest_memory, 11 tests) pass, and the non-GPU suite (ctest -E "^agc|gpu|vulkan|video_out") is 739/739, same asmain.Probe, added to
GuestMemory.cppbehind a command-line switch: allocate 4 pages, map them, then two threads callsceKernelCheckedReleaseDirectMemory(phys, 4 pages)on the same range at the same time. In one variant aGuestAllocationsAcquirelease is held for 50 ms, as in your new test. In the other there is no lease.main9f5efd4f9ENOENTin every iterationterminate:unmap address is not registered, first iteration, 3/3ENOENTin every iterationterminatewith the same messageBoth callers pass
DirectMemoryAllocatedand take the sameDirectMemoryViewssnapshot. The first one unmaps the views. When the second gets the mutation, it callsUnmapRegisteredon views that are already gone, and that throws before it reachesDirectMemoryCheckedFree, which would have returnedENOENT. OnmaintheCheckedFreecomes first and is atomic under the pool mutex, so the loser returns before it touches the views. One way to fix it is to claim the range under one lock before the unmap, so a second checked release sees it as already released. Re-reading the views after the mutation is taken would also work.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by Tamalero on 2026-10-19T05:41:31Z.
@MarcZX10 @jotitadev thanks, the race is real. The precheck dropped the pool lock before the unmap, and the lease wait inside the unmap also drops the registry lock, so re-reading the views under the mutation would still let two releasers both wait and then both unmap. I went with the first suggestion instead: claim the range in the pool.
Pushed
b574f2a51:DirectMemoryClaimRelease). After the unmap it frees them and drops the claim in one step (DirectMemoryFinishRelease). If the unmap throws, it drops the claim without freeing (DirectMemoryAbandonRelease).ENOENTbefore it touches any view. That is what the losing caller got onmain. So for the question in the review: the second call never takes a view snapshot, and it can't unmap a mapping created in the meantime.main(ForgetDirectMemoryrejects pages that are no longer allocated). I left that unchanged since it is outside this PR.CheckReleaseKeepsPhysicalUntilViewsUnmappedstill covers this for both calls.New test
CheckConcurrentCheckedReleasesUnmapViewsOnce, modelled on jotitadev's probe: two threads check-release the same 4-page mapped range while a lease is held for 50 ms. It requires exactly one 0 and oneENOENT, then reallocates the range.Linux (GCC, Release):
9f5efd4f9(release code restored, new test kept)terminate:unmap address is not registered, 3/3guest_memorytests onb574f2a51ctest -E "^agc|gpu|vulkan|video_out")tools/check_conventions.py --base origin/mainmain4ffb0cd12Not run on Windows yet.
Tested and written by Claude (AI assistant) on a contributor's machine.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-19T08:12:37Z.
Review: COMMENTED
Linux rerun of
b574f2a51with the same probe as my earlier report on9f5efd4f9(two threads callsceKernelCheckedReleaseDirectMemoryon the same mapped 4-page range).Machine: Linux x86_64, i7-8700, Ubuntu 26.04, GCC 15.2, Release,
BUILD_TESTING=ON, full build. Headb574f2a51merged ontomain6b8228b2b(clean merge).9f5efd4f9b574f2a51terminate: unmap address is not registeredin the first iteration, 3 of 3 runs0and oneENOENTin 150 of 1500and oneENOENTin 6000 of 6000That matches what
mainreturns. The 11 memory tests pass, including the newCheckConcurrentCheckedReleasesUnmapViewsOnce, and the non-GPU suite is 766/766, same asmain.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T21:29:18Z.
Checked the claim/unmap/free order in
Export.cppandMemoryPool.cpp: the claim is taken under the pool mutex before the views are read, overlapping releases wait (unchecked) or getENOENT(checked), and the claim is dropped on throw. The new tests pin the physical range staying unallocatable until the lease is gone and the two-concurrent-checked-release outcome. Matches the Linux probe by @jotitadev and the review by @MarcZX10; merged.