fix(libkernel): walk direct-memory physical ranges by block, not page #10528

Merged
akkadbakkad89 merged 3 commits from upstream-pr/10528 into main 2026-10-27 04:35:39 +00:00
akkadbakkad89 commented 2026-10-24 08:18:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by akkadbakkad89 on 2026-10-24T08:18:45Z.


What

ValidatePhysicalRange, AddMapping, and the backing-overlap check in CreateDirectMemoryBacking all walked g_physPages — one std::map node per 16 KiB page — on every call. A guest that remaps a large arena in a sliding window pays O(pages) per call and O(n²) overall.

Add g_physBlocks, one entry per CreateDirectMemoryBacking allocation, split at ForgetDirectMemory boundaries for partial releases. Validation, mapping, and the overlap check now run at block granularity; g_physPages stays populated unconditionally (CreateDirectMemoryBacking fills it, ForgetDirectMemory erases it) since SharedBacking/WriteSharedBacking and release-path validation still need per-page lookup — but the hot paths above no longer consult it.

RemapFixedIntoRegistered also short-circuits when the target range is already covered by a mapping with an identical guest-to-physical relationship and native protection: the per-block backing map is reissued so the requested host protection is reapplied even when sceKernelMprotect/sceKernelMtypeprotect left the recorded protection stale, but the g_directMappings record churn is skipped, so a sliding-window remap that re-requests the same tail avoids tearing down and rebuilding the bookkeeping.

Tested

Windows 11, MinGW build; guest_memory_pool_stats, MemoryPoolTest, guest_memory, windows_address_space, and agc_driver_depth_bits_guest_memory pass (last under VK_LAYER_KHRONOS_validation, no VUID- delta). guest_memory_tests additionally covers the same-range fast path after sceKernelMprotect changed the real host pages (CheckFixedRemapReprotectsAfterMprotect, verified red against the pre-fix code and green with it, checking both sceKernelVirtualQuery metadata and VirtualQuery/MEMORY_BASIC_INFORMATION).

Grand Theft Auto: Vice City – The Definitive Edition (PPSA03530) emits ~216k fixed remaps sliding 64 KiB across a 13.5 GiB arena; previously the process wedged early in the storm. With this change the storm completes and the title reaches engine initialization (a separate guest-internal allocation issue remains, tracked in discussion https://github.com/boykopovar/AnyPS5/discussions/10520 — this PR does not address it).

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
  • Fixes: #10521
  • Unblocks: PPSA03530 #10520
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4993801507 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10528). Originally posted by [akkadbakkad89](https://github.com/akkadbakkad89) on 2026-10-24T08:18:45Z. --- ### What `ValidatePhysicalRange`, `AddMapping`, and the backing-overlap check in `CreateDirectMemoryBacking` all walked `g_physPages` — one `std::map` node per 16 KiB page — on every call. A guest that remaps a large arena in a sliding window pays O(pages) per call and O(n²) overall. Add `g_physBlocks`, one entry per `CreateDirectMemoryBacking` allocation, split at `ForgetDirectMemory` boundaries for partial releases. Validation, mapping, and the overlap check now run at block granularity; `g_physPages` stays populated unconditionally (`CreateDirectMemoryBacking` fills it, `ForgetDirectMemory` erases it) since `SharedBacking`/`WriteSharedBacking` and release-path validation still need per-page lookup — but the hot paths above no longer consult it. `RemapFixedIntoRegistered` also short-circuits when the target range is already covered by a mapping with an identical guest-to-physical relationship and native protection: the per-block backing map is reissued so the requested host protection is reapplied even when `sceKernelMprotect`/`sceKernelMtypeprotect` left the recorded protection stale, but the `g_directMappings` record churn is skipped, so a sliding-window remap that re-requests the same tail avoids tearing down and rebuilding the bookkeeping. ### Tested Windows 11, MinGW build; `guest_memory_pool_stats`, `MemoryPoolTest`, `guest_memory`, `windows_address_space`, and `agc_driver_depth_bits_guest_memory` pass (last under `VK_LAYER_KHRONOS_validation`, no `VUID-` delta). `guest_memory_tests` additionally covers the same-range fast path after `sceKernelMprotect` changed the real host pages (`CheckFixedRemapReprotectsAfterMprotect`, verified red against the pre-fix code and green with it, checking both `sceKernelVirtualQuery` metadata and `VirtualQuery`/`MEMORY_BASIC_INFORMATION`). Grand Theft Auto: Vice City – The Definitive Edition (PPSA03530) emits ~216k fixed remaps sliding 64 KiB across a 13.5 GiB arena; previously the process wedged early in the storm. With this change the storm completes and the title reaches engine initialization (a separate guest-internal allocation issue remains, tracked in discussion https://github.com/boykopovar/AnyPS5/discussions/10520 — this PR does not address it). ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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 - [x] Fixes: #10521 - [x] Unblocks: PPSA03530 #10520 - [x] GPUs tested: n/a - [x] AI-assisted: yes
MarcZX10 commented 2026-10-24 11:10:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T11:10:55Z.

Review: CHANGES_REQUESTED


The new identical-physical-range shortcut skips the whole mutation.Protect apply callback. That callback is where AddMapping(..., nativeProtection) remaps the backing with the requested host protection. GuestAllocationsProtect_nid_postfix only changes allocation metadata and invokes the callback; it does not call mprotect/VirtualProtect itself. Therefore, when a fixed remap reuses the same virtual-to-physical relationship but changes prot (for example RW to read-only or no-access), the shortcut leaves the old host page protection in place while recording the new guest protection. Please preserve the shortcut only when both the mapping and effective native protection already match, or explicitly apply the requested host protection on this path, and add a regression that remaps the same physical range with changed protection and checks both guest metadata and actual access behavior.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638034906 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10528#pullrequestreview-5638034906). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T11:10:55Z. **Review:** CHANGES_REQUESTED --- The new identical-physical-range shortcut skips the whole `mutation.Protect` apply callback. That callback is where `AddMapping(..., nativeProtection)` remaps the backing with the requested host protection. `GuestAllocationsProtect_nid_postfix` only changes allocation metadata and invokes the callback; it does not call `mprotect`/`VirtualProtect` itself. Therefore, when a fixed remap reuses the same virtual-to-physical relationship but changes `prot` (for example RW to read-only or no-access), the shortcut leaves the old host page protection in place while recording the new guest protection. Please preserve the shortcut only when both the mapping and effective native protection already match, or explicitly apply the requested host protection on this path, and add a regression that remaps the same physical range with changed protection and checks both guest metadata and actual access behavior.
MarcZX10 commented 2026-10-24 11:49:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T11:49:09Z.

Review: CHANGES_REQUESTED


The optimization is useful, but the new same-range fast path skips the protection apply callback. That callback calls AddMapping with nativeProtection, which remaps the backing with the requested host protection; GuestAllocationsProtect_nid_postfix only updates allocation metadata and invokes the callback. If a fixed remap preserves the same guest-to-physical mapping while changing prot (for example RW to read-only or no-access), this return leaves the old host protection active while recording the new guest protection. Please limit the shortcut to cases where the effective native protection also matches, or apply the host protection on this path, and add a regression that checks both metadata and actual access behavior.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638133027 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10528#pullrequestreview-5638133027). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T11:49:09Z. **Review:** CHANGES_REQUESTED --- The optimization is useful, but the new same-range fast path skips the protection apply callback. That callback calls AddMapping with nativeProtection, which remaps the backing with the requested host protection; GuestAllocationsProtect_nid_postfix only updates allocation metadata and invokes the callback. If a fixed remap preserves the same guest-to-physical mapping while changing prot (for example RW to read-only or no-access), this return leaves the old host protection active while recording the new guest protection. Please limit the shortcut to cases where the effective native protection also matches, or apply the host protection on this path, and add a regression that checks both metadata and actual access behavior.
MarcZX10 commented 2026-10-24 13:56:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T13:56:36Z.

Review: CHANGES_REQUESTED


Follow-up review of exact head 52c4d77c0a3111a8145c50a1de86f850d3c9337c: the protection regression addresses my previous finding. The exact-head diff passes git diff --check; I could not run the native guest_memory_tests here because this isolated worktree has uninitialized submodules and no configured build.

Before merging, please resolve the newly visible overlap with open PRs:

  • #7105's TryForgetDirectMemory and ForgetDirectMemory still validate each page with g_physPages.contains(...). This PR now populates g_physPages only on Linux. If #10528 lands first, #7105's release path will reject every otherwise-valid direct-memory range on Windows. Please coordinate with #7105's author and update its validation to use the block-range metadata (or agree on another compatible merge order), then record the prerequisite in Depends on and add/confirm Windows coverage.
  • #7149's Windows mapping changes conflict in DirectMemory.cpp/.hpp with this PR; its MapPlaced/commit-granule and unmap changes need an agreed integration order. The merge-tree check also reports a test-file conflict with #6321 in GuestMemory.cpp; retain both test additions and record any required prerequisite.

I checked the overlap with git merge-tree against the current PR heads. This is a coordination and cross-PR compatibility request; I found no new defect in the protection-preserving fast path itself.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638496556 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10528#pullrequestreview-5638496556). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T13:56:36Z. **Review:** CHANGES_REQUESTED --- Follow-up review of exact head `52c4d77c0a3111a8145c50a1de86f850d3c9337c`: the protection regression addresses my previous finding. The exact-head diff passes `git diff --check`; I could not run the native `guest_memory_tests` here because this isolated worktree has uninitialized submodules and no configured build. Before merging, please resolve the newly visible overlap with open PRs: - #7105's `TryForgetDirectMemory` and `ForgetDirectMemory` still validate each page with `g_physPages.contains(...)`. This PR now populates `g_physPages` only on Linux. If #10528 lands first, #7105's release path will reject every otherwise-valid direct-memory range on Windows. Please coordinate with #7105's author and update its validation to use the block-range metadata (or agree on another compatible merge order), then record the prerequisite in `Depends on` and add/confirm Windows coverage. - #7149's Windows mapping changes conflict in `DirectMemory.cpp`/`.hpp` with this PR; its `MapPlaced`/commit-granule and unmap changes need an agreed integration order. The merge-tree check also reports a test-file conflict with #6321 in `GuestMemory.cpp`; retain both test additions and record any required prerequisite. I checked the overlap with `git merge-tree` against the current PR heads. This is a coordination and cross-PR compatibility request; I found no new defect in the protection-preserving fast path itself.
MarcZX10 commented 2026-10-24 14:07:26 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T14:07:26Z.

Review: CHANGES_REQUESTED


Follow-up on exact head 52c4d77c0a3111a8145c50a1de86f850d3c9337c. The protection regression still addresses my original finding. I am narrowing my previous overlap review: I withdraw the git merge-tree-based conflict claims for #7149 and #6321; those comparisons used divergent PR histories, and the current-base-relative changes I inspected do not substantiate those conflicts. The substantive compatibility issue with #7105 remains: this PR populates g_physPages only on Linux, while #7105’s TryForgetDirectMemory/ForgetDirectMemory still require every page in that map. If #10528 lands first, valid Windows release requests will fail because that map is empty there. Please coordinate with #7105’s author on block-range validation or a compatible order, record the dependency where needed, and ensure Windows coverage. The isolated review worktree still lacks initialized submodules/configured build, so I could not independently run guest_memory_tests; the author reports its Windows Release regression passes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638533982 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10528#pullrequestreview-5638533982). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T14:07:26Z. **Review:** CHANGES_REQUESTED --- Follow-up on exact head `52c4d77c0a3111a8145c50a1de86f850d3c9337c`. The protection regression still addresses my original finding. I am narrowing my previous overlap review: I withdraw the `git merge-tree`-based conflict claims for #7149 and #6321; those comparisons used divergent PR histories, and the current-base-relative changes I inspected do not substantiate those conflicts. The substantive compatibility issue with #7105 remains: this PR populates `g_physPages` only on Linux, while #7105’s `TryForgetDirectMemory`/`ForgetDirectMemory` still require every page in that map. If #10528 lands first, valid Windows release requests will fail because that map is empty there. Please coordinate with #7105’s author on block-range validation or a compatible order, record the dependency where needed, and ensure Windows coverage. The isolated review worktree still lacks initialized submodules/configured build, so I could not independently run `guest_memory_tests`; the author reports its Windows Release regression passes.
MarcZX10 commented 2026-10-24 19:52:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T19:52:52Z.

Review: DISMISSED


Re-reviewed exact head 9d807ac9d0802dab93d01ed73b0b53b1d3c92585. The protection-aware same-range shortcut fixes the original host-permission finding, and g_physPages is now populated unconditionally, which resolves the compatibility concern with release-path validation on other platforms. The current diff passes git diff --check and tools/check_conventions.py --base upstream/main; the author reports the Windows guest_memory_tests run passing at this head. I did not run the native library suite locally because this checkout has no configured build.

One PR-body statement is now stale and materially contradicts the code: What says g_physPages is populated only on Linux, but CreateDirectMemoryBacking now fills it on every platform and ForgetDirectMemory erases it on every platform. Please update that description before merge so the performance and cross-platform behavior are accurately stated.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5639709588 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10528#pullrequestreview-5639709588). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T19:52:52Z. **Review:** DISMISSED --- Re-reviewed exact head `9d807ac9d0802dab93d01ed73b0b53b1d3c92585`. The protection-aware same-range shortcut fixes the original host-permission finding, and `g_physPages` is now populated unconditionally, which resolves the compatibility concern with release-path validation on other platforms. The current diff passes `git diff --check` and `tools/check_conventions.py --base upstream/main`; the author reports the Windows `guest_memory_tests` run passing at this head. I did not run the native library suite locally because this checkout has no configured build. One PR-body statement is now stale and materially contradicts the code: `What` says `g_physPages` is populated only on Linux, but `CreateDirectMemoryBacking` now fills it on every platform and `ForgetDirectMemory` erases it on every platform. Please update that description before merge so the performance and cross-platform behavior are accurately stated.
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!10528
No description provided.