fix(libkernel): keep direct-memory aliases consistent across retype, release and remap #17794
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/17794"
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 chitters2004 on 2026-11-09T16:23:50Z.
What
Three correctness fixes for direct-memory aliasing in
libkernel/DirectMemory, one commit each, all in the same mapping table and physical pool, and three follow-ups from review of the second fix: a map and a release of the same physical range no longer interleave,sceKernelMtypeprotectretypes under the pool lock, and a release no longer rescans every view after each unmap. They share the test files (GuestMemory.cpp,MemoryPoolTest.cpp), so one PR avoids three conflicting ones.1. One memory type for every mapping of a direct-memory range.
sceKernelMtypeprotect(andsceKernelBatchMap2operation 4) retyped only the direct mappings inside the requested range and the pool block. Other mappings of the same direct memory, and every later map of it, kept the allocation-time type, sosceKernelVirtualQuerygave different types for the same physical pages depending on which alias was asked and when it was created.QueryDirectMappingreads it from the pool and clips the extent to the pool block, andCreateDirectMemoryBackingno longer takes a type. ThesceKernelMtypeprotectdebt line now says every mapping reports the new type.CheckMtypeprotect(GuestMemory.cpp) andMemoryPoolTest.2. Release excludes new mappings and allocations of the claimed range.
sceKernelReleaseDirectMemoryandsceKernelCheckedReleaseDirectMemoryclaim a physical range, snapshot its mappings, unmap them and free the range.sceKernelMapDirectMemory(alsoMAP_FIXED) andsceKernelAllocateDirectMemorynever consulted the claim, so while a release waited (for example for a lease on a mapped page) a new alias created after the snapshot outlived the release, and an allocation into a hole of the range was handed out and then freed by the release.g_releaseClaims).DoMapDirectrefuses a claimed range (SCE_KERNEL_ERROR_ENOMEM, as for an unallocated page) and registers the physical range it maps until it returns (DirectMapHold); a release claim waits until no map of the range is in flight (DirectMemoryTryAddReleaseClaim, woken byDirectMemoryWakeReleaseClaims). The pool skips claimed ranges when searching for free memory (allocation returnsEAGAIN), and the release reads the next remaining view after each unmap (UnmapDirectMemoryRange) and fails loudly if a view survives.MAP_FIXEDmap remove the mapping it was replacing and then throw, and a fixed remap inside a mapping throw. Now a map that has passed the check finishes, and the release unmaps it afterwards.CheckReleaseExcludesMappingsAndAllocations(a release waits on a held lease while a second thread tries an alias, a fixed alias and an allocation into a hole),CheckFixedMapRacingAReleaseKeepsItsDestination(a release of the source starts while aMAP_FIXEDmap waits for a lease on its destination, through a pin waiter, for a destination that is partly and fully mapped: the map succeeds and the release then unmaps it, nothing throws), and theMemoryPoolTestcasesalloc_skips_a_claimed_releaseandclaims_wait_for_map_holds.3. Same-backing fixed remap inside a mapping joins its aliases (Linux and macOS).
WatchMappingregisters a mapping with the guest write watch and joins it to every other mapping of the same backing, so a store through any alias is reported at all of them (the aliasing from #12452). It searched from the first mapping at or after the new address, so a fixedsceKernelMapDirectMemoryof the same physical pages over the interior of an existing mapping skipped the mapping that contains the range. The remapped pages were registered alone and never joined to the alias.MAP_FIXED(to change protection or type of part of a heap, or to place a view inside a larger one) while another view of the same pages exists loses the GPU's and host's view of CPU stores through the other view on those pages: stale texture, buffer and snapshot contents on Linux, with no error. Windows does not compile this code and is unaffected.CheckDirectMemoryWriteWatch: remap the middle page of a three-page mapping over the same physical page while a separate alias maps it, then store through the alias and require the store to be collected on both views.4.
sceKernelMtypeprotectretypes under the pool lock.DirectMemoryPoolLock,DirectMemoryRetypeLocked).CheckMtypeprotectLeavesAReplacementAllocationpauses the retype after its lookup (DirectMemoryPauseBeforeRetypeForTest), releases and reallocates the physical page with another type from a second thread, and checks that the new allocation keeps its type;MemoryPoolTestretype_locked_needs_the_pool_lock.5. Release unmaps its views in linear time.
FirstPhysicalView). It still reads the view again after every unmap, because a lease wait inside the unmap lets other threads change the mappings. The same release now takes 13 ms against 0.93 ms.CheckReleaseOfManyViewsScalesLinearlyreleases 256 and 4096 scattered one-page views, best of five each, and requires the larger release to take less than 64 times as long (14 times now, 254 before).6. Query extents of retyped memory.
CheckMtypeprotectnow checks the start, end and physical offset of queries before, inside and after the retyped page of an alias, of a mapping whose physical start lies inside the allocation, and of a later map of the same memory. Removing the clip of the start or the end to the pool block passed the earlier type-only checks and fails these.Found by a Sol audit of the direct-memory code (general findings G1 and G4, plus the remap case).
Tested
Fixes 4 to 6 and the map hold in fix 2 (head
72dc8fcf72onc2235860de), no GPU involved:BUILD_TESTING=ON):guest_memory,guest_mmap_fixed_anonymousandMemoryPoolTestpass, also with sixguest_memoryruns in parallel beside four busy loops on four cores (the scaling check of fix 5).ANYPS5_ENABLE_TSAN=ON, RelWithDebInfo,tools/tsan-suppressions.txt): the same three tests pass with no report;guest_memorytakes 10.9 s (6.9 s onc2235860de).CheckFixedMapRacingAReleaseKeepsItsDestination(the map throws); a pool claim that ignores map holds failsclaims_wait_for_map_holds; the old lookup-then-retype order failsCheckMtypeprotectLeavesAReplacementAllocation(the new allocation gets type 4); the old release loop failsCheckReleaseOfManyViewsScalesLinearly(2048 views 0.13 s against 0.88 ms for 128); removing the start or the end clip ofQueryDirectMappingfails the newCheckMtypeprotectextent checks and passed the type-only ones.guest_memory_tests,MemoryPoolTestbuild and link with WinLibs GCC 15.2.0 (the CI toolchain) under Wine;MemoryPoolTestpasses there.guest_memorycannot run under Wine, which refuses the 16 KiB-aligned shared views of direct memory (map shared guest page: Incorrect alignment, onc2235860detoo), so the Windows run of the new checks is the fork CI windows job.Fixes 1 to 3, all on the combined head, no GPU involved. Base
origin/main364ceeba2f.guest_memory,MemoryPoolTest,guest_memory_pool_stats,guest_memory_resource,guest_direct_memory_for_app,windows_write_watch,windows_write_watch_verify_direct,windows_mappings_release*(11 tests).BUILD_TESTING=ON): green with all three fixes:guest_memory,MemoryPoolTest,guest_memory_pool_stats,guest_memory_resource,guest_direct_memory_for_app(5 tests).origin/main364ceeba2fwith only the test change, per fix, Windows and Linux:Guest memory check failed at GuestMemory.cpp:1117(an alias reports the allocation-time type).guest allocation ... is still pinned by GPU work or an import (waited 1000 ms for the lease).Guest memory check failed at GuestMemory.cpp:3344(the store through the alias is missing on the remapped page).guest_memoryfails atGuestMemory.cpp:1117on Windows and on Linux (rebuilt on the combined head).guest_memoryfails atGuestMemory.cpp:3397on Linux (the line moved because the three tests share the file).WatchMappingis not compiled on Windows): its test passes on Windows with and without the fix, so there is no Windows red for it.Checklist
main; no other open PR implements the same functionsNotImplemented_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)EACCESfor unknown ranges on release, and #7149, which changesUnmapRegisteredandDoMapDirect; both conflict with main already and are different changes)🤖 Generated with Claude Code