Repository navigation
xmem: commit physical pages on first touch, not when they are allocated - #7556
Conversation
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.
|
Independent Windows test of Setup: Windows 11 x64, MSVC 19.44.35220 (
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
left a comment
There was a problem hiding this comment.
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.
|
@tupacfan04, thanks, both races were real. Fixed in 75c2b87:
RTX 4070, Windows 11, MSVC 14.43 RelWithDebInfo: with the fix, AI-assisted: yes |
|
Tested
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.
|
Tested Built Without the fix: the new test asks for 1 GiB more than the free commit, which the old |
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.
|
@AirKyzzZ, thanks for the clang-cl run and the bisect. Fixed in e85ebec: AI-assisted: yes |
svds12343
left a comment
There was a problem hiding this comment.
Independent review and native Windows 11 verification of #7556 at head e85ebec7d438b111b14a1355e2c42c3d193a68d4 (merge-base 37398f98d91ec6992d5621e9f4fdef64d59dc09b; clean git merge-tree against upstream/main 47428cc2). AI-assisted review; synthetic inputs only (no game files).
Environment
- OS: Windows 11 x64
- Compiler / build: MSVC
19.44.35230(x64), CMake4.4.5, Ninja (RelWithDebInfo) - Python: CPython
3.12.5(python -I)
Checks run & results
git diff --check 37398f98..HEAD— clean.git merge-tree --write-tree upstream/main HEAD— exit 0 (clean merge with47428cc2).python -I scripts/check_no_game_data.pyon all 4 changed files — clean (exit 0).cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo&cmake --build runtime/build --target xmem_test gta6rt pe_loader_test test_pe_loader_bounds dll_thread_calls_test— built cleanly with zero warnings in changed files.ctest --test-dir runtime/build -R "^(xmem|pe_loader|pe_loader_bounds|dll_thread_calls)$" --output-on-failure— 4/4 passed (1.11s), withxmem_test: OK (210 checks). On this host the 1 GiB over-free-commit allocation test ran live (did not skip) and passed alongside thecommit_physical_range/ReadFile,commit_physical_pages, protection-fault, and 4-thread 256-slice remap race checks.- Stress check: 20/20 consecutive runs of
runtime/build/xmem_test.exepassed (210/210checks per run,0failures).
Code audit notes
- Confirmed the
e85ebec7dconcurrency fix for@tupacfan04's race finding:unmap_page()holdsFaultLockExclusiveacross bothunmap_view2()andg_mapped.erase(), andmap_page()holdsFaultLockExclusiveacross bothmap_view3()andg_mapped[address] = ..., preventing both post-unmap use-after-free and pre-insert fault misses.- Lock hierarchy is strictly
g_phys_mutex->g_fault_lock;physical_page_fault()never acquiresg_phys_mutex, and neitherunmap_page()normap_page()dereferences caller buffers while holdingFaultLockExclusive, so a page fault on a caller-suppliedpage_arrayoraddressesbuffer inside an uncommitted physical page cannot deadlock. MappedPageretains its ownstd::shared_ptr<Section>, preserving the contract that freeing a still-mapped physical page keeps its backing section andscratchview alive until unmapped.access_allowed()handlesPAGE_GUARDand read/write/execute (0/1/8) checks cleanly so committed protection violations still reach the next handler without looping.
- Not tested:
clang-clcross-build ($<$<CXX_COMPILER_ID:Clang>:/EHa>) and Wine execution.
Looks clean and ready to merge.
|
Tested
No game files. AI-assisted (Claude Code). |
|
Tested
AI-assisted: yes |
|
@Cattn, a measurement on this PR from a retail boot (Windows 11 26200, RTX 5070 Ti Laptop, NVIDIA 621.24, my own 1.0.2.1 copy, a local integration stack that includes this PR's head; counts only). Kernel writes into first-touch physical pages fail. Almost all of the title's Suggested fix: before a shim hands a buffer to a kernel write ( I am not taking this; it's your PR. If you'd rather I open a small follow-up PR on top of yours, say so. AI-assisted (Claude Code). |
throny
left a comment
There was a problem hiding this comment.
Tested e85ebec merged onto main 867d922 on Windows 11, RTX 4080 610.88: the tests pass, but ReadFile into a mapped page the title has not touched fails with ERROR_NOACCESS, which works on main. Requesting changes for that.
- Build and tests: MSVC 14.44, Ninja, RelWithDebInfo, clean merge.
xmem_test: 210 checks OK (remap race: 17,642 writes landed, 3,047 hit an unmapped page, 31 ms);loader_test88 checks, 0 failed;gta6rtlinks. - Repro, synthetic: a temporary probe after the
commit_physical_rangecheck intest_physical_pages_commit_on_touchreads 64 KiB withReadFileintowindow + (kTouched + 2) * kPage64k(mapped, never written, not pre-committed). Result:FALSE,GetLastError()998. On main the section isSEC_COMMIT, so the same call has committed memory. This is the cause of the count @Etr0p posted from a retail boot. - Why it matters here: the title's
ReadFileis bound to the host (there is noReadFileshim), andrt::xmem::commit_physical_rangehas no caller ingta6rt, so the PR as it is turns reads into fresh physical pages into failures. The description lists this as a follow-up "if a trace shows the title doing that"; it does. - Asked for in this PR: a
ReadFileshim (plusReadFileEx/ReadFileScatterif the executable imports them) that callscommit_physical_range(buffer, size)and forwards, and a test that reads a file into a never-touched mapped page and compares the bytes. Kernel reads of an untouched page (WriteFilefrom it) have the same problem and could go through the same helper. - Whole diff read; nothing else found. The lock order is consistent (
g_phys_mutex, theng_fault_lock; the fault handler takes only the shared fault lock), the handler passes on faults it does not own, and a failed commit is not swallowed. - Not measured yet: private bytes of our frame-loop boot with and without it. That stack maps pages in runs (#7584), which conflicts with
map_page/unmap_pagehere; I have a local port and will add the numbers when the GPU is free.
AI-assisted (Claude Code). No game data.
|
Tested e85ebec merged with main 867d922 under Wine: On: Linux, Ubuntu 24.04, cross-built with clang-cl 19.1.1 + xwin SDK (RelWithDebInfo), run through Wine 9.0; CPU only, no game files. The 4 failures:
The checks next to them pass under Wine: mapping 1,024 pages does not charge them, each touched page keeps its data, and two windows see each other's writes. So Wine's protection and commit bookkeeping for these views differs from Windows, not the data path. I haven't dug into which Wine call differs yet. If Wine is meant to be supported here, these four may need a Wine-aware expectation ( AI-assisted (Claude Code). |
throny
left a comment
There was a problem hiding this comment.
Boot measurement for my review above, on Windows 11, RTX 4080 610.88, own 1.0.2.1 copy: about 7 GB less system commit with first-touch commit; the process's private bytes do not change.
- Not this head as it is: our frame-loop stack maps pages in runs (#7584), which conflicts with
map_page/unmap_pagehere. I ported the fault handler to look the address up in the run table (same lock scheme), and added aReadFileshim and a DirectStorage read that callcommit_physical_rangefirst, so the boot is not changed by failing reads. Baseline: the same tree without those changes. 2 runs each, alternating, 60 s,LEONIDA_D3D12=vulkan, offline. - System commit above the level before the start, at 5 s: +12.3 and +12.6 GB without, +5.4 and +5.5 GB with. Peak in 60 s: +23.3 and +22.8 GB without, +15.9 and +15.4 GB with.
- Lowest free commit: 8.0 GB (my 8 GB watchdog stopped that run after about 50 s) and 8.9 GB without; 15.2 and 16.8 GB with.
- Peak private bytes: 15.6 and 15.4 GB without, 15.7 and 15.4 GB with. Pages of a pagefile-backed section are not private bytes, so the saving shows only in the system commit.
- Same progress in all four runs: 65,071 to 65,391 D3D12 calls with 152 to 172
ExecuteCommandLists, and no failed DirectStorage entry.
AI-assisted (Claude Code). Counts only, no game data.
|
Merge note for whoever stacks this with #7492 (both are open; |
|
Tested e85ebec (merged onto a local tree:
Not run: the PR's |
…inter import xmem commits physical pages on first touch (#7556), so a range the title has mapped but not written yet is still MEM_RESERVE when it places a buffer on it through device slot 133, and the Vulkan layer's import (#7218) refuses reserved pages and answers with its fallback buffer, which the title's writes never reach. Slot 133 now calls a registered pages hook (set_placed_at_va_pages_hook, next to set_placed_at_va_handler) with the buffer's range before the handler; gta6rt registers rt::xmem::commit_physical_range. A failed commit is logged once and the handler still runs. Textures don't call it. The Vulkan layer doesn't link xmem. Tests: xs_proxy_mock_test checks the hook order, arguments, failure and texture cases; the new d3d12_xmem_placed_test places a buffer on untouched xmem physical pages and checks the fallback without the hook, and with it the import and a GPU copy reading the CPU's writes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A measurement page in its own file: which stops of docs/retail_boot_chain.md and of #8554's ladder hold on an Intel CPU with #7111's emulation, the stop that is specific to a 16 GB host (the 6.1 GiB physical-page request against the commit limit, cleared by #7556), the frame loop to the 900 s timeout with stub pipelines, and what the layer refuses at that depth, including the console mesh-shader stream subobject. Counts and slot numbers only; no addresses. Plus the docs/README.md row. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GDgoLP2cV47KaCDkbmckob
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
mainonly). Touches the samexmem.cppfunctions as #7492, #7550, #7580, #7331 and #7499; whichever lands second may need a small rebase aroundmap_page/view_protect.#7652 (DirectStorage DestinationIsPhysicalPages): its
rt::xmem::write_physical_pageswrites through its own section view, so on top of this PR it must callrt::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, oneVirtualAllocper contiguous run;xmem_testchecks 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_rangeerasesg_mappedentries underg_phys_mutexonly. On top of this PR, everyg_mappedinsert/erase must also holdg_fault_lockexclusively (FaultLockExclusive), because the fault handler readsg_mappedunder the shared lock withoutg_phys_mutex. Whichever lands second adds that one line. The same applies to the claimed shimVirtualFreeon xmem reservations (#7694 (comment)).What and why
XMemAllocatePhysicalPages(from #6919) backed each call with one pagefile-backedSEC_COMMITsection, 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 withERROR_COMMITMENT_LIMIT(1450) orERROR_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:
SEC_RESERVE. Each section also keeps one reserve-onlyFILE_MAP_WRITEview 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_mappedrecords, 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).XMemAllocatePhysicalPages, takes an access violation only when its address is in a live mapping and the view's page is stillMEM_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 orPAGE_NOACCESSviews, 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)(newruntime/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 returnsERROR_NOACCESSinstead of faulting. Onmainno 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 requiresMEM_COMMIT) and a DirectStorage shim (runtime: console DirectStorage (DStorageGetFactory) with file-to-memory reads #4348) should call it before using title pages. A titleReadFilestraight into a physical page it has never touched is the remaining gap; I'll follow up with a pre-commit in aReadFileshim if a trace shows the title doing that.Unchanged: the 64 KiB page model, free/unmap semantics,
view_protect,XMemVirtualAlloc. The doc comment ofXMemAllocatePhysicalPagesnow 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.
test_physical_pages_commit_on_touchinxmem_test: allocate (free system commit + 1 GiB) of pages, map 1,024 of them and write 512, checking systemCommitTotal(a pagefile-backed section is not charged toPrivateUsage): 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_rangecommits an untouched page soReadFileinto 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 on37398f98d:xmempasses again.main'sxmem.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 oversizedSEC_COMMITitself succeeded because Windows grew the system-managed page file; with a fixed page file it fails as in the finding.LEONIDA_D3D12=vulkan, on a local integration tree (main-era boot stand-ins, not proposed here) with thisxmem.cppdropped in versusmain's: both reach the same stop with 2,246 D3D12 calls. Peak system commit during the run: +12.39 GiB withmain'sxmem.cpp, +5.45 GiB with this PR. Time to that stop: 3.5 to 3.7 s with this PR, 3.8 s withmain, alternating runs.Expect small textual merges with the open
xmem.cppPRs nearmap_page(#7499 cache modifiers, #7331 rollback of failed batches); they don't change what this PR does.AI-assisted: yes
Checklist
docs/design.md, with how it was confirmed. (n/a: no translator change)