runtime: back physical pages with shared sections and map adjacent pages as one view #1299

Merged
JohnConnorNPC merged 10 commits from upstream-pr/1306 into main 2026-11-24 08:54:39 +00:00
JohnConnorNPC commented 2026-11-24 07:24:13 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-24T07:24:13Z.


Refs #870.

Problem

src/xmem_mapped_pages.cpp gives 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

  • Shared sections. A page is a 64 KiB slot of a 256 MiB pagefile-backed section (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.
  • Shared views. In one mapping call, adjacent addresses whose pages are adjacent slots of one section are mapped with a single 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.views still records every page; memory.runs records the real views.
  • Unmapping inside a view. Windows cannot unmap part of a view. The views that hold a page of the batch are unmapped, the batch's pages are dropped, and the surviving pages are mapped again as views.
  • Fault retry. A thread that touches a surviving page in that window takes an access violation. A vectored handler takes the same mutex, and retries the access if the page is mapped; otherwise it passes the exception on. It ignores the mapping thread itself.

x2w_xmem_write_physical maps its temporary view at the page's slot offset.

Behaviour that changes

  • VirtualQuery on a page of a shared view reports the view's base and size, not the page's. d3d12_xs_device.cpp uses 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.
  • After unmapping, the placeholder left behind is the size of the view, not page-sized. Mapping into part of it splits it as before; a range that spans two such placeholders takes the per-page fallback.
  • Callers that pre-split page-sized placeholders (the contract in the comment above map_pages, and what tests/xmem_mapped_pages_check.py does) 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 main at 93cb6a2a. xmem.dll built 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:

Aliased writes, scatter order, remap, rollback, and grant lifetime agree

New tests/xmem_page_runs_check.py (registered as xmem_shim_page_runs):

xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, 196 neighbour toggles under 5786988 reads, reuse zeroed)

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_control with WILL_FAIL: with X2W_XMEM_NO_FAULT_RETRY=1 the 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.dll 100,000 pages mapped in
main at 93cb6a2a 42,897 ms
this branch 82 ms

Whole-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) and git diff --check (clean).

Not measured

  • Windows. I have no Windows host. Neither test has run there, and the timing table is Wine only. If one section and view per page is fast on Windows, the case for this change is the handle count and translation layers, and that may not be worth the added paths; I would rather hear that than have it merged on the Wine numbers alone.
  • MSVC has not compiled this file with the change; CI is the first.
  • The fault-retry handler is a process-wide vectored handler. It returns EXCEPTION_CONTINUE_SEARCH unless the faulting address's page is in memory.views, but I have not looked for other handlers in the stand-ins that it could interact with beyond the __try probes, which target unmapped addresses.
  • A reader that faults repeatedly on a page that is mapped but genuinely inaccessible for another reason would spin. Views are always read-write, so I do not know a way to reach that.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6576793882 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306). Originally posted by [JohnConnorNPC](https://github.com/JohnConnorNPC) on 2026-11-24T07:24:13Z. --- Refs #870. ## Problem `src/xmem_mapped_pages.cpp` gives 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 - **Shared sections.** A page is a 64 KiB slot of a 256 MiB pagefile-backed section (`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. - **Shared views.** In one mapping call, adjacent addresses whose pages are adjacent slots of one section are mapped with a single `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.views` still records every page; `memory.runs` records the real views. - **Unmapping inside a view.** Windows cannot unmap part of a view. The views that hold a page of the batch are unmapped, the batch's pages are dropped, and the surviving pages are mapped again as views. - **Fault retry.** A thread that touches a surviving page in that window takes an access violation. A vectored handler takes the same mutex, and retries the access if the page is mapped; otherwise it passes the exception on. It ignores the mapping thread itself. `x2w_xmem_write_physical` maps its temporary view at the page's slot offset. ## Behaviour that changes - `VirtualQuery` on a page of a shared view reports the view's base and size, not the page's. `d3d12_xs_device.cpp` uses 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. - After unmapping, the placeholder left behind is the size of the view, not page-sized. Mapping into part of it splits it as before; a range that spans two such placeholders takes the per-page fallback. - Callers that pre-split page-sized placeholders (the contract in the comment above `map_pages`, and what `tests/xmem_mapped_pages_check.py` does) 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 `main` at `93cb6a2a`. `xmem.dll` built 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: ``` Aliased writes, scatter order, remap, rollback, and grant lifetime agree ``` New `tests/xmem_page_runs_check.py` (registered as `xmem_shim_page_runs`): ``` xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, 196 neighbour toggles under 5786988 reads, reuse zeroed) ``` 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_control` with `WILL_FAIL`: with `X2W_XMEM_NO_FAULT_RETRY=1` the 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.dll` | 100,000 pages mapped in | |---|---| | `main` at `93cb6a2a` | 42,897 ms | | this branch | 82 ms | Whole-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) and `git diff --check` (clean). ## Not measured - **Windows.** I have no Windows host. Neither test has run there, and the timing table is Wine only. If one section and view per page is fast on Windows, the case for this change is the handle count and translation layers, and that may not be worth the added paths; I would rather hear that than have it merged on the Wine numbers alone. - MSVC has not compiled this file with the change; CI is the first. - The fault-retry handler is a process-wide vectored handler. It returns `EXCEPTION_CONTINUE_SEARCH` unless the faulting address's page is in `memory.views`, but I have not looked for other handlers in the stand-ins that it could interact with beyond the `__try` probes, which target unmapped addresses. - A reader that faults repeatedly on a page that is mapped but genuinely inaccessible for another reason would spin. Views are always read-write, so I do not know a way to reach that.
R0Y00 commented 2026-11-24 08:01:31 +00:00 (Migrated from github.com)

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.views claiming 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 VirtualQuery before 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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6035265973 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6035265973). Originally posted by [R0Y00](https://github.com/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.views` claiming 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 `VirtualQuery` before 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.
tedin7 commented 2026-11-24 08:01:31 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T07:30:11Z.

Review: COMMENTED


Dual-platform review at commit a78c3322a01c5fb036549f088f0f6ac5eaa47849:

Verification

  • Linux:
    • 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)
  • Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP):
    • Debug (--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 with WILL_FAIL TRUE
    • Positive tests (^xmem_shim_(mapped_pages|page_runs)$):
      • Debug (--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)
      • Release /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

  1. ~PhysicalMemory() unmaps views instead of runs (src/xmem_mapped_pages.cpp): ~PhysicalMemory() still iterates views (64 KiB page entries) and calls UnmapViewOfFile(view.first), which will fail on non-head pages of a multi-page run; it should unmap runs (the actual OS view bases) instead.
  2. Inconsistent state on partial unmap/remap failure (src/xmem_mapped_pages.cpp): In the tokens == nullptr branch of map_pages, if UnmapViewOfFile2 fails after unmapping an earlier run, or if map_run fails partway through remapping surviving pages, memory.views still records pages whose Windows views are unmapped (and made is not rolled back on map_run failure).
  3. Unbounded AV retry in retry_remapped_page (src/xmem_mapped_pages.cpp): Returning EXCEPTION_CONTINUE_EXECUTION whenever memory.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.
  4. xmem_shim_page_runs_no_retry_control CTest failure: Running the crashing control under a parent wrapper that verifies the expected 0xC0000005 termination (and fails on unexpected outcomes) will let CTest pass cleanly instead of reporting SEGFAULT.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6035285741 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6035285741). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T07:30:11Z. **Review:** COMMENTED --- Dual-platform review at commit `a78c3322a01c5fb036549f088f0f6ac5eaa47849`: ### Verification - **Linux**: - `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) - **Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP)**: - **Debug (`--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 with `WILL_FAIL TRUE` - **Positive tests (`^xmem_shim_(mapped_pages|page_runs)$`)**: - **Debug (`--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`) - **Release `/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 1. **`~PhysicalMemory()` unmaps `views` instead of `runs` (`src/xmem_mapped_pages.cpp`)**: `~PhysicalMemory()` still iterates `views` (64 KiB page entries) and calls `UnmapViewOfFile(view.first)`, which will fail on non-head pages of a multi-page run; it should unmap `runs` (the actual OS view bases) instead. 2. **Inconsistent state on partial unmap/remap failure (`src/xmem_mapped_pages.cpp`)**: In the `tokens == nullptr` branch of `map_pages`, if `UnmapViewOfFile2` fails after unmapping an earlier run, or if `map_run` fails partway through remapping surviving pages, `memory.views` still records pages whose Windows views are unmapped (and `made` is not rolled back on `map_run` failure). 3. **Unbounded AV retry in `retry_remapped_page` (`src/xmem_mapped_pages.cpp`)**: Returning `EXCEPTION_CONTINUE_EXECUTION` whenever `memory.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. 4. **`xmem_shim_page_runs_no_retry_control` CTest failure**: Running the crashing control under a parent wrapper that verifies the expected `0xC0000005` termination (and fails on unexpected outcomes) will let CTest pass cleanly instead of reporting `SEGFAULT`.
R0Y00 commented 2026-11-24 08:01:32 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T07:51:58Z.

Review: CHANGES_REQUESTED


Retested ce9dc423 on 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

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6035505616 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6035505616). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T07:51:58Z. **Review:** CHANGES_REQUESTED --- Retested ce9dc423 on 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](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-addvectoredexceptionhandler#remarks)
tedin7 commented 2026-11-24 08:01:32 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T07:54:00Z.

Review: COMMENTED


Retest & dual-platform review at commit ce9dc423c126febe84a1e69d6e5b64382fdf66da (since a78c3322):

Checks

  • Linux:
    • git diff --check origin/main...HEAD: passed
    • tests/docs_links_check.py: passed (16 Markdown files, 289 links)
    • tests/bidi_controls_check.py: passed (1093 tracked files)
  • Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP):
    • Debug (--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_pages 0.07s, xmem_page_runs_device_warp 0.15s, xmem_shim_page_runs 2.61s)
    • Release /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_pages 0.07s, xmem_page_runs_device_warp 0.13s, xmem_shim_page_runs 2.55s)

Verification of Prior Findings (a78c3322)

  1. ~PhysicalMemory() unmapping runs: Fixed — ~PhysicalMemory() now unmaps runs (UnmapViewOfFile) and closes slabs.
  2. Inconsistent state on partial unmap/remap failure: Fixed — map_pages now rolls back made on map failure, keeps batch in memory.views and restores unmapped runs when UnmapViewOfFile2 is refused, and calls forget_page if a surviving page cannot be remapped.
  3. Unbounded AV retry in retry_remapped_page: Fixed — scoped to RemapWindow (ranges + generation), thread_local per-page/per-break single retry, and verified against memory.views + memory.runs under memory.mutex.
  4. CTest WILL_FAIL segfault control: Fixed — expect_access_violation in tests/xmem_page_runs_check.py now runs both reader-without-retry and read-forgotten in child processes and verifies 0xC0000005 + stdout markers.

Remaining Finding

  • Unregistered VEH on DLL unload (src/xmem_mapped_pages.cpp, map_pages): AddVectoredExceptionHandler(1, retry_remapped_page) is registered once via a function-local static and is never unregistered via RemoveVectoredExceptionHandler before xmem.dll unloads (FreeLibrary / teardown). Echoing @R0Y00's review: the handler needs explicit lifetime management (unregistering before teardown while synchronizing with any in-flight callback).
<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6035526017 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6035526017). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T07:54:00Z. **Review:** COMMENTED --- Retest & dual-platform review at commit `ce9dc423c126febe84a1e69d6e5b64382fdf66da` (since `a78c3322`): ### Checks - **Linux**: - `git diff --check origin/main...HEAD`: passed - `tests/docs_links_check.py`: passed (16 Markdown files, 289 links) - `tests/bidi_controls_check.py`: passed (1093 tracked files) - **Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP)**: - **Debug (`--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_pages` `0.07s`, `xmem_page_runs_device_warp` `0.15s`, `xmem_shim_page_runs` `2.61s`) - **Release `/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_pages` `0.07s`, `xmem_page_runs_device_warp` `0.13s`, `xmem_shim_page_runs` `2.55s`) ### Verification of Prior Findings (`a78c3322`) 1. **`~PhysicalMemory()` unmapping `runs`**: **Fixed** — `~PhysicalMemory()` now unmaps `runs` (`UnmapViewOfFile`) and closes `slabs`. 2. **Inconsistent state on partial unmap/remap failure**: **Fixed** — `map_pages` now rolls back `made` on map failure, keeps `batch` in `memory.views` and restores unmapped runs when `UnmapViewOfFile2` is refused, and calls `forget_page` if a surviving page cannot be remapped. 3. **Unbounded AV retry in `retry_remapped_page`**: **Fixed** — scoped to `RemapWindow` (`ranges` + `generation`), `thread_local` per-page/per-break single retry, and verified against `memory.views` + `memory.runs` under `memory.mutex`. 4. **CTest `WILL_FAIL` segfault control**: **Fixed** — `expect_access_violation` in `tests/xmem_page_runs_check.py` now runs both `reader-without-retry` and `read-forgotten` in child processes and verifies `0xC0000005` + stdout markers. ### Remaining Finding - **Unregistered VEH on DLL unload (`src/xmem_mapped_pages.cpp`, `map_pages`)**: `AddVectoredExceptionHandler(1, retry_remapped_page)` is registered once via a function-local `static` and is never unregistered via `RemoveVectoredExceptionHandler` before `xmem.dll` unloads (`FreeLibrary` / teardown). Echoing `@R0Y00`'s review: the handler needs explicit lifetime management (unregistering before teardown while synchronizing with any in-flight callback).
JohnConnorNPC commented 2026-11-24 08:01:40 +00:00 (Migrated from github.com)

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 of main).

The control (R0Y00; tedin7 #4). The WILL_FAIL test is gone. tests/xmem_page_runs_check.py now 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 code 0xC0000005 exactly; 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:

  • An unmap refused part of the way: the views already unmapped are mapped again whole, nothing is removed from the record, and the call fails with that error.
  • A surviving page that cannot be mapped again (as a group, then on its own): it is removed from the record (forget_page), counted and logged. Its bytes stay in the section. The batch is unmapped and the call fails.
  • If the restore after a refused unmap also fails, those pages are forgotten the same way.

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, VirtualQuery state 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.

  • VirtualQuery before 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 simultaneous views of the same backing (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.
  • Placed-buffer boundary (new 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 return S_OK with an object, no device removal, and unchanged memory, and the test first checks with VirtualQuery that 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, hardware only:

xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 197 neighbour toggles under 5747425 reads, 2 access-violation controls)
Aliased writes, scatter order, remap, rollback, and grant lifetime agree

inside one view: 1 view(s), slot 133 -> 0x00000000, object created, memory unchanged
across two mapping calls: 2 view(s), slot 133 -> 0x00000000, object created, memory unchanged
across two backing sections: 2 view(s), slot 133 -> 0x00000000, object created, memory unchanged
across two single-page views: 2 view(s), slot 133 -> 0x00000000, object created, memory unchanged
xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary)

python -B tests/docs_links_check.py passes and git diff --check origin/main...HEAD is clean.

Still not verified by me:

  • Windows. In particular the VirtualQuery expectations (base, remaining size, MEM_RESERVE for 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.
  • The child's exit code under CTest on Windows. It is 0xC0000005 here; the parent compares the low 32 bits.
  • A real refusal by Windows. The three failure cases are injected; I do not know a way to make UnmapViewOfFile2 or a remap fail for real from a test.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7125299614 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#issuecomment-7125299614). Originally posted by [JohnConnorNPC](https://github.com/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 of `main`). **The control (R0Y00; tedin7 #4).** The `WILL_FAIL` test is gone. `tests/xmem_page_runs_check.py` now 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 code `0xC0000005` exactly; 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: - An unmap refused part of the way: the views already unmapped are mapped again whole, nothing is removed from the record, and the call fails with that error. - A surviving page that cannot be mapped again (as a group, then on its own): it is removed from the record (`forget_page`), counted and logged. Its bytes stay in the section. The batch is unmapped and the call fails. - If the restore after a refused unmap also fails, those pages are forgotten the same way. `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, `VirtualQuery` state 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.** - *`VirtualQuery` before 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 simultaneous views of the same backing* (`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. - *Placed-buffer boundary* (new `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 return `S_OK` with an object, no device removal, and unchanged memory, and the test first checks with `VirtualQuery` that 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, `hardware` only: ``` xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 197 neighbour toggles under 5747425 reads, 2 access-violation controls) Aliased writes, scatter order, remap, rollback, and grant lifetime agree inside one view: 1 view(s), slot 133 -> 0x00000000, object created, memory unchanged across two mapping calls: 2 view(s), slot 133 -> 0x00000000, object created, memory unchanged across two backing sections: 2 view(s), slot 133 -> 0x00000000, object created, memory unchanged across two single-page views: 2 view(s), slot 133 -> 0x00000000, object created, memory unchanged xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary) ``` `python -B tests/docs_links_check.py` passes and `git diff --check origin/main...HEAD` is clean. **Still not verified by me:** - Windows. In particular the `VirtualQuery` expectations (base, remaining size, `MEM_RESERVE` for 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. - The child's exit code under CTest on Windows. It is `0xC0000005` here; the parent compares the low 32 bits. - A real refusal by Windows. The three failure cases are injected; I do not know a way to make `UnmapViewOfFile2` or a remap fail for real from a test.
JohnConnorNPC commented 2026-11-24 08:01:41 +00:00 (Migrated from github.com)

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, calls RemoveVectoredExceptionHandler and 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.
  • During process termination it removes the handler but does not wait: other threads are already gone and one may have been stopped inside the handler (RtlDllShutdownInProgress).

Coverage, as asked. A new child case in tests/xmem_page_runs_check.py, in a process of its own:

  1. load the shim, map 16 pages, split a view and put the page back (the handler is registered), unmap and release;
  2. FreeLibrary, and require GetModuleHandleW to report the module gone;
  3. take an unrelated access violation (a read of address 1 through ctypes) and require it to arrive at its own handler as an OSError;
  4. load the shim again and run the reader-while-toggling case for half a second, which needs the handler to work;
  5. unload again and take the unrelated exception again.

The parent requires exit code 0 and the final marker. Control: with X2W_XMEM_KEEP_FAULT_RETRY=1 the 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, hardware only), run twice:

xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 195 neighbour toggles under 5789700 reads, unload and reload with its stale-handler control, 2 access-violation controls)
Aliased writes, scatter order, remap, rollback, and grant lifetime agree
xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary)

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 RemoveVectoredExceptionHandler returned 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 of xmem.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.dll has no other reference in the test process that would keep it loaded after one FreeLibrary; the test asserts that and will say so if it is wrong.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7125574294 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#issuecomment-7125574294). Originally posted by [JohnConnorNPC](https://github.com/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, calls `RemoveVectoredExceptionHandler` and 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. - During process termination it removes the handler but does not wait: other threads are already gone and one may have been stopped inside the handler (`RtlDllShutdownInProgress`). **Coverage, as asked.** A new child case in `tests/xmem_page_runs_check.py`, in a process of its own: 1. load the shim, map 16 pages, split a view and put the page back (the handler is registered), unmap and release; 2. `FreeLibrary`, and require `GetModuleHandleW` to report the module gone; 3. take an unrelated access violation (a read of address 1 through `ctypes`) and require it to arrive at its own handler as an `OSError`; 4. load the shim again and run the reader-while-toggling case for half a second, which needs the handler to work; 5. unload again and take the unrelated exception again. The parent requires exit code 0 and the final marker. **Control:** with `X2W_XMEM_KEEP_FAULT_RETRY=1` the 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, `hardware` only), run twice: ``` xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 195 neighbour toggles under 5789700 reads, unload and reload with its stale-handler control, 2 access-violation controls) Aliased writes, scatter order, remap, rollback, and grant lifetime agree xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary) ``` **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 `RemoveVectoredExceptionHandler` returned 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 of `xmem.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.dll` has no other reference in the test process that would keep it loaded after one `FreeLibrary`; the test asserts that and will say so if it is wrong.
upstream-sync closed this pull request 2026-11-24 09:04:26 +00:00
R0Y00 commented 2026-11-24 09:04:27 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6035752362 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6035752362). Originally posted by [R0Y00](https://github.com/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.
R0Y00 commented 2026-11-24 09:04:27 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T08:32:05Z.

Review: CHANGES_REQUESTED


Windows Release on 769c83e1 passed 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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6035960309 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6035960309). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T08:32:05Z. **Review:** CHANGES_REQUESTED --- Windows Release on 769c83e1 passed 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.
R0Y00 commented 2026-11-24 09:04:27 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6036218882 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#pullrequestreview-6036218882). Originally posted by [R0Y00](https://github.com/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.
R0Y00 commented 2026-11-24 09:04:44 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7126006081 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#issuecomment-7126006081). Originally posted by [R0Y00](https://github.com/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.
R0Y00 commented 2026-11-24 09:04:44 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7126058979 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#issuecomment-7126058979). Originally posted by [R0Y00](https://github.com/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.
JohnConnorNPC commented 2026-11-24 09:04:44 +00:00 (Migrated from github.com)

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. 769c83e1 changes 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:

  • The first mapping call registers the handler and pins xmem.dll (GetModuleHandleExW with GET_MODULE_HANDLE_EX_FLAG_PIN). From then on FreeLibrary leaves 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.
  • Nothing is removed, waited for or torn down at DLL detach. The static destructor, the in-flight counter and the RtlDllShutdownInProgress check are gone.
  • A shim that never maps a page is not pinned and unloads like any DLL.
  • Shared views exist only under that guarantee. If the pin or the registration fails, every page gets a view of its own (the layout on 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_RETRY no longer exists. The two remaining controls (X2W_XMEM_NO_FAULT_RETRY, X2W_XMEM_TEST_FAULT) are compiled only under X2W_XMEM_TEST_CONTROLS, into a second target xmem_shim_test_controls built from the same sources into xmem-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 with X2W_XMEM_TEST_FAULT set succeeds; the reader with X2W_XMEM_NO_FAULT_RETRY set 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 after FreeLibrary and an unrelated handled access violation is delivered; a used shim (pages sharing a view, one split) is still loaded after three FreeLibrary calls, 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 calls FreeLibrary in 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, hardware only), three consecutive runs of the first:

xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 194 neighbour toggles under 5815009 reads, pinned lifetime, FreeLibrary and process exit under running threads, 2 access-violation controls)
Aliased writes, scatter order, remap, rollback, and grant lifetime agree
xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary)

Not verified: Windows, for all of the above. Two things I would look at first there: that FreeLibrary on 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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7126105775 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#issuecomment-7126105775). Originally posted by [JohnConnorNPC](https://github.com/JohnConnorNPC) on 2026-11-24T08:24:55Z. --- Agreed on all three points, and thanks for the Windows timing. `769c83e1` changes 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: - The first mapping call registers the handler **and pins `xmem.dll`** (`GetModuleHandleExW` with `GET_MODULE_HANDLE_EX_FLAG_PIN`). From then on `FreeLibrary` leaves 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. - Nothing is removed, waited for or torn down at DLL detach. The static destructor, the in-flight counter and the `RtlDllShutdownInProgress` check are gone. - A shim that never maps a page is not pinned and unloads like any DLL. - Shared views exist only under that guarantee. If the pin or the registration fails, every page gets a view of its own (the layout on `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_RETRY` no longer exists. The two remaining controls (`X2W_XMEM_NO_FAULT_RETRY`, `X2W_XMEM_TEST_FAULT`) are compiled only under `X2W_XMEM_TEST_CONTROLS`, into a second target `xmem_shim_test_controls` built from the same sources into `xmem-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 with `X2W_XMEM_TEST_FAULT` set succeeds; the reader with `X2W_XMEM_NO_FAULT_RETRY` set 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 after `FreeLibrary` and an unrelated handled access violation is delivered; a used shim (pages sharing a view, one split) is still loaded after three `FreeLibrary` calls, 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 calls `FreeLibrary` in 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, `hardware` only), three consecutive runs of the first: ``` xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 194 neighbour toggles under 5815009 reads, pinned lifetime, FreeLibrary and process exit under running threads, 2 access-violation controls) Aliased writes, scatter order, remap, rollback, and grant lifetime agree xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary) ``` **Not verified:** Windows, for all of the above. Two things I would look at first there: that `FreeLibrary` on 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.
JohnConnorNPC commented 2026-11-24 09:04:46 +00:00 (Migrated from github.com)

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=1 in the process environment; the shim reads it once, on that call.

Default X2W_XMEM_SHARED_VIEWS=1
Views one per page one per run of adjacent pages
Fault handler none registered registered by the first mapping call, never removed
FreeLibrary unloads xmem.dll module pinned until the process ends

If 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.md has the same table and says that a host which needs to unload the shim keeps the default. Nothing in tools/startup sets the variable.

Tests, production build. Two lifetime children of tests/xmem_page_runs_check.py run on the deployed xmem.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, FreeLibrary unloads 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 FreeLibrary and process-exit children, the large batch, VirtualQuery and reader cases run in the opt-in mode. xmem_page_runs_device_check sets the variable itself before its first map.

Test switches. Unchanged: X2W_XMEM_TEST_FAULT and X2W_XMEM_NO_FAULT_RETRY exist only in xmem_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, hardware only), first test run twice:

xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 195 neighbour toggles under 5741540 reads, default mode unloads after mapping, opt-in stays pinned, FreeLibrary and process exit under running threads, 2 access-violation controls)
Aliased writes, scatter order, remap, rollback, and grant lifetime agree
live physical-page sections: grant=0 mapped=2 unmapped=2 released=0; page-token write created and released 1
xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary)

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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7126389132 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1306#issuecomment-7126389132). Originally posted by [JohnConnorNPC](https://github.com/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=1` in the process environment; the shim reads it once, on that call. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| | Views | one per page | one per run of adjacent pages | | Fault handler | none registered | registered by the first mapping call, never removed | | `FreeLibrary` | unloads `xmem.dll` | module pinned until the process ends | If 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.md` has the same table and says that a host which needs to unload the shim keeps the default. Nothing in `tools/startup` sets the variable. **Tests, production build.** Two lifetime children of `tests/xmem_page_runs_check.py` run on the deployed `xmem.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, `FreeLibrary` unloads 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 `FreeLibrary` and process-exit children, the large batch, `VirtualQuery` and reader cases run in the opt-in mode. `xmem_page_runs_device_check` sets the variable itself before its first map. **Test switches.** Unchanged: `X2W_XMEM_TEST_FAULT` and `X2W_XMEM_NO_FAULT_RETRY` exist only in `xmem_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, `hardware` only), first test run twice: ``` xmem_page_runs: PASS (6000 pages mapped in 4 ms, 5 holes, VirtualQuery before and after a split, two views, 3 refused steps, 195 neighbour toggles under 5741540 reads, default mode unloads after mapping, opt-in stays pinned, FreeLibrary and process exit under running threads, 2 access-violation controls) Aliased writes, scatter order, remap, rollback, and grant lifetime agree live physical-page sections: grant=0 mapped=2 unmapped=2 released=0; page-token write created and released 1 xmem_page_runs_device: PASS (a buffer inside one view and across three kinds of view boundary) ``` **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.
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
R0Y00/Xbox2Windows!1299
No description provided.