From eb587ad63f1237fe23c1e5b71ca0f53115d6f7bf Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:18:25 +0100 Subject: [PATCH 1/5] xmem: commit mapped physical pages on first touch (X2W_XMEM_LAZY_COMMIT, #1199) Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 8 ++ docs/experiments.md | 28 +++++ docs/startup-runtime.md | 5 +- src/startup_stubs/d3d12_xs_device.cpp | 4 +- src/startup_stubs/local_log.h | 14 +++ src/startup_stubs/xcrdapi.cpp | 1 + src/xmem_mapped_pages.cpp | 143 +++++++++++++++++++++++-- src/xmem_shim.def | 1 + tests/xmem_lazy_commit_check.py | 148 ++++++++++++++++++++++++++ 9 files changed, 344 insertions(+), 8 deletions(-) create mode 100644 tests/xmem_lazy_commit_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d301b2b72..2d5749b14f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -221,6 +221,14 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/xmem_mapped_pages_commit_check.py" "$" failure) set_tests_properties(xmem_mapped_pages_commit xmem_mapped_pages_commit_failure PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE) set_tests_properties(xmem_mapped_pages_commit_failure PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_COMMIT_FAILURE=1") + # X2W_XMEM_LAZY_COMMIT=1: pages committed on first touch; kernel writes need x2w_xmem_commit_range (#1199). + add_test(NAME xmem_lazy_commit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_lazy_commit_check.py" "$") + set_tests_properties(xmem_lazy_commit PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=1") + # Control: with the switch off, mapping commits every page as before. + add_test(NAME xmem_lazy_commit_off COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_lazy_commit_check.py" "$" off) + set_tests_properties(xmem_lazy_commit_off PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=0") add_test(NAME startup_heartbeat_commit COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_heartbeat_check.py" "$" "$") diff --git a/docs/experiments.md b/docs/experiments.md index f8a077fc56..3616c01cbc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8861,6 +8861,34 @@ cmake --build --preset dev --target xmem_startup_below_40_check ctest --preset dev --no-tests=error -R '^xmem_startup_below_40' -V ``` +### Mapped pages committed on first touch + +Experimental, for [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199). Physical pages are 64 KiB slots of `SEC_RESERVE` slabs (see [Startup memory accounting](startup-runtime.md#startup-memory-accounting)). By default a fresh slot is committed when its page is first mapped. A startup run maps far more pages than it touches before the main load, and slab commit is charged to the system commit limit, not to the process. On a 16 GB host this pushes the system to its commit limit during the load. + +`X2W_XMEM_LAZY_COMMIT=1` leaves a fresh slot uncommitted when its page is mapped. The first CPU access faults, and a vectored exception handler installed when `xmem.dll` loads commits that slot and resumes the thread. A thread that loses the race to commit the same slot finds it committed and retries once. GPU-view addresses resolve to the CPU-view slot (the same section). Reused slots and `x2w_xmem_write_physical` still commit before use, as before. + +Some writers cannot fault a slot in, so they commit the range first through the experimental export `x2w_xmem_commit_range(address, bytes)`: + +- **Kernel-mode I/O.** `ReadFile` into an uncommitted mapped page fails with `ERROR_NOACCESS` instead of faulting. The main module's `ReadFile` import is wrapped to commit the buffer first. +- **GPU placement.** Device slot 133 commits a placed buffer's range before it measures the allocation. +- **Stand-in writes behind a commit check**, such as the DirectStorage destination check. + +Without the switch, nothing changes: no handler is installed, no import is wrapped, and `x2w_xmem_commit_range` returns TRUE. + +Measured in startup runs on Windows 10 22H2 (16 GB RAM, RTX 3080 Ti), same build and input, two runs each, with `-MemoryGiB 16`: system commit stayed about 5 GiB lower from 20 s to 170 s (23.3–24.6 GiB against 29.0–29.5 GiB), and 1.6 to 3.1 GiB lower in the late load, when most mapped pages have been touched. The process's own commit charge was the same with and without the switch. Where a run ends was not changed: on that host the late load also reaches the process commit cap. + +| CTest case | Inputs and checks | +|---|---| +| `xmem_lazy_commit` | With the switch: mapping 1,024 pages (64 MiB) grows system commit by less than 24 MiB, and the pages stay `MEM_RESERVE`. A CPU write commits only its page, reads back, and the rest of the page reads zero. `ReadFile` into an untouched page fails with `ERROR_NOACCESS`; after `x2w_xmem_commit_range` the same read succeeds. Eight threads writing to the same 32 untouched pages at once all succeed. Released pages are zero-filled when their slots are reused. | +| `xmem_lazy_commit_off` | Control, with `X2W_XMEM_LAZY_COMMIT=0`: the same 1,024-page mapping commits every page when it is mapped (system commit grows by about 64 MiB), and `x2w_xmem_commit_range` returns TRUE. | + +The other `xmem_` cases run without the switch and check that the default path is unchanged. + +```powershell +cmake --build --preset release --target xmem_shim +ctest --preset release --no-tests=error -R '^xmem_' -V +``` + ### Second commit and protection comparison `xmem_commit_protection` ([`tests/xmem_commit_protection_check.cpp`](../tests/xmem_commit_protection_check.cpp)) is a source-built x64 check for [#870](https://github.com/R0Y00/Xbox2Windows/issues/870) using synthetic 64 KiB page patterns. Its scope is separate from the first-commit alignment/zero-fill/rounding check (`xmem_committed_memory`), the reserve-only profile in [#888](https://github.com/R0Y00/Xbox2Windows/pull/888), and the device/queue work in [#874](https://github.com/R0Y00/Xbox2Windows/issues/874). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index dfd07921b4..721adc5fac 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -957,6 +957,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr |---|---| | `X2W_XMEM_PERMISSIVE=1` | accepts the reservation, mapping and allocation shapes a startup run uses | | `X2W_XMEM_STARTUP_BELOW_40=1` (`run.ps1 -StartupBelow40`) | startup compatibility configuration ([#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758)): the large-page startup blocks with attribute `0x283` (null address, type `0x20003000`, protection `0x2004` or `0x2404`) are placed so that the whole block, last byte included, lies below 2^40. A block that does not fit there returns NULL with the Windows error and logs `x2w-xmem startup block below 2^40 refused:`; nothing is truncated or placed higher. Other shapes and explicit addresses keep their placement. See [Startup blocks below 2^40](experiments.md#startup-blocks-below-240) | +| `X2W_XMEM_LAZY_COMMIT=1` | experimental ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): a fresh physical-page slot is committed on its first CPU access instead of when its page is mapped. A vectored exception handler commits the slot. Writers that cannot fault one in (the main module's `ReadFile`, slot 133 placement, stand-in writes behind a commit check) call `x2w_xmem_commit_range` first. See [Mapped pages committed on first touch](experiments.md#mapped-pages-committed-on-first-touch) | | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | @@ -1916,7 +1917,9 @@ committed, is zeroed on reuse, and is chosen before a fresh slot. The experiment export reports open slabs and used and free slots. `xmem_slab_slots` checks the bookkeeping without Windows calls. `xmem_mapped_pages_commit` measures commit for a small map, and `xmem_mapped_pages_commit_failure` injects a commitment failure and checks that the reservation and slab counts are unchanged and the pages -can be mapped on retry. Caller-owned placeholders must already match the requested view size. The +can be mapped on retry. With the experimental `X2W_XMEM_LAZY_COMMIT=1`, a fresh slot waits for its first +CPU access instead of its mapping (see [Mapped pages committed on first touch](experiments.md#mapped-pages-committed-on-first-touch)). +Caller-owned placeholders must already match the requested view size. The heartbeat also prints while the request counters are unchanged when either memory value changed, so the cost of a stalled load is visible. Each report is followed by a line of failed requests by cause and a line of page-destination requests by end (see diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0450fd8b4c..4dfd1fcab7 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3229,7 +3229,9 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 } // The allocation holding the address, and whether every byte from its base to the end of the // buffer is committed in it: one region-information call for a fully committed private - // allocation, otherwise a region walk that stops at the end of the buffer. + // allocation, otherwise a region walk that stops at the end of the buffer. The GPU cannot fault in a lazily + // mapped physical page (X2W_XMEM_LAZY_COMMIT), so the buffer's pages are committed first. + x2w_local::commit_lazy(address, static_cast(desc->Width)); x2w_startup::PlacedBufferRange range; const bool committed = x2w_startup::measure_placed_buffer(address, desc->Width, range); InterlockedIncrement64(&placed_buffer_calls); diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index 330faf7652..ebfc1cd645 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -82,12 +82,26 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc return done; } +// With X2W_XMEM_LAZY_COMMIT, physical pages are committed on first touch (xmem_mapped_pages.cpp). A check of the +// commit state, or a write that cannot fault (kernel I/O, GPU), commits the range first. A no-op without xmem.dll +// or without the switch. +inline void commit_lazy(const void* pointer, std::size_t bytes) noexcept +{ + using CommitRange = BOOL(WINAPI*)(const void*, SIZE_T); + static const CommitRange commit_range = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_commit_range")) : nullptr; + }(); + if (commit_range) commit_range(pointer, bytes); +} + // Readability by probing (see probe_readable); writability by one VirtualQuery (rare callers). inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexcept { const auto start = reinterpret_cast(pointer); if (start < 0x10000 || start > 0x00007FFFFFFEFFFFull || bytes == 0) return false; if (!write) return probe_readable(start, bytes) == bytes; + commit_lazy(pointer, bytes); MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(pointer, &info, sizeof(info)) || info.State != MEM_COMMIT) return false; const DWORD protect = info.Protect & 0xFF; diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index fb84c1e3f5..64e17e0bec 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -159,6 +159,7 @@ static bool destination_writable(const void* destination, std::size_t bytes) if (bytes == 0) return true; std::uintptr_t cursor = reinterpret_cast(destination); if (!destination || bytes > UINTPTR_MAX - cursor) return false; + x2w_local::commit_lazy(destination, bytes); // lazily mapped physical pages (X2W_XMEM_LAZY_COMMIT) const std::uintptr_t end = cursor + bytes; while (cursor < end) { MEMORY_BASIC_INFORMATION info{}; diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index f447f8d063..c2dc2e7a7c 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -24,6 +24,7 @@ struct Backing { ULONG_PTR views = 0; ULONG64 offset = 0; // the page is one 64 KiB slot of a shared section (see section_for) std::size_t slab = 0; // index of that section among the slabs + bool committed = true; // false while a lazily mapped slot is untouched (X2W_XMEM_LAZY_COMMIT) }; // Keep grant transitions and section views serialized. A grant can outlive all its @@ -99,11 +100,67 @@ bool commit_slot(HANDLE slab, ULONG64 offset, bool zero) return ok; } -HANDLE section_for(ULONG_PTR page) +// Experimental (X2W_XMEM_LAZY_COMMIT=1, #1199): a fresh slot is not committed when its page is mapped. The first +// CPU access faults and lazy_commit_fault commits that slot. Writers that do not fault -- kernel-mode I/O into +// mapped pages, GPU placement, stand-in writes behind a commit-state check -- call x2w_xmem_commit_range first. +// Reused slots and x2w_xmem_write_physical still commit before use. +bool lazy_commit() +{ + static const bool on = x2w_local::env_on("X2W_XMEM_LAZY_COMMIT"); + return on; +} + +// Commits a lazily mapped slot under memory.mutex; false with the system error if the commit fails. +bool commit_backing(Backing& backing) +{ + if (backing.committed) return true; + if (!commit_slot(backing.section, backing.offset, false)) return false; + backing.committed = true; + return true; +} + +// The backing behind a mapped address (CPU view, or its GPU-view mirror), under memory.mutex. +Backing* backing_at(ULONG_PTR address) +{ + if (memory.mirror_bytes && address - memory.mirror_gpu < memory.mirror_bytes) + address = address - memory.mirror_gpu + memory.mirror_cpu; // the GPU view shows the same section + const auto view = memory.views.find(address & ~(ULONG_PTR{page_bytes} - 1)); + if (view == memory.views.end()) return nullptr; + const auto backing = memory.backings.find(view->second); + return backing == memory.backings.end() ? nullptr : &backing->second; +} + +LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) +{ + const EXCEPTION_RECORD* record = e->ExceptionRecord; + if (record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH; + const ULONG_PTR address = record->ExceptionInformation[1]; + // A thread that raced another one to the same slot finds it committed: retry once, then pass the fault on. + thread_local ULONG_PTR retried = 0; + const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); + const std::lock_guard guard(memory.mutex); + Backing* backing = backing_at(address); + if (!backing) return EXCEPTION_CONTINUE_SEARCH; + if (backing->committed) { + if (retried == page) return EXCEPTION_CONTINUE_SEARCH; + retried = page; + return EXCEPTION_CONTINUE_EXECUTION; + } + if (!commit_backing(*backing)) return EXCEPTION_CONTINUE_SEARCH; + retried = 0; + return EXCEPTION_CONTINUE_EXECUTION; +} + +HANDLE section_for(ULONG_PTR page, bool need_commit = true) { const auto existing = memory.backings.find(page); - if (existing != memory.backings.end()) + if (existing != memory.backings.end()) { + if (need_commit && !commit_backing(existing->second)) return nullptr; return existing->second.section; + } + // A fresh slot (never used) of a SEC_RESERVE slab reads as zero once committed, so it can wait for its first + // touch. A reused slot is committed and zeroed now, as before. + const bool defer = !need_commit && lazy_commit(); x2w_xmem::SlabSlots::Slot slot; if (memory.slots.lowest_free(slot)) { if (!commit_slot(slot.slab, slot.offset, true)) return nullptr; @@ -113,10 +170,11 @@ HANDLE section_for(ULONG_PTR page) } const ULONG64 slab_bytes = memory.slots.slab_bytes(); bool first_slot_committed = false; - const auto make_slab = [slab_bytes, &first_slot_committed](HANDLE& slab) { + const auto make_slab = [slab_bytes, &first_slot_committed, defer](HANDLE& slab) { slab = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, static_cast(slab_bytes >> 32), static_cast(slab_bytes), nullptr); if (!slab) return false; + if (defer) return true; first_slot_committed = commit_slot(slab, 0, false); if (!first_slot_committed) { const DWORD error = GetLastError(); @@ -126,14 +184,14 @@ HANDLE section_for(ULONG_PTR page) return first_slot_committed; }; if (!memory.slots.take_fresh(make_slab, [](HANDLE slab) { CloseHandle(slab); }, slot)) return nullptr; - if (!first_slot_committed && !commit_slot(slot.slab, slot.offset, false)) { + if (!defer && !first_slot_committed && !commit_slot(slot.slab, slot.offset, false)) { const DWORD error = GetLastError(); memory.slots.unwind_fresh(slot); SetLastError(error); return nullptr; } try { - memory.backings.emplace(page, Backing{slot.slab, 0, slot.offset, slot.slab_index}); + memory.backings.emplace(page, Backing{slot.slab, 0, slot.offset, slot.slab_index, !defer}); } catch (...) { memory.slots.unwind_fresh(slot); throw; @@ -468,7 +526,7 @@ BOOL map_pages(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& addres // multi-gigabyte batch then takes a few views instead of one per 64 KiB page. if (tokens) { for (const auto& [address, page] : batch) { - if (!section_for(page)) return FALSE; + if (!section_for(page, false)) return FALSE; // committed on first touch with X2W_XMEM_LAZY_COMMIT } std::vector> made; auto first = batch.begin(); @@ -782,6 +840,79 @@ extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in return TRUE; } +// Experimental export (X2W_XMEM_LAZY_COMMIT): commits the lazily mapped slots behind [address, address + bytes) +// before a writer that cannot fault one in uses the range: kernel-mode I/O into mapped pages fails with +// STATUS_ACCESS_VIOLATION instead of faulting, and the GPU reads and writes placed resources without the CPU. +// GPU-view addresses resolve to the same slots. TRUE without the switch or when nothing in the range is lazy; +// FALSE with the system error when a commit fails. +extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) +{ + if (!lazy_commit() || !address || !bytes) return TRUE; + const auto start = reinterpret_cast(address); + const ULONG_PTR end = bytes > ~ULONG_PTR{0} - start ? ~ULONG_PTR{0} : start + bytes; + const std::lock_guard guard(memory.mutex); + for (ULONG_PTR page = start & ~(ULONG_PTR{page_bytes} - 1); page < end; page += page_bytes) { + Backing* backing = backing_at(page); + if (backing && !commit_backing(*backing)) return FALSE; + if (page > ~ULONG_PTR{0} - page_bytes) break; + } + return TRUE; +} + +namespace { +// The title reads files straight into mapped physical pages; a kernel-mode write into an uncommitted slot fails +// with STATUS_ACCESS_VIOLATION (no fault), so with X2W_XMEM_LAZY_COMMIT the main module's ReadFile import commits +// the buffer first. +using ReadFileFn = BOOL(WINAPI*)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED); +ReadFileFn real_read_file; + +BOOL WINAPI read_file_committed(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) +{ + if (buffer && bytes && !x2w_xmem_commit_range(buffer, bytes)) return FALSE; + return real_read_file(file, buffer, bytes, read, overlapped); +} + +// Points the main module's imports of name at replacement; returns how many import slots were changed. +int patch_main_import(const char* name, const void* replacement) noexcept +{ + auto* base = reinterpret_cast(GetModuleHandleW(nullptr)); + if (!base) return 0; + const auto* nt = reinterpret_cast(base + reinterpret_cast(base)->e_lfanew); + const IMAGE_DATA_DIRECTORY& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + int patched = 0; + for (auto* imp = reinterpret_cast(base + dir.VirtualAddress); dir.Size && imp->Name; ++imp) { + const auto* names = reinterpret_cast(base + (imp->OriginalFirstThunk ? imp->OriginalFirstThunk : imp->FirstThunk)); + auto* slots = reinterpret_cast(base + imp->FirstThunk); + for (; names->u1.AddressOfData; ++names, ++slots) { + if (IMAGE_SNAP_BY_ORDINAL64(names->u1.Ordinal)) continue; + const auto* by_name = reinterpret_cast(base + names->u1.AddressOfData); + if (std::strcmp(reinterpret_cast(by_name->Name), name) != 0) continue; + DWORD old = 0; + if (!VirtualProtect(&slots->u1.Function, sizeof(slots->u1.Function), PAGE_READWRITE, &old)) continue; + slots->u1.Function = reinterpret_cast(replacement); + VirtualProtect(&slots->u1.Function, sizeof(slots->u1.Function), old, &old); + ++patched; + } + } + return patched; +} + +// With the switch, install the fault handler and the ReadFile wrapper when xmem.dll loads, before the title runs. +// The module is pinned: the handler must outlive any unload. +const bool lazy_commit_installed = [] { + if (!lazy_commit()) return false; + HMODULE self = nullptr; + const bool handler = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&lazy_commit_fault), &self) && + AddVectoredExceptionHandler(1, lazy_commit_fault); + real_read_file = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "ReadFile")); + const int reads = real_read_file ? patch_main_import("ReadFile", reinterpret_cast(&read_file_committed)) : 0; + x2w_local::logf("x2w-xmem lazy commit (X2W_XMEM_LAZY_COMMIT): fault handler %s, %d ReadFile import(s) wrapped", + handler ? "on" : "failed", reads); + return handler; +}(); +} // namespace + // Experimental export: writes bytes into physical pages named by the title's // page tokens (page number << 4, as XMemMapPhysicalPages takes them), starting offset bytes into the // first page. DirectStorage requests can name such pages as their destination. diff --git a/src/xmem_shim.def b/src/xmem_shim.def index a5beb47866..135b99a948 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -16,3 +16,4 @@ EXPORTS x2w_xmem_write_physical @14 x2w_xmem_page_stats @15 x2w_xmem_slab_stats @16 + x2w_xmem_commit_range @17 diff --git a/tests/xmem_lazy_commit_check.py b/tests/xmem_lazy_commit_check.py new file mode 100644 index 0000000000..3e603e2683 --- /dev/null +++ b/tests/xmem_lazy_commit_check.py @@ -0,0 +1,148 @@ +"""Check X2W_XMEM_LAZY_COMMIT=1: mapped physical pages are committed on first touch (#1199). + +- Mapping commits almost nothing: the mapped pages stay reserved until they are touched. +- A CPU write commits only the page it touches, and the bytes read back. +- A kernel-mode write (ReadFile) into an untouched page fails without a fault; after x2w_xmem_commit_range + the same read succeeds. This is why writers that cannot fault commit first. +- Threads that touch the same untouched pages at once all succeed. +- Released pages come back zero-filled when their slots are reused. +With `off` (control, switch set to 0): mapping commits every page up front as before, and +x2w_xmem_commit_range returns TRUE without doing anything. +usage: xmem_lazy_commit_check.py [off] +""" +import ctypes as C +from ctypes import wintypes as W +import os +import sys +import tempfile +import threading + +from xmem_page_runs_check import MEM_COMMIT, MEM_RESERVE, PAGE, Shim, bind + +PAGES = 1024 # 64 MiB of mapped pages +# Other processes move system commit a little while this runs; committing every mapped page would be 64 MiB. +LIMIT_BYTES = 24 << 20 +ERROR_NOACCESS = 998 +GENERIC_READ, OPEN_EXISTING = 0x80000000, 3 +THREADS = 8 + + +class PerformanceInformation(C.Structure): + _fields_ = [("cb", W.DWORD)] + [(name, C.c_size_t) for name in ( + "CommitTotal", "CommitLimit", "CommitPeak", "PhysicalTotal", "PhysicalAvailable", "SystemCache", + "KernelTotal", "KernelPaged", "KernelNonpaged", "PageSize")] + [ + (name, W.DWORD) for name in ("HandleCount", "ProcessCount", "ThreadCount")] + + +def main(path, mode=""): + kernel32 = C.WinDLL("kernel32.dll", use_last_error=True) + lazy = mode != "off" + # The shim reads the switch when it loads. + assert bind(kernel32, "SetEnvironmentVariableW", [W.LPCWSTR, W.LPCWSTR], W.BOOL)( + "X2W_XMEM_LAZY_COMMIT", "1" if lazy else "0") + shim = Shim(path) + commit_range = bind(shim.library, "x2w_xmem_commit_range", [C.c_void_p, C.c_size_t], W.BOOL) + performance = bind(kernel32, "K32GetPerformanceInfo", [C.POINTER(PerformanceInformation), W.DWORD], W.BOOL) + create_file = bind(kernel32, "CreateFileW", [W.LPCWSTR, W.DWORD, W.DWORD, C.c_void_p, W.DWORD, W.DWORD, W.HANDLE], + W.HANDLE) + read_file = bind(kernel32, "ReadFile", [W.HANDLE, C.c_void_p, W.DWORD, C.POINTER(W.DWORD), C.c_void_p], W.BOOL) + close_handle = bind(kernel32, "CloseHandle", [W.HANDLE], W.BOOL) + + def commit_bytes(): + info = PerformanceInformation() + info.cb = C.sizeof(info) + assert performance(C.byref(info), info.cb), C.get_last_error() + return info.CommitTotal * info.PageSize + + def state(address): + return shim.query(address)[3] + + base = shim.whole + pages = shim.pages(PAGES) + try: + # Mapping: the pages are reserved, not committed. + before = commit_bytes() + assert shim.contiguous(base, PAGES, pages) == base, C.get_last_error() + grown = commit_bytes() - before + print(f"mapping {PAGES} pages ({PAGES * PAGE >> 20} MiB) grew commit by {grown >> 20} MiB") + if not lazy: + # Without the switch every mapped page is committed when it is mapped, and the export does nothing. + assert state(base) == MEM_COMMIT and state(base + (PAGES - 1) * PAGE) == MEM_COMMIT, "off: a page was left lazy" + assert grown >= PAGES * PAGE - LIMIT_BYTES, f"off: mapping committed only {grown >> 20} MiB" + assert commit_range(C.c_void_p(base), PAGES * PAGE) + assert shim.contiguous(base, PAGES, None) == base + print("ok (off)") + return + assert grown < LIMIT_BYTES, f"mapping committed {grown >> 20} MiB: the pages were not left lazy" + assert state(base) == MEM_RESERVE and state(base + (PAGES - 1) * PAGE) == MEM_RESERVE + + # First CPU write: only that page is committed; the bytes read back. + C.c_uint32.from_address(base + 8).value = 0x12345678 + assert C.c_uint32.from_address(base + 8).value == 0x12345678 + assert state(base) == MEM_COMMIT and state(base + PAGE) == MEM_RESERVE, "a write committed more than its page" + assert C.c_uint32.from_address(base + PAGE - 4).value == 0, "a committed page is not zero-filled" + + # Kernel-mode write: no fault, so it fails on an untouched page until the range is committed. + data = bytes(range(256)) * 16 + with tempfile.NamedTemporaryFile(delete=False) as file: + file.write(data) + try: + target = base + 2 * PAGE + for committed in (False, True): + if committed: + assert commit_range(C.c_void_p(target), len(data)), C.get_last_error() + assert state(target) == MEM_COMMIT + handle = create_file(file.name, GENERIC_READ, 0, None, OPEN_EXISTING, 0, None) + assert handle and handle != W.HANDLE(-1).value, C.get_last_error() + read = W.DWORD() + ok = read_file(handle, C.c_void_p(target), len(data), C.byref(read), None) + error = C.get_last_error() + close_handle(handle) + if committed: + assert ok and read.value == len(data) and C.string_at(target, len(data)) == data, error + else: + assert not ok and error == ERROR_NOACCESS, f"expected ERROR_NOACCESS, got ok={ok} error={error}" + finally: + os.unlink(file.name) + assert commit_range(C.c_void_p(base), PAGES * PAGE * 2), "a range reaching past the mapping must not fail" + + # Threads touching the same untouched pages at once: each write lands, none faults through. + first = 16 + barrier = threading.Barrier(THREADS) + errors = [] + + def touch(index): + try: + barrier.wait() + for page in range(first, first + 32): + value = C.c_uint32(page << 8 | index) + C.memmove(base + page * PAGE + index * 4, C.byref(value), 4) + except Exception as error: # noqa: BLE001 - reported below + errors.append(error) + + threads = [threading.Thread(target=touch, args=(i,)) for i in range(THREADS)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert not errors, errors + for page in range(first, first + 32): + for index in range(THREADS): + assert C.c_uint32.from_address(base + page * PAGE + index * 4).value == page << 8 | index + + # Released pages: their slots are reused zero-filled. + assert shim.contiguous(base, PAGES, None) == base + assert shim.release(PAGES, pages) + pages = shim.pages(PAGES) + assert shim.contiguous(base, PAGES, pages) == base, C.get_last_error() + for page in (0, 2, first, first + 31): + assert not any(C.string_at(base + page * PAGE, 64)), f"reused page {page} is not zero-filled" + assert shim.contiguous(base, PAGES, None) == base + finally: + shim.release(PAGES, pages) + shim.close() + print("ok") + + +if __name__ == "__main__": + main(*sys.argv[1:3]) From b4c6676319da17de47d1782d4f7491731f052a7d Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:10:04 +0100 Subject: [PATCH 2/5] xmem: commit large startup blocks on first touch (X2W_XMEM_LAZY_STARTUP, #1199) With X2W_XMEM_LAZY_STARTUP=1 and X2W_XMEM_LAZY_COMMIT=1, commit_startup_block reserves blocks of 32 MiB and up; the fault handler commits them 256 KiB at a time on first touch, x2w_xmem_commit_range commits the chunks behind a range for writers that cannot fault, and x2w_xmem_commit_block commits a whole block before slot 133 places a GPU resource in it. The title's VirtualFree import drops released blocks from the list. Blocks placed below 2^40 stay committed up front. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 9 ++ docs/experiments.md | 29 +++++ docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_xs_device.cpp | 4 +- src/startup_stubs/local_log.h | 12 ++ src/xmem_mapped_pages.cpp | 155 +++++++++++++++++++++++--- src/xmem_shim.def | 1 + tests/xmem_lazy_startup_check.py | 134 ++++++++++++++++++++++ 8 files changed, 331 insertions(+), 14 deletions(-) create mode 100644 tests/xmem_lazy_startup_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2d5749b14f..e2b427e761 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -229,6 +229,15 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME xmem_lazy_commit_off COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_lazy_commit_check.py" "$" off) set_tests_properties(xmem_lazy_commit_off PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=0") + add_test(NAME xmem_lazy_startup COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_lazy_startup_check.py" "$") + set_tests_properties(xmem_lazy_startup PROPERTIES TIMEOUT 60 + ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=1;X2W_XMEM_LAZY_STARTUP=1") + # Control: with X2W_XMEM_LAZY_STARTUP off, the startup blocks are committed as before. + add_test(NAME xmem_lazy_startup_off COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_lazy_startup_check.py" "$" off) + set_tests_properties(xmem_lazy_startup_off PROPERTIES TIMEOUT 60 + ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=1;X2W_XMEM_LAZY_STARTUP=0") add_test(NAME startup_heartbeat_commit COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_heartbeat_check.py" "$" "$") diff --git a/docs/experiments.md b/docs/experiments.md index 3616c01cbc..f3427d9855 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8889,6 +8889,35 @@ cmake --build --preset release --target xmem_shim ctest --preset release --no-tests=error -R '^xmem_' -V ``` +### Startup blocks committed on first touch + +Experimental, for [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199), on top of [Mapped pages committed on first touch](#mapped-pages-committed-on-first-touch). The [startup commit profile](#reserve-and-commit-startup-blocks) commits each block in full when it is allocated. Several of those blocks are large, and the title touches them gradually. Their commit is charged to the process, so in a startup run with `-MemoryGiB 16` the late load reaches the job's commit cap. + +`X2W_XMEM_LAZY_STARTUP=1` takes effect only together with `X2W_XMEM_LAZY_COMMIT=1`. Blocks of 32 MiB and up from the startup commit profile are then reserved and recorded, with the same alignment and size as before. The same vectored exception handler commits the 256 KiB chunk a first access touches. A thread that finds its chunk already committed by another thread retries once. `x2w_xmem_commit_range` also commits the chunks behind a range in such a block, so the `ReadFile` wrapper and the stand-in writers above keep working. + +- **GPU placement.** A GPU heap opened on a block covers the committed run from its base and is reused for later resources in that block. So device slot 133 calls the experimental export `x2w_xmem_commit_block(address)` before a placed buffer is measured. It commits the whole block once and removes it from the list. +- **Release.** The title releases these blocks through its `VirtualFree` import, which is wrapped to remove a released block from the list first. A later allocation at the same addresses is then never committed as part of the old block. +- **Below 2^40.** Blocks placed by [`X2W_XMEM_STARTUP_BELOW_40`](#startup-blocks-below-240) stay committed up front. +- **Smaller blocks** are committed as before. If the list cannot record a block, the block is committed in full instead. + +Measured in startup runs on Windows 10 22H2 (16 GB RAM, RTX 3080 Ti), same input, with `-MemoryGiB 16` and both switches: + +- **Process commit:** 10.8 GiB through startup (11.8 GiB with only `X2W_XMEM_LAZY_COMMIT`), and 14.7–15.1 GiB at 180 s (15.6 GiB). +- **Without the 40-bit placement:** three runs out of three reached the BVH builder's address check described in [#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758) without a commit failure. Earlier runs with neither switch or only the first one did so in one run out of six. +- **With `-StartupBelow40`:** system commit had 3.75 GiB free at its peak, and the run reached the builder's upload allocation (command-list slot 148, #1758). In two runs without either switch, system commit fell to 0.74 and 1.03 GiB free before that point, and a host-side commit watchdog stopped them. + +| CTest case | Inputs and checks | +|---|---| +| `xmem_lazy_startup` | With both switches: a 64 MiB block of type `0x20403000` and a 32 MiB large-page block are reserved, the second 2 MiB aligned; a 16 MiB block is committed. A CPU write commits only its 256 KiB chunk, reads back, and the rest of the chunk reads zero. `ReadFile` into an untouched chunk fails with `ERROR_NOACCESS`; after `x2w_xmem_commit_range` over a range that crosses into the next chunk, the read succeeds. Eight threads writing to the same 32 untouched chunks at once all succeed. `x2w_xmem_commit_block` commits a whole block, a write to its last bytes succeeds, and an address outside the lazy blocks returns TRUE. | +| `xmem_lazy_startup_off` | Control, with `X2W_XMEM_LAZY_STARTUP=0` and `X2W_XMEM_LAZY_COMMIT=1`: the same 64 MiB and 32 MiB blocks are committed when they are allocated, and `x2w_xmem_commit_block` returns TRUE. | + +The `VirtualFree` wrapper patches the main module's import, so the Python test does not reach it: it was checked only in the startup runs. + +```powershell +cmake --build --preset release --target xmem_shim +ctest --preset release --no-tests=error -R '^xmem_lazy' -V +``` + ### Second commit and protection comparison `xmem_commit_protection` ([`tests/xmem_commit_protection_check.cpp`](../tests/xmem_commit_protection_check.cpp)) is a source-built x64 check for [#870](https://github.com/R0Y00/Xbox2Windows/issues/870) using synthetic 64 KiB page patterns. Its scope is separate from the first-commit alignment/zero-fill/rounding check (`xmem_committed_memory`), the reserve-only profile in [#888](https://github.com/R0Y00/Xbox2Windows/pull/888), and the device/queue work in [#874](https://github.com/R0Y00/Xbox2Windows/issues/874). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 721adc5fac..8b090bbb44 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -958,6 +958,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_XMEM_PERMISSIVE=1` | accepts the reservation, mapping and allocation shapes a startup run uses | | `X2W_XMEM_STARTUP_BELOW_40=1` (`run.ps1 -StartupBelow40`) | startup compatibility configuration ([#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758)): the large-page startup blocks with attribute `0x283` (null address, type `0x20003000`, protection `0x2004` or `0x2404`) are placed so that the whole block, last byte included, lies below 2^40. A block that does not fit there returns NULL with the Windows error and logs `x2w-xmem startup block below 2^40 refused:`; nothing is truncated or placed higher. Other shapes and explicit addresses keep their placement. See [Startup blocks below 2^40](experiments.md#startup-blocks-below-240) | | `X2W_XMEM_LAZY_COMMIT=1` | experimental ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): a fresh physical-page slot is committed on its first CPU access instead of when its page is mapped. A vectored exception handler commits the slot. Writers that cannot fault one in (the main module's `ReadFile`, slot 133 placement, stand-in writes behind a commit check) call `x2w_xmem_commit_range` first. See [Mapped pages committed on first touch](experiments.md#mapped-pages-committed-on-first-touch) | +| `X2W_XMEM_LAZY_STARTUP=1` | experimental, with `X2W_XMEM_LAZY_COMMIT=1` ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): the [startup commit profile](experiments.md#reserve-and-commit-startup-blocks) only reserves blocks of 32 MiB and up, and the same handler commits them 256 KiB at a time on first touch. Slot 133 commits a whole block (`x2w_xmem_commit_block`) before a GPU resource is placed in it. The main module's `VirtualFree` import drops released blocks. Blocks placed by `X2W_XMEM_STARTUP_BELOW_40` stay committed up front. See [Startup blocks committed on first touch](experiments.md#startup-blocks-committed-on-first-touch) | | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 4dfd1fcab7..6ea9a4373c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3230,8 +3230,10 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 // The allocation holding the address, and whether every byte from its base to the end of the // buffer is committed in it: one region-information call for a fully committed private // allocation, otherwise a region walk that stops at the end of the buffer. The GPU cannot fault in a lazily - // mapped physical page (X2W_XMEM_LAZY_COMMIT), so the buffer's pages are committed first. + // mapped physical page (X2W_XMEM_LAZY_COMMIT), so the buffer's pages are committed first; a lazy startup + // block (X2W_XMEM_LAZY_STARTUP) is committed whole, as the heap opened on it is reused for the block. x2w_local::commit_lazy(address, static_cast(desc->Width)); + x2w_local::commit_lazy_block(address); x2w_startup::PlacedBufferRange range; const bool committed = x2w_startup::measure_placed_buffer(address, desc->Width, range); InterlockedIncrement64(&placed_buffer_calls); diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index ebfc1cd645..bea306fde9 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -95,6 +95,18 @@ inline void commit_lazy(const void* pointer, std::size_t bytes) noexcept if (commit_range) commit_range(pointer, bytes); } +// Commits the whole lazy startup block holding pointer (xmem's x2w_xmem_commit_block, X2W_XMEM_LAZY_STARTUP) +// before the GPU uses memory in it; does nothing when xmem.dll lacks the export. +inline void commit_lazy_block(const void* pointer) noexcept +{ + using CommitBlock = BOOL(WINAPI*)(const void*); + static const CommitBlock commit_block = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_commit_block")) : nullptr; + }(); + if (commit_block) commit_block(pointer); +} + // Readability by probing (see probe_readable); writability by one VirtualQuery (rare callers). inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexcept { diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index c2dc2e7a7c..ea26f30150 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -110,6 +110,50 @@ bool lazy_commit() return on; } +// Experimental (X2W_XMEM_LAZY_STARTUP=1 with X2W_XMEM_LAZY_COMMIT=1, #1199): the large startup blocks +// XMemVirtualAlloc commits for the title (commit_startup_block, 32 MiB and up) are only reserved. The fault +// handler commits them 256 KiB at a time on first touch. x2w_xmem_commit_range commits the chunks behind a range +// for writers that cannot fault, and x2w_xmem_commit_block commits a whole block before the GPU uses it. +bool lazy_startup() +{ + static const bool on = lazy_commit() && x2w_local::env_on("X2W_XMEM_LAZY_STARTUP"); + return on; +} + +constexpr SIZE_T lazy_chunk = SIZE_T{256} << 10; +constexpr SIZE_T lazy_block_min = SIZE_T{32} << 20; + +// The reserved startup blocks that are still committed lazily: base -> bytes. +struct LazyBlocks { + SRWLOCK lock = SRWLOCK_INIT; + std::map blocks; +}; +LazyBlocks lazy_blocks; + +// The lazy block holding address, as base and size; false when there is none. +bool lazy_block_at(ULONG_PTR address, ULONG_PTR& base, SIZE_T& bytes) +{ + AcquireSRWLockShared(&lazy_blocks.lock); + auto it = lazy_blocks.blocks.upper_bound(address); + const bool inside = it != lazy_blocks.blocks.begin() && (--it, address - it->first < it->second); + if (inside) { + base = it->first; + bytes = it->second; + } + ReleaseSRWLockShared(&lazy_blocks.lock); + return inside; +} + +// Commits the whole chunks of a lazy block that [from, to) touches; false with the system error if that fails. +bool commit_block_chunks(ULONG_PTR base, SIZE_T bytes, ULONG_PTR from, ULONG_PTR to) +{ + const SIZE_T first = (from - base) & ~(lazy_chunk - 1); + SIZE_T last = to - base < bytes ? to - base : bytes; // offsets in the block; to is exclusive + last = (last + lazy_chunk - 1) & ~(lazy_chunk - 1); + if (last > bytes) last = bytes; + return VirtualAlloc(reinterpret_cast(base + first), last - first, MEM_COMMIT, PAGE_READWRITE) != nullptr; +} + // Commits a lazily mapped slot under memory.mutex; false with the system error if the commit fails. bool commit_backing(Backing& backing) { @@ -137,6 +181,25 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) const ULONG_PTR address = record->ExceptionInformation[1]; // A thread that raced another one to the same slot finds it committed: retry once, then pass the fault on. thread_local ULONG_PTR retried = 0; + if (lazy_startup()) { + ULONG_PTR base = 0; + SIZE_T bytes = 0; + MEMORY_BASIC_INFORMATION info{}; + if (lazy_block_at(address, base, bytes) && VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) && + info.State == MEM_RESERVE) { + if (!commit_block_chunks(base, bytes, address, address + 1)) return EXCEPTION_CONTINUE_SEARCH; + retried = 0; + return EXCEPTION_CONTINUE_EXECUTION; + } + // Another thread committed this chunk (or the whole block, which then leaves the list) between the fault + // and the query: committed read-write memory cannot fault, so retry once. + const ULONG_PTR chunk = address & ~(ULONG_PTR{lazy_chunk} - 1); + if (VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) && info.Type == MEM_PRIVATE && + info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE && retried != chunk) { + retried = chunk; + return EXCEPTION_CONTINUE_EXECUTION; + } + } const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); const std::lock_guard guard(memory.mutex); Backing* backing = backing_at(address); @@ -850,6 +913,13 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) if (!lazy_commit() || !address || !bytes) return TRUE; const auto start = reinterpret_cast(address); const ULONG_PTR end = bytes > ~ULONG_PTR{0} - start ? ~ULONG_PTR{0} : start + bytes; + if (lazy_startup()) { + ULONG_PTR from = start, base = 0; + SIZE_T block_bytes = 0; + for (; from < end && lazy_block_at(from, base, block_bytes); from = base + block_bytes) + if (!commit_block_chunks(base, block_bytes, from, end)) return FALSE; + if (from >= end) return TRUE; // the range lies in lazy startup blocks + } const std::lock_guard guard(memory.mutex); for (ULONG_PTR page = start & ~(ULONG_PTR{page_bytes} - 1); page < end; page += page_bytes) { Backing* backing = backing_at(page); @@ -859,6 +929,22 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) return TRUE; } +// Experimental export (X2W_XMEM_LAZY_STARTUP): commits the whole lazy startup block holding address and stops +// committing it lazily. A GPU heap opened on the block covers the committed run from its base and is reused for +// later resources in the block, so the block is committed whole before the first one is placed. TRUE without the +// switch or when the address is in no lazy block; FALSE with the system error when the commit fails. +extern "C" BOOL WINAPI x2w_xmem_commit_block(const void* address) +{ + ULONG_PTR base = 0; + SIZE_T bytes = 0; + if (!lazy_startup() || !lazy_block_at(reinterpret_cast(address), base, bytes)) return TRUE; + if (!VirtualAlloc(reinterpret_cast(base), bytes, MEM_COMMIT, PAGE_READWRITE)) return FALSE; + AcquireSRWLockExclusive(&lazy_blocks.lock); + lazy_blocks.blocks.erase(base); + ReleaseSRWLockExclusive(&lazy_blocks.lock); + return TRUE; +} + namespace { // The title reads files straight into mapped physical pages; a kernel-mode write into an uncommitted slot fails // with STATUS_ACCESS_VIOLATION (no fault), so with X2W_XMEM_LAZY_COMMIT the main module's ReadFile import commits @@ -872,6 +958,21 @@ BOOL WINAPI read_file_committed(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD return real_read_file(file, buffer, bytes, read, overlapped); } +// The title releases its startup blocks through its VirtualFree import: with X2W_XMEM_LAZY_STARTUP a released +// block leaves the lazy list first, so a later allocation at the same addresses is never committed as part of it. +using VirtualFreeFn = BOOL(WINAPI*)(LPVOID, SIZE_T, DWORD); +VirtualFreeFn real_virtual_free; + +BOOL WINAPI virtual_free_lazy(LPVOID address, SIZE_T bytes, DWORD type) +{ + if (type & MEM_RELEASE) { + AcquireSRWLockExclusive(&lazy_blocks.lock); + lazy_blocks.blocks.erase(reinterpret_cast(address)); + ReleaseSRWLockExclusive(&lazy_blocks.lock); + } + return real_virtual_free(address, bytes, type); +} + // Points the main module's imports of name at replacement; returns how many import slots were changed. int patch_main_import(const char* name, const void* replacement) noexcept { @@ -909,6 +1010,11 @@ const bool lazy_commit_installed = [] { const int reads = real_read_file ? patch_main_import("ReadFile", reinterpret_cast(&read_file_committed)) : 0; x2w_local::logf("x2w-xmem lazy commit (X2W_XMEM_LAZY_COMMIT): fault handler %s, %d ReadFile import(s) wrapped", handler ? "on" : "failed", reads); + if (lazy_startup()) { + real_virtual_free = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "VirtualFree")); + const int frees = real_virtual_free ? patch_main_import("VirtualFree", reinterpret_cast(&virtual_free_lazy)) : 0; + x2w_local::logf("x2w-xmem lazy startup blocks (X2W_XMEM_LAZY_STARTUP): %d VirtualFree import(s) wrapped", frees); + } return handler; }(); } // namespace @@ -1063,19 +1169,42 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG SetLastError(ERROR_INVALID_PARAMETER); return nullptr; } - if (!large_pages) return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - MEM_ADDRESS_REQUIREMENTS requirements{}; - requirements.Alignment = SIZE_T{2} << 20; - // supported already limits attribute 0x283 to protection 0x2004 or 0x2404. - const bool below_40 = attributes == 0x283 && x2w_local::env_on("X2W_XMEM_STARTUP_BELOW_40"); - if (below_40 && !startup_below_40_mutant("no_limit")) - requirements.HighestEndingAddress = reinterpret_cast(startup_low_limit - 1); - MEM_EXTENDED_PARAMETER parameter{}; - parameter.Type = MemExtendedParameterAddressRequirements; - parameter.Pointer = &requirements; - void* const block = VirtualAlloc2(GetCurrentProcess(), nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE, - ¶meter, 1); - return below_40 ? keep_startup_block_below_40(block, bytes, attributes, protection) : block; + const bool below_40 = large_pages && attributes == 0x283 && x2w_local::env_on("X2W_XMEM_STARTUP_BELOW_40"); + // X2W_XMEM_LAZY_STARTUP: a large block is reserved and committed on first touch (lazy_startup). + const bool lazy = lazy_startup() && bytes >= lazy_block_min && !below_40; + const DWORD type = lazy ? MEM_RESERVE : MEM_RESERVE | MEM_COMMIT; + void* block = nullptr; + if (!large_pages) { + block = VirtualAlloc(nullptr, bytes, type, PAGE_READWRITE); + } else { + MEM_ADDRESS_REQUIREMENTS requirements{}; + requirements.Alignment = SIZE_T{2} << 20; + // supported already limits attribute 0x283 to protection 0x2004 or 0x2404. + if (below_40 && !startup_below_40_mutant("no_limit")) + requirements.HighestEndingAddress = reinterpret_cast(startup_low_limit - 1); + MEM_EXTENDED_PARAMETER parameter{}; + parameter.Type = MemExtendedParameterAddressRequirements; + parameter.Pointer = &requirements; + block = VirtualAlloc2(GetCurrentProcess(), nullptr, bytes, type, PAGE_READWRITE, ¶meter, 1); + if (below_40) return keep_startup_block_below_40(block, bytes, attributes, protection); + } + if (block && lazy) { + bool listed = false; + AcquireSRWLockExclusive(&lazy_blocks.lock); + try { + lazy_blocks.blocks[reinterpret_cast(block)] = bytes; + listed = true; + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockExclusive(&lazy_blocks.lock); + if (!listed && !VirtualAlloc(block, bytes, MEM_COMMIT, PAGE_READWRITE)) { // not listed: commit it now + const DWORD error = GetLastError(); + VirtualFree(block, 0, MEM_RELEASE); + SetLastError(error); + return nullptr; + } + } + return block; } // The startup commit profile above, and the reserve-only desktop profile from the source-built diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 135b99a948..19e193c919 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -17,3 +17,4 @@ EXPORTS x2w_xmem_page_stats @15 x2w_xmem_slab_stats @16 x2w_xmem_commit_range @17 + x2w_xmem_commit_block @18 diff --git a/tests/xmem_lazy_startup_check.py b/tests/xmem_lazy_startup_check.py new file mode 100644 index 0000000000..e98f519e37 --- /dev/null +++ b/tests/xmem_lazy_startup_check.py @@ -0,0 +1,134 @@ +"""Check X2W_XMEM_LAZY_STARTUP=1 (with X2W_XMEM_LAZY_COMMIT=1): large startup blocks are committed on first +touch (#1199). + +- A 64 MiB startup block (type 0x20403000) and a 32 MiB large-page block (type 0x20003000) are only reserved; + the large-page one keeps its 2 MiB alignment. A 16 MiB block, below the threshold, is committed as before. +- A CPU write commits the 256 KiB chunk it touches, and the bytes read back; the rest of the block reads zero. +- A kernel-mode write (ReadFile) into an untouched chunk fails without a fault; after x2w_xmem_commit_range the + same read succeeds. +- Threads that touch the same untouched chunks at once all succeed. +- x2w_xmem_commit_block commits the whole block; later writes anywhere in it succeed. +With `off` (control, X2W_XMEM_LAZY_STARTUP=0 and X2W_XMEM_LAZY_COMMIT=1): every block is committed when it is +allocated, as before, and x2w_xmem_commit_block returns TRUE. +usage: xmem_lazy_startup_check.py [off] +""" +import ctypes as C +from ctypes import wintypes as W +import os +import sys +import tempfile +import threading + +from xmem_page_runs_check import MEM_COMMIT, MEM_RESERVE, WIN_RELEASE, Shim, bind + +CHUNK = 256 << 10 +STARTUP_64K, LARGE = 0x20403000, 0x20003000 +ERROR_NOACCESS = 998 +GENERIC_READ, OPEN_EXISTING = 0x80000000, 3 +THREADS = 8 + + +def main(path, mode=""): + kernel32 = C.WinDLL("kernel32.dll", use_last_error=True) + set_env = bind(kernel32, "SetEnvironmentVariableW", [W.LPCWSTR, W.LPCWSTR], W.BOOL) + lazy = mode != "off" + # The shim reads the switches when it loads. + assert set_env("X2W_XMEM_LAZY_COMMIT", "1") and set_env("X2W_XMEM_LAZY_STARTUP", "1" if lazy else "0") + shim = Shim(path) + commit_range = bind(shim.library, "x2w_xmem_commit_range", [C.c_void_p, C.c_size_t], W.BOOL) + commit_block = bind(shim.library, "x2w_xmem_commit_block", [C.c_void_p], W.BOOL) + create_file = bind(kernel32, "CreateFileW", [W.LPCWSTR, W.DWORD, W.DWORD, C.c_void_p, W.DWORD, W.DWORD, W.HANDLE], + W.HANDLE) + read_file = bind(kernel32, "ReadFile", [W.HANDLE, C.c_void_p, W.DWORD, C.POINTER(W.DWORD), C.c_void_p], W.BOOL) + close_handle = bind(kernel32, "CloseHandle", [W.HANDLE], W.BOOL) + + def state(address): + return shim.query(address)[3] + + blocks = [] + try: + # Reserved, not committed; below the threshold a block is committed as before. + block = shim.reserve_startup(None, 64 << 20, STARTUP_64K, 0x181, 4) + large = shim.reserve_startup(None, 32 << 20, LARGE, 0x183, 0x22004) + small = shim.reserve_startup(None, 16 << 20, STARTUP_64K, 0x181, 4) + blocks += [b for b in (block, large, small) if b] + assert block and large and small, C.get_last_error() + if not lazy: + for base, size in ((block, 64 << 20), (large, 32 << 20)): + assert state(base) == MEM_COMMIT and state(base + size - 1) == MEM_COMMIT, "off: a block was left lazy" + assert large % (2 << 20) == 0 and commit_block(C.c_void_p(block)) + print("ok (off)") + return + assert state(block) == MEM_RESERVE and state(block + (64 << 20) - 1) == MEM_RESERVE, "a large block was committed" + assert state(large) == MEM_RESERVE and large % (2 << 20) == 0, "the large-page block lost its 2 MiB alignment" + assert state(small) == MEM_COMMIT and state(small + (16 << 20) - 1) == MEM_COMMIT, "a small block was left lazy" + + # First CPU write: only its chunk is committed; the bytes read back, the rest reads zero. + target = block + CHUNK + 300 + C.c_uint32.from_address(target).value = 0x12345678 + assert C.c_uint32.from_address(target).value == 0x12345678 + assert state(block + CHUNK) == MEM_COMMIT and state(block + 2 * CHUNK - 1) == MEM_COMMIT + assert state(block) == MEM_RESERVE and state(block + 2 * CHUNK) == MEM_RESERVE, "a write committed more than its chunk" + assert C.c_uint32.from_address(block + 2 * CHUNK - 4).value == 0, "a committed chunk is not zero-filled" + + # Kernel-mode write: no fault, so it fails on an untouched chunk until the range is committed. + data = bytes(range(256)) * 16 + with tempfile.NamedTemporaryFile(delete=False) as file: + file.write(data) + try: + target = block + 4 * CHUNK - 1024 # crosses into the next chunk + for committed in (False, True): + if committed: + assert commit_range(C.c_void_p(target), len(data)), C.get_last_error() + assert state(target) == MEM_COMMIT and state(target + len(data) - 1) == MEM_COMMIT + handle = create_file(file.name, GENERIC_READ, 0, None, OPEN_EXISTING, 0, None) + assert handle and handle != W.HANDLE(-1).value, C.get_last_error() + read = W.DWORD() + ok = read_file(handle, C.c_void_p(target), len(data), C.byref(read), None) + error = C.get_last_error() + close_handle(handle) + if committed: + assert ok and read.value == len(data) and C.string_at(target, len(data)) == data, error + else: + assert not ok and error == ERROR_NOACCESS, f"expected ERROR_NOACCESS, got ok={ok} error={error}" + finally: + os.unlink(file.name) + + # Threads touching the same untouched chunks at once: each write lands, none faults through. + first = 16 + barrier = threading.Barrier(THREADS) + errors = [] + + def touch(index): + try: + barrier.wait() + for chunk in range(first, first + 32): + value = C.c_uint32(chunk << 8 | index) + C.memmove(block + chunk * CHUNK + index * 4, C.byref(value), 4) + except Exception as error: # noqa: BLE001 - reported below + errors.append(error) + + threads = [threading.Thread(target=touch, args=(i,)) for i in range(THREADS)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert not errors, errors + for chunk in range(first, first + 32): + for index in range(THREADS): + assert C.c_uint32.from_address(block + chunk * CHUNK + index * 4).value == chunk << 8 | index + + # The whole block, as before a GPU heap is opened on it; then writes anywhere succeed. + assert commit_block(C.c_void_p(large + 12345)), C.get_last_error() + assert state(large) == MEM_COMMIT and state(large + (32 << 20) - 1) == MEM_COMMIT, "commit_block left part lazy" + C.c_uint32.from_address(large + (32 << 20) - 4).value = 7 + assert commit_block(C.c_void_p(small)), "an address outside the lazy blocks must not fail" + print("ok") + finally: + for b in blocks: + shim.free(b, 0, WIN_RELEASE) + shim.close() + + +if __name__ == "__main__": + main(*sys.argv[1:3]) From ea454aff6382601d690f3888d4eee1fe886bd957 Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:39:53 +0100 Subject: [PATCH 3/5] xmem: address review of the lazy commit switches - x2w_xmem_commit_range starts the slot loop where the lazy startup blocks end, not at the range start. - The startup-block fault path has its own retry, keyed on the chunk and on the number of released lazy blocks, so a new block at the addresses of a released one can still be raced once. - docs: only the main module's ReadFile import is wrapped; name the kernel-mode accessors that are not. - xmem_lazy_imports: a source-built check whose own ReadFile and VirtualFree imports are wrapped. Without the commit in the ReadFile wrapper the read fails with ERROR_NOACCESS; without the list removal in the VirtualFree wrapper the handler commits a new reservation at the released addresses. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 7 ++ docs/experiments.md | 7 +- src/xmem_mapped_pages.cpp | 27 ++++--- tests/xmem_lazy_imports_check.cpp | 124 ++++++++++++++++++++++++++++++ 4 files changed, 152 insertions(+), 13 deletions(-) create mode 100644 tests/xmem_lazy_imports_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e2b427e761..00bec745c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -275,6 +275,13 @@ endforeach() # startup blocks entirely below 2^40 or refuses them. The check loads xmem.dll by path; the deployed # shim must ignore the test-build mutants, and each mutant in the test-controls build must make the # named check fail. +# The import wrappers of X2W_XMEM_LAZY_COMMIT / X2W_XMEM_LAZY_STARTUP (#1199): ReadFile and VirtualFree of the +# main module, which the Python checks cannot reach. +add_executable(xmem_lazy_imports_check tests/xmem_lazy_imports_check.cpp) +target_compile_features(xmem_lazy_imports_check PRIVATE cxx_std_17) +add_dependencies(xmem_lazy_imports_check xmem_shim) +add_test(NAME xmem_lazy_imports COMMAND xmem_lazy_imports_check "$") +set_tests_properties(xmem_lazy_imports PROPERTIES TIMEOUT 60) add_executable(xmem_startup_below_40_check tests/xmem_startup_below_40_check.cpp) target_link_libraries(xmem_startup_below_40_check PRIVATE OneCore) target_compile_features(xmem_startup_below_40_check PRIVATE cxx_std_17) diff --git a/docs/experiments.md b/docs/experiments.md index f3427d9855..033a2680ec 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8869,7 +8869,7 @@ Experimental, for [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199). Ph Some writers cannot fault a slot in, so they commit the range first through the experimental export `x2w_xmem_commit_range(address, bytes)`: -- **Kernel-mode I/O.** `ReadFile` into an uncommitted mapped page fails with `ERROR_NOACCESS` instead of faulting. The main module's `ReadFile` import is wrapped to commit the buffer first. +- **Kernel-mode I/O.** `ReadFile` into an uncommitted mapped page fails with `ERROR_NOACCESS` instead of faulting. The main module's `ReadFile` import is wrapped to commit the buffer first. Only that import is wrapped. Other kernel-mode accessors of an untouched page fail the same way: `ReadFileEx`, overlapped reads issued elsewhere, `WriteFile` from a lazy page, and calls from other modules' imports. The startup runs reached only the main module's `ReadFile`. - **GPU placement.** Device slot 133 commits a placed buffer's range before it measures the allocation. - **Stand-in writes behind a commit check**, such as the DirectStorage destination check. @@ -8910,11 +8910,10 @@ Measured in startup runs on Windows 10 22H2 (16 GB RAM, RTX 3080 Ti), same input |---|---| | `xmem_lazy_startup` | With both switches: a 64 MiB block of type `0x20403000` and a 32 MiB large-page block are reserved, the second 2 MiB aligned; a 16 MiB block is committed. A CPU write commits only its 256 KiB chunk, reads back, and the rest of the chunk reads zero. `ReadFile` into an untouched chunk fails with `ERROR_NOACCESS`; after `x2w_xmem_commit_range` over a range that crosses into the next chunk, the read succeeds. Eight threads writing to the same 32 untouched chunks at once all succeed. `x2w_xmem_commit_block` commits a whole block, a write to its last bytes succeeds, and an address outside the lazy blocks returns TRUE. | | `xmem_lazy_startup_off` | Control, with `X2W_XMEM_LAZY_STARTUP=0` and `X2W_XMEM_LAZY_COMMIT=1`: the same 64 MiB and 32 MiB blocks are committed when they are allocated, and `x2w_xmem_commit_block` returns TRUE. | - -The `VirtualFree` wrapper patches the main module's import, so the Python test does not reach it: it was checked only in the startup runs. +| `xmem_lazy_imports` | Source-built ([`tests/xmem_lazy_imports_check.cpp`](../tests/xmem_lazy_imports_check.cpp)), because the import wrappers patch the main module, which is `python.exe` in the checks above. With both switches, the program's own `ReadFile` reads a file into a mapped page that was never touched, and the bytes match. A 64 MiB startup block is released through its own `VirtualFree` and the same addresses are reserved again; a read there must still fault, and the range must stay reserved. Without the commit in the `ReadFile` wrapper the read fails with `ERROR_NOACCESS`; without the list removal in the `VirtualFree` wrapper the handler commits the new reservation. | ```powershell -cmake --build --preset release --target xmem_shim +cmake --build --preset release --target xmem_shim xmem_lazy_imports_check ctest --preset release --no-tests=error -R '^xmem_lazy' -V ``` diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index ea26f30150..0a05067e90 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -129,6 +129,7 @@ struct LazyBlocks { std::map blocks; }; LazyBlocks lazy_blocks; +volatile LONG lazy_block_releases = 0; // lazy blocks the title has released (keys the fault handler's retry) // The lazy block holding address, as base and size; false when there is none. bool lazy_block_at(ULONG_PTR address, ULONG_PTR& base, SIZE_T& bytes) @@ -179,8 +180,6 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) const EXCEPTION_RECORD* record = e->ExceptionRecord; if (record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH; const ULONG_PTR address = record->ExceptionInformation[1]; - // A thread that raced another one to the same slot finds it committed: retry once, then pass the fault on. - thread_local ULONG_PTR retried = 0; if (lazy_startup()) { ULONG_PTR base = 0; SIZE_T bytes = 0; @@ -188,18 +187,26 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) if (lazy_block_at(address, base, bytes) && VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) && info.State == MEM_RESERVE) { if (!commit_block_chunks(base, bytes, address, address + 1)) return EXCEPTION_CONTINUE_SEARCH; - retried = 0; return EXCEPTION_CONTINUE_EXECUTION; } // Another thread committed this chunk (or the whole block, which then leaves the list) between the fault - // and the query: committed read-write memory cannot fault, so retry once. + // and the query: committed read-write memory cannot fault, so retry once. The retry is keyed on the chunk + // and on the release count, so a fault that stays is passed on, while a new block later placed at the same + // addresses can still be raced once (separate from the slot path's retry below). + thread_local ULONG_PTR retried_chunk = 0; + thread_local LONG retried_releases = 0; const ULONG_PTR chunk = address & ~(ULONG_PTR{lazy_chunk} - 1); + const LONG releases = lazy_block_releases; if (VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) && info.Type == MEM_PRIVATE && - info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE && retried != chunk) { - retried = chunk; + info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE && + !(retried_chunk == chunk && retried_releases == releases)) { + retried_chunk = chunk; + retried_releases = releases; return EXCEPTION_CONTINUE_EXECUTION; } } + // A thread that raced another one to the same slot finds it committed: retry once, then pass the fault on. + thread_local ULONG_PTR retried = 0; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); const std::lock_guard guard(memory.mutex); Backing* backing = backing_at(address); @@ -913,15 +920,16 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) if (!lazy_commit() || !address || !bytes) return TRUE; const auto start = reinterpret_cast(address); const ULONG_PTR end = bytes > ~ULONG_PTR{0} - start ? ~ULONG_PTR{0} : start + bytes; + ULONG_PTR from = start; // the part of the range past any lazy startup blocks it starts in if (lazy_startup()) { - ULONG_PTR from = start, base = 0; + ULONG_PTR base = 0; SIZE_T block_bytes = 0; for (; from < end && lazy_block_at(from, base, block_bytes); from = base + block_bytes) if (!commit_block_chunks(base, block_bytes, from, end)) return FALSE; if (from >= end) return TRUE; // the range lies in lazy startup blocks } const std::lock_guard guard(memory.mutex); - for (ULONG_PTR page = start & ~(ULONG_PTR{page_bytes} - 1); page < end; page += page_bytes) { + for (ULONG_PTR page = from & ~(ULONG_PTR{page_bytes} - 1); page < end; page += page_bytes) { Backing* backing = backing_at(page); if (backing && !commit_backing(*backing)) return FALSE; if (page > ~ULONG_PTR{0} - page_bytes) break; @@ -967,8 +975,9 @@ BOOL WINAPI virtual_free_lazy(LPVOID address, SIZE_T bytes, DWORD type) { if (type & MEM_RELEASE) { AcquireSRWLockExclusive(&lazy_blocks.lock); - lazy_blocks.blocks.erase(reinterpret_cast(address)); + const bool listed = lazy_blocks.blocks.erase(reinterpret_cast(address)) != 0; ReleaseSRWLockExclusive(&lazy_blocks.lock); + if (listed) InterlockedIncrement(&lazy_block_releases); } return real_virtual_free(address, bytes, type); } diff --git a/tests/xmem_lazy_imports_check.cpp b/tests/xmem_lazy_imports_check.cpp new file mode 100644 index 0000000000..427a7a1aa2 --- /dev/null +++ b/tests/xmem_lazy_imports_check.cpp @@ -0,0 +1,124 @@ +// Lazy commit through the main module's imports (#1199). Source-built check of the two import wrappers that +// X2W_XMEM_LAZY_COMMIT=1 and X2W_XMEM_LAZY_STARTUP=1 install in the main module when xmem.dll loads +// (src/xmem_mapped_pages.cpp). The Python checks cannot reach them: there the main module is python.exe. +// +// - ReadFile: this program's own ReadFile import reads a file into a mapped physical page that was never +// touched. A kernel-mode write into an uncommitted page fails with ERROR_NOACCESS, so the read succeeds only +// if the wrapper commits the buffer first. +// - VirtualFree: this program releases a lazy startup block through its own VirtualFree import, reserves the +// same addresses again, and touches them. The touch must fault: a block still on the lazy list would be +// committed by the fault handler as if it were the old block. +// +// Usage: xmem_lazy_imports_check +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + +#include +#include + +namespace { +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*, SIZE_T*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, SIZE_T, SIZE_T*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T pages = 4; +constexpr SIZE_T block_bytes = SIZE_T{64} << 20; + +int failures = 0; + +void check(bool ok, const char* name) +{ + std::printf("%s: %s\n", ok ? "ok" : "check_failed", name); + if (!ok) ++failures; +} + +// True when reading the byte faults; kept free of C++ objects for __try. +bool read_faults(volatile const unsigned char* address) +{ + __try { + (void)*address; + return false; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return true; + } +} + +DWORD state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) { + std::printf("usage: xmem_lazy_imports_check \n"); + return 2; + } + // xmem.dll reads the switches and wraps this program's imports when it loads. + SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); + SetEnvironmentVariableA("X2W_XMEM_LAZY_STARTUP", "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + const auto virtual_alloc = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto allocate = reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")); + const auto release = reinterpret_cast(GetProcAddress(xmem, "XMemFreePhysicalPages")); + if (!virtual_alloc || !allocate || !map || !release) { + std::printf("check_failed: exports\n"); + return 1; + } + + // ReadFile into an untouched mapped page, through this program's import. + void* const reservation = virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE); + SIZE_T count = pages, tokens[pages] = {}; + const bool mapped = reservation && allocate(0x20400000, &count, tokens) && count == pages && + map(reservation, pages, tokens) == reservation; + check(mapped, "map"); + if (mapped) { + auto* const target = static_cast(reservation) + page; + check(state(target) == MEM_RESERVE, "page_left_lazy"); + char data[4096]; + for (size_t i = 0; i < sizeof(data); ++i) data[i] = static_cast(i * 7); + char path[MAX_PATH], name[MAX_PATH]; + GetTempPathA(MAX_PATH, path); + GetTempFileNameA(path, "x2w", 0, name); + HANDLE file = CreateFileA(name, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); + DWORD written = 0; + WriteFile(file, data, sizeof(data), &written, nullptr); + CloseHandle(file); + file = CreateFileA(name, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, nullptr); + DWORD read = 0; + const BOOL ok = ReadFile(file, target, sizeof(data), &read, nullptr); + const DWORD error = ok ? ERROR_SUCCESS : GetLastError(); + CloseHandle(file); + if (!ok) std::printf(" ReadFile failed with error %lu\n", error); + check(ok && read == sizeof(data) && std::memcmp(target, data, sizeof(data)) == 0, "readfile_into_lazy_page"); + map(reservation, pages, nullptr); + release(pages, tokens); + } + if (reservation) VirtualFree(reservation, 0, MEM_RELEASE); + + // A released lazy startup block leaves the list: the same addresses, reserved again, still fault. + void* const block = virtual_alloc(nullptr, block_bytes, 0x20403000, 0x181, PAGE_READWRITE); + check(block && state(block) == MEM_RESERVE, "block_left_lazy"); + if (block) { + check(VirtualFree(block, 0, MEM_RELEASE) != FALSE, "virtualfree_release"); + void* const again = VirtualAlloc(block, block_bytes, MEM_RESERVE, PAGE_READWRITE); + check(again == block, "reserve_same_addresses"); + if (again == block) { + check(read_faults(static_cast(again) + page), "released_block_not_committed"); + check(state(again) == MEM_RESERVE, "released_block_still_reserved"); + VirtualFree(again, 0, MEM_RELEASE); + } + } + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +} From 76b995fdadb445042399d7a9339418b6ff8301c8 Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:53:54 +0100 Subject: [PATCH 4/5] xmem: note the release-count race and clean up the imports check's temp file - virtual_free_lazy: comment that the count is bumped before the release; a racing thread retries at most once more. - xmem_lazy_imports_check: delete the temp file when it cannot be reopened for reading. Co-Authored-By: Claude Opus 5.5 --- src/xmem_mapped_pages.cpp | 2 ++ tests/xmem_lazy_imports_check.cpp | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 0a05067e90..8c05c328ce 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -977,6 +977,8 @@ BOOL WINAPI virtual_free_lazy(LPVOID address, SIZE_T bytes, DWORD type) AcquireSRWLockExclusive(&lazy_blocks.lock); const bool listed = lazy_blocks.blocks.erase(reinterpret_cast(address)) != 0; ReleaseSRWLockExclusive(&lazy_blocks.lock); + // Counted before the block is released: a thread that faults in between sees the new count while the old + // block is still reserved, which costs it at most one extra retry. if (listed) InterlockedIncrement(&lazy_block_releases); } return real_virtual_free(address, bytes, type); diff --git a/tests/xmem_lazy_imports_check.cpp b/tests/xmem_lazy_imports_check.cpp index 427a7a1aa2..c9402d9c91 100644 --- a/tests/xmem_lazy_imports_check.cpp +++ b/tests/xmem_lazy_imports_check.cpp @@ -96,9 +96,12 @@ int main(int argc, char** argv) CloseHandle(file); file = CreateFileA(name, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, nullptr); DWORD read = 0; - const BOOL ok = ReadFile(file, target, sizeof(data), &read, nullptr); + const BOOL ok = file != INVALID_HANDLE_VALUE && ReadFile(file, target, sizeof(data), &read, nullptr); const DWORD error = ok ? ERROR_SUCCESS : GetLastError(); - CloseHandle(file); + if (file != INVALID_HANDLE_VALUE) + CloseHandle(file); // FILE_FLAG_DELETE_ON_CLOSE removes the file + else + DeleteFileA(name); if (!ok) std::printf(" ReadFile failed with error %lu\n", error); check(ok && read == sizeof(data) && std::memcmp(target, data, sizeof(data)) == 0, "readfile_into_lazy_page"); map(reservation, pages, nullptr); From c40e3dacd0f712048d068c6c3ded0472e5747357 Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:00:34 +0100 Subject: [PATCH 5/5] xmem: keep a lazy block listed until its release succeeds Review of #2209: virtual_free_lazy removed a block from the lazy list before VirtualFree ran, so a refused MEM_RELEASE left a reserved block that no first touch could commit. The release now runs under the list lock and the block leaves the list only when it succeeds. The fault handler, x2w_xmem_commit_range and x2w_xmem_commit_block hold the same lock from the lookup to the commit, so a release cannot run between them. If the fault handler cannot be installed, the switches now act as off: pages and blocks are committed up front and no import is wrapped. xmem_lazy_imports adds a refused release (nonzero size) followed by a write to an untouched page; xmem_lazy_handler_failure runs the test-controls build with the handler refused (X2W_XMEM_TEST_LAZY_HANDLER_FAILURE=1). Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 6 +- docs/experiments.md | 9 +-- src/xmem_mapped_pages.cpp | 104 +++++++++++++++++++----------- tests/xmem_lazy_imports_check.cpp | 64 +++++++++++++++++- 4 files changed, 139 insertions(+), 44 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d613dd488..76c57cff32 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -279,9 +279,13 @@ endforeach() # main module, which the Python checks cannot reach. add_executable(xmem_lazy_imports_check tests/xmem_lazy_imports_check.cpp) target_compile_features(xmem_lazy_imports_check PRIVATE cxx_std_17) -add_dependencies(xmem_lazy_imports_check xmem_shim) +add_dependencies(xmem_lazy_imports_check xmem_shim xmem_shim_test_controls) add_test(NAME xmem_lazy_imports COMMAND xmem_lazy_imports_check "$") set_tests_properties(xmem_lazy_imports PROPERTIES TIMEOUT 60) +# A refused fault handler (test-controls build) leaves the switches off: pages and blocks are committed up front. +add_test(NAME xmem_lazy_handler_failure COMMAND xmem_lazy_imports_check + "$" handler-failure) +set_tests_properties(xmem_lazy_handler_failure PROPERTIES TIMEOUT 60) add_executable(xmem_startup_below_40_check tests/xmem_startup_below_40_check.cpp) target_link_libraries(xmem_startup_below_40_check PRIVATE OneCore) target_compile_features(xmem_startup_below_40_check PRIVATE cxx_std_17) diff --git a/docs/experiments.md b/docs/experiments.md index 897671e1e1..dda2dde05d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9114,7 +9114,7 @@ ctest --preset dev --no-tests=error -R '^xmem_startup_below_40' -V Experimental, for [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199). Physical pages are 64 KiB slots of `SEC_RESERVE` slabs (see [Startup memory accounting](startup-runtime.md#startup-memory-accounting)). By default a fresh slot is committed when its page is first mapped. A startup run maps far more pages than it touches before the main load, and slab commit is charged to the system commit limit, not to the process. On a 16 GB host this pushes the system to its commit limit during the load. -`X2W_XMEM_LAZY_COMMIT=1` leaves a fresh slot uncommitted when its page is mapped. The first CPU access faults, and a vectored exception handler installed when `xmem.dll` loads commits that slot and resumes the thread. A thread that loses the race to commit the same slot finds it committed and retries once. GPU-view addresses resolve to the CPU-view slot (the same section). Reused slots and `x2w_xmem_write_physical` still commit before use, as before. +`X2W_XMEM_LAZY_COMMIT=1` leaves a fresh slot uncommitted when its page is mapped. The first CPU access faults, and a vectored exception handler installed when `xmem.dll` loads commits that slot and resumes the thread. A thread that loses the race to commit the same slot finds it committed and retries once. If the handler cannot be installed, the switch acts as off: pages are committed when they are mapped and no import is wrapped. GPU-view addresses resolve to the CPU-view slot (the same section). Reused slots and `x2w_xmem_write_physical` still commit before use, as before. Some writers cannot fault a slot in, so they commit the range first through the experimental export `x2w_xmem_commit_range(address, bytes)`: @@ -9145,7 +9145,7 @@ Experimental, for [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199), on `X2W_XMEM_LAZY_STARTUP=1` takes effect only together with `X2W_XMEM_LAZY_COMMIT=1`. Blocks of 32 MiB and up from the startup commit profile are then reserved and recorded, with the same alignment and size as before. The same vectored exception handler commits the 256 KiB chunk a first access touches. A thread that finds its chunk already committed by another thread retries once. `x2w_xmem_commit_range` also commits the chunks behind a range in such a block, so the `ReadFile` wrapper and the stand-in writers above keep working. - **GPU placement.** A GPU heap opened on a block covers the committed run from its base and is reused for later resources in that block. So device slot 133 calls the experimental export `x2w_xmem_commit_block(address)` before a placed buffer is measured. It commits the whole block once and removes it from the list. -- **Release.** The title releases these blocks through its `VirtualFree` import, which is wrapped to remove a released block from the list first. A later allocation at the same addresses is then never committed as part of the old block. +- **Release.** The title releases these blocks through its `VirtualFree` import. The wrapper releases the block under the list's lock and removes it from the list only if the release succeeds, so a later allocation at the same addresses is never committed as part of the old block, and a refused release (a nonzero size, for instance) leaves the block reserved and still committed on first touch. The handler and `x2w_xmem_commit_range` hold the same lock from the lookup to the commit, so a release cannot run in between. - **Below 2^40.** Blocks placed by [`X2W_XMEM_STARTUP_BELOW_40`](#startup-blocks-below-240) stay committed up front. - **Smaller blocks** are committed as before. If the list cannot record a block, the block is committed in full instead. @@ -9159,10 +9159,11 @@ Measured in startup runs on Windows 10 22H2 (16 GB RAM, RTX 3080 Ti), same input |---|---| | `xmem_lazy_startup` | With both switches: a 64 MiB block of type `0x20403000` and a 32 MiB large-page block are reserved, the second 2 MiB aligned; a 16 MiB block is committed. A CPU write commits only its 256 KiB chunk, reads back, and the rest of the chunk reads zero. `ReadFile` into an untouched chunk fails with `ERROR_NOACCESS`; after `x2w_xmem_commit_range` over a range that crosses into the next chunk, the read succeeds. Eight threads writing to the same 32 untouched chunks at once all succeed. `x2w_xmem_commit_block` commits a whole block, a write to its last bytes succeeds, and an address outside the lazy blocks returns TRUE. | | `xmem_lazy_startup_off` | Control, with `X2W_XMEM_LAZY_STARTUP=0` and `X2W_XMEM_LAZY_COMMIT=1`: the same 64 MiB and 32 MiB blocks are committed when they are allocated, and `x2w_xmem_commit_block` returns TRUE. | -| `xmem_lazy_imports` | Source-built ([`tests/xmem_lazy_imports_check.cpp`](../tests/xmem_lazy_imports_check.cpp)), because the import wrappers patch the main module, which is `python.exe` in the checks above. With both switches, the program's own `ReadFile` reads a file into a mapped page that was never touched, and the bytes match. A 64 MiB startup block is released through its own `VirtualFree` and the same addresses are reserved again; a read there must still fault, and the range must stay reserved. Without the commit in the `ReadFile` wrapper the read fails with `ERROR_NOACCESS`; without the list removal in the `VirtualFree` wrapper the handler commits the new reservation. | +| `xmem_lazy_imports` | Source-built ([`tests/xmem_lazy_imports_check.cpp`](../tests/xmem_lazy_imports_check.cpp)), because the import wrappers patch the main module, which is `python.exe` in the checks above. With both switches, the program's own `ReadFile` reads a file into a mapped page that was never touched, and the bytes match. A 64 MiB startup block is released through its own `VirtualFree` and the same addresses are reserved again; a read there must still fault, and the range must stay reserved. Without the commit in the `ReadFile` wrapper the read fails with `ERROR_NOACCESS`; without the list removal in the `VirtualFree` wrapper the handler commits the new reservation. A second block is released with a nonzero size, which fails with `ERROR_INVALID_PARAMETER`; a write to an untouched page must then still be committed, and the block is released with size 0. Removing the block before the release is known to succeed fails that write. | +| `xmem_lazy_handler_failure` | The same program on the test-controls build, with `X2W_XMEM_TEST_LAZY_HANDLER_FAILURE=1` refusing the handler: a mapped page and a 64 MiB startup block must be committed and writable. Keeping the switch on without the handler leaves both reserved. | ```powershell -cmake --build --preset release --target xmem_shim xmem_lazy_imports_check +cmake --build --preset release --target xmem_shim xmem_shim_test_controls xmem_lazy_imports_check ctest --preset release --no-tests=error -R '^xmem_lazy' -V ``` diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 1157625958..1b0b079ffd 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -104,20 +104,29 @@ bool commit_slot(HANDLE slab, ULONG64 offset, bool zero) // CPU access faults and lazy_commit_fault commits that slot. Writers that do not fault -- kernel-mode I/O into // mapped pages, GPU placement, stand-in writes behind a commit-state check -- call x2w_xmem_commit_range first. // Reused slots and x2w_xmem_write_physical still commit before use. -bool lazy_commit() +bool lazy_commit_requested() { static const bool on = x2w_local::env_on("X2W_XMEM_LAZY_COMMIT"); return on; } +// Set when xmem.dll loads, once the fault handler is installed. Without the handler a lazy page could never be +// committed, so the switch then acts as off: pages and blocks are committed up front. +bool lazy_handler_installed = false; + +bool lazy_commit() +{ + return lazy_handler_installed && lazy_commit_requested(); +} + // Experimental (X2W_XMEM_LAZY_STARTUP=1 with X2W_XMEM_LAZY_COMMIT=1, #1199): the large startup blocks // XMemVirtualAlloc commits for the title (commit_startup_block, 32 MiB and up) are only reserved. The fault // handler commits them 256 KiB at a time on first touch. x2w_xmem_commit_range commits the chunks behind a range // for writers that cannot fault, and x2w_xmem_commit_block commits a whole block before the GPU uses it. bool lazy_startup() { - static const bool on = lazy_commit() && x2w_local::env_on("X2W_XMEM_LAZY_STARTUP"); - return on; + static const bool on = x2w_local::env_on("X2W_XMEM_LAZY_STARTUP"); + return on && lazy_commit(); } constexpr SIZE_T lazy_chunk = SIZE_T{256} << 10; @@ -131,17 +140,17 @@ struct LazyBlocks { LazyBlocks lazy_blocks; volatile LONG lazy_block_releases = 0; // lazy blocks the title has released (keys the fault handler's retry) -// The lazy block holding address, as base and size; false when there is none. +// The lazy block holding address, as base and size; false when there is none. The caller holds lazy_blocks.lock +// until it has committed what it found, so that a release (virtual_free_lazy) cannot run in between and leave it +// committing addresses that no longer belong to the block. bool lazy_block_at(ULONG_PTR address, ULONG_PTR& base, SIZE_T& bytes) { - AcquireSRWLockShared(&lazy_blocks.lock); auto it = lazy_blocks.blocks.upper_bound(address); const bool inside = it != lazy_blocks.blocks.begin() && (--it, address - it->first < it->second); if (inside) { base = it->first; bytes = it->second; } - ReleaseSRWLockShared(&lazy_blocks.lock); return inside; } @@ -184,11 +193,12 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) ULONG_PTR base = 0; SIZE_T bytes = 0; MEMORY_BASIC_INFORMATION info{}; - if (lazy_block_at(address, base, bytes) && VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) && - info.State == MEM_RESERVE) { - if (!commit_block_chunks(base, bytes, address, address + 1)) return EXCEPTION_CONTINUE_SEARCH; - return EXCEPTION_CONTINUE_EXECUTION; - } + AcquireSRWLockShared(&lazy_blocks.lock); + const bool lazy = lazy_block_at(address, base, bytes) && + VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) && info.State == MEM_RESERVE; + const bool committed = lazy && commit_block_chunks(base, bytes, address, address + 1); + ReleaseSRWLockShared(&lazy_blocks.lock); + if (lazy) return committed ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; // Another thread committed this chunk (or the whole block, which then leaves the list) between the fault // and the query: committed read-write memory cannot fault, so retry once. The retry is keyed on the chunk // and on the release count, so a fault that stays is passed on, while a new block later placed at the same @@ -1017,8 +1027,14 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) if (lazy_startup()) { ULONG_PTR base = 0; SIZE_T block_bytes = 0; - for (; from < end && lazy_block_at(from, base, block_bytes); from = base + block_bytes) - if (!commit_block_chunks(base, block_bytes, from, end)) return FALSE; + bool committed = true; + AcquireSRWLockShared(&lazy_blocks.lock); + for (; from < end && lazy_block_at(from, base, block_bytes); from = base + block_bytes) { + committed = commit_block_chunks(base, block_bytes, from, end); + if (!committed) break; + } + ReleaseSRWLockShared(&lazy_blocks.lock); // keeps the commit's error + if (!committed) return FALSE; if (from >= end) return TRUE; // the range lies in lazy startup blocks } const std::lock_guard guard(memory.mutex); @@ -1036,14 +1052,15 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) // switch or when the address is in no lazy block; FALSE with the system error when the commit fails. extern "C" BOOL WINAPI x2w_xmem_commit_block(const void* address) { + if (!lazy_startup()) return TRUE; ULONG_PTR base = 0; SIZE_T bytes = 0; - if (!lazy_startup() || !lazy_block_at(reinterpret_cast(address), base, bytes)) return TRUE; - if (!VirtualAlloc(reinterpret_cast(base), bytes, MEM_COMMIT, PAGE_READWRITE)) return FALSE; AcquireSRWLockExclusive(&lazy_blocks.lock); - lazy_blocks.blocks.erase(base); - ReleaseSRWLockExclusive(&lazy_blocks.lock); - return TRUE; + const bool lazy = lazy_block_at(reinterpret_cast(address), base, bytes); + const bool committed = !lazy || VirtualAlloc(reinterpret_cast(base), bytes, MEM_COMMIT, PAGE_READWRITE); + if (lazy && committed) lazy_blocks.blocks.erase(base); + ReleaseSRWLockExclusive(&lazy_blocks.lock); // keeps the commit's error + return committed; } namespace { @@ -1060,21 +1077,23 @@ BOOL WINAPI read_file_committed(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD } // The title releases its startup blocks through its VirtualFree import: with X2W_XMEM_LAZY_STARTUP a released -// block leaves the lazy list first, so a later allocation at the same addresses is never committed as part of it. +// block leaves the lazy list, so a later allocation at the same addresses is never committed as part of it. The +// release runs under the list lock, so no commit of the block is in flight, and the block leaves the list only if +// the release succeeded: a refused release (a nonzero size, for instance) leaves it reserved and still lazy. using VirtualFreeFn = BOOL(WINAPI*)(LPVOID, SIZE_T, DWORD); VirtualFreeFn real_virtual_free; BOOL WINAPI virtual_free_lazy(LPVOID address, SIZE_T bytes, DWORD type) { - if (type & MEM_RELEASE) { - AcquireSRWLockExclusive(&lazy_blocks.lock); - const bool listed = lazy_blocks.blocks.erase(reinterpret_cast(address)) != 0; - ReleaseSRWLockExclusive(&lazy_blocks.lock); - // Counted before the block is released: a thread that faults in between sees the new count while the old - // block is still reserved, which costs it at most one extra retry. - if (listed) InterlockedIncrement(&lazy_block_releases); - } - return real_virtual_free(address, bytes, type); + if (!(type & MEM_RELEASE)) return real_virtual_free(address, bytes, type); + AcquireSRWLockExclusive(&lazy_blocks.lock); + const BOOL released = real_virtual_free(address, bytes, type); + const DWORD error = GetLastError(); + if (released && lazy_blocks.blocks.erase(reinterpret_cast(address))) + InterlockedIncrement(&lazy_block_releases); + ReleaseSRWLockExclusive(&lazy_blocks.lock); + SetLastError(error); + return released; } // Points the main module's imports of name at replacement; returns how many import slots were changed. @@ -1102,24 +1121,37 @@ int patch_main_import(const char* name, const void* replacement) noexcept return patched; } +// Test build only (tests/xmem_lazy_imports_check.cpp): X2W_XMEM_TEST_LAZY_HANDLER_FAILURE=1 refuses the handler. +bool add_lazy_handler() +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (x2w_local::env_on("X2W_XMEM_TEST_LAZY_HANDLER_FAILURE")) return false; +#endif + return AddVectoredExceptionHandler(1, lazy_commit_fault) != nullptr; +} + // With the switch, install the fault handler and the ReadFile wrapper when xmem.dll loads, before the title runs. -// The module is pinned: the handler must outlive any unload. +// The module is pinned: the handler must outlive any unload. If the handler cannot be installed, lazy commit stays +// off and nothing is wrapped. const bool lazy_commit_installed = [] { - if (!lazy_commit()) return false; + if (!lazy_commit_requested()) return false; HMODULE self = nullptr; - const bool handler = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, - reinterpret_cast(&lazy_commit_fault), &self) && - AddVectoredExceptionHandler(1, lazy_commit_fault); + lazy_handler_installed = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&lazy_commit_fault), &self) && + add_lazy_handler(); + if (!lazy_handler_installed) { + x2w_local::logf("x2w-xmem lazy commit (X2W_XMEM_LAZY_COMMIT): fault handler failed, pages committed when mapped"); + return false; + } real_read_file = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "ReadFile")); const int reads = real_read_file ? patch_main_import("ReadFile", reinterpret_cast(&read_file_committed)) : 0; - x2w_local::logf("x2w-xmem lazy commit (X2W_XMEM_LAZY_COMMIT): fault handler %s, %d ReadFile import(s) wrapped", - handler ? "on" : "failed", reads); + x2w_local::logf("x2w-xmem lazy commit (X2W_XMEM_LAZY_COMMIT): fault handler on, %d ReadFile import(s) wrapped", reads); if (lazy_startup()) { real_virtual_free = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "VirtualFree")); const int frees = real_virtual_free ? patch_main_import("VirtualFree", reinterpret_cast(&virtual_free_lazy)) : 0; x2w_local::logf("x2w-xmem lazy startup blocks (X2W_XMEM_LAZY_STARTUP): %d VirtualFree import(s) wrapped", frees); } - return handler; + return true; }(); } // namespace diff --git a/tests/xmem_lazy_imports_check.cpp b/tests/xmem_lazy_imports_check.cpp index c9402d9c91..2f0620bb6e 100644 --- a/tests/xmem_lazy_imports_check.cpp +++ b/tests/xmem_lazy_imports_check.cpp @@ -8,8 +8,13 @@ // - VirtualFree: this program releases a lazy startup block through its own VirtualFree import, reserves the // same addresses again, and touches them. The touch must fault: a block still on the lazy list would be // committed by the fault handler as if it were the old block. +// - A refused release: MEM_RELEASE with a nonzero size fails, so the block stays reserved and must stay lazy. A +// write to an untouched page after it must still be committed by the fault handler; then the block is released. // -// Usage: xmem_lazy_imports_check +// With `handler-failure` (the test-controls build, X2W_XMEM_TEST_LAZY_HANDLER_FAILURE=1): the fault handler is +// refused, so the switches must act as off. A mapped page and a startup block are committed up front. +// +// Usage: xmem_lazy_imports_check [handler-failure] #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include @@ -46,6 +51,17 @@ bool read_faults(volatile const unsigned char* address) } } +// True when writing the byte faults; kept free of C++ objects for __try. +bool write_faults(volatile unsigned char* address) +{ + __try { + *address = 0x5a; + return false; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return true; + } +} + DWORD state(const void* address) { MEMORY_BASIC_INFORMATION info{}; @@ -55,13 +71,15 @@ DWORD state(const void* address) int main(int argc, char** argv) { - if (argc < 2) { - std::printf("usage: xmem_lazy_imports_check \n"); + const bool handler_failure = argc > 2 && std::strcmp(argv[2], "handler-failure") == 0; + if (argc < 2 || (argc > 2 && !handler_failure)) { + std::printf("usage: xmem_lazy_imports_check [handler-failure]\n"); return 2; } // xmem.dll reads the switches and wraps this program's imports when it loads. SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); SetEnvironmentVariableA("X2W_XMEM_LAZY_STARTUP", "1"); + if (handler_failure) SetEnvironmentVariableA("X2W_XMEM_TEST_LAZY_HANDLER_FAILURE", "1"); const HMODULE xmem = LoadLibraryA(argv[1]); if (!xmem) { std::printf("check_failed: load (error %lu)\n", GetLastError()); @@ -76,6 +94,32 @@ int main(int argc, char** argv) return 1; } + if (handler_failure) { + // No fault handler: nothing may be left for a first touch to commit. + void* const reservation = virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE); + SIZE_T count = pages, tokens[pages] = {}; + const bool mapped = reservation && allocate(0x20400000, &count, tokens) && count == pages && + map(reservation, pages, tokens) == reservation; + check(mapped, "map"); + if (mapped) { + auto* const target = static_cast(reservation) + page; + check(state(target) == MEM_COMMIT, "page_committed_without_handler"); + check(!write_faults(target), "page_writable_without_handler"); + map(reservation, pages, nullptr); + release(pages, tokens); + } + if (reservation) VirtualFree(reservation, 0, MEM_RELEASE); + void* const block = virtual_alloc(nullptr, block_bytes, 0x20403000, 0x181, PAGE_READWRITE); + auto* const inside = static_cast(block) + page; + check(block && state(inside) == MEM_COMMIT, "block_committed_without_handler"); + if (block) { + check(!write_faults(inside), "block_writable_without_handler"); + VirtualFree(block, 0, MEM_RELEASE); + } + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } + // ReadFile into an untouched mapped page, through this program's import. void* const reservation = virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE); SIZE_T count = pages, tokens[pages] = {}; @@ -122,6 +166,20 @@ int main(int argc, char** argv) VirtualFree(again, 0, MEM_RELEASE); } } + + // A refused release leaves the block reserved and lazy: a later first touch is still committed. + void* const kept = virtual_alloc(nullptr, block_bytes, 0x20403000, 0x181, PAGE_READWRITE); + check(kept && state(kept) == MEM_RESERVE, "kept_block_left_lazy"); + if (kept) { + SetLastError(ERROR_SUCCESS); + const BOOL refused = VirtualFree(kept, block_bytes, MEM_RELEASE); // MEM_RELEASE needs size 0 + check(!refused && GetLastError() == ERROR_INVALID_PARAMETER, "release_with_size_refused"); + auto* const untouched = static_cast(kept) + 2 * page; + check(state(untouched) == MEM_RESERVE, "refused_release_kept_reservation"); + check(!write_faults(untouched), "refused_release_block_still_lazy"); + check(state(untouched) == MEM_COMMIT && *untouched == 0x5a, "refused_release_write_committed"); + check(VirtualFree(kept, 0, MEM_RELEASE) != FALSE, "release_after_refusal"); + } std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; }