Recycle freed XMem physical page numbers before 21-bit limit #409

Closed
github-bot wants to merge 661 commits from github-bot/gh-409 into main AGit
Owner

@⁠safesearch77 on GitHub · 2026-11-28 13:25 UTC · original
safesearch77:fix/xmem-recycle-page-numbers → main · +60204 −5433 · 206 files · 661 commits · closed without merging

XMemAllocatePhysicalPages previously incremented Pages::next_page monotonically. Because the title stores page numbers in 21 bits as number >> 4 (FRAMES), crossing PAGE_LIMIT (1 << 25, roughly 124 GiB of cumulative allocations over a long session) truncates returned page numbers, causing unknown-page or live-page aliasing faults.

Pages::take now continues handing out sequential numbers while next_page + n * FRAMES <= PAGE_LIMIT, then falls back to free_run to find the lowest contiguous run of n freed page slots within [FIRST_PAGE, PAGE_LIMIT). That fallback collects and sorts active page keys (O(P log P)), which only fires once cumulative allocations pass ~124 GiB. If no contiguous run fits, XMemAllocatePhysicalPages logs a warning, sets *count = 0, and returns 0 cleanly (dropping the newly created Arc<Section>).

Ported from trustno1-coder/VIctory-NVIDIA@108a8971 (by illuminatedfellow, from avatarmanz/VIctory-7900XTX#316).

Verification

  • cargo +1.98.1 test --locked --target x86_64-pc-windows-msvc -p victory-hle --lib -- modules::xmem (Wine): 19 passed; 0 failed; 1 ignored (map_bench), all pure CPU/Win32 memory tests, including page_numbers_freed_are_given_again_past_the_title_s_21_bits (covers sequential boundary up to PAGE_LIMIT, lowest-gap reuse, fragmentation, usize::MAX overflow, and (p >> 4 & 0x1f_ffff) << 4 == p round-trip).
  • cargo +1.98.1 clippy --locked --target x86_64-pc-windows-msvc -p victory-hle --all-targets -- -D warnings: clean (0 warnings).
  • cargo +1.98.1 xtask policy: asset policy: 322 files ok.
**@⁠safesearch77** on GitHub · 2026-11-28 13:25 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/409) `safesearch77:fix/xmem-recycle-page-numbers` → `main` · +60204 −5433 · 206 files · 661 commits · closed without merging `XMemAllocatePhysicalPages` previously incremented `Pages::next_page` monotonically. Because the title stores page numbers in 21 bits as `number >> 4` (`FRAMES`), crossing `PAGE_LIMIT` (`1 << 25`, roughly 124 GiB of cumulative allocations over a long session) truncates returned page numbers, causing unknown-page or live-page aliasing faults. `Pages::take` now continues handing out sequential numbers while `next_page + n * FRAMES <= PAGE_LIMIT`, then falls back to `free_run` to find the lowest contiguous run of `n` freed page slots within `[FIRST_PAGE, PAGE_LIMIT)`. That fallback collects and sorts active page keys (`O(P log P)`), which only fires once cumulative allocations pass ~124 GiB. If no contiguous run fits, `XMemAllocatePhysicalPages` logs a warning, sets `*count = 0`, and returns `0` cleanly (dropping the newly created `Arc<Section>`). Ported from `trustno1-coder/VIctory-NVIDIA@108a8971` (by `illuminatedfellow`, from `avatarmanz/VIctory-7900XTX#316`). ### Verification - `cargo +1.98.1 test --locked --target x86_64-pc-windows-msvc -p victory-hle --lib -- modules::xmem` (Wine): `19 passed; 0 failed; 1 ignored` (`map_bench`), all pure CPU/Win32 memory tests, including `page_numbers_freed_are_given_again_past_the_title_s_21_bits` (covers sequential boundary up to `PAGE_LIMIT`, lowest-gap reuse, fragmentation, `usize::MAX` overflow, and `(p >> 4 & 0x1f_ffff) << 4 == p` round-trip). - `cargo +1.98.1 clippy --locked --target x86_64-pc-windows-msvc -p victory-hle --all-targets -- -D warnings`: clean (`0` warnings). - `cargo +1.98.1 xtask policy`: `asset policy: 322 files ok`.
Keep handing out sequential page numbers while they fit the title's
21-bit number >> 4 representation, then reuse the lowest contiguous
free run and fail cleanly with count=0 if exhausted. The O(P log P)
key sort only fires past ~124 GiB of cumulative allocations.

Ported from trustno1-coder/VIctory-NVIDIA 108a897 (illuminatedfellow,
from avatarmanz/VIctory-7900XTX#316).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-28 13:36:42 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-11-28 16:16 UTC · original

Read through this one. The xmem tests pass on native Windows too (19 passed, 1 ignored at ba5a8bd), since the description only had Wine.

Things I checked and that look right:

  • free_run with sorted keys and the PAGE_LIMIT sentinel, and every number it can return stays a multiple of 16 below 1 << 25, so >> 4 and << 4 round-trip.
  • Reusing a freed number while its old pages are still mapped is fine, because Physical::views holds the Slice (and so the section), not the number. A stale view keeps showing the old section.
  • The GPU side tracks sections by handle and memory by address, never by page number, so it doesn't see the reuse.
  • The out-of-numbers return drops the new Section, and its Drop calls title_memory_section_gone, so nothing is left registered.

One thing to keep in mind, not a blocker: past the limit every XMemAllocatePhysicalPages collects and sorts all live page keys while holding the PAGES write lock, and the map/fault paths take the read side of it. With ~100k live pages that's a noticeable pause per allocation if the title allocates often by then. Keeping the freed numbers in a BTreeSet (filled in XMemFreePhysicalPages once past the limit) would avoid the scan. I don't know how often the title allocates physical pages that late in a session, so it may never matter.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-11-28 16:16 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/409#issuecomment-7242115980) Read through this one. The `xmem` tests pass on native Windows too (19 passed, 1 ignored at `ba5a8bd`), since the description only had Wine. Things I checked and that look right: - `free_run` with sorted keys and the `PAGE_LIMIT` sentinel, and every number it can return stays a multiple of 16 below `1 << 25`, so `>> 4` and `<< 4` round-trip. - Reusing a freed number while its old pages are still mapped is fine, because `Physical::views` holds the `Slice` (and so the section), not the number. A stale view keeps showing the old section. - The GPU side tracks sections by handle and memory by address, never by page number, so it doesn't see the reuse. - The out-of-numbers return drops the new `Section`, and its `Drop` calls `title_memory_section_gone`, so nothing is left registered. One thing to keep in mind, not a blocker: past the limit every `XMemAllocatePhysicalPages` collects and sorts all live page keys while holding the `PAGES` write lock, and the map/fault paths take the read side of it. With ~100k live pages that's a noticeable pause per allocation if the title allocates often by then. Keeping the freed numbers in a `BTreeSet` (filled in `XMemFreePhysicalPages` once past the limit) would avoid the scan. I don't know how often the title allocates physical pages that late in a session, so it may never matter. AI-assisted: yes
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-29 11:35 UTC · original

Thanks for the native Windows check. Reusing freed page numbers needs to preserve live mappings and reject allocations that cross PAGE_LIMIT. The native test result complements the Wine coverage; please keep the limit and fragmented-free-run cases explicit.

**@⁠TaynanGT** on GitHub · 2026-11-29 11:35 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/409#issuecomment-7255220339) Thanks for the native Windows check. Reusing freed page numbers needs to preserve live mappings and reject allocations that cross PAGE_LIMIT. The native test result complements the Wine coverage; please keep the limit and fragmented-free-run cases explicit.
A freed run found past the 21-bit limit could reach into the numbers
never given out without moving next_page, so the next allocation that
still fit there got live numbers again and replaced their pages. Move
next_page past such a run. Add explicit tests for reuse around live
pages, refusal at PAGE_LIMIT, and this case.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Author
Owner

@⁠safesearch77 on GitHub · 2026-11-29 13:20 UTC · original

Thanks for the review. Adding the explicit tests you asked for turned up a real bug in the reuse path, so this update fixes it too.

The bug. After the sequential numbers run out, take() scans for the lowest free run up to PAGE_LIMIT. The numbers from next_page up to the limit were never given out, so they count as free. A run can therefore start in freed numbers just below next_page and continue into that never-given tail. next_page didn't move, so a later small allocation that still fit the tail got the same numbers again from the sequential path. XMemAllocatePhysicalPages then inserted over the live Slice. The earlier page number silently moved to the new section, and freeing either allocation dropped the other's page.

It's only reachable once the 21-bit space has been used up (about 124 GiB of cumulative physical allocations), which is the situation this PR exists for. A test found it. No game run has hit it. The same take() is in VIctory-NVIDIA and in #439 (cfd5ebd), and the patch applies to #439 unchanged.

The fix (2 lines in Pages::take): when a freed run is given, next_page moves past the run's end (self.next_page = self.next_page.max(first + len)). That keeps the invariant that no live number is at or past next_page. A refusal (None) changes nothing.

Tests, one per point you raised, all on a Pages of their own that holds live entries (Slices of real sections):

  • page_numbers_given_again_take_the_lowest_fit_around_live_pages: covers fragmented free runs (gaps of 1 and 3 between live numbers). Allocations of 2, 1, 2 and 1 pages get f(4), f(2), f(9) and f(6), so each takes the lowest run that fits. Every pre-existing entry still points at its own section and index, and next_page is unchanged.
  • page_numbers_that_would_cross_the_title_s_21_bits_are_refused: only 2 never-given numbers are left below PAGE_LIMIT, and no freed run of 1,024 exists. take(1024) returns None and leaves next_page, the map's size and every live entry unchanged. The 2 numbers left are still given afterwards.
  • page_numbers_given_again_from_the_unused_tail_are_not_given_twice: the regression test for the bug above. It fails without the fix (0x1ffe000 was given while still live) and passes with it.

Each test gives numbers the way XMemAllocatePhysicalPages does. It asserts that no number given is already live and that each survives the title's >> 4 / << 4 round trip.

Verified under Wine: victory-hle --lib -- modules::xmem 22/22 on this branch (19 before plus 3 new, 1 ignored), and 23/23 with the patch applied on #439 (the new test fails there without the fix). cargo clippy -p victory-hle --all-targets -- -D warnings and cargo xtask policy (322 files ok) are clean. The new tests are CPU-only. I haven't run them natively on Windows.

@⁠Kal0s-design's BTreeSet idea for avoiding the key scan past the limit is a good follow-up. I've left it out to keep this change to the correctness fix.

AI-assisted: yes (Claude), reviewed locally before posting.

**@⁠safesearch77** on GitHub · 2026-11-29 13:20 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/409#issuecomment-7256459907) Thanks for the review. Adding the explicit tests you asked for turned up a real bug in the reuse path, so this update fixes it too. **The bug.** After the sequential numbers run out, `take()` scans for the lowest free run up to `PAGE_LIMIT`. The numbers from `next_page` up to the limit were never given out, so they count as free. A run can therefore start in freed numbers just below `next_page` and continue into that never-given tail. `next_page` didn't move, so a later small allocation that still fit the tail got the same numbers again from the sequential path. `XMemAllocatePhysicalPages` then `insert`ed over the live `Slice`. The earlier page number silently moved to the new section, and freeing either allocation dropped the other's page. It's only reachable once the 21-bit space has been used up (about 124 GiB of cumulative physical allocations), which is the situation this PR exists for. A test found it. No game run has hit it. The same `take()` is in VIctory-NVIDIA and in #439 (cfd5ebd), and the patch applies to #439 unchanged. **The fix** (2 lines in `Pages::take`): when a freed run is given, `next_page` moves past the run's end (`self.next_page = self.next_page.max(first + len)`). That keeps the invariant that no live number is at or past `next_page`. A refusal (`None`) changes nothing. **Tests**, one per point you raised, all on a `Pages` of their own that holds live entries (`Slice`s of real sections): - `page_numbers_given_again_take_the_lowest_fit_around_live_pages`: covers fragmented free runs (gaps of 1 and 3 between live numbers). Allocations of 2, 1, 2 and 1 pages get `f(4)`, `f(2)`, `f(9)` and `f(6)`, so each takes the lowest run that fits. Every pre-existing entry still points at its own section and index, and `next_page` is unchanged. - `page_numbers_that_would_cross_the_title_s_21_bits_are_refused`: only 2 never-given numbers are left below `PAGE_LIMIT`, and no freed run of 1,024 exists. `take(1024)` returns `None` and leaves `next_page`, the map's size and every live entry unchanged. The 2 numbers left are still given afterwards. - `page_numbers_given_again_from_the_unused_tail_are_not_given_twice`: the regression test for the bug above. It fails without the fix (`0x1ffe000 was given while still live`) and passes with it. Each test gives numbers the way `XMemAllocatePhysicalPages` does. It asserts that no number given is already live and that each survives the title's `>> 4` / `<< 4` round trip. Verified under Wine: `victory-hle --lib -- modules::xmem` 22/22 on this branch (19 before plus 3 new, 1 ignored), and 23/23 with the patch applied on #439 (the new test fails there without the fix). `cargo clippy -p victory-hle --all-targets -- -D warnings` and `cargo xtask policy` (322 files ok) are clean. The new tests are CPU-only. I haven't run them natively on Windows. @⁠Kal0s-design's `BTreeSet` idea for avoiding the key scan past the limit is a good follow-up. I've left it out to keep this change to the correctness fix. AI-assisted: yes (Claude), reviewed locally before posting.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-29 13:24 UTC · original

Thanks for finding the duplicate page-number allocation and adding the three regression cases. I integrated the follow-up locally; moving next_page past the reused run preserves the invariant that live numbers cannot be issued again. Native Windows tests are still pending. I agree that optimizing the free-run search should stay separate from this correctness fix.

**@⁠TaynanGT** on GitHub · 2026-11-29 13:24 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/409#issuecomment-7256512423) Thanks for finding the duplicate page-number allocation and adding the three regression cases. I integrated the follow-up locally; moving next_page past the reused run preserves the invariant that live numbers cannot be issued again. Native Windows tests are still pending. I agree that optimizing the free-run search should stay separate from this correctness fix.
github-bot closed this pull request 2026-11-30 17:14:29 +00:00
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-30 17:08 UTC · original

main has moved to a new line of the code and everything is now named Vice-Tay, so this PR no longer applies as it is (details in #468). If you'd like this change in, please rebuild it on the current main and open a new PR; I'll review it there.

**@⁠TaynanGT** on GitHub · 2026-11-30 17:08 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/409#issuecomment-7285793248) `main` has moved to a new line of the code and everything is now named Vice-Tay, so this PR no longer applies as it is (details in #468). If you'd like this change in, please rebuild it on the current `main` and open a new PR; I'll review it there.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.