Skip to content

xmem: commit physical pages on first touch, not when they are allocated - #7556

Open
Cattn wants to merge 5 commits into
ItsNotRexed:mainfrom
Cattn:xmem-commit-on-touch
Open

Cattn wants to merge 5 commits into
ItsNotRexed:mainfrom
Cattn:xmem-commit-on-touch

Conversation

@Cattn

@Cattn Cattn commented Nov 23, 2026 •

Copy link
Copy Markdown

Claimed in the coordination issue: #7333 (comment) (plan updated in #7333 (comment)), from @controldebils's finding #7333 (comment). @rafaelpssz measured the same failure and that commit-on-map is not enough (#7333 (comment)); thanks to both.

Depends on: none (based on main only). Touches the same xmem.cpp functions as #7492, #7550, #7580, #7331 and #7499; whichever lands second may need a small rebase around map_page / view_protect.

#7652 (DirectStorage DestinationIsPhysicalPages): its rt::xmem::write_physical_pages writes through its own section view, so on top of this PR it must call rt::xmem::commit_physical_pages(page_array, count) before copying (pages the title has not touched are reserve-only here). Raised by @nurtrino in #7599 (comment). commit_physical_pages (second commit) commits pages by page number through each section's own view, one VirtualAlloc per contiguous run; xmem_test checks that two never-mapped pages committed this way show as committed once mapped while a third stays reserved, and that a null array or unknown page number fails (201 checks OK, ctest -R "xmem|loader" 5/5, RTX 4070).

#7712 (g_windows/g_mapped cleanup on window reuse): merges cleanly with this PR, but its clear_window_range erases g_mapped entries under g_phys_mutex only. On top of this PR, every g_mapped insert/erase must also hold g_fault_lock exclusively (FaultLockExclusive), because the fault handler reads g_mapped under the shared lock without g_phys_mutex. Whichever lands second adds that one line. The same applies to the claimed shim VirtualFree on xmem reservations (#7694 (comment)).

What and why

XMemAllocatePhysicalPages (from #6919) backed each call with one pagefile-backed SEC_COMMIT section, so the whole request was charged at once. Right after boot stop 17 the title asks for 99,776 pages (about 6.1 GiB) in one call; on a 16 GB machine with a fixed page file that fails with ERROR_COMMITMENT_LIMIT (1450) or ERROR_COMMITMENT_MINIMUM (1455) and the boot stops a little later. The title then maps nearly all of those pages in one go, so committing at map time charges almost the same amount a few seconds later.

Now the commit follows first access:

  • The section is created with SEC_RESERVE. Each section also keeps one reserve-only FILE_MAP_WRITE view of itself (address space, no commit), through which pages are committed, so the title's view protection never matters and a committed page is visible through every view of it.
  • g_mapped records, for each mapped 64 KiB address, the page, its section and the offset, under an SRW lock (exclusive for map/unmap, shared on the fault path; unmap removes the entry before unmapping and restores it if the unmap fails).
  • A vectored handler, installed once by the first XMemAllocatePhysicalPages, takes an access violation only when its address is in a live mapping and the view's page is still MEM_RESERVE: it commits that page through the section's own view and resumes. A fault on a committed page resumes only when the view's protection now permits the access (two threads faulting the same page); every other fault (read-only or PAGE_NOACCESS views, runtime: the CPU half of Xbox physical pages, with write-fault dirty tracking #5381-style write tracking, addresses outside the mapped pages) goes to the next handler, and a failed commit is not swallowed, so a real out-of-memory still faults where it happened. It is first in the chain so that --trace's logging handler does not record every first touch.
  • rt::xmem::commit_physical_range(address, size) (new runtime/shims/xmem.h) commits a range up front and ignores memory that is not a mapped physical page. It is for shims that hand guest memory to the kernel or a driver, where an uncommitted page returns ERROR_NOACCESS instead of faulting. On main no shim does kernel I/O into guest memory; d3d12_xs: device slot 133 (CreatePlacedResourceX) makes a buffer on the title's own pages (VK_EXT_external_memory_host) #7218 (host-memory import, which requires MEM_COMMIT) and a DirectStorage shim (runtime: console DirectStorage (DStorageGetFactory) with file-to-memory reads #4348) should call it before using title pages. A title ReadFile straight into a physical page it has never touched is the remaining gap; I'll follow up with a pre-commit in a ReadFile shim if a trace shows the title doing that.

Unchanged: the 64 KiB page model, free/unmap semantics, view_protect, XMemVirtualAlloc. The doc comment of XMemAllocatePhysicalPages now says "charged on touch" instead of "at once".

Tested

Windows 11, NVIDIA GeForce RTX 4070 (driver 617.42), Ryzen 7 7800X3D, 31 GB RAM with a system-managed page file, MSVC 14.43 RelWithDebInfo.

  • New test_physical_pages_commit_on_touch in xmem_test: allocate (free system commit + 1 GiB) of pages, map 1,024 of them and write 512, checking system CommitTotal (a pagefile-backed section is not charged to PrivateUsage): allocating and mapping charge nothing, writing charges about the 512 pages, values read back and an untouched page reads zero; two pages mapped into a second window share data both ways; a write to a committed read-only page and a fault outside the mapped pages still reach the next handler; commit_physical_range commits an untouched page so ReadFile into it succeeds, and skips memory it doesn't own.
  • xmem_test: 191 checks OK (201 with the second commit). ctest -R "xmem|loader": 5/5 (loader, pe_loader, pe_loader_bounds, loader_tls, xmem). After rebasing on 37398f98d: xmem passes again.
  • Negative control, the new test against main's xmem.cpp: 2 failures, "allocating those pages does not charge them" and "writing to 512 of them charges about those 512 pages". On this machine the oversized SEC_COMMIT itself succeeded because Windows grew the system-managed page file; with a fixed page file it fails as in the finding.
  • Retail boot, own 1.0.2.1 copy, LEONIDA_D3D12=vulkan, on a local integration tree (main-era boot stand-ins, not proposed here) with this xmem.cpp dropped in versus main's: both reach the same stop with 2,246 D3D12 calls. Peak system commit during the run: +12.39 GiB with main's xmem.cpp, +5.45 GiB with this PR. Time to that stop: 3.5 to 3.7 s with this PR, 3.8 s with main, alternating runs.
  • No game data in this PR or its tests.

Expect small textual merges with the open xmem.cpp PRs near map_page (#7499 cache modifiers, #7331 rollback of failed batches); they don't change what this PR does.

AI-assisted: yes

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator change)

XMemAllocatePhysicalPages backed each call with one SEC_COMMIT section, so
the title's ~6.1 GiB page-pool request after boot stop 17 was charged in
full at once and fails with ERROR_COMMITMENT_LIMIT on a 16 GB machine.
Mapping the pages right away (as the title does) would charge most of it
within seconds too, so the commit now follows first access.

The section is SEC_RESERVE. A vectored handler commits the faulting 64 KiB
page through a reserve-only view of the whole section when the address
lies in a live mapping, so every view of that page sees it. Faults on
committed pages whose protection forbids the access, and faults outside
the mapped pages, go on to the next handler, and a failed commit is not
swallowed. rt::xmem::commit_physical_range commits a range up front for
shims that hand guest memory to the kernel.

Reported by controldebils and rafaelpssz in ItsNotRexed#7333.
@MartinIndra02

Copy link
Copy Markdown

Independent Windows test of a07c8c0e8: pass.

Setup: Windows 11 x64, MSVC 19.44.35220 (RelWithDebInfo, Windows SDK 10.0.26100.0), no game files.

  • xmem_test.exe: PASS (exit 0).

AI-assisted review/test.

A writer that copies into physical pages through its own view of their
section (a DirectStorage destination given as page numbers, ItsNotRexed#7652) sees
reserve-only memory for pages the title has not touched yet, and no
fault handler can resolve that address. commit_physical_pages commits
the given pages through each section's own view, one VirtualAlloc per
contiguous run, so such a writer can commit before it copies. Raised by
nurtrino in ItsNotRexed#7599.

@tupacfan04 tupacfan04 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The race is still present at head abd85df49.

runtime/shims/xmem.cpp:455-469 moves the MappedPage out of g_mapped before acquiring FaultLockExclusive:

MappedPage mapped = std::move(it->second);   // :458
{
    const FaultLockExclusive lock;           // :459-462
    g_mapped.erase(it);
}

The first-touch fault path holds FaultLockShared and reads the same entry (:542-545), then dereferences it->second.section->scratch at :497. In the move window the entry’s section is already moved-from.

Deterministic instrumentation (pause after the move) observes:

fault_seen=1 fault_section=0 faulted=1

The threaded faults + concurrent map/unmap run on the unmodified new-head binary hangs past the timeout (RACE_NEW_EXIT=-1), while fault-only and map-only runs complete. map_page also publishes the new view before inserting the g_mapped entry (:474-490), so a fault in that window finds no entry and falls through.

Expected: take the exclusive lock before moving/erasing (or copy under it), and publish/register the map atomically; add a threaded fault-vs-unmap regression. Synthetic only; no game files. AI-assisted (OpenCode).

…record

unmap_page moved the record out of g_mapped before taking the exclusive
lock, so a first-touch fault on that page could read a moved-from
section, and map_page made the view live before recording it, so a
fault in between was not recognised. unmap_page now holds the exclusive
lock from the lookup to the erase, and map_page holds it across mapping
the view and recording it. xmem_test adds four threads writing into a
window while 256 slices of pages are mapped and unmapped under them.
Reported by tupacfan04 in the review of ItsNotRexed#7556.
@Cattn

Cattn commented Nov 23, 2026

Copy link
Copy Markdown
Author

@tupacfan04, thanks, both races were real. Fixed in 75c2b87:

  • unmap_page now takes FaultLockExclusive before the g_mapped lookup and holds it through unmap_view2 and the erase, so a first-touch fault either sees the complete record (and the view still mapped) or no record at all. The move-out is gone.
  • map_page holds the exclusive lock across map_view3 and the g_mapped insert, so the view and its record appear together; a fault in that window waits on the shared lock and then finds the record.
  • New test_first_touch_during_remap in xmem_test: four threads keep writing (under __try) into a 16-page window while the main thread maps and unmaps 256 slices of fresh, untouched pages there, so every mapped slice is first-touched concurrently with remaps. It checks that the remaps succeed, that it finishes within 30 s, that writes land, and that the last slice is still writable.

RTX 4070, Windows 11, MSVC 14.43 RelWithDebInfo: with the fix, xmem_test (208 checks) passed 85 of 85 consecutive runs after one unexplained failure in the first batch of 15 (not captured; the first batch ran right after a rebuild, and the commit-charge checks in the commit-on-touch test are the noisy ones); ctest -R "xmem|loader" 5/5. With the new test on the previous head (abd85df), 2 of 15 runs hung until the 60 s timeout, as in your report.

AI-assisted: yes

@airp1ane

Copy link
Copy Markdown
Contributor

Tested a07c8c0e8 on Windows 11, MSVC 19.52 (VS 18 / CMake + Ninja, RelWithDebInfo), CPU-only (no GPU/game files needed): pass.

  • Targeted build (xmem_test, gta6rt): clean.
  • xmem_test.exe: OK (191 checks, exit 0) — including commit-on-first-touch over-commit allocation (1 GiB more pages than the system has commit free), commit-charge tracking on 512 touched pages, dual-window aliasing, VEH pass-through on committed read-only & unowned faults, and commit_physical_range + ReadFile.
  • Merge check onto main 7ef2fdd46 (git merge-tree), git diff --check, and scripts/check_no_game_data.py: all clean.

AI-assisted.

…ting address

The handler queried the protection at the start of the 64 KiB page, so
a write to a 4 KiB part the title had made read-only looked allowed and
was resumed, faulting again forever instead of reaching the title's own
handler. It now looks the record up by the page and the protection up
by the faulting address. xmem_test writes to a read-only 4 KiB part of
a read-write page and expects the fault.
@AirKyzzZ

Copy link
Copy Markdown
Contributor

Tested af75a43dc on Windows 10 22H2 (16 GB RAM, about 18 GB of commit free), clang-cl 23.1.6 + lld-link (MSVC 14.44 STL), SDK 10.0.26100: fail with clang-cl, pass with /EHa

Built xmem_test at the head as is. It crashes with an access violation (0xC0000005, ctest: Exception: SegFault) after PASS scattered pages land at their own addresses and a 0 entry unmaps, the same at a07c8c0e8, abd85df49 and 75c2b87a7; the merge base 37398f98d passes (173 checks). The fault offset symbolizes to access_faults, runtime/test/xmem_test.cpp:450: the fault there is the expected one, but clang-cl only catches a hardware exception raised by an inline load or store inside __try with /EHa (asynchronous SEH), which xmem_test doesn't set, so it escapes the __except. The MSVC runs above don't hit this. With /EHa added to xmem_test's compile options (local change only), the head passes: xmem_test: OK (210 checks).

Without the fix: the new test asks for 1 GiB more than the free commit, which the old SEC_COMMIT path would charge on a shared machine, so I lowered that count to 2 GiB for this check only. With /EHa and the lowered count, the head passes 210 checks; with SEC_RESERVE put back to SEC_COMMIT in XMemAllocatePhysicalPages, 3 fail (allocating those pages does not charge them, writing to 512 of them charges about those 512 pages, the two committed by number are committed in the window and the third is not yet). No game files. AI-assisted (Claude Code).

The commit-on-touch checks expect hardware faults from plain loads and
stores inside __try. MSVC catches those as it is; clang-cl only with
asynchronous exceptions, so without /EHa the expected fault escaped and
xmem_test crashed. Same option as tiny_dll. Reported by AirKyzzZ in ItsNotRexed#7556.
@Cattn

Cattn commented Nov 23, 2026

Copy link
Copy Markdown
Author

@AirKyzzZ, thanks for the clang-cl run and the bisect. Fixed in e85ebec: xmem_test now gets $<$<CXX_COMPILER_ID:Clang>:/EHa> (the same generator expression tiny_dll uses), so the expected faults in access_faults are caught under clang-cl as they are under MSVC. I have no clang-cl here: with MSVC 14.43 the test still passes (210 checks); the clang-cl result is yours (210 checks with /EHa). Also good to know the new checks fail when SEC_COMMIT is put back.

AI-assisted: yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants