fix(libkernel): keep direct-memory aliases consistent across retype, release and remap #17794

Merged
chitters2004 merged 11 commits from upstream-pr/17794 into main 2026-11-16 05:43:34 +00:00
chitters2004 commented 2026-11-09 16:23:50 +00:00 (Migrated from github.com)

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, sceKernelMtypeprotect retypes 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.

  • Bug: sceKernelMtypeprotect (and sceKernelBatchMap2 operation 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, so sceKernelVirtualQuery gave different types for the same physical pages depending on which alias was asked and when it was created.
  • Fix: the type belongs to the direct memory, so the pool block is the only record. Mappings no longer carry a type, QueryDirectMapping reads it from the pool and clips the extent to the pool block, and CreateDirectMemoryBacking no longer takes a type. The sceKernelMtypeprotect debt line now says every mapping reports the new type.
  • Consequence for titles: a title that retypes memory and then maps or queries it through a second address read back the allocation-time type instead of the one it set, so anything choosing a cache or coherency policy from the reported type was told the wrong one.
  • Test: new aliasing assertions in CheckMtypeprotect (GuestMemory.cpp) and MemoryPoolTest.

2. Release excludes new mappings and allocations of the claimed range.

  • Bug: sceKernelReleaseDirectMemory and sceKernelCheckedReleaseDirectMemory claim a physical range, snapshot its mappings, unmap them and free the range. sceKernelMapDirectMemory (also MAP_FIXED) and sceKernelAllocateDirectMemory never 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.
  • Fix: the claims live under the direct memory lock (g_releaseClaims). DoMapDirect refuses 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 by DirectMemoryWakeReleaseClaims). The pool skips claimed ranges when searching for free memory (allocation returns EAGAIN), and the release reads the next remaining view after each unmap (UnmapDirectMemoryRange) and fails loudly if a view survives.
  • Why the map holds its range: a map checked the claim, then waited for leases on its destination and aliases with the registry unlocked, and only then replaced the destination. A release that claimed the range in that wait made a MAP_FIXED map 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.
  • Consequence for titles: a title releasing a heap while another thread maps or allocates direct memory (streaming, heap teardown and growth) could end with a live mapping, or an allocation, over physical memory the pool had freed and handed out again: guest memory corruption, not an error. The window is as wide as the wait for leases, which is the GPU-pinned case.
  • Test: 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 a MAP_FIXED map 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 the MemoryPoolTest cases alloc_skips_a_claimed_release and claims_wait_for_map_holds.

3. Same-backing fixed remap inside a mapping joins its aliases (Linux and macOS).

  • Bug: WatchMapping registers 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 fixed sceKernelMapDirectMemory of 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.
  • Fix: the containing mapping is included, its physical span is clipped to the remapped interval before aliases are searched, and a mapping is skipped as its own alias.
  • Consequence for titles: a title that re-maps a sub-range of a direct-memory mapping with 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.
  • Test: the same-backing interior remap case in 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. sceKernelMtypeprotect retypes under the pool lock.

  • Bug: the retype read the physical ranges behind the virtual range under the direct memory lock, released it and then retyped those ranges in the pool. With fix 1 the pool type is what every alias reports, so a release and a new allocation of the same physical range in that window gave the new allocation the type meant for the old one.
  • Fix: the pool lock is taken before the direct memory lock, the order the pool already uses, and held across the lookup and the retype (DirectMemoryPoolLock, DirectMemoryRetypeLocked).
  • Test: CheckMtypeprotectLeavesAReplacementAllocation pauses 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; MemoryPoolTest retype_locked_needs_the_pool_lock.

5. Release unmaps its views in linear time.

  • Bug: the release rebuilt the list of every remaining view of the range after each unmap, so releasing a range with many scattered views was quadratic: 4096 one-page views took 0.69 s against 2.6 ms for 256 (Linux, Release).
  • Fix: after each unmap the release looks up only the first remaining view in the physical span index (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.
  • Test: CheckReleaseOfManyViewsScalesLinearly releases 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. CheckMtypeprotect now 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 72dc8fcf72 on c2235860de), no GPU involved:

  • Linux (Ubuntu 24.04, GCC 13, Release, BUILD_TESTING=ON): guest_memory, guest_mmap_fixed_anonymous and MemoryPoolTest pass, also with six guest_memory runs in parallel beside four busy loops on four cores (the scaling check of fix 5).
  • Linux ThreadSanitizer (ANYPS5_ENABLE_TSAN=ON, RelWithDebInfo, tools/tsan-suppressions.txt): the same three tests pass with no report; guest_memory takes 10.9 s (6.9 s on c2235860de).
  • Each new test fails with its fix reverted on this head: the old map check order fails CheckFixedMapRacingAReleaseKeepsItsDestination (the map throws); a pool claim that ignores map holds fails claims_wait_for_map_holds; the old lookup-then-retype order fails CheckMtypeprotectLeavesAReplacementAllocation (the new allocation gets type 4); the old release loop fails CheckReleaseOfManyViewsScalesLinearly (2048 views 0.13 s against 0.88 ms for 128); removing the start or the end clip of QueryDirectMapping fails the new CheckMtypeprotect extent checks and passed the type-only ones.
  • Windows: the libraries and guest_memory_tests, MemoryPoolTest build and link with WinLibs GCC 15.2.0 (the CI toolchain) under Wine; MemoryPoolTest passes there. guest_memory cannot run under Wine, which refuses the 16 KiB-aligned shared views of direct memory (map shared guest page: Incorrect alignment, on c2235860de too), 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/main 364ceeba2f.

  • Windows 11, MinGW, AMD Ryzen 7 5800X: green with all three fixes: 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).
  • WSL Linux (Ubuntu, Release, 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).
  • Red on origin/main 364ceeba2f with only the test change, per fix, Windows and Linux:
    • mtype: Guest memory check failed at GuestMemory.cpp:1117 (an alias reports the allocation-time type).
    • release: the test needs the new claim query, so this red run used a one-off variant of the test with the claim polling replaced by a 300 ms wait; it is not the committed test. On main the alias map is not refused and the process aborts: guest allocation ... is still pinned by GPU work or an import (waited 1000 ms for the lease).
    • remap (Linux only): Guest memory check failed at GuestMemory.cpp:3344 (the store through the alias is missing on the remapped page).
  • On the combined head, reverting only one fix's production changes makes that fix's test fail again:
    • mtype reverted: guest_memory fails at GuestMemory.cpp:1117 on Windows and on Linux (rebuilt on the combined head).
    • remap reverted: guest_memory fails at GuestMemory.cpp:3397 on Linux (the line moved because the three tests share the file).
    • release reverted: not rebuilt. The committed test cannot compile without the claim query, so the earlier red run (the one-off 300 ms variant above) is reused; the release code is unchanged since.
  • Remap is Linux/macOS code only (WatchMapping is not compiled on Windows): its test passes on Windows with and without the fix, so there is no Windows red for it.
  • Not tested: macOS, AMD GPUs (no GPU code touched). No contention measurement for the release claim: the check is a lookup under a lock the mapping path already takes.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none (touches the same functions as #7105, which returns EACCES for unknown ranges on release, and #7149, which changes UnmapRegistered and DoMapDirect; both conflict with main already and are different changes)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5227228406 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17794). Originally posted by [chitters2004](https://github.com/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, `sceKernelMtypeprotect` retypes 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.** - Bug: `sceKernelMtypeprotect` (and `sceKernelBatchMap2` operation 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, so `sceKernelVirtualQuery` gave different types for the same physical pages depending on which alias was asked and when it was created. - Fix: the type belongs to the direct memory, so the pool block is the only record. Mappings no longer carry a type, `QueryDirectMapping` reads it from the pool and clips the extent to the pool block, and `CreateDirectMemoryBacking` no longer takes a type. The `sceKernelMtypeprotect` debt line now says every mapping reports the new type. - Consequence for titles: a title that retypes memory and then maps or queries it through a second address read back the allocation-time type instead of the one it set, so anything choosing a cache or coherency policy from the reported type was told the wrong one. - Test: new aliasing assertions in `CheckMtypeprotect` (`GuestMemory.cpp`) and `MemoryPoolTest`. **2. Release excludes new mappings and allocations of the claimed range.** - Bug: `sceKernelReleaseDirectMemory` and `sceKernelCheckedReleaseDirectMemory` claim a physical range, snapshot its mappings, unmap them and free the range. `sceKernelMapDirectMemory` (also `MAP_FIXED`) and `sceKernelAllocateDirectMemory` never 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. - Fix: the claims live under the direct memory lock (`g_releaseClaims`). `DoMapDirect` refuses 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 by `DirectMemoryWakeReleaseClaims`). The pool skips claimed ranges when searching for free memory (allocation returns `EAGAIN`), and the release reads the next remaining view after each unmap (`UnmapDirectMemoryRange`) and fails loudly if a view survives. - Why the map holds its range: a map checked the claim, then waited for leases on its destination and aliases with the registry unlocked, and only then replaced the destination. A release that claimed the range in that wait made a `MAP_FIXED` map 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. - Consequence for titles: a title releasing a heap while another thread maps or allocates direct memory (streaming, heap teardown and growth) could end with a live mapping, or an allocation, over physical memory the pool had freed and handed out again: guest memory corruption, not an error. The window is as wide as the wait for leases, which is the GPU-pinned case. - Test: `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 a `MAP_FIXED` map 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 the `MemoryPoolTest` cases `alloc_skips_a_claimed_release` and `claims_wait_for_map_holds`. **3. Same-backing fixed remap inside a mapping joins its aliases (Linux and macOS).** - Bug: `WatchMapping` registers 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 fixed `sceKernelMapDirectMemory` of 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. - Fix: the containing mapping is included, its physical span is clipped to the remapped interval before aliases are searched, and a mapping is skipped as its own alias. - Consequence for titles: a title that re-maps a sub-range of a direct-memory mapping with `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. - Test: the same-backing interior remap case in `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. `sceKernelMtypeprotect` retypes under the pool lock.** - Bug: the retype read the physical ranges behind the virtual range under the direct memory lock, released it and then retyped those ranges in the pool. With fix 1 the pool type is what every alias reports, so a release and a new allocation of the same physical range in that window gave the new allocation the type meant for the old one. - Fix: the pool lock is taken before the direct memory lock, the order the pool already uses, and held across the lookup and the retype (`DirectMemoryPoolLock`, `DirectMemoryRetypeLocked`). - Test: `CheckMtypeprotectLeavesAReplacementAllocation` pauses 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; `MemoryPoolTest` `retype_locked_needs_the_pool_lock`. **5. Release unmaps its views in linear time.** - Bug: the release rebuilt the list of every remaining view of the range after each unmap, so releasing a range with many scattered views was quadratic: 4096 one-page views took 0.69 s against 2.6 ms for 256 (Linux, Release). - Fix: after each unmap the release looks up only the first remaining view in the physical span index (`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. - Test: `CheckReleaseOfManyViewsScalesLinearly` releases 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.** `CheckMtypeprotect` now 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 `72dc8fcf72` on `c2235860de`), no GPU involved: - Linux (Ubuntu 24.04, GCC 13, Release, `BUILD_TESTING=ON`): `guest_memory`, `guest_mmap_fixed_anonymous` and `MemoryPoolTest` pass, also with six `guest_memory` runs in parallel beside four busy loops on four cores (the scaling check of fix 5). - Linux ThreadSanitizer (`ANYPS5_ENABLE_TSAN=ON`, RelWithDebInfo, `tools/tsan-suppressions.txt`): the same three tests pass with no report; `guest_memory` takes 10.9 s (6.9 s on `c2235860de`). - Each new test fails with its fix reverted on this head: the old map check order fails `CheckFixedMapRacingAReleaseKeepsItsDestination` (the map throws); a pool claim that ignores map holds fails `claims_wait_for_map_holds`; the old lookup-then-retype order fails `CheckMtypeprotectLeavesAReplacementAllocation` (the new allocation gets type 4); the old release loop fails `CheckReleaseOfManyViewsScalesLinearly` (2048 views 0.13 s against 0.88 ms for 128); removing the start or the end clip of `QueryDirectMapping` fails the new `CheckMtypeprotect` extent checks and passed the type-only ones. - Windows: the libraries and `guest_memory_tests`, `MemoryPoolTest` build and link with WinLibs GCC 15.2.0 (the CI toolchain) under Wine; `MemoryPoolTest` passes there. `guest_memory` cannot run under Wine, which refuses the 16 KiB-aligned shared views of direct memory (`map shared guest page: Incorrect alignment`, on `c2235860de` too), 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/main` 364ceeba2f. - Windows 11, MinGW, AMD Ryzen 7 5800X: green with all three fixes: `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). - WSL Linux (Ubuntu, Release, `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). - Red on `origin/main` 364ceeba2f with only the test change, per fix, Windows and Linux: - mtype: `Guest memory check failed at GuestMemory.cpp:1117` (an alias reports the allocation-time type). - release: the test needs the new claim query, so this red run used a one-off variant of the test with the claim polling replaced by a 300 ms wait; it is not the committed test. On main the alias map is not refused and the process aborts: `guest allocation ... is still pinned by GPU work or an import (waited 1000 ms for the lease)`. - remap (Linux only): `Guest memory check failed at GuestMemory.cpp:3344` (the store through the alias is missing on the remapped page). - On the combined head, reverting only one fix's production changes makes that fix's test fail again: - mtype reverted: `guest_memory` fails at `GuestMemory.cpp:1117` on Windows and on Linux (rebuilt on the combined head). - remap reverted: `guest_memory` fails at `GuestMemory.cpp:3397` on Linux (the line moved because the three tests share the file). - release reverted: not rebuilt. The committed test cannot compile without the claim query, so the earlier red run (the one-off 300 ms variant above) is reused; the release code is unchanged since. - Remap is Linux/macOS code only (`WatchMapping` is not compiled on Windows): its test passes on Windows with and without the fix, so there is no Windows red for it. - Not tested: macOS, AMD GPUs (no GPU code touched). No contention measurement for the release claim: the check is a lookup under a lock the mapping path already takes. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none (touches the same functions as #7105, which returns `EACCES` for unknown ranges on release, and #7149, which changes `UnmapRegistered` and `DoMapDirect`; both conflict with main already and are different changes) - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!17794
No description provided.