runtime: back physical pages with shared sections and map adjacent pages as one view #1299
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/1306"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-24T07:24:13Z.
Refs #870.
Problem
src/xmem_mapped_pages.cppgives every 64 KiB physical page a section of its own and maps it with a view of its own. A console executable maps about 100,000 pages in one batch at start-up. That is 100,000 section handles and 100,000 views, twice that with the GPU-view mirror.Under Wine this is slow enough to matter: the batch did not finish within 30 s in a startup run, and the executable's own watchdog ended the run. I have no measurement on Windows (see "Not measured"); the handle and view counts are the same there.
Change
Backing::offset). Slots are handed out in order; a freed slot goes on a free list and is zeroed when it is reused, as a fresh section was.MapViewOfFile3(map_run). If the range is not inside one placeholder, it falls back to one view per page, which is the old behaviour.memory.viewsstill records every page;memory.runsrecords the real views.x2w_xmem_write_physicalmaps its temporary view at the page's slot offset.Behaviour that changes
VirtualQueryon a page of a shared view reports the view's base and size, not the page's.d3d12_xs_device.cppuses the allocation base for placed buffers; startup runs with this change behave the same there, but any caller that assumed one region per page would see a difference.map_pages, and whattests/xmem_mapped_pages_check.pydoes) get one view per page exactly as before, because a multi-page map cannot replace several placeholders.Evidence
Commit under test: the head of this branch, on
mainat93cb6a2a.xmem.dllbuilt with clang-cl against the Windows SDK; tests run with CPython 3.12 for Windows under Wine 11.0 (Proton Experimental) on Linux. Translation-layer results, not Windows.Existing contract check, unchanged, against the changed DLL:
New
tests/xmem_page_runs_check.py(registered asxmem_shim_page_runs):It maps 6,000 pages in one call (across the 4,096-page section boundary) and writes a marker at both ends of each; unmaps five pages from the middle, including both sides of the boundary, and requires every other page intact; maps those five elsewhere and requires the same bytes; puts them back; then has a second thread read one page continuously for 2 s while the main thread unmaps and remaps its neighbour (same view); finally releases everything and requires reused pages to read zero.
Negative control, registered as
xmem_shim_page_runs_no_retry_controlwithWILL_FAIL: withX2W_XMEM_NO_FAULT_RETRY=1the handler is not installed, and the same check dies in the reader with an access violation (exit code 5 here). So the reader does fault during the toggles, and the handler is what makes it pass.The new check also passes against the unchanged DLL from
main(6,000 pages in 380 ms). It is a regression check for the new paths plus a timing print, not a test that only the new code can pass.Timing with the same script and a larger batch (
xmem_page_runs_check.py <dll> 100000):xmem.dllmainat93cb6a2aWhole-program: with an earlier local build of this change, the startup run that had been ended by the watchdog passed the batch within 5 s of starting.
Also ran
python -B tests/docs_links_check.py(pass) andgit diff --check(clean).Not measured
EXCEPTION_CONTINUE_SEARCHunless the faulting address's page is inmemory.views, but I have not looked for other handlers in the stand-ins that it could interact with beyond the__tryprobes, which target unmapped addresses.Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T07:28:36Z.
Review: CHANGES_REQUESTED
On Windows Release the positive 6,000-page run passed, including partial unmap, remap and reuse. The no-retry control terminated with an access violation, which CTest reported as SEGFAULT despite
WILL_FAIL. Please put that control behind a parent process that checks the expected child outcome and fails on unrelated errors.Two production cases need to be addressed before this can land. A failure partway through unmapping or remapping leaves
memory.viewsclaiming some pages whose Windows view is already gone. The process-wide exception handler then treats registry membership alone as permission to retry, including faults outside the transient remap window. Please preserve a consistent mapping state on failure and restrict any retry to a verified transient remap with bounded behavior.Please also add a source-built comparison of
VirtualQuerybefore and after splitting a run, two simultaneous views of the same backing with writes visible in both directions, and the placed-buffer boundary across adjacent backing ranges. The existing GPU address collision fixture is independent of this change.Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T07:30:11Z.
Review: COMMENTED
Dual-platform review at commit
a78c3322a01c5fb036549f088f0f6ac5eaa47849:Verification
git diff --check origin/main...HEAD: clean (exit 0)/root/.local/share/x2w-rev-venv/bin/python -B tests/docs_links_check.py: passed (16 Markdown files, 289 links)/root/.local/share/x2w-rev-venv/bin/python -B tests/bidi_controls_check.py: passed (1087 tracked files)--preset dev) with^xmem_shim_(mapped_pages|page_runs(_no_retry_control)?)$:xmem_shim_mapped_pages: passed (0.07s)xmem_shim_page_runs: passed (2.25s)xmem_shim_page_runs_no_retry_control: failed (***Exception: SegFault,0.60s) — CTest does not invert OS access-violation crashes withWILL_FAIL TRUE^xmem_shim_(mapped_pages|page_runs)$):--preset dev):cmake --build --preset dev --target xmem_shim -- -j 6(3.04s),ctest --preset dev -R '^xmem_shim_(mapped_pages|page_runs)$' --parallel 4 --no-tests=error --output-on-failure: 2/2 passed (2.30s:0.06s,2.23s)/O2(--preset release):cmake --build --preset release --target xmem_shim -- -j 6(2.38s),ctest --preset release -R '^xmem_shim_(mapped_pages|page_runs)$' --parallel 4 --no-tests=error --output-on-failure: 2/2 passed (2.24s:0.07s,2.17s)Code Review Findings
~PhysicalMemory()unmapsviewsinstead ofruns(src/xmem_mapped_pages.cpp):~PhysicalMemory()still iteratesviews(64 KiB page entries) and callsUnmapViewOfFile(view.first), which will fail on non-head pages of a multi-page run; it should unmapruns(the actual OS view bases) instead.src/xmem_mapped_pages.cpp): In thetokens == nullptrbranch ofmap_pages, ifUnmapViewOfFile2fails after unmapping an earlier run, or ifmap_runfails partway through remapping surviving pages,memory.viewsstill records pages whose Windows views are unmapped (andmadeis not rolled back onmap_runfailure).retry_remapped_page(src/xmem_mapped_pages.cpp): ReturningEXCEPTION_CONTINUE_EXECUTIONwhenevermemory.views.count(page)is non-zero will retry any access violation on a mapped page (even outside an active remap or if a view is missing after a partial failure). Scoping retry to an active remap window with bounded retries avoids infinite AV loops.xmem_shim_page_runs_no_retry_controlCTest failure: Running the crashing control under a parent wrapper that verifies the expected0xC0000005termination (and fails on unexpected outcomes) will let CTest pass cleanly instead of reportingSEGFAULT.Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T07:51:58Z.
Review: CHANGES_REQUESTED
Retested
ce9dc423on Windows Release with the RTX 4060 Laptop and WARP. All four selected tests passed, including the wrapped fault control, VirtualQuery after a split, alias readback and the placed-buffer boundary checks.One lifetime blocker remains in
map_pages. The first call registers a process-wide vectored exception handler whose callback is inside xmem.dll. The handle is never unregistered. Windows keeps that registration after FreeLibrary, even though the callback code and state can be gone. Please tie registration to an explicit lifetime that keeps the module/state valid through in-flight callbacks and removes the handler before teardown. Please cover normal unload and reload in a source-built process, then verify an unrelated handled exception is still delivered normally.Microsoft Win32 documentation
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T07:54:00Z.
Review: COMMENTED
Retest & dual-platform review at commit
ce9dc423c126febe84a1e69d6e5b64382fdf66da(sincea78c3322):Checks
git diff --check origin/main...HEAD: passedtests/docs_links_check.py: passed (16 Markdown files, 289 links)tests/bidi_controls_check.py: passed (1093 tracked files)--preset dev):cmake --build --preset dev --target xmem_shim xmem_page_runs_device_check -- -j 6(23.70s),ctest --preset dev -R '^(xmem_shim_mapped_pages|xmem_shim_page_runs|xmem_page_runs_device_warp)$' --parallel 4 --no-tests=error --output-on-failure: 3/3 passed (xmem_shim_mapped_pages0.07s,xmem_page_runs_device_warp0.15s,xmem_shim_page_runs2.61s)/O2(--preset release):cmake --build --preset release --target xmem_shim xmem_page_runs_device_check -- -j 6(36.54s),ctest --preset release -R '^(xmem_shim_mapped_pages|xmem_shim_page_runs|xmem_page_runs_device_warp)$' --parallel 4 --no-tests=error --output-on-failure: 3/3 passed (xmem_shim_mapped_pages0.07s,xmem_page_runs_device_warp0.13s,xmem_shim_page_runs2.55s)Verification of Prior Findings (
a78c3322)~PhysicalMemory()unmappingruns: Fixed —~PhysicalMemory()now unmapsruns(UnmapViewOfFile) and closesslabs.map_pagesnow rolls backmadeon map failure, keepsbatchinmemory.viewsand restores unmapped runs whenUnmapViewOfFile2is refused, and callsforget_pageif a surviving page cannot be remapped.retry_remapped_page: Fixed — scoped toRemapWindow(ranges+generation),thread_localper-page/per-break single retry, and verified againstmemory.views+memory.runsundermemory.mutex.WILL_FAILsegfault control: Fixed —expect_access_violationintests/xmem_page_runs_check.pynow runs bothreader-without-retryandread-forgottenin child processes and verifies0xC0000005+ stdout markers.Remaining Finding
src/xmem_mapped_pages.cpp,map_pages):AddVectoredExceptionHandler(1, retry_remapped_page)is registered once via a function-localstaticand is never unregistered viaRemoveVectoredExceptionHandlerbeforexmem.dllunloads (FreeLibrary/ teardown). Echoing@R0Y00's review: the handler needs explicit lifetime management (unregistering before teardown while synchronizing with any in-flight callback).Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-24T07:43:24Z.
Thanks for running it on Windows, and for the Debug and Release numbers. All points from both reviews are addressed in
ce9dc423(plus a merge ofmain).The control (R0Y00; tedin7 #4). The
WILL_FAILtest is gone.tests/xmem_page_runs_check.pynow runs the two cases that must crash in a child process. The child prints a marker just before the step, and the parent requires the marker, no completion line, and exit code0xC0000005exactly; anything else fails the check with the child's output.Consistent state on failure (R0Y00; tedin7 #2). The unmap path now keeps the record equal to what Windows shows on every way out:
forget_page), counted and logged. Its bytes stay in the section. The batch is unmapped and the call fails.X2W_XMEM_TEST_FAULT=<stage>:<skip>refuses one step of the next unmap so each of the three can be reached. The check asserts, for each: the return value and error,VirtualQuerystate of the affected pages, that the other run is untouched, and that the record agrees (a forgotten run's pages can be released or mapped again and still hold their bytes; a restored run still refuses release).Retry scope (R0Y00; tedin7 #3). The handler no longer answers from registry membership. It retries only when all of these hold: the address is inside a view that the unmap in progress, or the last finished one, took apart (ranges and an in-progress generation are recorded by the unmap); after that unmap has finished, the page is recorded and covered by a view; and this thread has not already retried this page for this unmap. So a fault outside a remap window is passed on at once, and one inside it is retried at most once. The second child case covers the bounded part: it reads a page that lies in the range of the last unmap but was forgotten, and must die with an access violation instead of spinning.
Destructor (tedin7 #1). It unmaps
runs.One more change that the new cases exposed: freed slots were reused last-in-first-out, so pages reused together were no longer adjacent slots and each got a view of its own. They are now reused in address order.
The three comparisons.
VirtualQuerybefore and after splitting a run (query_before_and_after_split): eight pages in one view report the view's base as allocation base and the bytes to the end of the view; after page 3 is unmapped, pages 0-2 and 4-7 report two views with their own bases and page 3 is a reserved placeholder of one page; mapping page 3 again gives three views.two_views): six pages mapped twice, each as one view; writes through each are read through the other for every page; after one page of the first view is unmapped, its neighbours still alias, a write through the second view during the gap is there when the page is mapped again, and release is refused until both views are gone.tests/xmem_page_runs_device_check.cpp,xmem_page_runs_device_warp/_hardware): a two-page buffer through slot 133 inside one view, across two mapping calls, across the boundary between two backing sections inside one call, and across single-page views. Each must returnS_OKwith an object, no device removal, and unchanged memory, and the test first checks withVirtualQuerythat the buffer really touches one or two views. On section-backed pages the wrapper already took the committed, not-aliased path (info.Type != MEM_PRIVATE), so the allocation-base change does not reach placement; the test pins that.Results here, at
ce9dc423, DLLs built with clang-cl against the Windows SDK, CPython 3.12 for Windows under Wine 11.0 with vkd3d-proton on an NVIDIA RTX 4070 Ti SUPER. Translation-layer results,hardwareonly:python -B tests/docs_links_check.pypasses andgit diff --check origin/main...HEADis clean.Still not verified by me:
VirtualQueryexpectations (base, remaining size,MEM_RESERVEfor the hole) are asserted exactly and have only run under Wine; if Windows reports a split differently, that case will fail there and I would like to see the values._warp: there is no WARP here.0xC0000005here; the parent compares the low 32 bits.UnmapViewOfFile2or a remap fail for real from a test.Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-24T07:58:12Z.
Thanks for the retest on the RTX 4060 Laptop and WARP. The lifetime blocker is addressed in
f208f3b6.What changed. The handler's registration is now an object (
FaultRetry) with a lifetime instead of a function-local static that was never undone:add(): the first mapping call registers the handler, as before.remove(): a static destructor, declared after the shim's state so that it runs first, callsRemoveVectoredExceptionHandlerand then waits until no callback is inside the handler (the handler counts entries and exits). Only then are the mutex, the page record and the remap window destroyed. After a reload the first mapping call registers it again.RtlDllShutdownInProgress).Coverage, as asked. A new child case in
tests/xmem_page_runs_check.py, in a process of its own:FreeLibrary, and requireGetModuleHandleWto report the module gone;ctypes) and require it to arrive at its own handler as anOSError;The parent requires exit code 0 and the final marker. Control: with
X2W_XMEM_KEEP_FAULT_RETRY=1the removal is skipped, the registration outlives the module, and the same child must not get its exception delivered. How that ends is not defined (the dispatcher calls an address that is no longer code), so for this one control the parent requires the "unloaded" marker, no "delivered" marker and a non-zero exit code, not a specific code. Here it ends with exit code 1.Results here at
f208f3b6(clang-cl build, CPython 3.12 for Windows under Wine 11.0 with vkd3d-proton, RTX 4070 Ti SUPER; translation-layer,hardwareonly), run twice:One limit I can't close from inside the module. The wait covers callbacks that have entered the handler. A thread whose exception dispatch had already picked this handler from the list but had not yet called it when
RemoveVectoredExceptionHandlerreturned is not something the module can observe; I don't know whether Windows makes the removal wait for that. If it does not, the remaining options are to pin the module while the handler is registered (so it is never unloaded once used) or to move the handler out ofxmem.dll. I chose removal because it is what the review asked for and what the test can show; say if you would rather have the pin.Not verified: Windows. In particular the control's outcome there (I expect a non-zero exit, but have only seen Wine's), and that
xmem.dllhas no other reference in the test process that would keep it loaded after oneFreeLibrary; the test asserts that and will say so if it is wrong.Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T08:14:33Z.
Review: CHANGES_REQUESTED
The serial unload/reload regression is useful. The destructor still waits for another thread from DLL process-detach, under the loader lock. A counter inside the callback also cannot account for all dispatch that may already be in flight, and the Win32 removal contract does not document waiting for quiescence. Please arrange teardown through a supported lifetime that prevents callback dispatch before unloading, outside DLL detach, or remove the process-wide handler from this design. Keep the serial fixture and add a source-built concurrent shutdown check for the supported lifetime. Please move the switch that leaves a callback installed after unload into a test-only build; the deployed DLL should always clean up with its supported lifecycle.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T08:32:05Z.
Review: CHANGES_REQUESTED
Windows Release on
769c83e1passed all four selected tests on RTX 4060 Laptop and WARP, including the concurrent pin/exit children and placed-buffer boundary checks. Please use the opt-in shared-view mode you proposed. Process-lifetime pinning can keep state across a host's unload/reload, so the default should preserve the current one-view-per-page, unloadable behavior. The opt-in can keep the measured fast path and its dedicated tests. In the normal production build please test both default unload after ordinary mapping and opt-in persistence, and document which mode the caller chooses before the first map. The test-only fault switches should remain confined to the separate test target.Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T08:53:19Z.
Review: APPROVED
Retested Windows Release (4/4, no skips). Default one-view-per-page unload/reload and opt-in pinning both pass, as do the dual-view, remap, subprocess controls and RTX/WARP placed-buffer boundary tests. The fault controls are in the dedicated test build.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T08:20:01Z.
Independent Windows timing on head
1988aa97. Five alternating fresh processes per version allocated 6,000 synthetic 64 KiB pages, mapped them contiguously, then removed and restored page 4,095. Both neighbours retained their expected words, and the restored page retained its original word on all ten runs.The contiguous map alone took a median 32.95 ms (30.93–37.30 ms) with the prior per-page implementation and 1.74 ms (1.69–2.15 ms) on this head. The net process handle increase measured from before the grant to immediately after mapping was 6,000 and 2, respectively. This measures a 375 MiB mapping in the source-built scenario. Full startup time, concurrent teardown, and the 100,000-page case were outside this timing run.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T08:22:37Z.
Follow-up at the observed batch size. In 45 saved diagnostic traces the largest logged call mapped 99,776 pages outside the recorded paired CPU/GPU reservations. I reproduced that geometry with synthetic sequential page grants in a separate reservation, with the permissive mapping path and GPU mirror enabled. The historical logs do not establish whether the original grants were sequential.
Three alternating fresh Windows processes per implementation, 99,776 pages of 64 KiB each. Median time inside the mapping call was 583.31 ms before (571.67–591.65) and 54.78 ms on
1988aa97(50.68–61.18). Net new process handles after granting and mapping fell from 99,776 to 25. All six runs preserved the neighbouring words after unmapping page 4,095, recovered that page's original word on remap, and successfully unmapped and freed the full grant. These measurements exclude startup, full-range memory initialization, and GPU submission.Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-24T08:24:55Z.
Agreed on all three points, and thanks for the Windows timing.
769c83e1changes the design rather than patching the teardown.Lifetime. You are right that removal cannot be made safe from inside the module: the wait ran under the loader lock, and a counter in the callback cannot see a dispatch that has picked the handler and not yet entered it. So the handler is no longer removed at all:
xmem.dll(GetModuleHandleExWwithGET_MODULE_HANDLE_EX_FLAG_PIN). From then onFreeLibraryleaves the module, the callback and the shim's state in place until the process ends, so a callback can never run in unloaded code or on destroyed state.RtlDllShutdownInProgresscheck are gone.main), where unmapping a page never takes a neighbour away and no handler is involved.That is the "supported lifetime that prevents callback dispatch before unloading" reading: there is no unloading once the handler exists. If you would rather have no process-wide handler at all, the consequence as far as I can see is giving up shared views wherever a page inside one may be unmapped while another thread uses its neighbours, because Windows cannot unmap part of a view; I could not find a way to keep the 1.7 ms map without one or the other. Say if you prefer that trade and I will make shared views opt-in instead.
Test-only switches.
X2W_XMEM_KEEP_FAULT_RETRYno longer exists. The two remaining controls (X2W_XMEM_NO_FAULT_RETRY,X2W_XMEM_TEST_FAULT) are compiled only underX2W_XMEM_TEST_CONTROLS, into a second targetxmem_shim_test_controlsbuilt from the same sources intoxmem-test-controls/xmem.dll. The check takes both DLLs, uses the test build for the refused-step cases and the two access-violation controls, and asserts that the deployed DLL ignores both switches (an unmap withX2W_XMEM_TEST_FAULTset succeeds; the reader withX2W_XMEM_NO_FAULT_RETRYset survives).Fixtures. The serial case is kept and rewritten for the new lifetime, and there are two concurrent ones. Each runs in a process of its own on the deployed DLL:
lifetime: an unused shim is gone afterFreeLibraryand an unrelated handled access violation is delivered; a used shim (pages sharing a view, one split) is still loaded after threeFreeLibrarycalls, the unrelated exception is still delivered to its own handler, the existing views are still usable, and the reader-while-toggling case still passes.concurrent-shutdown: one thread reads a page, another unmaps and maps its neighbour, and the main thread callsFreeLibraryin a loop for 1.5 s. Required: no error in either thread, no wrong byte, both made progress, the module never unloads, and the threads then stop cleanly with all 64 pages intact.concurrent-exit: the same, then the process exits with both threads still running. Required: exit code 0.Results here at
769c83e1(clang-cl build, CPython 3.12 for Windows under Wine 11.0 with vkd3d-proton, RTX 4070 Ti SUPER; translation-layer,hardwareonly), three consecutive runs of the first:Not verified: Windows, for all of the above. Two things I would look at first there: that
FreeLibraryon a pinned module returns success (the fixture asserts it), and the exit code of the process that ends with its threads running. The fallback to one view per page when the pin fails is not exercised; I do not know how to make the pin fail from a test.Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-24T08:38:51Z.
Done in
9f608935, and thanks for the Windows run on the previous head.Mode. Shared views are now opt-in. The caller chooses before the first mapping call by setting
X2W_XMEM_SHARED_VIEWS=1in the process environment; the shim reads it once, on that call.X2W_XMEM_SHARED_VIEWS=1FreeLibraryxmem.dllIf the opt-in is set and the pin or the registration fails, it is refused and logged, and pages get a view each.
docs/startup-runtime.mdhas the same table and says that a host which needs to unload the shim keeps the default. Nothing intools/startupsets the variable.Tests, production build. Two lifetime children of
tests/xmem_page_runs_check.pyrun on the deployedxmem.dll:default-unload(variable unset): 16 pages mapped contiguously each report a 64 KiB region, one is unmapped and mapped again with its neighbours' bytes intact, the mapping is released,FreeLibraryunloads the module and an unrelated handled access violation is still delivered. A second load maps and unloads again.lifetime(variable set): unchanged from the previous head; an unused shim unloads, a used one stays loaded.The concurrent
FreeLibraryand process-exit children, the large batch,VirtualQueryand reader cases run in the opt-in mode.xmem_page_runs_device_checksets the variable itself before its first map.Test switches. Unchanged:
X2W_XMEM_TEST_FAULTandX2W_XMEM_NO_FAULT_RETRYexist only inxmem_shim_test_controls, and the check still asserts that the deployed DLL ignores both.Results here at
9f608935(clang-cl build, CPython 3.12 for Windows under Wine 11.0 with vkd3d-proton, RTX 4070 Ti SUPER; translation-layer,hardwareonly), first test run twice:Not verified: Windows for this head. In the default mode pages are still slots of the 256 MiB sections (a view each, but not a section each), so your handle-count measurement should hold there while the map time should not; I have not timed the default mode.