From 17ee827d371ee589c4237369dbde8255c2bdb2c6 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:45:03 +1000 Subject: [PATCH 01/34] xmem: split slot 31 placeholders when the OS hides the placeholder bit The region query reports placeholders with Flags bit 0x100 on Windows. Wine leaves it 0, so alias_placeholders refused every split or coalesce and queue slot 31 batches failed with ERROR_INVALID_ADDRESS whenever a run was not exactly one placeholder. Probe once: if the bit is missing and VirtualFree with MEM_PRESERVE_PLACEHOLDER refuses a plain reservation and leaves it whole, offer any reserved region to the split. A plain one then fails the split instead of being released. Where the bit is reported nothing changes. --- src/xmem_mapped_pages.cpp | 54 ++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index c212772964..68b6e6bfd0 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1131,19 +1131,61 @@ struct AliasEdit { using AliasPlan = std::map; using ViewRuns = std::map; +// The region query exposes the placeholder reservation flag in Flags even though the SDK does not name that bit. +constexpr ULONG placeholder_reservation = 0x100; + +// Measured once: whether the region query reports placeholder_reservation for a fresh placeholder, and, when it does +// not, whether VirtualFree(MEM_PRESERVE_PLACEHOLDER) refuses a plain reservation and leaves it whole. Windows reports +// the bit. Wine (Proton Experimental, 2026-11) leaves Flags 0 for placeholders but refuses the plain case with +// ERROR_INVALID_ADDRESS. X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 skips the second probe (tests only). +bool placeholder_fallback() +{ + static const bool fallback = [] { + bool bit_reported = false, refuses_plain = false; + if (void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)) { + WIN32_MEMORY_REGION_INFORMATION info{}; + bit_reported = QueryVirtualMemoryInformation(GetCurrentProcess(), probe, MemoryRegionInfo, &info, + sizeof(info), nullptr) && + (info.Flags & placeholder_reservation); + VirtualFree(probe, 0, MEM_RELEASE); + } + if (!bit_reported && !x2w_local::env_on("X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK")) { + if (auto* plain = static_cast(VirtualAlloc(nullptr, 2 * page_bytes, MEM_RESERVE, PAGE_NOACCESS))) { + MEMORY_BASIC_INFORMATION after{}; + refuses_plain = !VirtualFree(plain + page_bytes, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) && + VirtualQuery(plain, &after, sizeof(after)) == sizeof(after) && + after.State == MEM_RESERVE && after.AllocationBase == plain && + after.RegionSize == 2 * page_bytes; + VirtualFree(plain, 0, MEM_RELEASE); + } + } + x2w_local::logf("x2w-xmem placeholder bit reported=%d, plain reservation kept by a placeholder release=%d", + bit_reported, refuses_plain); + return !bit_reported && refuses_plain; + }(); + return fallback; +} + bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) { - // The region query exposes the placeholder reservation flag in Flags even though the - // SDK does not name that bit. VirtualQuery alone cannot distinguish a reserved private - // allocation from a placeholder. PRESERVE_PLACEHOLDER can silently release that allocation. - constexpr ULONG placeholder_reservation = 0x100; + // VirtualQuery alone cannot distinguish a reserved private allocation from a placeholder, and on Windows + // PRESERVE_PLACEHOLDER can silently release that allocation. Where the region query does not report the bit + // and the OS refuses that release (placeholder_fallback), any reserved region may be offered: a plain one + // fails the split instead of being released. + const bool fallback = placeholder_fallback(); const auto end = address + bytes; while (address < end) { WIN32_MEMORY_REGION_INFORMATION info{}; if (!QueryVirtualMemoryInformation(GetCurrentProcess(), reinterpret_cast(address), - MemoryRegionInfo, &info, sizeof(info), nullptr) || - !(info.Flags & placeholder_reservation)) + MemoryRegionInfo, &info, sizeof(info), nullptr)) return false; + if (!(info.Flags & placeholder_reservation)) { + MEMORY_BASIC_INFORMATION region{}; + if (!fallback || VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) != sizeof(region) || + region.State != MEM_RESERVE) + return false; + } const auto base = reinterpret_cast(info.AllocationBase); if (address - base >= info.RegionSize) return false; address += info.RegionSize - (address - base); From 364d3b4b5ed6a93dfca94cc1d23bd6a6127ff1f9 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:50:05 +1000 Subject: [PATCH 02/34] tests: slot 31 split inside an XMem reservation, with a committed-target control xmem_placeholder_split maps two pool pages into the middle of an XMem reservation through X2WMapPageBatch and checks the bytes, a write through the destination and the reserved neighbours. A batch onto a committed page in the same reservation must fail and keep its bytes. xmem_placeholder_split_control disables the fallback and passes only when the split step fails; it skips where the OS reports the placeholder bit. --- CMakeLists.txt | 15 ++++ tests/xmem_placeholder_split_check.cpp | 109 +++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 tests/xmem_placeholder_split_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8d9886fdfc..add769f920 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -339,6 +339,21 @@ foreach(adapter warp hardware) add_test(NAME xmem_section_lease_vertex_${adapter} COMMAND xmem_section_lease_check ${adapter} "$" vertex) set_tests_properties(xmem_section_lease_vertex_${adapter} xmem_section_lease_mesh_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endforeach() +# Slot 31 placeholder split inside an XMem reservation. The control disables the fallback used where the OS does +# not report placeholders (Wine), so the split fails there; where the OS reports them, the control skips (77). +add_executable(xmem_placeholder_split_check tests/xmem_placeholder_split_check.cpp) +target_include_directories(xmem_placeholder_split_check PRIVATE src) +target_compile_features(xmem_placeholder_split_check PRIVATE cxx_std_17) +target_link_libraries(xmem_placeholder_split_check PRIVATE OneCore) +add_dependencies(xmem_placeholder_split_check xmem_shim) +set(xmem_placeholder_env "X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") +add_test(NAME xmem_placeholder_split COMMAND xmem_placeholder_split_check "$") +set_tests_properties(xmem_placeholder_split PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the split itself fails, not on an earlier setup failure. +add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check "$" control) +set_tests_properties(xmem_placeholder_split_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1" + PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 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/tests/xmem_placeholder_split_check.cpp b/tests/xmem_placeholder_split_check.cpp new file mode 100644 index 0000000000..767c3a6579 --- /dev/null +++ b/tests/xmem_placeholder_split_check.cpp @@ -0,0 +1,109 @@ +// Queue slot 31 (X2WMapPageBatch) into the middle of an XMem reservation needs a placeholder split. Where the region +// query does not report placeholders (Wine), xmem probes whether a placeholder release refuses a plain reservation +// and then offers reserved regions to the split (xmem placeholder_fallback). +// xmem_placeholder_split_check split succeeds; a committed target still fails and stays intact +// xmem_placeholder_split_check control the same checks, run with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 +// by CTest, which expects the split step to fail; exits 77 where +// the OS reports the bit, because there the fallback is never used +#include +#include "xmem_page_batch.h" +#include +#include +#include + +namespace { +constexpr SIZE_T page_bytes = 65536; +constexpr UINT pool_pages = 4; +using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +using Scatter = BOOL (WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); + +bool require(bool ok, const char* step) +{ + if (!ok) std::printf("FAIL: %s (last error %lu)\n", step, GetLastError()); + return ok; +} + +bool os_reports_placeholder_bit() +{ + void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, nullptr, 0); + if (!probe) return false; + WIN32_MEMORY_REGION_INFORMATION info{}; + const bool bit = QueryVirtualMemoryInformation(GetCurrentProcess(), probe, MemoryRegionInfo, &info, sizeof(info), + nullptr) && (info.Flags & 0x100); + VirtualFree(probe, 0, MEM_RELEASE); + return bit; +} + +MEMORY_BASIC_INFORMATION query(const BYTE* pointer) +{ + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(pointer, &info, sizeof(info)); + return info; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + if (argc != 2 && !control) return 2; + const bool bit = os_reports_placeholder_bit(); + std::printf("placeholder bit reported=%d\n", bit); + if (control && bit) { + std::puts("SKIP: the OS reports the placeholder bit, so the fallback is never used"); + return 77; + } + const HMODULE xmem = LoadLibraryW(argv[1]); + if (!require(xmem != nullptr, "load xmem.dll")) return 1; + const auto reserve = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto alloc = reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto scatter = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPagesScatter")); + const auto batch_map = reinterpret_cast(GetProcAddress(xmem, "X2WMapPageBatch")); + if (!require(reserve && alloc && scatter && batch_map, "find the xmem exports")) return 1; + + auto* const pool = static_cast(reserve(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!require(pool != nullptr, "reserve XMem addresses")) return 1; + ULONG_PTR grants[pool_pages]{}, count = pool_pages; + void* addresses[pool_pages]{}; + for (UINT i = 0; i < pool_pages; ++i) addresses[i] = pool + i * page_bytes; + if (!require(alloc(0x280, &count, grants) && count == pool_pages, "allocate the pool") || + !require(scatter(addresses, pool_pages, grants), "map the pool")) + return 1; + for (UINT i = 0; i < pool_pages; ++i) std::memset(addresses[i], 0x51 + i, page_bytes); + + // Negative control: a committed page inside the reservation is not a placeholder. The batch must fail and leave + // the page committed with its bytes. + BYTE* const committed = pool + 64 * page_bytes; + if (!require(VirtualFree(committed, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split out a page") || + !require(VirtualAlloc2(GetCurrentProcess(), committed, page_bytes, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == committed, "commit that page")) + return 1; + std::memset(committed, 0x77, page_bytes); + const X2WPageRange one{0, 0, 1}; + const X2WPageBatch onto_committed{reinterpret_cast(committed), 1, &one}; + const HRESULT refused = batch_map(1, &onto_committed, reinterpret_cast(pool), pool_pages, 0, nullptr); + std::printf("batch onto a committed page -> 0x%08lx\n", static_cast(refused)); + // The code is the OS's map failure: Windows 487, Wine 87 (measured 2026-11-26). + if (!require(FAILED(refused), "a committed target is refused") || + !require(query(committed).State == MEM_COMMIT && committed[0] == 0x77 && committed[page_bytes - 1] == 0x77, + "the committed target keeps its bytes")) + return 1; + + // The split: pool pages 1 and 2 into the middle of an untouched part of the reservation. + BYTE* const window = pool + 128 * page_bytes; + const X2WPageRange two{0, 1, 2}; + const X2WPageBatch split{reinterpret_cast(window + page_bytes), 1, &two}; + const HRESULT hr = batch_map(1, &split, reinterpret_cast(pool), pool_pages, 0, nullptr); + std::printf("batch into the middle of the reservation -> 0x%08lx\n", static_cast(hr)); + if (!require(SUCCEEDED(hr), "map two pool pages into the middle of the reservation") || + !require(window[page_bytes] == 0x52 && window[2 * page_bytes] == 0x53 && window[3 * page_bytes - 1] == 0x53, + "the destination reads the pool pages") || + !require(query(window).State == MEM_RESERVE && query(window + 3 * page_bytes).State == MEM_RESERVE, + "the neighbours stay reserved")) + return 1; + window[page_bytes] = 0x60; + if (!require(pool[page_bytes] == 0x60, "a write through the destination reaches the pool page")) return 1; + std::puts("slot31 split inside an XMem reservation matched; a committed target was refused and kept"); + return 0; +} From e44e3cd5a7d0ee6d8eeea19f7bb3d22315f88117 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:50:05 +1000 Subject: [PATCH 03/34] docs: placeholder fallback for slot 31 splits under Wine --- README.md | 2 +- docs/experiments.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b94df39ff..fc23d1a64f 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | PE 32/64-bit base fixups against Windows | `ctest --preset dev --no-tests=error -R '^cpu_native_highlow$' -V` · [scope and controls](docs/experiments.md#highlow-and-mixed-width-base-relocations) | | [CPU counted cache-line zero loops](docs/experiments.md#counted-cache-line-zero-loops) | `ctest --preset release --no-tests=error -R '^cpu_counted_clzero$' -V` | | [Experimental startup stand-ins and debugger (trap-by-default DLLs)](docs/startup-runtime.md) | `ctest --preset release --no-tests=error -R '^startup_stubs$' -V` | -| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight' -V` | +| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` | | [Sample a texture by address in a translated draw](docs/startup-runtime.md#textures-published-by-address-device-slot-70) | `ctest --preset release --no-tests=error -R '^startup_address_console_' -V` | | [Desktop audio render sink and its three-case fixture (WASAPI)](docs/experiments.md#desktop-audio-render-sink) | `ctest --preset release --no-tests=error -R '^startup_audio_output$' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index f9fb98d4ec..e1d91e855c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10494,6 +10494,8 @@ Command queue slot 31 resolves 64 KiB pool pages against the views XMem currentl The `xmem_page_batch_inflight_{warp,hardware}` fixture holds a submitted GPU read behind an unsignaled fence, remaps the same virtual address, then releases the fence. The held read must see the old pattern. A second read binds the new section, writes a different pattern through its CPU pool after recording, and checks every byte across a 64 KiB boundary. Run `ctest --preset release --no-tests=error -R '^xmem_page_batch_inflight_' -V`. +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. It skips (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. + `vm_page_provenance_warp` and `vm_page_provenance_hardware` test the source side independently. Two pagefile sections hold distinct data and are mapped into adjacent CPU addresses in reverse creation order. D3D12 reopens those same sections as heaps. The test copies a 4 KiB span centered on the page boundary into a GPU buffer using the logical page order, then compares its readback with the two expected token patterns. It writes new data through the CPU aliases and reads the GPU buffer again before uploading, which must still return the old data. A second upload must produce all the updated words. The tests skip (77) if the requested adapter or section-backed D3D12 buffers are unavailable. [Opening a D3D12 heap from a file mapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping) Run `ctest --preset dev --no-tests=error -R '^vm_page_provenance_' -V`. From f1f90abf6601f02b93eb1f6f0138b2e244bc5796 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:14:14 +1000 Subject: [PATCH 04/34] xmem: copy DirectStorage destinations under the mapping mutex Add x2w_xmem_copy_to_destination. It checks that the whole destination capacity is committed and writable, and copies the data, both under memory.mutex. A run break (unmapping a page of a shared run and mapping its other pages again) also runs under that mutex, so it can neither make the check see a transient reservation nor start during the copy. Lazily mapped pages of both ranges are committed before the mutex is taken. A fault under the mutex is passed on: the lazy commit handler now skips mapping threads, as retry_remapped_page already did. The region walk moves from XCRDAPI's destination_writable to x2w_local::committed_writable, so both DLLs share one implementation. --- src/startup_stubs/local_log.h | 26 ++++++++++++ src/startup_stubs/xcrdapi.cpp | 29 ++++--------- src/xmem_mapped_pages.cpp | 76 ++++++++++++++++++++++++++++++++++- src/xmem_shim.def | 1 + 4 files changed, 110 insertions(+), 22 deletions(-) diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index bea306fde9..d12049bef8 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -129,4 +129,30 @@ inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexc inline bool readable(const void* pointer, std::size_t bytes) noexcept { return accessible(pointer, bytes, false); } inline bool writable(const void* pointer, std::size_t bytes) noexcept { return accessible(pointer, bytes, true); } +// True when every byte of [pointer, pointer + bytes) is committed and writable, with no guard or no-access page +// in between. Walks the regions one VirtualQuery at a time, so a range that spans regions of different +// protection is judged page by page. Nothing is written, touched or committed (see commit_lazy), so it is safe +// under xmem's mapping lock. An empty range is writable; a null or wrapping one is not. +inline bool committed_writable(const void* pointer, std::size_t bytes) noexcept +{ + if (bytes == 0) return true; + std::uintptr_t cursor = reinterpret_cast(pointer); + if (!pointer || bytes > ~std::uintptr_t{0} - cursor) return false; + const std::uintptr_t end = cursor + bytes; + while (cursor < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; + const DWORD protect = info.Protect & 0xFF; + if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && + protect != PAGE_EXECUTE_WRITECOPY) + return false; + const std::uintptr_t region_end = reinterpret_cast(info.BaseAddress) + info.RegionSize; + if (region_end <= cursor) return false; + cursor = region_end; + } + return true; +} + } // namespace x2w_local diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index a711551975..6e55693dbe 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -200,30 +200,17 @@ static bool resident_read_write(std::uintptr_t start, std::uintptr_t end) // True when every byte of [destination, destination + bytes) is committed and writable, with no guard or // no-access page in between. Nothing is written or touched. Resident read-write pages are accepted from // their working-set attributes; any other page (not resident, copy-on-write, guard, no access) sends the -// destination to the VirtualQuery walk, which judges it region by region. That walk is slow on the title's -// large regions: each query scans to the end of the region (#2684). +// destination to the region walk (x2w_local::committed_writable), which judges it region by region. That walk +// is slow on the title's large regions: each query scans to the end of the region (#2684). Lazily mapped +// physical pages (X2W_XMEM_LAZY_COMMIT) are committed first. 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; - if (resident_read_write(cursor, end)) return true; - while (cursor < end) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) - return false; - if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; - const DWORD protect = info.Protect & 0xFF; - if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && - protect != PAGE_EXECUTE_WRITECOPY) - return false; - const std::uintptr_t region_end = reinterpret_cast(info.BaseAddress) + info.RegionSize; - if (region_end <= cursor) return false; - cursor = region_end; - } - return true; + const auto start = reinterpret_cast(destination); + if (!destination || bytes > UINTPTR_MAX - start) return false; + x2w_local::commit_lazy(destination, bytes); + if (resident_read_write(start, start + bytes)) return true; + return x2w_local::committed_writable(destination, bytes); } // Return the exact queued requests that continue this stream in this submission, in queue order. diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 68b6e6bfd0..eeb9b1ba44 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -262,6 +262,10 @@ const Backing* lease_backing(UINT version, ULONG_PTR page) return backing && backing->committed ? backing : nullptr; } +// Set while this thread holds memory.mutex to change mappings or to copy into mapped pages (MappingThread). The +// fault handlers pass such a thread's faults on: waiting for memory.mutex there would never return. +thread_local bool mapping_thread = false; + LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -296,6 +300,7 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) // 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); + if (mapping_thread) return EXCEPTION_CONTINUE_SEARCH; const std::lock_guard guard(memory.mutex); Backing* backing = backing_at(address); if (!backing) return EXCEPTION_CONTINUE_SEARCH; @@ -476,7 +481,6 @@ struct EndBreak { ~EndBreak() { end_break(); } }; // mutex) the page is recorded and covered by a view; and this thread has not already retried this // page for this break. Everything else is passed on, so a fault that is not the transient one is // reported after at most one retry. -thread_local bool mapping_thread = false; LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -1591,6 +1595,76 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) return TRUE; } +namespace { +// Keep the guarded copy out of functions that need unwinding (as read_alias_record). +bool copy_guarded(void* destination, const void* data, SIZE_T bytes) noexcept +{ + __try { + std::memcpy(destination, data, bytes); + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || + GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +// The longest hold of memory.mutex by a destination copy, and the largest copy, so far (under memory.mutex). +double copy_hold_max_ms = 0; +SIZE_T copy_bytes_max = 0; +} // namespace + +// The DirectStorage stand-in's copy into a plain-memory destination (XCRDAPI). The check that all of +// [destination, destination + capacity) is committed and writable and the copy of bytes from data both run under +// memory.mutex. Unmapping a page of a shared run takes the whole run away until its other pages are mapped again +// (map_pages_locked, remap_alias_pages), all under that mutex, so neither the check nor the copy can fall into that +// window, and no such window can open while the copy runs. Lazily mapped pages of both ranges are committed first, +// before the mutex is taken: a fault under it is passed on (mapping_thread), not served. +// TRUE when the bytes were copied. FALSE with ERROR_NOACCESS when the destination is not writable (nothing is +// written), ERROR_INVALID_ADDRESS when the copy faulted (a source page not readable; part of the destination may be +// written), or ERROR_INVALID_PARAMETER for more bytes than capacity or null data. +extern "C" BOOL WINAPI x2w_xmem_copy_to_destination(void* destination, SIZE_T capacity, const void* data, SIZE_T bytes) +{ + if (bytes > capacity || (bytes && !data)) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + const auto start = reinterpret_cast(destination); + if (capacity && destination && capacity <= ~ULONG_PTR{0} - start) x2w_xmem_commit_range(destination, capacity); + if (bytes) x2w_xmem_commit_range(data, bytes); + DWORD error = ERROR_SUCCESS; + double held_ms = 0; + bool longest = false, largest = false; + { + const MappingThread marker; + const std::lock_guard guard(memory.mutex); + LARGE_INTEGER frequency{}, begin{}, end{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&begin); + if (!x2w_local::committed_writable(destination, capacity)) + error = ERROR_NOACCESS; + else if (bytes && !copy_guarded(destination, data, bytes)) + error = ERROR_INVALID_ADDRESS; + QueryPerformanceCounter(&end); + held_ms = frequency.QuadPart ? 1000.0 * static_cast(end.QuadPart - begin.QuadPart) / frequency.QuadPart : 0; + if (held_ms > copy_hold_max_ms) { + copy_hold_max_ms = held_ms; + longest = true; + } + if (!error && bytes > copy_bytes_max) { + copy_bytes_max = bytes; + largest = true; + } + } + // A line per new maximum (about the logarithm of the number of copies), logged after the mutex is released. + static volatile LONG lines; + if ((longest || largest) && x2w_local::first_calls(lines, 64)) + x2w_local::logf("x2w-xmem destination copy: %s%s%.3f ms under the mapping mutex for 0x%llx bytes (capacity 0x%llx)", + longest ? "longest hold so far, " : "", largest ? "largest copy so far, " : "", held_ms, + static_cast(bytes), static_cast(capacity)); + SetLastError(error); + return error == ERROR_SUCCESS; +} + // 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 diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 3776c7529f..9e48a922bc 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -22,3 +22,4 @@ EXPORTS x2w_xmem_release_section @20 x2w_xmem_match_section @21 X2WMapPageBatch @22 + x2w_xmem_copy_to_destination @23 From b7b1552e253ce318b86767ccbc887d33b84ec34c Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:15:24 +1000 Subject: [PATCH 05/34] startup: copy DirectStorage data through x2w_xmem_copy_to_destination A plain-memory destination is now checked and written by xmem.dll under its mapping mutex when the export is there. Before, the VirtualQuery pre-check could run while an XMem run break had the destination's page unmapped for a moment, and refuse a destination that was mapped before and after. Without xmem.dll the check and the copy run in XCRDAPI as before. A copy that faults on its source now fails the request ("copy faulted (source not readable)") instead of raising in the stand-in. --- src/startup_stubs/xcrdapi.cpp | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 6e55693dbe..ac6df58902 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -213,6 +213,25 @@ static bool destination_writable(const void* destination, std::size_t bytes) return x2w_local::committed_writable(destination, bytes); } +// Copies bytes of data into a plain-memory destination whose whole declared capacity must be writable. With +// xmem.dll loaded, x2w_xmem_copy_to_destination makes the check and the copy under XMem's mapping mutex, so an +// XMem run break (the pages of a shared view unmapped and mapped again) can neither make a mapped destination +// look reserved nor take it away during the copy. Without xmem.dll the check and the copy run here. +// ERROR_SUCCESS; ERROR_NOACCESS when the destination is not writable (nothing written); another error when the +// copy faulted. +static DWORD copy_to_destination(void* destination, std::size_t capacity, const void* data, std::size_t bytes) +{ + using CopyToDestination = BOOL(WINAPI*)(void*, SIZE_T, const void*, SIZE_T); + static const CopyToDestination copy = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_copy_to_destination")) : nullptr; + }(); + if (copy) return copy(destination, capacity, data, bytes) ? ERROR_SUCCESS : GetLastError(); + if (!destination_writable(destination, capacity)) return ERROR_NOACCESS; + std::memcpy(destination, data, bytes); + return ERROR_SUCCESS; +} + // Return the exact queued requests that continue this stream in this submission, in queue order. // Status entries and requests for unrelated files are skipped. In the same file, any non-matching // size, non-consecutive offset, or submission boundary ends the continuation chain (Refs #1136, #1144, #1198, #1214). @@ -930,11 +949,10 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR // The title's destination can be smaller in memory than its declared capacity (#870: // a write fault inside this copy). Judge the whole declared capacity before the first // byte is written, so a refusal leaves every page untouched. - if (destination_writable(destination, destination_capacity)) { - std::memcpy(destination, data, decode_length); - } else { - outcome = "destination not writable"; - failure = StorageFailure::destination_not_writable; + const DWORD copied = copy_to_destination(destination, destination_capacity, data, decode_length); + if (copied != ERROR_SUCCESS) { + outcome = copied == ERROR_NOACCESS ? "destination not writable" : "copy faulted (source not readable)"; + failure = copied == ERROR_NOACCESS ? StorageFailure::destination_not_writable : StorageFailure::other; data = nullptr; written = false; } From 4de5c09e824d37c297ed406a12fde0e8b580e3b7 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:17:18 +1000 Subject: [PATCH 06/34] tests: DirectStorage copy during an XMem run break startup_dstorage_break_window holds an unmap of page 5 of an 8-page run in the window where the run is apart (the xmem test-controls build's X2W_XMEM_TEST_HOLD_WINDOW), checks that page 2 reads MEM_RESERVE there, and submits a memory-source request into page 2. The request must not complete within the 1000 ms hold, then complete with S_OK with every byte in place after the release. It also covers a request with no break and a read-only destination refused on the xmem path. startup_dstorage_break_window_control builds XCRDAPI with the export lookup's name changed, so it judges the destination with its own VirtualQuery inside the window. It must report "refused while the run was broken". --- CMakeLists.txt | 33 +++ tests/startup_dstorage_break_window_check.cpp | 240 ++++++++++++++++++ 2 files changed, 273 insertions(+) create mode 100644 tests/startup_dstorage_break_window_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index add769f920..6d5de9f5db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -958,6 +958,39 @@ target_compile_features(startup_dstorage_destination_check PRIVATE cxx_std_17) add_dependencies(startup_dstorage_destination_check startup_stub_xcrdapi) add_test(NAME startup_dstorage_destination COMMAND startup_dstorage_destination_check "$") set_tests_properties(startup_dstorage_destination PROPERTIES TIMEOUT 60) +# A request whose destination page an XMem run break holds unmapped (the xmem test-controls build's +# X2W_XMEM_TEST_HOLD_WINDOW) must not complete within the 1000 ms hold, then land after the release. +# Control: XCRDAPI without the x2w_xmem_copy_to_destination lookup judges the destination with its own VirtualQuery +# inside the window and refuses it. +add_executable(startup_dstorage_break_window_check tests/startup_dstorage_break_window_check.cpp) +target_compile_features(startup_dstorage_break_window_check PRIVATE cxx_std_17) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi xmem_shim_test_controls) +add_test(NAME startup_dstorage_break_window COMMAND startup_dstorage_break_window_check + "$" "$") +set_tests_properties(startup_dstorage_break_window PROPERTIES TIMEOUT 60) +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) +string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text + "${xcrdapi_text}") +if(xcrdapi_control_text STREQUAL xcrdapi_text) + message(FATAL_ERROR "xcrdapi.cpp lost the anchor used by startup_dstorage_break_window_control") +endif() +set(xcrdapi_control "${CMAKE_CURRENT_BINARY_DIR}/xcrdapi_break_window_control/xcrdapi.cpp") +file(WRITE "${xcrdapi_control}" "${xcrdapi_control_text}") +add_library(startup_stub_xcrdapi_break_window_control SHARED "${xcrdapi_control}" src/startup_stubs/xcrdapi.def) +set_target_properties(startup_stub_xcrdapi_break_window_control PROPERTIES OUTPUT_NAME XCRDAPI + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +target_include_directories(startup_stub_xcrdapi_break_window_control PRIVATE src) +target_compile_features(startup_stub_xcrdapi_break_window_control PRIVATE cxx_std_17) +target_link_libraries(startup_stub_xcrdapi_break_window_control PRIVATE psapi) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi_break_window_control) +add_test(NAME startup_dstorage_break_window_control COMMAND startup_dstorage_break_window_check + "$" "$") +set_tests_properties(startup_dstorage_break_window_control PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "FAIL break window: refused while the run was broken") add_executable(startup_storage_worker_start tests/startup_storage_worker_start.cpp) target_compile_features(startup_storage_worker_start PRIVATE cxx_std_17) target_include_directories(startup_storage_worker_start PRIVATE src) diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp new file mode 100644 index 0000000000..d04d329bac --- /dev/null +++ b/tests/startup_dstorage_break_window_check.cpp @@ -0,0 +1,240 @@ +// A DirectStorage request whose destination lies in an XMem run that is being taken apart must wait for the break +// and then land, not be refused. +// +// With shared views (X2W_XMEM_SHARED_VIEWS=1) adjacent pages of one batch share a view, and unmapping one page of +// such a run unmaps the whole run and maps its other pages again, under xmem's mapping mutex. For that moment a +// surviving page reads as reserved. The xmem build with its test controls holds an unmap in that window +// (X2W_XMEM_TEST_HOLD_WINDOW=: it sets ".unmapped" and waits up to five seconds for ".release"). +// +// usage: startup_dstorage_break_window_check +// Cases, each against the real stand-in's queue with a memory source: +// - no break: a request into a mapped page of the run lands; +// - read-only destination: refused, nothing written (the writability check also runs on the xmem path); +// - break held: while an unmap holds page 2's run apart (page 2 reads MEM_RESERVE), a request into page 2 must not +// complete for the whole hold window (1000 ms, polled every 10 ms); after the release it completes with S_OK and +// every byte landed. An XCRDAPI that judges the destination with its own VirtualQuery instead refuses inside the +// window: "FAIL break window: refused while the run was broken" (the negative control in CMakeLists.txt). +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include + +namespace { +using u64 = std::uint64_t; +struct Object { void** vtable; }; +using GetFactoryFn = long(__stdcall*)(const void*, void**); +using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const void*, void**); +using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); +using EnqueueRequestFn = void(__stdcall*)(void*, const void*); +using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using SubmitFn = void(__stdcall*)(void*); +using IsCompleteFn = bool(__stdcall*)(void*, unsigned); +using GetHResultFn = long(__stdcall*)(void*, unsigned); +using VirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocatePagesFn = BOOL(WINAPI*)(ULONG_PTR, PULONG_PTR, PULONG_PTR); +using MapPagesFn = void*(WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); +using ScatterFn = BOOL(WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); + +constexpr SIZE_T page = 65536; +constexpr unsigned run_pages = 8; +constexpr unsigned bytes = 4096; +constexpr DWORD hold_ms = 1000; // the window in which a request into the broken run must not complete +constexpr DWORD poll_ms = 10; +unsigned char source[bytes]; +int failures; + +Object* status; +Object* queue; +unsigned next_index; + +void fail(const char* name, const char* what) +{ + std::printf("FAIL %s: %s\n", name, what); + ++failures; +} + +// Enqueues one uncompressed memory-source request and submits it; returns its status index. +unsigned submit(unsigned char* destination, unsigned capacity, unsigned size) +{ + unsigned char request[0x48] = {}; + *reinterpret_cast(request + 0x00) = 0x400000; + *reinterpret_cast(request + 0x08) = destination; + *reinterpret_cast(request + 0x18) = capacity; + *reinterpret_cast(request + 0x20) = source; + *reinterpret_cast(request + 0x30) = size; + const unsigned index = next_index++; + reinterpret_cast(queue->vtable[3])(queue, request); + reinterpret_cast(queue->vtable[4])(queue, status, index); + reinterpret_cast(queue->vtable[6])(queue); + return index; +} + +// Polls the status entry for up to milliseconds; true with its HRESULT when it completed. +bool completed_within(unsigned index, DWORD milliseconds, long& hr) +{ + for (DWORD waited = 0;; waited += poll_ms) { + if (reinterpret_cast(status->vtable[3])(status, index)) { + hr = reinterpret_cast(status->vtable[4])(status, index); + return true; + } + if (waited >= milliseconds) return false; + Sleep(poll_ms); + } +} + +bool filled(const unsigned char* at, unsigned char value, unsigned count) +{ + for (unsigned i = 0; i < count; ++i) + if (at[i] != value) return false; + return true; +} + +DWORD query_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +struct Unmap { + ScatterFn scatter; + void* address; + BOOL result; +}; + +DWORD WINAPI unmap_one(void* context) +{ + auto* unmap = static_cast(context); + unmap->result = unmap->scatter(&unmap->address, 1, nullptr); // no pages: unmap + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) { + std::printf("usage: startup_dstorage_break_window_check \n"); + return 2; + } + char hold_name[64]; + std::snprintf(hold_name, sizeof(hold_name), "x2w-dstorage-break-window-%lu", GetCurrentProcessId()); + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold_name); + + // xmem first: XCRDAPI finds it by module name (GetModuleHandleW(L"xmem.dll")). + HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem || GetModuleHandleW(L"xmem.dll") != xmem) { + std::printf("FAIL setup: %s is not loaded as xmem.dll\n", argv[1]); + 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 scatter = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPagesScatter")); + HMODULE library = LoadLibraryA(argv[2]); + auto* get_factory = library ? reinterpret_cast(GetProcAddress(library, "DStorageGetFactory")) : nullptr; + if (!virtual_alloc || !allocate || !map || !scatter || !get_factory) { + std::printf("FAIL setup: missing export\n"); + return 1; + } + void* factory_pointer = nullptr; + if (get_factory(nullptr, &factory_pointer) != 0 || !factory_pointer) return 1; + auto* factory = static_cast(factory_pointer); + void* status_pointer = nullptr; + void* queue_pointer = nullptr; + unsigned char description[0x28] = {}; + *reinterpret_cast(description + 8) = 16; + if (reinterpret_cast(factory->vtable[5])(factory, 8, "Status", nullptr, &status_pointer) != 0 || + reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue_pointer) != 0) + return 1; + status = static_cast(status_pointer); + queue = static_cast(queue_pointer); + for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast(i % 251 + 1); + + // Eight physical pages mapped as one run at the start of a startup reservation (as xmem_page_runs_check.py). + auto* whole = static_cast(virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + ULONG_PTR count = run_pages, tokens[run_pages] = {}; + unsigned char* base = whole ? whole + page : nullptr; + if (!base || !allocate(0x20400000, &count, tokens) || count != run_pages || map(base, run_pages, tokens) != base) { + std::printf("FAIL setup: could not map %u pages (err %lu)\n", run_pages, GetLastError()); + return 1; + } + MEMORY_BASIC_INFORMATION run{}; + if (!VirtualQuery(base, &run, sizeof(run)) || run.Type != MEM_MAPPED || run.RegionSize < run_pages * page) { + std::printf("FAIL setup: the %u pages are not one view (region 0x%zx), so no unmap takes a run apart\n", run_pages, + static_cast(run.RegionSize)); + return 1; + } + unsigned char* target = base + 2 * page; + + // No break: the request lands. + std::memset(target, 0xAA, bytes); + long hr = -1; + if (!completed_within(submit(target, bytes, bytes), 5000, hr)) fail("no break", "no completion"); + else if (hr != 0) fail("no break", "request failed"); + else if (std::memcmp(target, source, bytes) != 0) fail("no break", "bytes differ"); + else std::printf("ok: no break: the request into page 2 of the run landed\n"); + + // Read-only destination: refused before any write, on the xmem path too. + auto* plain = static_cast(VirtualAlloc(nullptr, 2 * bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + DWORD old = 0; + if (!plain) { + fail("read-only destination", "VirtualAlloc"); + } else { + std::memset(plain, 0xAA, 2 * bytes); + if (!VirtualProtect(plain + bytes, bytes, PAGE_READONLY, &old)) fail("read-only destination", "VirtualProtect"); + else if (!completed_within(submit(plain, 2 * bytes, bytes), 5000, hr)) fail("read-only destination", "no completion"); + else if (hr == 0) fail("read-only destination", "request succeeded"); + else if (!filled(plain, 0xAA, 2 * bytes)) fail("read-only destination", "bytes were written"); + else std::printf("ok: read-only destination: refused, nothing written\n"); + VirtualFree(plain, 0, MEM_RELEASE); + } + + // Break held: an unmap of page 5 takes the run apart and holds it there until released. + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold_name); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold_name); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::memset(target, 0xAA, bytes); + Unmap unmap{scatter, base + 5 * page, FALSE}; + HANDLE thread = unmapped && release ? CreateThread(nullptr, 0, unmap_one, &unmap, 0, nullptr) : nullptr; + if (!thread || WaitForSingleObject(unmapped, 10000) != WAIT_OBJECT_0) { + std::printf("FAIL break window: the unmap never held the run apart (hook missing or timed out)\n"); + if (release) SetEvent(release); + return 1; + } + if (query_state(target) != MEM_RESERVE) { + std::printf("FAIL break window: page 2 is not reserved while the run is apart (state 0x%lx)\n", query_state(target)); + SetEvent(release); + return 1; + } + std::printf("ok: break held: page 2 reads MEM_RESERVE while the run is apart\n"); + const unsigned index = submit(target, bytes, bytes); + const bool early = completed_within(index, hold_ms, hr); + const long early_hr = hr; + SetEvent(release); + const bool joined = WaitForSingleObject(thread, 10000) == WAIT_OBJECT_0; + if (early) { + if (early_hr != 0) fail("break window", "refused while the run was broken"); + else fail("break window", "completed while the run was broken"); + } else { + std::printf("ok: break held: no completion within %lu ms\n", hold_ms); + if (!completed_within(index, 5000, hr)) fail("break window", "no completion after the release"); + else if (hr != 0) fail("break window", "request failed after the release"); + else if (std::memcmp(target, source, bytes) != 0) fail("break window", "bytes differ after the release"); + else std::printf("ok: break released: the request completed with S_OK and every byte landed\n"); + } + if (!joined || !unmap.result) fail("break window", "the unmap of page 5 did not finish"); + CloseHandle(thread); + + if (failures) return 1; + std::printf("dstorage break window: the request waited for the break and landed\n"); + return 0; +} From 06dfe20e1ca8fc920e58c49ec7c790315b24ca97 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:59:15 +1000 Subject: [PATCH 07/34] xmem: split an owned placeholder before mapping a page into it A map into the middle of a larger placeholder always fails first, so every single-page XMemMapPhysicalPages call made two MapViewOfFile3 attempts. Under Wine each attempt is a server round trip whose cost grows with the view count. Split first when the target is not an exact placeholder; fall back to the map-first path if the split or the map fails. X2W_XMEM_TEST_MAP_FIRST=1 keeps the old order for tests. x2w_xmem_map_counts reports the attempts. --- CMakeLists.txt | 11 ++++ src/xmem_mapped_pages.cpp | 51 +++++++++++++-- src/xmem_shim.def | 1 + tests/xmem_map_split_first_check.cpp | 93 ++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 tests/xmem_map_split_first_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d5de9f5db..89438b15ab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -354,6 +354,17 @@ add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_chec set_tests_properties(xmem_placeholder_split_control PROPERTIES ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1" PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) +add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) +target_include_directories(xmem_map_split_first_check PRIVATE src) +target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) +add_dependencies(xmem_map_split_first_check xmem_shim) +add_test(NAME xmem_map_split_first COMMAND xmem_map_split_first_check "$") +add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check "$" control) +set_tests_properties(xmem_map_split_first PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the map-first order is measured (2 maps per page), not on a setup failure. +set_tests_properties(xmem_map_split_first_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_MAP_FIRST=1" + PASS_REGULAR_EXPRESSION "map-first control: maps=2N" 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/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index eeb9b1ba44..44c935a125 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -370,18 +370,50 @@ auto owned_reservation(ULONG_PTR address) return address - it->first < it->second ? it : memory.reservations.end(); } +// MapViewOfFile3 and placeholder-split attempts made by map_split (x2w_xmem_map_counts). +volatile LONG64 map_attempts, split_attempts; + +// True when [target, target + bytes) is a whole reserved region of its own: a placeholder that +// MEM_REPLACE_PLACEHOLDER can take as it is, so no split is needed first. +bool exact_placeholder(void* target, SIZE_T bytes) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_RESERVE && + info.AllocationBase == target && info.BaseAddress == target && info.RegionSize == bytes; +} + // Only split a reservation owned by the shim. Caller-owned placeholders must already match the view. +// Inside an owned reservation the split comes first when the target is not already an exact placeholder: +// a map into the middle of a larger placeholder always fails, and under Wine every failed map is another +// server round trip whose cost grows with the number of views (one 64 KiB page per call at startup). +// The query and the split are not atomic, so if the split or the map after it fails, the map-first +// path below runs as before. X2W_XMEM_TEST_MAP_FIRST=1 skips the split-first step (tests only). // Once a split succeeds, report the retry's result even if it fails for a different reason. template bool map_split(void* target, SIZE_T bytes, Map map) { - if (map()) return true; - const DWORD error = GetLastError(); + static const bool map_first = x2w_local::env_on("X2W_XMEM_TEST_MAP_FIRST"); const auto address = reinterpret_cast(target); const auto reservation = owned_reservation(address); - if (reservation != memory.reservations.end() && bytes <= reservation->second - (address - reservation->first) && - VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) - return map(); + const bool owned = reservation != memory.reservations.end() && + bytes <= reservation->second - (address - reservation->first); + if (owned && !map_first && !exact_placeholder(target, bytes)) { + InterlockedIncrement64(&split_attempts); + if (VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + InterlockedIncrement64(&map_attempts); + if (map()) return true; + } + } + InterlockedIncrement64(&map_attempts); + if (map()) return true; + const DWORD error = GetLastError(); + if (owned) { + InterlockedIncrement64(&split_attempts); + if (VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + InterlockedIncrement64(&map_attempts); + return map(); + } + } SetLastError(error); return false; } @@ -1552,6 +1584,15 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) // Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free // in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs // are closed when all of their slots are freed and unpinned. +// Test export: MapViewOfFile3 and placeholder-split attempts made by the physical-page map path so far. +extern "C" BOOL WINAPI x2w_xmem_map_counts(ULONGLONG* maps, ULONGLONG* splits) +{ + if (!maps || !splits) return FALSE; + *maps = static_cast(map_attempts); + *splits = static_cast(split_attempts); + return TRUE; +} + extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in_use, ULONGLONG* slots_free) { if (!slabs || !slots_in_use || !slots_free) return FALSE; diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 9e48a922bc..fe9dd7581b 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -23,3 +23,4 @@ EXPORTS x2w_xmem_match_section @21 X2WMapPageBatch @22 x2w_xmem_copy_to_destination @23 + x2w_xmem_map_counts @25 diff --git a/tests/xmem_map_split_first_check.cpp b/tests/xmem_map_split_first_check.cpp new file mode 100644 index 0000000000..4514fc6f3b --- /dev/null +++ b/tests/xmem_map_split_first_check.cpp @@ -0,0 +1,93 @@ +// XMemMapPhysicalPages into an owned XMem reservation: when the target is in the middle of a larger placeholder, xmem +// splits first and maps once (one MapViewOfFile3 per page). Under Wine each failed map is a server round trip whose +// cost grows with the number of views, and the title maps one 64 KiB page per call at startup. +// xmem_map_split_first_check N single-page maps take N map attempts; an exact placeholder +// (left by an unmap) is mapped without a split +// xmem_map_split_first_check control run by CTest with X2W_XMEM_TEST_MAP_FIRST=1: the old order takes +// 2N map attempts and prints "map-first control: maps=2N" +#include +#include +#include + +namespace { +constexpr SIZE_T page_bytes = 65536; +constexpr ULONG_PTR pages = 8; +using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +using MapPages = void* (WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); +using MapCounts = BOOL (WINAPI*)(ULONGLONG*, ULONGLONG*); + +bool require(bool ok, const char* step) +{ + if (!ok) std::printf("FAIL: %s (last error %lu)\n", step, GetLastError()); + return ok; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + if (argc != 2 && !control) return 2; + const HMODULE xmem = LoadLibraryW(argv[1]); + if (!require(xmem != nullptr, "load xmem.dll")) return 1; + const auto reserve = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto alloc = reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")); + const auto counts = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_map_counts")); + if (!require(reserve && alloc && map && counts, "find the xmem exports")) return 1; + auto* const pool = static_cast(reserve(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!require(pool != nullptr, "reserve XMem addresses")) return 1; + ULONG_PTR grants[pages]{}, count = pages; + if (!require(alloc(0x280, &count, grants) && count == pages, "allocate the pages")) return 1; + + // N single-page maps, each into the middle of the reservation's placeholder (every other page, so no two + // targets are neighbours). + ULONGLONG maps0 = 0, splits0 = 0, maps1 = 0, splits1 = 0; + if (!require(counts(&maps0, &splits0), "read the map counts")) return 1; + for (ULONG_PTR i = 0; i < pages; ++i) { + BYTE* const target = pool + (16 + 2 * i) * page_bytes; + if (!require(map(target, 1, &grants[i]) == target, "map one page into the reservation")) return 1; + target[0] = static_cast(0x40 + i); + target[page_bytes - 1] = static_cast(0x40 + i); + } + if (!require(counts(&maps1, &splits1), "read the map counts")) return 1; + const ULONGLONG maps = maps1 - maps0, splits = splits1 - splits0; + std::printf("%llu single-page maps: map attempts %llu, split attempts %llu\n", static_cast(pages), + maps, splits); + for (ULONG_PTR i = 0; i < pages; ++i) { + const BYTE* const target = pool + (16 + 2 * i) * page_bytes; + if (!require(target[0] == 0x40 + i && target[page_bytes - 1] == 0x40 + i, "each mapped page keeps its bytes")) + return 1; + } + MEMORY_BASIC_INFORMATION gap{}; + VirtualQuery(pool + 17 * page_bytes, &gap, sizeof(gap)); + if (!require(gap.State == MEM_RESERVE, "the page between two targets stays reserved")) return 1; + if (control) { + if (maps == 2 * pages && splits == pages) { + std::puts("map-first control: maps=2N"); + return 1; // CTest passes the control on the line above, not on the exit code + } + std::printf("FAIL: map-first control measured %llu maps for %llu pages\n", maps, + static_cast(pages)); + return 1; + } + if (!require(maps == pages && splits == pages, "split-first: one map attempt and one split per page")) return 1; + + // An exact placeholder: unmap the first page (the placeholder is kept), then map a page there again. No split. + BYTE* const first = pool + 16 * page_bytes; + if (!require(map(first, 1, nullptr) == first, "unmap the first page")) return 1; + MEMORY_BASIC_INFORMATION hole{}; + VirtualQuery(first, &hole, sizeof(hole)); + std::printf("after unmap: state 0x%lx base %p allocation %p size 0x%llx\n", hole.State, hole.BaseAddress, + hole.AllocationBase, static_cast(hole.RegionSize)); + if (!require(counts(&maps0, &splits0), "read the map counts") || + !require(map(first, 1, &grants[0]) == first, "map a page into the exact placeholder") || + !require(counts(&maps1, &splits1), "read the map counts")) + return 1; + std::printf("exact placeholder: map attempts %llu, split attempts %llu\n", maps1 - maps0, splits1 - splits0); + if (!require(maps1 - maps0 == 1 && splits1 - splits0 == 0, "an exact placeholder is mapped without a split") || + !require(first[0] == 0x40, "the remapped page reads its bytes")) + return 1; + std::puts("split-first: maps=N; exact placeholder mapped without a split"); + return 0; +} From be3f918c0ec0f8d0e5b5fc1dfe3aa6caf3fa2337 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:22:39 +1000 Subject: [PATCH 08/34] xmem: answer non-faulting readers outside run breaks With X2W_XMEM_SHARED_VIEWS=1, unmapping a page inside a run unmaps the whole run and maps its other pages again. A touch of those pages in between is retried by the fault handler, but a region query or a kernel copy does not fault: it reads the pages as reserved, or fails. x2w_xmem_stable_call(fn, context) runs fn when no break begins or ends around it, else again under the mapping mutex. XMemVirtualQuery, and through x2w_local::outside_run_breaks the stand-ins' x2w_local::writable, measure_placed_buffer (slot 133) and snapshot_samplers, now answer that way. Without shared views no break begins, so fn runs once as before. xmem_run_break_readers holds a break open with the test-controls build and checks that each reader waits for it and then sees the page committed; its control build runs the stand-in readers directly and they answer inside the window. --- CMakeLists.txt | 23 +++ src/startup_stubs/local_log.h | 26 ++- src/startup_stubs/placed_buffer_range.h | 23 ++- .../translated_sampler_bindings.h | 13 +- src/xmem_mapped_pages.cpp | 36 ++++ src/xmem_shim.cpp | 16 +- src/xmem_shim.def | 1 + tests/xmem_run_break_readers_check.cpp | 179 ++++++++++++++++++ 8 files changed, 307 insertions(+), 10 deletions(-) create mode 100644 tests/xmem_run_break_readers_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 89438b15ab..caf45ea5f9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -324,6 +324,29 @@ set_tests_properties(xmem_lazy_imports PROPERTIES TIMEOUT 60) add_test(NAME xmem_lazy_handler_failure COMMAND xmem_lazy_imports_check "$" handler-failure) set_tests_properties(xmem_lazy_handler_failure PROPERTIES TIMEOUT 60) +# Readers that do not fault, inside a run break held open by the test-controls build: x2w_xmem_stable_call, +# XMemVirtualQuery, the VirtualQueryEx import wrapper and the stand-in readers that go through +# x2w_local::outside_run_breaks must answer after the break. Control: a copy of local_log.h that asks xmem.dll for +# a missing export, so the stand-in readers run directly and answer inside the window. +foreach(variant check control) + add_executable(xmem_run_break_readers_${variant} tests/xmem_run_break_readers_check.cpp) + target_compile_features(xmem_run_break_readers_${variant} PRIVATE cxx_std_17) + add_dependencies(xmem_run_break_readers_${variant} xmem_shim_test_controls) +endforeach() +target_include_directories(xmem_run_break_readers_check PRIVATE src) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/local_log.h" local_log_text) +string(REPLACE "\"x2w_xmem_stable_call\"" "\"x2w_xmem_stable_call_control\"" local_log_control_text "${local_log_text}") +if(local_log_control_text STREQUAL local_log_text) + message(FATAL_ERROR "local_log.h lost the anchor used by xmem_run_break_readers_control") +endif() +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control/startup_stubs/local_log.h" "${local_log_control_text}") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/local_log.h) +target_include_directories(xmem_run_break_readers_control BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control") +target_include_directories(xmem_run_break_readers_control PRIVATE src) +add_test(NAME xmem_run_break_readers COMMAND xmem_run_break_readers_check "$") +add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_control + "$" control) +set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control PROPERTIES TIMEOUT 60) add_executable(xmem_section_lease_check tests/xmem_section_lease_check.cpp tests/desktop_gpu.cpp) target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index d12049bef8..64f7d95f71 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -6,6 +6,7 @@ #include #include +#include namespace x2w_local { @@ -107,6 +108,27 @@ inline void commit_lazy_block(const void* pointer) noexcept if (commit_block) commit_block(pointer); } +// Runs f() outside xmem's run breaks (x2w_xmem_stable_call, X2W_XMEM_SHARED_VIEWS): inside a break the pages of +// the run being taken apart read as reserved to a VirtualQuery and make ReadProcessMemory fail, although a touch of +// them would be retried. f must be a query, or a copy into the caller's memory, that can run again; it may run +// twice. Without xmem.dll, or with one that lacks the export, f runs once, directly. +using StableCall = BOOL(WINAPI*)(void (*)(void*), void*); +inline StableCall stable_call_export() noexcept +{ + static const StableCall stable_call = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_stable_call")) : nullptr; + }(); + return stable_call; +} +template +inline void outside_run_breaks(F&& f) noexcept +{ + const StableCall stable_call = stable_call_export(); + using Call = std::remove_reference_t; + if (!stable_call || !stable_call([](void* context) { (*static_cast(context))(); }, &f)) f(); +} + // 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 { @@ -115,7 +137,9 @@ inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexc 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; + SIZE_T queried = 0; + outside_run_breaks([&] { queried = VirtualQuery(pointer, &info, sizeof(info)); }); + if (!queried || info.State != MEM_COMMIT) return false; const DWORD protect = info.Protect & 0xFF; if ((info.Protect & PAGE_GUARD) || protect == PAGE_NOACCESS || protect == 0) return false; const bool writable = protect == PAGE_READWRITE || protect == PAGE_EXECUTE_READWRITE || protect == PAGE_WRITECOPY || diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 115983e174..a185201143 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -22,6 +22,8 @@ #include #include +#include "startup_stubs/local_log.h" + namespace x2w_startup { struct PlacedBufferRange { @@ -70,11 +72,9 @@ inline std::uint64_t allocation_bytes(const void* address) return info.RegionSize; } -// False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is -// exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the -// full walk measures. -inline bool measure_placed_buffer(const void* address, std::uint64_t width, PlacedBufferRange& out, - PlacedProof proof = PlacedProof::exact) +namespace placed_detail { +// One pass of measure_placed_buffer; out is reset first, so a second pass replaces the first. +inline bool measure_once(const void* address, std::uint64_t width, PlacedBufferRange& out, PlacedProof proof) { out = PlacedBufferRange{}; if (!address) return false; @@ -118,6 +118,19 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac out.covered = true; return true; } +} // namespace placed_detail + +// False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is +// exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the +// full walk measures. The queries run outside xmem's run breaks (x2w_local::outside_run_breaks): inside +// one, pages of a shared-view run read as reserved, and the buffer would be refused although it is mapped. +inline bool measure_placed_buffer(const void* address, std::uint64_t width, PlacedBufferRange& out, + PlacedProof proof = PlacedProof::exact) +{ + bool committed = false; + x2w_local::outside_run_breaks([&] { committed = placed_detail::measure_once(address, width, out, proof); }); + return committed; +} // True when an uncovered buffer at [address, address + width) lies inside a MEM_PRIVATE // reservation at a 64 KiB-aligned offset, fits within its whole allocation size (nonzero and at diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 10149b3c1d..21720a3595 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -3,6 +3,8 @@ #include #include +#include "startup_stubs/local_log.h" + #include #include #include @@ -178,10 +180,15 @@ inline SamplerSnapshot snapshot_samplers(SamplerSource source, bool reserved_fal const UINT room = static_cast((page_size - address % page_size) / title_sampler_stride); const UINT available = snapshot.count - i; const UINT run = room ? (room < available ? room : available) : 1; - SIZE_T copied = 0; const SIZE_T bytes = SIZE_T{run} * title_sampler_stride; - if (ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(address), &snapshot.words[i], bytes, &copied) && - copied == bytes) { + // Outside xmem's run breaks, where a mapped page of the title's heap would read as missing. + bool whole = false; + x2w_local::outside_run_breaks([&] { + SIZE_T copied = 0; + whole = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(address), &snapshot.words[i], bytes, + &copied) && copied == bytes; + }); + if (whole) { for (UINT j = i; j < i + run; ++j) snapshot.readable.set(j); } else { // ReadProcessMemory can copy part of a record on failure. diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 44c935a125..92f94a5947 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1581,6 +1581,42 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) return TRUE; } +// Runs fn(context) so that its answer does not come from inside a run break: the moment, under memory.mutex, +// when a run of shared views is unmapped and its surviving pages are mapped again (map_pages_locked, +// remap_alias_pages). A thread that touches such a page faults and retry_remapped_page retries it, but a region +// query (VirtualQuery) or a kernel copy (ReadProcessMemory) does not fault: inside the break it reports the pages +// as reserved, or fails. fn must be a query, or a copy into the caller's memory, that can simply run again, and +// must not take memory.mutex or call the mapping exports. +// fn runs once when no break begins or ends around it (the break generation is even before and unchanged +// after): every call without X2W_XMEM_SHARED_VIEWS, where no break ever begins, and nearly every call with it. +// Otherwise it runs again under memory.mutex, so after the break. A thread that holds memory.mutex runs it directly. +extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context) +{ + if (!fn) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + if (mapping_thread) { + fn(context); + return TRUE; + } + const auto generation = [] { + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; + }; + const ULONG64 before = generation(); + if (!(before & 1)) { + fn(context); + if (generation() == before) return TRUE; + } + const MappingThread marker; + const std::lock_guard guard(memory.mutex); + fn(context); + return TRUE; +} + // Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free // in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs // are closed when all of their slots are freed and unpinned. diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index 50272449cc..6d10cbbef8 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -104,9 +104,23 @@ extern "C" void XMemFree(void* allocation, ULONGLONG attributes) era_heap::release_with_attributes(allocation, attributes); } +extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context); + +// The answer for a page of a shared-view run is taken outside a run break (x2w_xmem_stable_call): inside one the +// page would read as reserved. extern "C" BOOL XMemVirtualQuery(HANDLE process, LPCVOID address, void* buffer) { - return era_query::query(process, address, buffer, query_buffer_bytes) != 0; + struct Query { + HANDLE process; + LPCVOID address; + void* buffer; + std::size_t result; + } query{process, address, buffer, 0}; + x2w_xmem_stable_call([](void* context) { + auto& q = *static_cast(context); + q.result = era_query::query(q.process, q.address, q.buffer, query_buffer_bytes); + }, &query); + return query.result != 0; } // Desktop policy (docs/experiments.md): writes only +8, with this process's GPU memory in bytes; diff --git a/src/xmem_shim.def b/src/xmem_shim.def index fe9dd7581b..06c581eb0c 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -24,3 +24,4 @@ EXPORTS X2WMapPageBatch @22 x2w_xmem_copy_to_destination @23 x2w_xmem_map_counts @25 + x2w_xmem_stable_call @26 diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp new file mode 100644 index 0000000000..346b4c3479 --- /dev/null +++ b/tests/xmem_run_break_readers_check.cpp @@ -0,0 +1,179 @@ +// Readers that do not fault, inside a run break of the shared-view mode (X2W_XMEM_SHARED_VIEWS=1). Unmapping one +// page of a run unmaps the whole run, then maps its other pages again (src/xmem_mapped_pages.cpp, map_pages_locked). +// A thread that touches one of those pages in between faults and is retried; a region query or a kernel copy does +// not fault, so it reads the pages as reserved or fails. Each case below opens that window with the test-controls +// build's X2W_XMEM_TEST_HOLD_WINDOW, proves it is open with a raw VirtualQuery of a neighbour page (not committed), +// starts the reader under test on another thread, checks that it has not answered 300 ms later, releases the window +// and then checks the reader's answer: the neighbour page is committed, mapped and holds its data. +// +// Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, x2w_local::writable, +// x2w_startup::measure_placed_buffer and x2w_startup::snapshot_samplers. +// +// With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run +// directly) the three header readers answer inside the window: the check expects that, and fails if they wait. +// +// Usage: xmem_run_break_readers_check [control] +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + +#include + +#include "startup_stubs/local_log.h" +#include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/translated_sampler_bindings.h" + +#include +#include +#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*); +using XMemVirtualQueryFn = BOOL(WINAPI*)(HANDLE, LPCVOID, void*); +using StableCallFn = BOOL(WINAPI*)(void (*)(void*), void*); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T pages = 8; +constexpr SIZE_T broken_page = 5; // the page unmapped; its run [0, 8) is taken apart +constexpr SIZE_T neighbour = 2; // a surviving page of that run, unmapped while the window is held + +int failures = 0; + +void check(bool ok, const char* name, const char* reader) +{ + std::printf("%s: %s %s\n", ok ? "ok" : "check_failed", reader, name); + if (!ok) ++failures; +} + +DWORD raw_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +struct Shim { + XMemVirtualAllocFn virtual_alloc; + XMemAllocatePhysicalPagesFn allocate; + XMemMapPhysicalPagesFn map; + XMemFreePhysicalPagesFn release; + XMemVirtualQueryFn query; + StableCallFn stable_call; +}; + +// One window: maps a fresh run of eight pages at base, marks every page, unmaps broken_page on a thread of its own +// with the hold set, and runs reader on another thread once the window is open. reader returns whether its answer +// says the neighbour page is committed and readable. waits: the reader must not answer before the release. +void window_case(const Shim& shim, unsigned char* base, int index, const char* name, bool waits, + const std::function& reader) +{ + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(base + i * page) = 0x51000000u + static_cast(i); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-readers-%lu-%d", GetCurrentProcessId(), index); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + unsigned char* const broken = base + broken_page * page; + std::thread unmapper([&] { shim.map(broken, 1, nullptr); }); + const bool opened = WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0; + check(opened, "window_reached", name); + unsigned char* const target = base + neighbour * page; + if (opened) check(raw_state(target) != MEM_COMMIT, "window_open_raw_query_not_committed", name); + std::atomic answered{false}; + bool answer = false; + std::thread reading([&] { + answer = reader(target); + answered = true; + }); + Sleep(300); + const bool early = answered.load(); + check(waits ? !early : early, waits ? "reader_waits_for_the_break" : "reader_answers_inside_the_window", name); + SetEvent(release); + reading.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(waits ? answer : !answer, waits ? "answer_after_the_break_committed" : "answer_inside_the_window_not_committed", name); + check(*reinterpret_cast(target) == 0x51000000u + neighbour, "neighbour_data_kept", name); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 2 && std::strcmp(argv[2], "control") == 0; + if (argc < 2 || (argc > 2 && !control)) { + std::printf("usage: xmem_run_break_readers_check [control]\n"); + return 2; + } + // The mode is read by the first mapping call. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + Shim shim{reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")), + reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemFreePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemVirtualQuery")), + reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_stable_call"))}; + if (!shim.virtual_alloc || !shim.allocate || !shim.map || !shim.release || !shim.query || !shim.stable_call) { + std::printf("check_failed: exports\n"); + return 1; + } + auto* const base = static_cast(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!base) { + std::printf("check_failed: startup reservation (error %lu)\n", GetLastError()); + return 1; + } + unsigned char* const at = base + page; + int index = 0; + if (!control) { + window_case(shim, at, index++, "x2w_xmem_stable_call", true, [&](unsigned char* target) { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast(context); + q.state = raw_state(q.target); + }, &query); + return query.state == MEM_COMMIT; + }); + window_case(shim, at, index++, "XMemVirtualQuery", true, [&](unsigned char* target) { + unsigned char buffer[64] = {}; + DWORD state = 0; + if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&state, buffer + 0x20, sizeof(state)); + return state == MEM_COMMIT; + }); + } + // The header readers: waiting with the export, answering inside the window without it (control). + const bool waits = !control; + window_case(shim, at, index++, "x2w_local::writable", waits, [&](unsigned char* target) { + return x2w_local::writable(target, 64); + }); + window_case(shim, at, index++, "measure_placed_buffer", waits, [&](unsigned char* target) { + x2w_startup::PlacedBufferRange range; + return x2w_startup::measure_placed_buffer(target, 4096, range) && range.type == MEM_MAPPED && range.covered; + }); + window_case(shim, at, index++, "snapshot_samplers", waits, [&](unsigned char* target) { + const auto snapshot = x2w_startup::snapshot_samplers({reinterpret_cast(target), 4}, false); + return snapshot.count == 4 && snapshot.readable.count() == 4 && snapshot.words[0][0] == 0x51000000u + neighbour; + }); + VirtualFree(base, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +} From e6e7d9b934d830f49421d0a28cdb24343d3f20e4 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:23:02 +1000 Subject: [PATCH 09/34] xmem: answer the main module's VirtualQueryEx outside run breaks The title queries its own pages through its VirtualQueryEx import. With X2W_XMEM_SHARED_VIEWS=1 xmem.dll now points that import at a wrapper that runs the query through x2w_xmem_stable_call, so a page of a run that is being taken apart is not reported as reserved. The module is pinned only when an import was changed (the pin is undone with the import if it is refused), so a main module without the import can still unload the shim before its first mapping call. xmem_run_break_readers checks the wrapped import of its own executable inside a held break. --- src/xmem_mapped_pages.cpp | 38 ++++++++++++++++++++++++++ tests/xmem_run_break_readers_check.cpp | 11 ++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 92f94a5947..d7604d487c 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1849,6 +1849,44 @@ const bool lazy_commit_installed = [] { } return true; }(); + +// With X2W_XMEM_SHARED_VIEWS=1 the main module's VirtualQueryEx imports answer outside run breaks +// (x2w_xmem_stable_call): inside one, a page of the run being taken apart reads as reserved. A query of another +// process runs the same way; it only costs the retry. The module is pinned once an import points into it (a main +// module without the import leaves it unloadable, as before); if the pin is refused, the imports are restored. +using VirtualQueryExFn = SIZE_T(WINAPI*)(HANDLE, LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T); +VirtualQueryExFn real_virtual_query_ex; + +SIZE_T WINAPI virtual_query_ex_stable(HANDLE process, LPCVOID address, PMEMORY_BASIC_INFORMATION info, SIZE_T bytes) +{ + struct Query { + HANDLE process; + LPCVOID address; + PMEMORY_BASIC_INFORMATION info; + SIZE_T bytes, result; + } query{process, address, info, bytes, 0}; + x2w_xmem_stable_call([](void* context) { + auto& q = *static_cast(context); + q.result = real_virtual_query_ex(q.process, q.address, q.info, q.bytes); + }, &query); + return query.result; +} + +const int virtual_query_ex_wrapped = [] { + if (!x2w_local::env_on("X2W_XMEM_SHARED_VIEWS")) return 0; + real_virtual_query_ex = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "VirtualQueryEx")); + if (!real_virtual_query_ex) return 0; + int queries = patch_main_import("VirtualQueryEx", reinterpret_cast(&virtual_query_ex_stable)); + HMODULE self = nullptr; + if (queries && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&virtual_query_ex_stable), &self)) { + patch_main_import("VirtualQueryEx", reinterpret_cast(real_virtual_query_ex)); + queries = 0; + } + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d VirtualQueryEx import(s) answer outside run breaks", + queries); + return queries; +}(); } // namespace // Experimental export: writes bytes into physical pages named by the title's diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index 346b4c3479..504714a4a3 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -6,8 +6,9 @@ // starts the reader under test on another thread, checks that it has not answered 300 ms later, releases the window // and then checks the reader's answer: the neighbour page is committed, mapped and holds its data. // -// Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, x2w_local::writable, -// x2w_startup::measure_placed_buffer and x2w_startup::snapshot_samplers. +// Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, this program's VirtualQueryEx import (wrapped by +// xmem.dll when it loads with the switch), x2w_local::writable, x2w_startup::measure_placed_buffer and +// x2w_startup::snapshot_samplers. // // With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run // directly) the three header readers answer inside the window: the check expects that, and fails if they wait. @@ -120,7 +121,7 @@ int main(int argc, char** argv) std::printf("usage: xmem_run_break_readers_check [control]\n"); return 2; } - // The mode is read by the first mapping call. + // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); const HMODULE xmem = LoadLibraryA(argv[1]); if (!xmem) { @@ -159,6 +160,10 @@ int main(int argc, char** argv) if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&state, buffer + 0x20, sizeof(state)); return state == MEM_COMMIT; }); + window_case(shim, at, index++, "VirtualQueryEx_import", true, [&](unsigned char* target) { + MEMORY_BASIC_INFORMATION info{}; + return VirtualQueryEx(GetCurrentProcess(), target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_COMMIT; + }); } // The header readers: waiting with the export, answering inside the window without it (control). const bool waits = !control; From 0ebef8a70df43e26f30d2199a82724ea4ebf744a Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:44:34 +1000 Subject: [PATCH 10/34] xmem: retry a fault in the break after the one the handler saw end retry_remapped_page names the break a fault belongs to as seen | 1. When the handler reads the generation after the break has ended (even), that names the next break, so a fault on the same page in that next break is not retried and the access violation ends the process. Name the break that just ended instead: (seen - 1) | 1. Back-to-back breaks over one page made this show up: with a reader on page 20 and page 21 toggled, the hold-ignored child of xmem_page_runs_check.py crashed in 6 of 6 runs once map calls also open a break, and passed 6 of 6 with this. Test build: X2W_XMEM_TEST_HOLD_RETRY= holds the handler before it reads the break. xmem_run_break_readers gets a case that faults in break A, is held until A ends, and faults on the same page in break B. The xmem_run_break_readers_next_break_control test runs it without the hold. --- CMakeLists.txt | 5 +- src/xmem_mapped_pages.cpp | 29 +++++++- tests/xmem_run_break_readers_check.cpp | 99 +++++++++++++++++++++++++- 3 files changed, 128 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index caf45ea5f9..4647765b54 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -346,7 +346,10 @@ target_include_directories(xmem_run_break_readers_control PRIVATE src) add_test(NAME xmem_run_break_readers COMMAND xmem_run_break_readers_check "$") add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_control "$" control) -set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control PROPERTIES TIMEOUT 60) +add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_readers_check + "$" next-break-control) +set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control + PROPERTIES TIMEOUT 60) add_executable(xmem_section_lease_check tests/xmem_section_lease_check.cpp tests/desktop_gpu.cpp) target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index d7604d487c..cf09ab8f8e 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -508,6 +508,30 @@ void end_break() struct EndBreak { ~EndBreak() { end_break(); } }; +// Test build only: X2W_XMEM_TEST_HOLD_RETRY= holds the fault handler before it reads the break: it sets +// ".faulted", then waits up to five seconds for ".go", so that a test can end the break first. +#ifdef X2W_XMEM_TEST_CONTROLS +void hold_retry() +{ + char name[96]; + const DWORD length = GetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", name, sizeof(name) - 16); + if (!length || length >= sizeof(name) - 16) return; + char event_name[128]; + std::snprintf(event_name, sizeof(event_name), "%s.faulted", name); + HANDLE faulted = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.go", name); + HANDLE go = CreateEventA(nullptr, TRUE, FALSE, event_name); + if (faulted && go) { + SetEvent(faulted); + WaitForSingleObject(go, 5000); + } + if (faulted) CloseHandle(faulted); + if (go) CloseHandle(go); +} +#else +void hold_retry() {} +#endif + // Retries an access violation only when all of this holds: the address is inside a run that the // break in progress, or the last finished one, took apart; after that break has finished (the // mutex) the page is recorded and covered by a view; and this thread has not already retried this @@ -520,6 +544,7 @@ LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) return EXCEPTION_CONTINUE_SEARCH; const ULONG_PTR address = record->ExceptionInformation[1]; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); + hold_retry(); bool inside = false; AcquireSRWLockShared(&remap_window.lock); const ULONG64 seen = remap_window.generation; @@ -527,7 +552,9 @@ LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) inside |= address - base < size; ReleaseSRWLockShared(&remap_window.lock); if (!inside || seen == 0) return EXCEPTION_CONTINUE_SEARCH; - const ULONG64 break_id = seen | 1; // the break in progress, or the one that just finished + // The break in progress (odd), or the one that just finished (even: the one before). Not seen | 1, which for an + // even generation names the next break, so that a fault in it, on the same page, would not be retried. + const ULONG64 break_id = (seen - 1) | 1; thread_local ULONG_PTR retried_page = 0; thread_local ULONG64 retried_break = 0; if (retried_page == page && retried_break == break_id) return EXCEPTION_CONTINUE_SEARCH; diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index 504714a4a3..d68e8fc73e 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -13,7 +13,14 @@ // With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run // directly) the three header readers answer inside the window: the check expects that, and fails if they wait. // -// Usage: xmem_run_break_readers_check [control] +// Then a page that faults in two breaks in a row (retry_remapped_page): a thread faults on a page of a run taken +// apart by break A, and the test build's X2W_XMEM_TEST_HOLD_RETRY holds the handler until break A has ended, so the +// handler reads the generation after it; the thread is retried and reads its page. Break B then takes the same page +// apart, and the thread faults on it again: that fault must be retried as well (a different break). With +// `next-break-control` the handler is not held, so it reads break A while A is open: that order passes even when +// the handler names the breaks wrongly, which shows the hold is what this case depends on. +// +// Usage: xmem_run_break_readers_check [control|next-break-control] #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include @@ -112,13 +119,92 @@ void window_case(const Shim& shim, unsigned char* base, int index, const char* n CloseHandle(unmapped); CloseHandle(release); } +struct Events { + char name[64]; + HANDLE first, second; + Events(const char* stem, const char* a, const char* b) + { + std::snprintf(name, sizeof(name), "x2w-run-break-%s-%lu", stem, GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.%s", name, a); + first = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.%s", name, b); + second = CreateEventA(nullptr, TRUE, FALSE, event_name); + } + ~Events() + { + CloseHandle(first); + CloseHandle(second); + } +}; + +// Break A: unmap page 7 of a run of eight; break B: unmap page 6 of what is left, [0, 7). The reader's page 2 is in +// both. hold_retry: the handler for the fault in break A reads the break only after A has ended. +void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) +{ + const char* const name = hold_retry ? "next_break" : "next_break_control"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(base + i * page) = 0x52000000u + static_cast(i); + unsigned char* const target = base + 2 * page; + Events window_a("a", "unmapped", "release"), window_b("b", "unmapped", "release"), retry("retry", "faulted", "go"); + HANDLE second_read = CreateEventA(nullptr, TRUE, FALSE, nullptr); + std::atomic reads{0}; + std::uint32_t first_value = 0, second_value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_a.name); + std::thread unmap_a([&] { shim.map(base + 7 * page, 1, nullptr); }); + const bool a_open = WaitForSingleObject(window_a.first, 10000) == WAIT_OBJECT_0; + check(a_open, "break_a_held", name); + if (hold_retry) SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + first_value = *reinterpret_cast(target); // faults in break A + ++reads; + WaitForSingleObject(second_read, 10000); + second_value = *reinterpret_cast(target); // faults in break B + ++reads; + }); + if (hold_retry) { + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_break", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + } else { + Sleep(100); // the handler reads break A while it is open, then waits for it + } + SetEvent(window_a.second); + unmap_a.join(); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + if (hold_retry) SetEvent(retry.second); // the handler now reads the generation after break A + for (int i = 0; i < 200 && reads.load() < 1; ++i) Sleep(10); + check(reads.load() == 1 && first_value == 0x52000002u, "first_fault_retried", name); + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_b.name); + std::thread unmap_b([&] { shim.map(base + 6 * page, 1, nullptr); }); + const bool b_open = WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0; + check(b_open && raw_state(target) != MEM_COMMIT, "break_b_held_page_not_committed", name); + SetEvent(second_read); + Sleep(300); + check(reads.load() == 1, "second_fault_waits_for_break_b", name); + SetEvent(window_b.second); + unmap_b.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(reads.load() == 2 && second_value == 0x52000002u, "second_fault_retried", name); + shim.map(base, 6, nullptr); + shim.release(pages, tokens); + CloseHandle(second_read); + if (!hold_retry) std::printf("next-break control: the handler read break A while it was open\n"); +} } // namespace int main(int argc, char** argv) { const bool control = argc > 2 && std::strcmp(argv[2], "control") == 0; - if (argc < 2 || (argc > 2 && !control)) { - std::printf("usage: xmem_run_break_readers_check [control]\n"); + const bool next_break_control = argc > 2 && std::strcmp(argv[2], "next-break-control") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control)) { + std::printf("usage: xmem_run_break_readers_check [control|next-break-control]\n"); return 2; } // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. @@ -144,6 +230,12 @@ int main(int argc, char** argv) return 1; } unsigned char* const at = base + page; + if (next_break_control) { + next_break_case(shim, at, false); + VirtualFree(base, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } int index = 0; if (!control) { window_case(shim, at, index++, "x2w_xmem_stable_call", true, [&](unsigned char* target) { @@ -178,6 +270,7 @@ int main(int argc, char** argv) const auto snapshot = x2w_startup::snapshot_samplers({reinterpret_cast(target), 4}, false); return snapshot.count == 4 && snapshot.readable.count() == 4 && snapshot.words[0][0] == 0x51000000u + neighbour; }); + if (!control) next_break_case(shim, at, true); VirtualFree(base, 0, MEM_RELEASE); std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; From 284f05eca20aae4ded7212a00b2369ce4bdd2f3d Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:51:46 +1000 Subject: [PATCH 11/34] xmem: run readers once without shared views, and write their answers after a break Without X2W_XMEM_SHARED_VIEWS, every unmap still counts in the break generation (begin_break is not gated on the switch), so x2w_xmem_stable_call made default-mode readers wait for memory.mutex. Each page has a view of its own there, and no break takes a page away from a reader, so stable_call now runs fn directly until shared views are on. The comment, and the message of "xmem: answer non-faulting readers outside run breaks", saying no break begins without the switch were wrong. XMemVirtualQuery and the VirtualQueryEx import wrapper answered into the caller's buffer inside stable_call. On its mutex path the lazy-commit handler passes faults on, so a buffer in an uncommitted mapped slot was not committed there. Both now answer into a local copy and write it out after the call. A refused pin of the VirtualQueryEx wrapper is logged with its error and the restore count. measure_placed_buffer keeps the query count of a pass that ran again. The docs describe stable_call and the load-time read of the switch. "xmem: answer the main module's VirtualQueryEx outside run breaks" said the title queries its own pages through VirtualQueryEx. An import scan shows only that the executable under test imports it. How often it is called was not measured. Checks in xmem_run_break_readers: a break that begins while fn runs makes it run again under the mutex (pins the after-check); default mode answers inside an unmap (xmem_run_break_readers_default); lazy commit with the output in an uncommitted slot (xmem_run_break_readers_lazy); the reader's 300 ms now count from its start. --- CMakeLists.txt | 8 +- docs/startup-runtime.md | 14 +- src/startup_stubs/placed_buffer_range.h | 7 +- src/xmem_mapped_pages.cpp | 39 +++-- src/xmem_shim.cpp | 13 +- tests/xmem_run_break_readers_check.cpp | 205 ++++++++++++++++++++++-- 6 files changed, 259 insertions(+), 27 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4647765b54..256440b469 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -348,8 +348,14 @@ add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_cont "$" control) add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_readers_check "$" next-break-control) +# Default mode (no X2W_XMEM_SHARED_VIEWS): readers that overlap an unmap answer inside it, as before. Lazy commit: +# the readers' output buffer in a mapped slot not yet committed. +add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) +add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control - PROPERTIES TIMEOUT 60) + xmem_run_break_readers_default xmem_run_break_readers_lazy PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_run_break_readers_default PROPERTIES + PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") add_executable(xmem_section_lease_check tests/xmem_section_lease_check.cpp tests/desktop_gpu.cpp) target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2563133bb5..d3cf15571d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3168,13 +3168,23 @@ has not already retried that page for that unmap. Any other fault is passed on, retry. Shared views are opt-in. The caller chooses before the first mapping call by setting -`X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. +`X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. It also +reads it once when `xmem.dll` loads: with it set then, the main module's `VirtualQueryEx` imports +are wrapped (see below), and the module is pinned at load when one is. + +A region query or a kernel copy does not fault, so inside an unmap it would see the pages of the +view being taken apart as reserved. With shared views such readers run through the export +`x2w_xmem_stable_call`: the reader runs once, and runs again after the unmap if one began or ended +around it. `XMemVirtualQuery`, the main module's `VirtualQueryEx` imports and the shim's own +`VirtualQuery` and `ReadProcessMemory` readers (`src/startup_stubs/local_log.h`, slot 133, +the sampler snapshot) use it. Without shared views every page has a view of its own and readers +run once, as before. Title `ReadFile`/`WriteFile` into mapped pages are not covered. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| | Views | one per page | one per run of adjacent pages | | Fault handler | none | registered by the first mapping call, never removed | -| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends | +| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends (at load when the main module imports `VirtualQueryEx`, else at the first mapping call) | The handler is process-wide, and Windows has no removal that also waits for a dispatch already under way, so the opt-in keeps the module, the handler and the shim's state in place for the life diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index a185201143..27d6400788 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -128,7 +128,12 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac PlacedProof proof = PlacedProof::exact) { bool committed = false; - x2w_local::outside_run_breaks([&] { committed = placed_detail::measure_once(address, width, out, proof); }); + unsigned queries = 0; // over every pass: a pass run again after a break replaces out + x2w_local::outside_run_breaks([&] { + committed = placed_detail::measure_once(address, width, out, proof); + queries += out.queries; + }); + out.queries = queries; return committed; } diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index cf09ab8f8e..d9a9bb6fce 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -490,6 +490,10 @@ struct RemapWindow { ULONG64 generation = 0; }; RemapWindow remap_window; +// Set once shared views are on (FaultRetry::ready). Breaks also begin without them (every unmap counts in the +// generation), but then a page has a view of its own and no break takes a neighbour away, so x2w_xmem_stable_call +// does not wait for them. +std::atomic shared_views_on{false}; void begin_break(const std::map& broken) { @@ -576,7 +580,9 @@ struct MappingThread { // Shared views are opt-in: X2W_XMEM_SHARED_VIEWS=1, read once by the first mapping call. Without // it every page has a view of its own, as before: unmapping a page never takes a neighbour away, -// no handler is registered, and the module unloads like any DLL. +// no handler is registered, and the module unloads like any DLL. The switch is also read once when +// xmem.dll loads (virtual_query_ex_wrapped): with it set then, the main module's VirtualQueryEx imports +// are wrapped, and the module is pinned at load when one is. // // With it, the first mapping call registers the handler and pins the module. The handler is // process-wide and Windows offers no way to remove one that also waits for every dispatch already @@ -614,6 +620,7 @@ struct FaultRetry { x2w_local::logf("x2w-xmem shared views are off: the fault handler could not be set up (error %lu)", GetLastError()); } const bool result = guaranteed; + if (result) shared_views_on.store(true, std::memory_order_release); ReleaseSRWLockExclusive(&lock); return result; } @@ -1614,16 +1621,17 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) // query (VirtualQuery) or a kernel copy (ReadProcessMemory) does not fault: inside the break it reports the pages // as reserved, or fails. fn must be a query, or a copy into the caller's memory, that can simply run again, and // must not take memory.mutex or call the mapping exports. -// fn runs once when no break begins or ends around it (the break generation is even before and unchanged -// after): every call without X2W_XMEM_SHARED_VIEWS, where no break ever begins, and nearly every call with it. -// Otherwise it runs again under memory.mutex, so after the break. A thread that holds memory.mutex runs it directly. +// Without shared views (X2W_XMEM_SHARED_VIEWS unset, or no mapping call yet) fn runs once, directly: every page has +// a view of its own, so no break takes a page away from a reader. With them fn runs once when no break begins or +// ends around it (the break generation is even before and unchanged after), which is nearly every call; otherwise +// it runs again under memory.mutex, so after the break. A thread that holds memory.mutex runs it directly. extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context) { if (!fn) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } - if (mapping_thread) { + if (mapping_thread || !shared_views_on.load(std::memory_order_acquire)) { fn(context); return TRUE; } @@ -1884,18 +1892,26 @@ const bool lazy_commit_installed = [] { using VirtualQueryExFn = SIZE_T(WINAPI*)(HANDLE, LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T); VirtualQueryExFn real_virtual_query_ex; +// The answer goes to a local buffer and is copied to the caller's after x2w_xmem_stable_call: on its mutex path the +// lazy-commit handler passes faults on (MappingThread), so a write into an uncommitted mapped slot would not be +// committed there. SIZE_T WINAPI virtual_query_ex_stable(HANDLE process, LPCVOID address, PMEMORY_BASIC_INFORMATION info, SIZE_T bytes) { + if (!info || bytes < sizeof(MEMORY_BASIC_INFORMATION)) return real_virtual_query_ex(process, address, info, bytes); struct Query { HANDLE process; LPCVOID address; - PMEMORY_BASIC_INFORMATION info; - SIZE_T bytes, result; - } query{process, address, info, bytes, 0}; + MEMORY_BASIC_INFORMATION info; + SIZE_T result; + DWORD error; + } query{process, address, {}, 0, ERROR_SUCCESS}; x2w_xmem_stable_call([](void* context) { auto& q = *static_cast(context); - q.result = real_virtual_query_ex(q.process, q.address, q.info, q.bytes); + q.result = real_virtual_query_ex(q.process, q.address, &q.info, sizeof(q.info)); + q.error = GetLastError(); }, &query); + if (query.result) std::memcpy(info, &query.info, query.result); + SetLastError(query.error); return query.result; } @@ -1907,7 +1923,10 @@ const int virtual_query_ex_wrapped = [] { HMODULE self = nullptr; if (queries && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, reinterpret_cast(&virtual_query_ex_stable), &self)) { - patch_main_import("VirtualQueryEx", reinterpret_cast(real_virtual_query_ex)); + const DWORD error = GetLastError(); + const int restored = patch_main_import("VirtualQueryEx", reinterpret_cast(real_virtual_query_ex)); + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): xmem.dll could not be pinned (error %lu); " + "%d of %d VirtualQueryEx import(s) restored", static_cast(error), restored, queries); queries = 0; } x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d VirtualQueryEx import(s) answer outside run breaks", diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index 6d10cbbef8..a198c3f256 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -107,19 +107,24 @@ extern "C" void XMemFree(void* allocation, ULONGLONG attributes) extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context); // The answer for a page of a shared-view run is taken outside a run break (x2w_xmem_stable_call): inside one the -// page would read as reserved. +// page would read as reserved. era_query writes a copy of the caller's buffer, which goes back after the call: on +// stable_call's mutex path the lazy-commit handler passes faults on, so an uncommitted mapped slot is not written +// there. extern "C" BOOL XMemVirtualQuery(HANDLE process, LPCVOID address, void* buffer) { struct Query { HANDLE process; LPCVOID address; - void* buffer; + unsigned char* buffer; + unsigned char copy[query_buffer_bytes]; std::size_t result; - } query{process, address, buffer, 0}; + } query{process, address, static_cast(buffer), {}, 0}; + if (query.buffer) std::memcpy(query.copy, query.buffer, query_buffer_bytes); x2w_xmem_stable_call([](void* context) { auto& q = *static_cast(context); - q.result = era_query::query(q.process, q.address, q.buffer, query_buffer_bytes); + q.result = era_query::query(q.process, q.address, q.buffer ? q.copy : nullptr, query_buffer_bytes); }, &query); + if (query.buffer) std::memcpy(query.buffer, query.copy, query_buffer_bytes); return query.result != 0; } diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index d68e8fc73e..be07ade9db 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -20,7 +20,16 @@ // `next-break-control` the handler is not held, so it reads break A while A is open: that order passes even when // the handler names the breaks wrongly, which shows the hold is what this case depends on. // -// Usage: xmem_run_break_readers_check [control|next-break-control] +// A break that begins while x2w_xmem_stable_call's fn runs (break_during_fn): fn itself starts the unmap, waits until +// the window is open and queries a page of the run (reserved). stable_call must see the generation change and run fn +// again under memory.mutex: 2 calls, the last one committed. +// +// `default` (X2W_XMEM_SHARED_VIEWS unset): every page has a view of its own, and readers that overlap an unmap +// answer inside it, without waiting for memory.mutex, as before x2w_xmem_stable_call. +// `lazy` (X2W_XMEM_SHARED_VIEWS=1, X2W_XMEM_LAZY_COMMIT=1): XMemVirtualQuery and VirtualQueryEx wait for a break +// with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. +// +// Usage: xmem_run_break_readers_check [control|next-break-control|default|lazy] #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include @@ -52,10 +61,11 @@ constexpr SIZE_T neighbour = 2; // a surviving page of that run, unmapped wh int failures = 0; -void check(bool ok, const char* name, const char* reader) +bool check(bool ok, const char* name, const char* reader) { std::printf("%s: %s %s\n", ok ? "ok" : "check_failed", reader, name); if (!ok) ++failures; + return ok; } DWORD raw_state(const void* address) @@ -98,12 +108,14 @@ void window_case(const Shim& shim, unsigned char* base, int index, const char* n check(opened, "window_reached", name); unsigned char* const target = base + neighbour * page; if (opened) check(raw_state(target) != MEM_COMMIT, "window_open_raw_query_not_committed", name); - std::atomic answered{false}; + std::atomic started{false}, answered{false}; bool answer = false; std::thread reading([&] { + started = true; answer = reader(target); answered = true; }); + for (int i = 0; i < 10000 && !started.load(); ++i) Sleep(1); // the 300 ms count from the reader's start Sleep(300); const bool early = answered.load(); check(waits ? !early : early, waits ? "reader_waits_for_the_break" : "reader_answers_inside_the_window", name); @@ -119,6 +131,173 @@ void window_case(const Shim& shim, unsigned char* base, int index, const char* n CloseHandle(unmapped); CloseHandle(release); } +// fn starts the unmap and waits for the window inside x2w_xmem_stable_call. +void break_during_fn(const Shim& shim, unsigned char* base) +{ + const char* const name = "break_during_fn"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + struct Context { + const Shim* shim; + unsigned char* base; + char hold[64]; + HANDLE unmapped, release; + std::thread unmapper, releaser; + int calls = 0; + DWORD first = 0, last = 0; + bool opened = false; + } c{&shim, base, {}, nullptr, nullptr}; + std::snprintf(c.hold, sizeof(c.hold), "x2w-run-break-during-fn-%lu", GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", c.hold); + c.unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", c.hold); + c.release = CreateEventA(nullptr, TRUE, FALSE, event_name); + shim.stable_call([](void* context) { + auto& c = *static_cast(context); + if (++c.calls == 1) { + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", c.hold); + c.unmapper = std::thread([&c] { c.shim->map(c.base + broken_page * page, 1, nullptr); }); + c.opened = WaitForSingleObject(c.unmapped, 10000) == WAIT_OBJECT_0; + c.first = raw_state(c.base + neighbour * page); + c.releaser = std::thread([&c] { // stable_call waits for memory.mutex until the window is released + Sleep(100); + SetEvent(c.release); + }); + } + c.last = raw_state(c.base + neighbour * page); + }, &c); + c.unmapper.join(); + c.releaser.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(c.opened, "window_reached", name); + check(c.first != MEM_COMMIT, "first_call_inside_the_window_not_committed", name); + check(c.calls == 2, "fn_ran_again_after_the_break", name); + check(c.last == MEM_COMMIT, "answer_after_the_break_committed", name); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(c.unmapped); + CloseHandle(c.release); +} + +// Default mode: eight single-page views; the unmap of page 5 is held open while readers query page 2. +void default_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "default"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map", name); + return; + } + unsigned char* const target = base + neighbour * page; + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(target, &info, sizeof(info)) && info.RegionSize == page, "one_view_per_page", name); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-default-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread unmapper([&] { shim.map(base + broken_page * page, 1, nullptr); }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0, "window_reached", name); + std::atomic answered{0}; + DWORD stable = 0, xmem = 0; + bool writable = false; + std::thread reading([&] { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast(context); + q.state = raw_state(q.target); + }, &query); + stable = query.state; + unsigned char buffer[64] = {}; + if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&xmem, buffer + 0x20, sizeof(xmem)); + writable = x2w_local::writable(target, 64); + answered = 1; + }); + for (int i = 0; i < 300 && !answered.load(); ++i) Sleep(10); + check(answered.load() == 1, "readers_answer_inside_the_unmap", name); + check(stable == MEM_COMMIT && xmem == MEM_COMMIT && writable, "answers_committed", name); + SetEvent(release); + reading.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); + std::printf("default mode: readers answer inside an unmap\n"); +} + +// Lazy commit: the output buffers lie in a mapped page whose slot is not committed until it is touched. +void lazy_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "lazy"; + SIZE_T count = pages, tokens[pages] = {}, out_count = 1, out_token = 0; + unsigned char* const out = base + 32 * page; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base || + !shim.allocate(0x20400000, &out_count, &out_token) || shim.map(out, 1, &out_token) != out) { + check(false, "map", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(base + i * page) = 0x53000000u + static_cast(i); + if (!check(raw_state(out) != MEM_COMMIT, "output_slot_not_committed_yet", name)) return; + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-lazy-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread unmapper([&] { shim.map(base + broken_page * page, 1, nullptr); }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0, "window_reached", name); + unsigned char* const target = base + neighbour * page; + BOOL xmem_ok = FALSE; + SIZE_T ex_bytes = 0; + auto* const ex_info = reinterpret_cast(out + 0x100); + std::atomic answered{0}; + std::thread xmem_reader([&] { + xmem_ok = shim.query(GetCurrentProcess(), target, out); + ++answered; + }); + std::thread ex_reader([&] { + ex_bytes = VirtualQueryEx(GetCurrentProcess(), target, ex_info, sizeof(*ex_info)); + ++answered; + }); + Sleep(300); + check(answered.load() == 0, "readers_wait_for_the_break", name); + SetEvent(release); + xmem_reader.join(); + ex_reader.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + // The answers are the state after the break, read back from the slot they were written to. Measured under Wine: a + // slot committed lazily (through the slab) still reads as reserved in the title's view, and so does a page of the + // view mapped again after the break (its bytes are kept), so compare with a raw query taken now. + const DWORD after = raw_state(target); + DWORD xmem_state = 0; + std::memcpy(&xmem_state, out + 0x20, sizeof(xmem_state)); + std::printf("lazy: target 0x%lx after the break; XMemVirtualQuery %d 0x%lx; VirtualQueryEx %zu 0x%lx\n", + static_cast(after), xmem_ok, static_cast(xmem_state), + static_cast(ex_bytes), static_cast(ex_info->State)); + check(xmem_ok && xmem_state == after, "XMemVirtualQuery_answer_after_the_break_in_the_lazy_slot", name); + check(ex_bytes == sizeof(*ex_info) && ex_info->State == after, "VirtualQueryEx_answer_after_the_break_in_the_lazy_slot", name); + check(*reinterpret_cast(target) == 0x53000000u + neighbour, "neighbour_data_kept", name); + shim.map(out, 1, nullptr); + shim.release(1, &out_token); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} + struct Events { char name[64]; HANDLE first, second; @@ -203,12 +382,15 @@ int main(int argc, char** argv) { const bool control = argc > 2 && std::strcmp(argv[2], "control") == 0; const bool next_break_control = argc > 2 && std::strcmp(argv[2], "next-break-control") == 0; - if (argc < 2 || (argc > 2 && !control && !next_break_control)) { - std::printf("usage: xmem_run_break_readers_check [control|next-break-control]\n"); + const bool default_mode = argc > 2 && std::strcmp(argv[2], "default") == 0; + const bool lazy = argc > 2 && std::strcmp(argv[2], "lazy") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy)) { + std::printf("usage: xmem_run_break_readers_check [control|next-break-control|default|lazy]\n"); return 2; } // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. - SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", default_mode ? nullptr : "1"); + if (lazy) SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); const HMODULE xmem = LoadLibraryA(argv[1]); if (!xmem) { std::printf("check_failed: load (error %lu)\n", GetLastError()); @@ -230,8 +412,10 @@ int main(int argc, char** argv) return 1; } unsigned char* const at = base + page; - if (next_break_control) { - next_break_case(shim, at, false); + if (next_break_control || default_mode || lazy) { + if (next_break_control) next_break_case(shim, at, false); + if (default_mode) default_case(shim, at); + if (lazy) lazy_case(shim, at); VirtualFree(base, 0, MEM_RELEASE); std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; @@ -270,7 +454,10 @@ int main(int argc, char** argv) const auto snapshot = x2w_startup::snapshot_samplers({reinterpret_cast(target), 4}, false); return snapshot.count == 4 && snapshot.readable.count() == 4 && snapshot.words[0][0] == 0x51000000u + neighbour; }); - if (!control) next_break_case(shim, at, true); + if (!control) { + next_break_case(shim, at, true); + break_during_fn(shim, at); + } VirtualFree(base, 0, MEM_RELEASE); std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; From 4408f03ac5dca6c366a517caf73181d7cce6d3de Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:59:25 +1000 Subject: [PATCH 12/34] xmem: join a page mapped on its own call to the view before it Start-up maps nearly every page with a call of its own (45595 of 45602 runs had one page), and under Wine each map costs more the more views the process has. With X2W_XMEM_SHARED_VIEWS=1, a mapping call whose pages form one run now joins the recorded run that ends at its address. It joins only when its first page is the next slot of the section behind that run's last page, and both lie in one reservation of the shim. The new pages' range is split to a placeholder of its own, the run is unmapped inside a break (begin_break, as for an unmap), the two placeholders are joined, and one view is mapped over both. A refused step before the unmap changes nothing. After it, the run is mapped again as it was (map_recorded) and the new pages get a view of their own. If the run cannot be restored, its pages are forgotten and the call fails, as in an unmap. Default mode is unchanged. Test build: X2W_XMEM_TEST_NO_MERGE=1 turns the merge off; X2W_XMEM_TEST_FAULT stages 4 (joined map) and 5 (joining the placeholders) refuse a step. xmem_cross_call_merge covers 32 single-page calls -> one view, an unmap in the middle, slots in reverse order (32 views), a reader held in the window, both refused steps, and two reservations. xmem_cross_call_merge_control keeps the old one-view-per-call layout under NO_MERGE. xmem_cross_call_merge_deployed shows the deployed shim ignores that switch. xmem_cross_call_merge_default covers default mode. xmem_page_runs_check.py expected "Mapping the page again does not join the pieces: three views". The page now joins the lower piece (two views). The three-view layout stays asserted by xmem_cross_call_merge_control. xmem_page_runs_device_check maps the upper view first and the single pages in reverse slot order, so its view boundaries stay. --- CMakeLists.txt | 19 ++ docs/startup-runtime.md | 7 + src/xmem_mapped_pages.cpp | 73 +++++- tests/xmem_cross_call_merge_check.cpp | 329 ++++++++++++++++++++++++++ tests/xmem_page_runs_check.py | 6 +- tests/xmem_page_runs_device_check.cpp | 12 +- 6 files changed, 437 insertions(+), 9 deletions(-) create mode 100644 tests/xmem_cross_call_merge_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 256440b469..ca5ed3c012 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -356,6 +356,25 @@ set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_ xmem_run_break_readers_default xmem_run_break_readers_lazy PROPERTIES TIMEOUT 60) set_tests_properties(xmem_run_break_readers_default PROPERTIES PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") +# Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and +# the steps around it (an unmap inside, slots out of order, a reader inside the held window, refused steps, two +# reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test build only); the deployed shim +# ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its own. +add_executable(xmem_cross_call_merge_check tests/xmem_cross_call_merge_check.cpp) +target_compile_features(xmem_cross_call_merge_check PRIVATE cxx_std_17) +add_dependencies(xmem_cross_call_merge_check xmem_shim xmem_shim_test_controls) +add_test(NAME xmem_cross_call_merge COMMAND xmem_cross_call_merge_check "$" check) +add_test(NAME xmem_cross_call_merge_control COMMAND xmem_cross_call_merge_check "$" control) +add_test(NAME xmem_cross_call_merge_deployed COMMAND xmem_cross_call_merge_check "$" deployed) +add_test(NAME xmem_cross_call_merge_default COMMAND xmem_cross_call_merge_check "$" default) +set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed + xmem_cross_call_merge_default PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_cross_call_merge_control PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_deployed PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "merge: 1 view of 32 pages" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_default PROPERTIES + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") add_executable(xmem_section_lease_check tests/xmem_section_lease_check.cpp tests/desktop_gpu.cpp) target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d3cf15571d..d33bb4c391 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3160,6 +3160,13 @@ view (`src/xmem_mapped_pages.cpp`). Before, every page had a section and a view slow for a start-up batch of about 100,000 pages (measured under Wine: 42.9 s for 100,000 pages, 82 ms with shared sections and views). +Start-up maps nearly every page with a call of its own, and under Wine each map costs more the +more views the process has. So a mapping call whose pages all continue the view that ends at its +address, on the next slots of the same section and inside the same reservation of the shim, joins +that view: the view is unmapped, its placeholder is joined with the new pages' placeholder, and one +view is mapped over both. It is taken apart the same way as in an unmap (below), and if a step is +refused the view is mapped again as it was and the new pages get a view of their own. + Unmapping a page inside a shared view unmaps that view and maps its other pages again. A thread that touches one of those pages in between takes an access violation. A vectored handler retries it only when the address is inside a view that the unmap in progress, or the last finished one, diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index d9a9bb6fce..720202346e 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -630,13 +630,15 @@ FaultRetry fault_retry; // Test build only (X2W_XMEM_TEST_CONTROLS; tests/xmem_page_runs_check.py): X2W_XMEM_TEST_FAULT=: makes one step of // the next unmap fail as if Windows had refused it, after skipping such steps. Stage 1 is // unmapping a run, stage 2 mapping surviving pages again, stage 3 both the unmap and the restore. +// Stages 4 and 5 are steps of a cross-call merge (merge_with_previous): 4 the map of the joined view, +// 5 joining the two placeholders. #ifdef X2W_XMEM_TEST_CONTROLS struct TestFault { unsigned stage = 0, skip = 0; TestFault() { char text[32]; - if (GetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", text, sizeof(text)) && text[0] >= '1' && text[0] <= '3' && text[1] == ':') { + if (GetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", text, sizeof(text)) && text[0] >= '1' && text[0] <= '5' && text[1] == ':') { stage = static_cast(text[0] - '0'); skip = static_cast(std::strtoul(text + 2, nullptr, 10)); } @@ -762,6 +764,63 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } +// Shared views only. Startup maps nearly every page with a call of its own, and under Wine each map +// costs more the more views the process has. A run mapped by a call of its own therefore joins the +// recorded run R that ends at its address, when its first page is the next slot of the section behind +// R's last page and R and the new pages lie in one reservation of the shim: the new pages' range is +// split to a placeholder of its own, R is unmapped, the two placeholders are joined and one view is +// mapped over both. R is taken apart as in an unmap (begin_break), so a thread that touches R in +// between is retried and x2w_xmem_stable_call readers wait. On a refused step before R is unmapped +// nothing changed; after it, R is mapped again as it was (map_recorded). Both return separate, and +// the caller maps the new pages on their own. lost: R could not be mapped again; the pages that have +// no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 turns the merge off (tests only). +enum class Merge { joined, separate, lost }; + +Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, MapFailure* failure) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (x2w_local::env_on("X2W_XMEM_TEST_NO_MERGE")) return Merge::separate; +#endif + const auto next = memory.runs.lower_bound(address); + if (next == memory.runs.begin()) return Merge::separate; + const auto [base, size] = *std::prev(next); + if (base + size != address) return Merge::separate; + const auto tail = memory.views.find(address - page_bytes); + if (tail == memory.views.end()) return Merge::separate; + const Backing& previous = memory.backings.at(tail->second); + if (previous.section != head.section || previous.offset + page_bytes != head.offset) return Merge::separate; + const auto reservation = owned_reservation(base); + if (reservation == memory.reservations.end() || address + bytes > reservation->first + reservation->second) + return Merge::separate; + const Backing start = memory.backings.at(memory.views.at(base)); + auto* const target = reinterpret_cast(address); + if (!exact_placeholder(target, bytes)) { + InterlockedIncrement64(&split_attempts); + if (!VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return Merge::separate; + } + TestFault test; + begin_break({{base, size}}); + const EndBreak end; + if (!unmap_view(base)) return Merge::separate; + memory.runs.erase(base); + hold_window(); + auto* const whole = reinterpret_cast(base); + if (!test.hit(5) && VirtualFree(whole, size + bytes, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) { + InterlockedIncrement64(&map_attempts); + if (!test.hit(4) && MapViewOfFile3(start.section, GetCurrentProcess(), whole, start.offset, size + bytes, + MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) { + memory.runs[base] = size + bytes; + return Merge::joined; + } + } + // map_recorded splits the joined placeholder back to R's size (map_split: the reservation is the shim's). + const ULONG_PTR lost = map_recorded(base, size, false, failure); + if (!lost) return Merge::separate; + x2w_local::logf("x2w-xmem merge of a run with the next mapping call failed: %llu page(s) of the run could not be " + "mapped again and were forgotten", static_cast(lost)); + return Merge::lost; +} + // Destinations must be caller-owned, page-sized Windows placeholders. Live views // are owned by this shim until it unmaps them. The caller must not replace them. template @@ -806,8 +865,18 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& const Backing& b = memory.backings.at(last->second); if (last->first != first->first + bytes || b.section != head.section || b.offset != head.offset + bytes) break; } + // Only a run that is the whole batch joins an earlier one: a later run of the batch that + // fails unmaps everything in made, which a joined run is not. + const Merge merge = share_views && first == batch.begin() && last == batch.end() + ? merge_with_previous(first->first, head, bytes, failure) + : Merge::separate; + if (merge == Merge::lost) { + coalesce_unused(batch); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } ULONG_PTR failed_address; - if (!map_run(first->first, head, bytes, made, failed_address)) { + if (merge == Merge::separate && !map_run(first->first, head, bytes, made, failed_address)) { const DWORD error = GetLastError(); if (failure) failure->record("map-view", failed_address, batch.at(failed_address), error); for (const auto& [base, size] : made) { diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp new file mode 100644 index 0000000000..558b497a22 --- /dev/null +++ b/tests/xmem_cross_call_merge_check.cpp @@ -0,0 +1,329 @@ +// Cross-call merge of shared views (X2W_XMEM_SHARED_VIEWS=1, src/xmem_mapped_pages.cpp, merge_with_previous). A run +// mapped by a call of its own joins the recorded run that ends at its address when its first page is the next slot of +// the section behind that run's last page and both lie in one reservation of the shim. What a view is, is measured +// with VirtualQuery: inside a view AllocationBase is the view's base and RegionSize the bytes to the view's end. +// +// Modes: +// check (test-controls xmem.dll) every case below. +// control (test-controls xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) single-page calls keep a view each: the layout +// before the merge. Prints "no-merge control: 32 views". +// deployed (deployed xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) the deployed shim ignores the test switch and merges. +// default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own. +// +// Cases of `check`: +// joined 32 single-page calls on consecutive slots: one view of 32 pages; each page keeps the mark written +// right after its own call. +// middle unmapping page 10 of that view leaves views [0, 10) and [11, 32) with their marks. +// reversed 32 single-page calls on slots in reverse order (adjacent addresses, not adjacent slots): 32 views, +// page i shows slot 31 - i. +// window X2W_XMEM_TEST_HOLD_WINDOW holds the merge while the earlier run is unmapped: a raw query of one +// of its pages is not committed; a thread that reads the page and an x2w_xmem_stable_call query both +// wait, then read the mark and MEM_COMMIT; the result is one view of 9 pages. +// refused-4/5 X2W_XMEM_TEST_FAULT=4:0 (the joined map refused) and 5:0 (joining the placeholders refused): the call +// succeeds, the earlier run is a view of 8 pages again, the new page a view of its own, marks kept, +// the pages unmap and release, and the live page count returns to where it was. +// two-reservations a caller placeholder split in two pieces, each recorded with XMemVirtualAlloc (permissive +// replace-placeholder call): a page at the start of the second piece does not join the first's run. +// +// Usage: xmem_cross_call_merge_check check|control|deployed|default +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + +#include +#include +#include +#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*); +using StableCallFn = BOOL(WINAPI*)(void (*)(void*), void*); +using PageStatsFn = BOOL(WINAPI*)(ULONGLONG*); +using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T count = 32; + +int failures = 0; + +bool check(bool ok, const char* name, const char* detail = "") +{ + std::printf("%s: %s%s%s\n", ok ? "ok" : "check_failed", name, *detail ? " " : "", detail); + if (!ok) ++failures; + return ok; +} + +struct Region { + ULONG_PTR allocation_base = 0; + SIZE_T size = 0; + DWORD state = 0; +}; + +Region region(const unsigned char* address) +{ + MEMORY_BASIC_INFORMATION info{}; + if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info)) return {}; + return {reinterpret_cast(info.AllocationBase), info.RegionSize, info.State}; +} + +// The view that holds address starts at first and ends at end (exclusive). +bool view_is(const unsigned char* address, const unsigned char* first, const unsigned char* end) +{ + const Region r = region(address); + return r.state == MEM_COMMIT && r.allocation_base == reinterpret_cast(first) && + r.size == static_cast(end - address); +} + +std::uint32_t& word(unsigned char* address) { return *reinterpret_cast(address); } + +struct Shim { + XMemVirtualAllocFn virtual_alloc; + XMemAllocatePhysicalPagesFn allocate; + XMemMapPhysicalPagesFn map; + XMemFreePhysicalPagesFn release; + StableCallFn stable_call; + PageStatsFn page_stats; + + std::vector pages(SIZE_T n) const + { + std::vector tokens(n); + SIZE_T got = n; + if (!allocate(0x20400000, &got, tokens.data()) || got != n) tokens.clear(); + return tokens; + } + ULONGLONG live() const + { + ULONGLONG value = ~0ull; + page_stats(&value); + return value; + } +}; + +// Maps tokens[order(i)] at base + i pages, one call each, and marks each page right after its call, before the next +// call merges it. Returns false when a call fails. +template +bool map_one_by_one(const Shim& shim, unsigned char* base, std::vector& tokens, std::uint32_t tag, Order order) +{ + for (SIZE_T i = 0; i < tokens.size(); ++i) { + unsigned char* const at = base + i * page; + if (shim.map(at, 1, &tokens[order(i)]) != at) return false; + word(at) = tag + static_cast(i); + word(at + page - 4) = static_cast(order(i)); + } + return true; +} + +bool marked(unsigned char* base, SIZE_T n, std::uint32_t tag, SIZE_T skip = SIZE_T(-1)) +{ + for (SIZE_T i = 0; i < n; ++i) { + if (i == skip) continue; + if (region(base + i * page).state != MEM_COMMIT || word(base + i * page) != tag + i) return false; + } + return true; +} + +// joined (merging modes) or the per-page layout (control, default); then middle in `check`. +void single_page_calls(const Shim& shim, unsigned char* base, bool merges, bool middle) +{ + auto tokens = shim.pages(count); + if (!check(tokens.size() == count, "allocate 32 pages")) return; + if (!check(map_one_by_one(shim, base, tokens, 0x61000000u, [](SIZE_T i) { return i; }), "32 single-page calls")) return; + if (merges) { + check(view_is(base, base, base + count * page) && view_is(base + (count - 1) * page, base, base + count * page), + "joined: one view of 32 pages"); + std::printf("merge: 1 view of 32 pages\n"); + } else { + bool each = true; + for (SIZE_T i = 0; i < count; ++i) each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); + if (check(each, "one view per call")) std::printf("no-merge control: 32 views\n"); + } + check(marked(base, count, 0x61000000u), "joined: marks kept"); + if (middle) { + check(shim.map(base + 10 * page, 1, nullptr) == base + 10 * page, "middle: unmap page 10"); + check(view_is(base, base, base + 10 * page) && view_is(base + 9 * page, base, base + 10 * page), "middle: view [0, 10)"); + check(view_is(base + 11 * page, base + 11 * page, base + count * page), "middle: view [11, 32)"); + check(region(base + 10 * page).state == MEM_RESERVE, "middle: page 10 reserved"); + check(marked(base, count, 0x61000000u, 10), "middle: neighbours keep their marks"); + check(shim.map(base, 10, nullptr) == base && shim.map(base + 11 * page, count - 11, nullptr) == base + 11 * page, + "middle: unmap the rest"); + } else { + check(shim.map(base, count, nullptr) == base, "unmap 32 pages"); + } + check(shim.release(count, tokens.data()) != FALSE, "release 32 pages"); +} + +void reversed(const Shim& shim, unsigned char* base, unsigned char* scratch) +{ + auto tokens = shim.pages(count); + if (!check(tokens.size() == count, "reversed: allocate")) return; + // Mark every slot through one view first: slot k holds 0x62000000 + k. + if (!check(shim.map(scratch, count, tokens.data()) == scratch, "reversed: map the slots in order")) return; + for (SIZE_T k = 0; k < count; ++k) word(scratch + k * page) = 0x62000000u + static_cast(k); + check(shim.map(scratch, count, nullptr) == scratch, "reversed: unmap the slots"); + bool mapped = true; + for (SIZE_T i = 0; i < count && mapped; ++i) + mapped = shim.map(base + i * page, 1, &tokens[count - 1 - i]) == base + i * page; + if (!check(mapped, "reversed: 32 single-page calls")) return; + bool each = true, data = true; + for (SIZE_T i = 0; i < count; ++i) { + each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); + data &= region(base + i * page).state == MEM_COMMIT && word(base + i * page) == 0x62000000u + (count - 1 - i); + } + check(each, "reversed: 32 views"); + check(data, "reversed: page i shows slot 31 - i"); + check(shim.map(base, count, nullptr) == base && shim.release(count, tokens.data()), "reversed: unmap and release"); +} + +void window(const Shim& shim, unsigned char* base) +{ + auto tokens = shim.pages(9); + if (!check(tokens.size() == 9 && shim.map(base, 8, tokens.data()) == base, "window: map a run of 8 pages")) return; + for (SIZE_T i = 0; i < 8; ++i) word(base + i * page) = 0x63000000u + static_cast(i); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-cross-call-merge-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + bool joined_call = false; + std::thread mapper([&] { joined_call = shim.map(base + 8 * page, 1, &tokens[8]) == base + 8 * page; }); + const bool opened = WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0; + check(opened, "window: the merge held the window"); + unsigned char* const target = base + 2 * page; + if (opened) check(region(target).state != MEM_COMMIT, "window: raw query inside the window not committed"); + std::atomic read_done{false}, query_done{false}; + std::uint32_t value = 0; + DWORD state = 0; + std::thread reader([&] { + value = word(target); // faults inside the window; retried by the shim after it + read_done = true; + }); + std::thread querier([&] { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast(context); + q.state = region(q.target).state; + }, &query); + state = query.state; + query_done = true; + }); + Sleep(300); + check(!read_done.load(), "window: the reader waits for the merge"); + check(!query_done.load(), "window: x2w_xmem_stable_call waits for the merge"); + SetEvent(release); + reader.join(); + querier.join(); + mapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(joined_call, "window: the mapping call succeeded"); + check(value == 0x63000002u, "window: the reader read the mark"); + check(state == MEM_COMMIT, "window: x2w_xmem_stable_call answered committed"); + check(view_is(base, base, base + 9 * page), "window: one view of 9 pages"); + check(marked(base, 8, 0x63000000u), "window: marks kept"); + check(shim.map(base, 9, nullptr) == base && shim.release(9, tokens.data()), "window: unmap and release"); + CloseHandle(unmapped); + CloseHandle(release); +} + +void refused(const Shim& shim, unsigned char* base, const char* stage, const char* name) +{ + const ULONGLONG live_before = shim.live(); + auto tokens = shim.pages(9); + if (!check(tokens.size() == 9 && shim.map(base, 8, tokens.data()) == base, name, "map a run of 8 pages")) return; + for (SIZE_T i = 0; i < 8; ++i) word(base + i * page) = 0x64000000u + static_cast(i); + SetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", stage); + const bool mapped = shim.map(base + 8 * page, 1, &tokens[8]) == base + 8 * page; + SetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", nullptr); + check(mapped, name, "the mapping call succeeded"); + // State first: a page without a view is not touched. + bool committed = true; + for (SIZE_T i = 0; i < 9; ++i) committed &= region(base + i * page).state == MEM_COMMIT; + if (!check(committed, name, "all 9 pages committed")) return; + check(view_is(base, base, base + 8 * page) && view_is(base + 7 * page, base, base + 8 * page), name, + "the run is a view of 8 pages again"); + check(view_is(base + 8 * page, base + 8 * page, base + 9 * page), name, "the new page has a view of its own"); + check(marked(base, 8, 0x64000000u), name, "marks kept"); + word(base + 8 * page) = 0x64000008u; + check(marked(base, 9, 0x64000000u), name, "the new page holds its write"); + check(shim.map(base, 9, nullptr) == base, name, "unmap 9 pages"); + check(shim.release(9, tokens.data()) != FALSE, name, "release 9 pages"); + check(shim.live() == live_before, name, "live page count back where it was"); +} + +void two_reservations(const Shim& shim) +{ + const auto virtual_alloc2 = reinterpret_cast( + GetProcAddress(GetModuleHandleA("kernelbase.dll"), "VirtualAlloc2")); + if (!check(virtual_alloc2 != nullptr, "two-reservations: VirtualAlloc2")) return; + auto* const piece = static_cast(virtual_alloc2(GetCurrentProcess(), nullptr, 8 * page, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)); + if (!check(piece && VirtualFree(piece, 4 * page, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "two-reservations: split a placeholder")) + return; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + const bool recorded = shim.virtual_alloc(piece, 4 * page, 0x20406000, 0x21, PAGE_READWRITE) == piece && + shim.virtual_alloc(piece + 4 * page, 4 * page, 0x20406000, 0x21, PAGE_READWRITE) == piece + 4 * page; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + if (!check(recorded, "two-reservations: record both pieces")) return; + auto tokens = shim.pages(5); + if (!check(tokens.size() == 5 && shim.map(piece, 4, tokens.data()) == piece && + shim.map(piece + 4 * page, 1, &tokens[4]) == piece + 4 * page, "two-reservations: map 4 + 1 pages")) + return; + check(view_is(piece, piece, piece + 4 * page), "two-reservations: the first piece's run stays 4 pages"); + check(view_is(piece + 4 * page, piece + 4 * page, piece + 5 * page), "two-reservations: the page has a view of its own"); + check(shim.map(piece, 4, nullptr) == piece && shim.map(piece + 4 * page, 1, nullptr) == piece + 4 * page && + shim.release(5, tokens.data()), "two-reservations: unmap and release"); + VirtualFree(piece, 0, MEM_RELEASE); + VirtualFree(piece + 4 * page, 0, MEM_RELEASE); +} +} // namespace + +int main(int argc, char** argv) +{ + const char* const mode = argc == 3 ? argv[2] : ""; + const bool all = std::strcmp(mode, "check") == 0, control = std::strcmp(mode, "control") == 0, + deployed = std::strcmp(mode, "deployed") == 0, plain = std::strcmp(mode, "default") == 0; + if (!all && !control && !deployed && !plain) { + std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default\n"); + return 2; + } + // The mode is read by the first mapping call. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", plain ? nullptr : "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + const Shim shim{reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")), + reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemFreePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_stable_call")), + reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_page_stats"))}; + if (!shim.virtual_alloc || !shim.allocate || !shim.map || !shim.release || !shim.stable_call || !shim.page_stats) { + std::printf("check_failed: exports\n"); + return 1; + } + auto* const whole = static_cast(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!whole) { + std::printf("check_failed: startup reservation (error %lu)\n", GetLastError()); + return 1; + } + unsigned char* const base = whole + page; + single_page_calls(shim, base, all || deployed, all); + if (all) { + reversed(shim, base + 64 * page, base + 128 * page); + window(shim, base + 192 * page); + refused(shim, base + 256 * page, "4:0", "refused-4"); + refused(shim, base + 320 * page, "5:0", "refused-5"); + two_reservations(shim); + } + VirtualFree(whole, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/xmem_page_runs_check.py b/tests/xmem_page_runs_check.py index afb878d74f..b9bf799cd8 100644 --- a/tests/xmem_page_runs_check.py +++ b/tests/xmem_page_runs_check.py @@ -153,9 +153,11 @@ def view(page, first, last): assert view(i, 4, 7), f"upper piece, page {i}: {shim.query(base + i * PAGE)}" hole = shim.query(base + 3 * PAGE) assert hole[1] == base + 3 * PAGE and hole[2] == PAGE and hole[3] == MEM_RESERVE, hole - # Mapping the page again does not join the pieces: three views. + # Mapping the page again on its own call joins the lower piece, which ends at it on the slot before + # (merge_with_previous): two views. It never joins the upper piece. One view per call without the merge is + # asserted by xmem_cross_call_merge_control (tests/xmem_cross_call_merge_check.cpp). assert shim.contiguous(base + 3 * PAGE, 1, C.byref(shim.number(tokens[3]))) == base + 3 * PAGE - assert view(3, 3, 3) and view(2, 0, 2) and view(4, 4, 7) + assert view(3, 0, 3) and view(2, 0, 3) and view(4, 4, 7), (shim.query(base + 3 * PAGE), shim.query(base + 4 * PAGE)) assert shim.contiguous(base, 8, None) == base and shim.release(8, tokens) diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index e89264236e..991284af35 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -88,10 +88,11 @@ int main(int argc, char** argv) if (!whole) return 1; unsigned char* const first = whole + page; - // Two mapping calls next to each other: two views that meet at first + 8 pages. + // Two mapping calls next to each other: two views that meet at first + 8 pages. The upper one is mapped first: a + // call joins only a view that ends at its address (merge_with_previous), never one that starts after it. const auto a = pages(8), b = pages(8); - if (a.empty() || b.empty() || XMemMapPhysicalPages(first, 8, a.data()) != first || - XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page) + if (a.empty() || b.empty() || XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page || + XMemMapPhysicalPages(first, 8, a.data()) != first) return 1; place("inside one view", wrapper.Get(), first + 4 * page, 1); place("across two mapping calls", wrapper.Get(), first + 8 * page, 2); @@ -107,12 +108,13 @@ int main(int argc, char** argv) } place("across two backing sections", wrapper.Get(), second + info.RegionSize, 2); - // Pages mapped one call at a time get a view each: the layout every page had before views were shared. + // Pages mapped one call at a time get a view each: the layout every page had before views were shared. The slots + // go in reverse order, so that no call continues the slot before it and joins its view (merge_with_previous). unsigned char* const third = second + 8192 * page; const auto single = pages(8); if (single.empty()) return 1; for (int i = 0; i < 8; ++i) - if (XMemMapPhysicalPages(third + i * page, 1, &single[i]) != third + i * page) return 1; + if (XMemMapPhysicalPages(third + i * page, 1, &single[7 - i]) != third + i * page) return 1; place("across two single-page views", wrapper.Get(), third + 4 * page, 2); if (failures) { From a4dc3f9c193b1644af05215d20a84174f33e84fb Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:58:01 +1000 Subject: [PATCH 13/34] xmem: stop a joined run at 64 pages An unmap inside a run takes the whole run apart and maps its other pages again, and a cross-call merge does the same to the run it joins. Nothing bounded the joined run, so after loading every title unmap inside a run of thousands of pages cost one long break: 46-72 ms each in a gate run under Wine, with readers waiting 63 s in all and presents at 2.4/s. merge_with_previous now leaves a page on its own when the joined run would be longer than max_merged_run_pages (64); the next pages join that one. The test build's X2W_XMEM_TEST_MERGE_CAP replaces the cap for a timing mode. Measured under Wine with every byte of the run written (xmem_cross_call_merge_check timing, median of 5): an unmap inside a run of 64 pages takes 0.28 ms, of 512 pages 2.1 ms, of 4096 pages 13 ms; joining a page to a run of 63 takes 1.5 ms, about what a page mapped on its own costs (1.4 ms). The fixture process has a few views, the title process tens of thousands. xmem_cross_call_merge gets a capped case: 192 single-page calls make three views of 64 pages, and an unmap held in its window in the middle one takes apart 64 pages while the outer two stay mapped. The control, deployed and default modes now print their pass line at the end of main, only with no failed check. --- docs/startup-runtime.md | 8 +- src/xmem_mapped_pages.cpp | 17 +++ tests/xmem_cross_call_merge_check.cpp | 151 ++++++++++++++++++++++++-- 3 files changed, 167 insertions(+), 9 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d33bb4c391..97cee7e926 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3165,7 +3165,13 @@ more views the process has. So a mapping call whose pages all continue the view address, on the next slots of the same section and inside the same reservation of the shim, joins that view: the view is unmapped, its placeholder is joined with the new pages' placeholder, and one view is mapped over both. It is taken apart the same way as in an unmap (below), and if a step is -refused the view is mapped again as it was and the new pages get a view of their own. +refused the view is mapped again as it was and the new pages get a view of their own. A joined +view stops at 64 pages (`max_merged_run_pages`): a page that would make it longer starts a view of +its own, which the next pages join. Every later unmap inside a view takes the whole view apart, so +the cap bounds that work too. Measured under Wine with every byte of the view written +(`xmem_cross_call_merge_check timing`): an unmap inside a view of 64 pages took 0.28 ms, of 512 +pages 2.1 ms and of 4096 pages 13 ms; joining a page to a view of 63 took 1.5 ms, about what a page +mapped on its own costs (1.4 ms). Unmapping a page inside a shared view unmaps that view and maps its other pages again. A thread that touches one of those pages in between takes an access violation. A vectored handler retries diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 720202346e..0e3f747eda 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -774,8 +774,24 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu // nothing changed; after it, R is mapped again as it was (map_recorded). Both return separate, and // the caller maps the new pages on their own. lost: R could not be mapped again; the pages that have // no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 turns the merge off (tests only). +// A joined run stops at max_merged_run_pages: a page that would make R longer starts a run of its own, which the +// next pages join. An unmap inside a run takes the whole run apart and maps its other pages again, so the cap bounds +// the work of every later break of the run as well as of each join. enum class Merge { joined, separate, lost }; +constexpr SIZE_T max_merged_run_pages = 64; + +// Test build only: X2W_XMEM_TEST_MERGE_CAP= replaces the cap (xmem_cross_call_merge_check's timing mode). +SIZE_T merged_run_cap() +{ +#ifdef X2W_XMEM_TEST_CONTROLS + char text[24]; + if (GetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", text, sizeof(text))) + if (const auto pages = std::strtoull(text, nullptr, 10)) return static_cast(pages); +#endif + return max_merged_run_pages; +} + Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, MapFailure* failure) { #ifdef X2W_XMEM_TEST_CONTROLS @@ -785,6 +801,7 @@ Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, if (next == memory.runs.begin()) return Merge::separate; const auto [base, size] = *std::prev(next); if (base + size != address) return Merge::separate; + if ((size + bytes) / page_bytes > merged_run_cap()) return Merge::separate; const auto tail = memory.views.find(address - page_bytes); if (tail == memory.views.end()) return Merge::separate; const Backing& previous = memory.backings.at(tail->second); diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp index 558b497a22..3d0aa09cf2 100644 --- a/tests/xmem_cross_call_merge_check.cpp +++ b/tests/xmem_cross_call_merge_check.cpp @@ -9,6 +9,9 @@ // before the merge. Prints "no-merge control: 32 views". // deployed (deployed xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) the deployed shim ignores the test switch and merges. // default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own. +// timing (test-controls xmem.dll; not a ctest case) ms of a join, of a break and of an own-view map against the +// run length R (X2W_XMEM_TEST_MERGE_CAP), for the cap's table in the review notes. +// The pass line of control, deployed and default is printed at the end of main, only when no check failed. // // Cases of `check`: // joined 32 single-page calls on consecutive slots: one view of 32 pages; each page keeps the mark written @@ -24,12 +27,15 @@ // the pages unmap and release, and the live page count returns to where it was. // two-reservations a caller placeholder split in two pieces, each recorded with XMemVirtualAlloc (permissive // replace-placeholder call): a page at the start of the second piece does not join the first's run. +// capped 192 single-page calls make three runs of 64 pages (max_merged_run_pages); an unmap held in its window +// inside the middle run takes apart at most 64 pages, and the outer runs stay mapped. // -// Usage: xmem_cross_call_merge_check check|control|deployed|default +// Usage: xmem_cross_call_merge_check check|control|deployed|default|timing #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include +#include #include #include #include @@ -50,6 +56,7 @@ constexpr SIZE_T page = SIZE_T{64} << 10; constexpr SIZE_T count = 32; int failures = 0; +const char* token = nullptr; // the mode's pass line; main prints it at its end, and only with no failure bool check(bool ok, const char* name, const char* detail = "") { @@ -134,13 +141,13 @@ void single_page_calls(const Shim& shim, unsigned char* base, bool merges, bool if (!check(tokens.size() == count, "allocate 32 pages")) return; if (!check(map_one_by_one(shim, base, tokens, 0x61000000u, [](SIZE_T i) { return i; }), "32 single-page calls")) return; if (merges) { - check(view_is(base, base, base + count * page) && view_is(base + (count - 1) * page, base, base + count * page), - "joined: one view of 32 pages"); - std::printf("merge: 1 view of 32 pages\n"); + if (check(view_is(base, base, base + count * page) && view_is(base + (count - 1) * page, base, base + count * page), + "joined: one view of 32 pages")) + token = "merge: 1 view of 32 pages"; } else { bool each = true; for (SIZE_T i = 0; i < count; ++i) each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); - if (check(each, "one view per call")) std::printf("no-merge control: 32 views\n"); + if (check(each, "one view per call")) token = "no-merge control: 32 views"; } check(marked(base, count, 0x61000000u), "joined: marks kept"); if (middle) { @@ -256,6 +263,125 @@ void refused(const Shim& shim, unsigned char* base, const char* stage, const cha check(shim.live() == live_before, name, "live page count back where it was"); } +// Named events for X2W_XMEM_TEST_HOLD_WINDOW: ".unmapped" (set by the held call) and ".release". +struct Hold { + char name[64]; + HANDLE unmapped, release; + explicit Hold(const char* stem) + { + std::snprintf(name, sizeof(name), "x2w-cross-call-merge-%s-%lu", stem, GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", name); + unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", name); + release = CreateEventA(nullptr, TRUE, FALSE, event_name); + } + ~Hold() + { + CloseHandle(unmapped); + CloseHandle(release); + } +}; + +// capped: 3 * cap single-page calls make three runs of cap pages (the cap of the shim, 64), not one. The unmap of a +// page in the middle run is held in its window: the pages that read as not committed there are the pages the break +// took apart, at most one run of cap pages; the runs before and after it stay mapped. +void capped(const Shim& shim, unsigned char* base) +{ + constexpr SIZE_T cap = 64, n = 3 * cap, hole = cap + cap / 2; + auto tokens = shim.pages(n); + if (!check(tokens.size() == n, "capped: allocate 192 pages")) return; + if (!check(map_one_by_one(shim, base, tokens, 0x65000000u, [](SIZE_T i) { return i; }), "capped: 192 single-page calls")) + return; + bool runs = true; + for (SIZE_T r = 0; r < 3; ++r) + runs &= view_is(base + r * cap * page, base + r * cap * page, base + (r + 1) * cap * page) && + view_is(base + ((r + 1) * cap - 1) * page, base + r * cap * page, base + (r + 1) * cap * page); + check(runs, "capped: three views of 64 pages"); + Hold hold("capped"); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold.name); + bool unmapped_call = false; + std::thread unmapper([&] { unmapped_call = shim.map(base + hole * page, 1, nullptr) == base + hole * page; }); + const bool opened = WaitForSingleObject(hold.unmapped, 10000) == WAIT_OBJECT_0; + SIZE_T taken_apart = 0; + bool outer_mapped = true; + for (SIZE_T i = 0; opened && i < n; ++i) { + const bool committed = region(base + i * page).state == MEM_COMMIT; + taken_apart += !committed; + if (i < cap || i >= 2 * cap) outer_mapped &= committed; + } + SetEvent(hold.release); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + char detail[64]; + std::snprintf(detail, sizeof(detail), "(%zu pages)", static_cast(taken_apart)); + check(opened, "capped: the unmap held the window"); + check(opened && taken_apart <= cap, "capped: the break took apart at most 64 pages", detail); + check(opened && outer_mapped, "capped: the runs before and after stay mapped in the window"); + check(unmapped_call, "capped: the unmap succeeded"); + check(view_is(base + cap * page, base + cap * page, base + hole * page) && + view_is(base + (hole + 1) * page, base + (hole + 1) * page, base + 2 * cap * page), "capped: views [64, 96) and [97, 128)"); + check(marked(base, n, 0x65000000u, hole), "capped: marks kept"); + check(shim.map(base, hole, nullptr) == base && shim.map(base + (hole + 1) * page, n - hole - 1, nullptr) == base + (hole + 1) * page && + shim.release(n, tokens.data()), "capped: unmap and release"); +} + +// timing (not a ctest case; ready.md's table): for a run of R pages, the ms of the call that joins page R to a run of +// R - 1 (X2W_XMEM_TEST_MERGE_CAP=R), of the unmap of page R/2 (one break of the whole run) and, for comparison, of a +// single-page call that maps a view of its own (X2W_XMEM_TEST_NO_MERGE=1). Every byte of the run is written before +// the join and before the break, as a title's use of the pages would (a run that is mostly untouched unmaps much +// faster). Median of 5 (3 from 1024 pages). This process has a few +// views; a title process has tens of thousands, and under Wine each map costs more the more views there are. +double ms_since(const LARGE_INTEGER& from) +{ + LARGE_INTEGER now, frequency; + QueryPerformanceCounter(&now); + QueryPerformanceFrequency(&frequency); + return 1000.0 * static_cast(now.QuadPart - from.QuadPart) / static_cast(frequency.QuadPart); +} + +double median(std::vector v) +{ + std::sort(v.begin(), v.end()); + return v.empty() ? 0.0 : v[v.size() / 2]; +} + +void timing(const Shim& shim, unsigned char* base) +{ + std::printf("timing: R pages | join ms | break ms | own-view map ms (median of 5)\n"); + for (const SIZE_T r : {SIZE_T{16}, SIZE_T{32}, SIZE_T{64}, SIZE_T{128}, SIZE_T{256}, SIZE_T{512}, SIZE_T{1024}, + SIZE_T{2048}, SIZE_T{4096}}) { + std::vector join, unmap, own; + char cap[24]; + std::snprintf(cap, sizeof(cap), "%zu", static_cast(r)); + for (int rep = 0; rep < (r >= 1024 ? 3 : 5); ++rep) { + auto tokens = shim.pages(r + 1); + if (!check(tokens.size() == r + 1 && shim.map(base, r - 1, tokens.data()) == base, "timing: map R - 1 pages")) return; + std::memset(base, 0x5a, (r - 1) * page); + SetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", cap); + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + const bool joined = shim.map(base + (r - 1) * page, 1, &tokens[r - 1]) == base + (r - 1) * page; + join.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", nullptr); + check(joined && view_is(base, base, base + r * page), "timing: joined run of R pages"); + std::memset(base, 0x5b, r * page); + QueryPerformanceCounter(&t); + check(shim.map(base + (r / 2) * page, 1, nullptr) == base + (r / 2) * page, "timing: unmap page R/2"); + unmap.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_NO_MERGE", "1"); + QueryPerformanceCounter(&t); + const bool alone = shim.map(base + r * page, 1, &tokens[r]) == base + r * page; + own.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_NO_MERGE", nullptr); + check(alone && view_is(base + r * page, base + r * page, base + (r + 1) * page), "timing: own view"); + check(shim.map(base, r / 2, nullptr) == base && shim.map(base + (r / 2 + 1) * page, r / 2, nullptr) && + shim.release(r + 1, tokens.data()), "timing: unmap and release"); + } + std::printf("timing: %4zu | %7.3f | %7.3f | %7.3f\n", static_cast(r), median(join), median(unmap), median(own)); + } +} + void two_reservations(const Shim& shim) { const auto virtual_alloc2 = reinterpret_cast( @@ -287,9 +413,10 @@ int main(int argc, char** argv) { const char* const mode = argc == 3 ? argv[2] : ""; const bool all = std::strcmp(mode, "check") == 0, control = std::strcmp(mode, "control") == 0, - deployed = std::strcmp(mode, "deployed") == 0, plain = std::strcmp(mode, "default") == 0; - if (!all && !control && !deployed && !plain) { - std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default\n"); + deployed = std::strcmp(mode, "deployed") == 0, plain = std::strcmp(mode, "default") == 0, + timed = std::strcmp(mode, "timing") == 0; + if (!all && !control && !deployed && !plain && !timed) { + std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default|timing\n"); return 2; } // The mode is read by the first mapping call. @@ -315,6 +442,12 @@ int main(int argc, char** argv) return 1; } unsigned char* const base = whole + page; + if (timed) { + timing(shim, base); + VirtualFree(whole, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } single_page_calls(shim, base, all || deployed, all); if (all) { reversed(shim, base + 64 * page, base + 128 * page); @@ -322,8 +455,10 @@ int main(int argc, char** argv) refused(shim, base + 256 * page, "4:0", "refused-4"); refused(shim, base + 320 * page, "5:0", "refused-5"); two_reservations(shim); + capped(shim, base + 512 * page); } VirtualFree(whole, 0, MEM_RELEASE); + if (!failures && token) std::printf("%s\n", token); std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; } From 1bf82dd2d9a7c9121d576d19e0830ba4435baddf Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:58:23 +1000 Subject: [PATCH 14/34] xmem: retry a fault from any of the last 64 breaks, not only the last begin_break replaced the recorded ranges, so retry_remapped_page saw only the last break. A handler that ran after a later break on another run had begun found its address outside those ranges and passed the fault on. Joins made that the normal case: one permissive XMemMapPhysicalPages call joins the CPU run and then its GPU mirror run under one memory.mutex hold, and each map call opens a break of its own. RemapWindow now keeps the ranges of the last 64 breaks with their id (the odd generation). The handler names the newest break whose ranges hold the address, so a fault in a later break of the same page is still retried once more. xmem_run_break_readers_two_runs faults in break A on run 1 and holds the handler until break B on a disjoint run 2 is held open. xmem_run_break_readers_mirror does the same across the CPU join and the GPU mirror join of one call (X2W_XMEM_PERMISSIVE, X2W_XMEM_GPU_MIRROR). With one kept break both end the process with an access violation (exit 5). The RemapWindow and hold_window comments now also name the merge. --- CMakeLists.txt | 7 +- docs/startup-runtime.md | 10 +- src/xmem_mapped_pages.cpp | 63 +++++++---- tests/xmem_run_break_readers_check.cpp | 141 ++++++++++++++++++++++++- 4 files changed, 191 insertions(+), 30 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ca5ed3c012..aff3e2c46c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -352,8 +352,13 @@ add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_r # the readers' output buffer in a mapped slot not yet committed. add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) +# A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint +# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR). +add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) +add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$" mirror) set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control - xmem_run_break_readers_default xmem_run_break_readers_lazy PROPERTIES TIMEOUT 60) + xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs + xmem_run_break_readers_mirror PROPERTIES TIMEOUT 60) set_tests_properties(xmem_run_break_readers_default PROPERTIES PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") # Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 97cee7e926..a46587a89d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3175,10 +3175,12 @@ mapped on its own costs (1.4 ms). Unmapping a page inside a shared view unmaps that view and maps its other pages again. A thread that touches one of those pages in between takes an access violation. A vectored handler retries -it only when the address is inside a view that the unmap in progress, or the last finished one, -took apart, the page is recorded and covered by a view once that unmap is over, and the thread -has not already retried that page for that unmap. Any other fault is passed on, after at most one -retry. +it only when the address is inside a view that one of the last 64 unmaps or joins (the one in +progress included) took apart, the page is recorded and covered by a view once that one is over, +and the thread has not already retried that page for the newest such unmap or join. A handler that +runs late, after a later unmap or join of another view has begun (one call joins a CPU view and +then its GPU mirror), still finds the one its fault came from. Any other fault is passed on, after +at most one retry for each unmap or join. Shared views are opt-in. The caller chooses before the first mapping call by setting `X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. It also diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 0e3f747eda..c20857835b 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -481,13 +481,36 @@ void coalesce_unused(const Pages& batch) } } -// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages). -// A thread that touches one of those pages in between faults. The break records the address -// ranges of the runs it takes apart and a generation that is odd while it is in progress. +// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages), and so does a +// cross-call merge (merge_with_previous) for the run it joins. A thread that touches one of those pages in between +// faults. Each break records the address ranges of the runs it takes apart, and a generation that is odd while it +// is in progress; the break's id is that odd value. The last `kept` breaks stay recorded, so that a fault handler +// that runs late, after later breaks on other runs have begun (a merge of the CPU view and then of its GPU mirror +// in one call, or the next call's merge), still finds the break its fault came from. struct RemapWindow { + static constexpr std::size_t kept = 64; + struct Break { + ULONG64 id = 0; // 0: no break recorded in this slot yet + std::vector> ranges; + }; SRWLOCK lock = SRWLOCK_INIT; - std::vector> ranges; // the runs of the break in progress, or of the last one + Break recent[kept]; // break id i in recent[(i / 2) % kept] ULONG64 generation = 0; + + // The newest recorded break whose ranges hold address, or 0. Caller holds lock (shared). + ULONG64 newest_holding(ULONG_PTR address) const + { + ULONG64 found = 0; + for (const Break& b : recent) { + if (b.id <= found) continue; + for (const auto& [base, size] : b.ranges) + if (address - base < size) { + found = b.id; + break; + } + } + return found; + } }; RemapWindow remap_window; // Set once shared views are on (FaultRetry::ready). Breaks also begin without them (every unmap counts in the @@ -499,8 +522,10 @@ void begin_break(const std::map& broken) { std::vector> ranges(broken.begin(), broken.end()); AcquireSRWLockExclusive(&remap_window.lock); - remap_window.ranges.swap(ranges); - ++remap_window.generation; + const ULONG64 id = ++remap_window.generation; + auto& slot = remap_window.recent[(id / 2) % RemapWindow::kept]; + slot.id = id; + slot.ranges.swap(ranges); // the old slot's ranges are freed after the lock ReleaseSRWLockExclusive(&remap_window.lock); } void end_break() @@ -536,11 +561,11 @@ void hold_retry() void hold_retry() {} #endif -// Retries an access violation only when all of this holds: the address is inside a run that the -// break in progress, or the last finished one, took apart; after that break has finished (the -// mutex) the page is recorded and covered by a view; and this thread has not already retried this -// page for this break. Everything else is passed on, so a fault that is not the transient one is -// reported after at most one retry. +// Retries an access violation only when all of this holds: the address is inside a run that one of the recorded +// breaks (the one in progress or the last RemapWindow::kept) took apart; after that break has finished (the mutex) +// the page is recorded and covered by a view; and this thread has not already retried this page for the newest +// such break. Everything else is passed on, so a fault that is not the transient one is reported after at most one +// retry per break. LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -549,16 +574,12 @@ LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) const ULONG_PTR address = record->ExceptionInformation[1]; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); hold_retry(); - bool inside = false; AcquireSRWLockShared(&remap_window.lock); - const ULONG64 seen = remap_window.generation; - for (const auto& [base, size] : remap_window.ranges) - inside |= address - base < size; + // The newest break that took the page apart, in progress or finished; a later break on another run does not + // hide it. A fault in a later break of the same page names that break, so it is retried again. + const ULONG64 break_id = remap_window.newest_holding(address); ReleaseSRWLockShared(&remap_window.lock); - if (!inside || seen == 0) return EXCEPTION_CONTINUE_SEARCH; - // The break in progress (odd), or the one that just finished (even: the one before). Not seen | 1, which for an - // even generation names the next break, so that a fault in it, on the same page, would not be retried. - const ULONG64 break_id = (seen - 1) | 1; + if (!break_id) return EXCEPTION_CONTINUE_SEARCH; thread_local ULONG_PTR retried_page = 0; thread_local ULONG64 retried_break = 0; if (retried_page == page && retried_break == break_id) return EXCEPTION_CONTINUE_SEARCH; @@ -662,8 +683,8 @@ struct TestFault { }; #endif -// Test build only: X2W_XMEM_TEST_HOLD_WINDOW= keeps an unmap in the window where the run is -// unmapped and not yet mapped again. It sets the event ".unmapped", then waits up to +// Test build only: X2W_XMEM_TEST_HOLD_WINDOW= keeps an unmap, or a cross-call merge (merge_with_previous), in the +// window where the run is unmapped and not yet mapped again. It sets the event ".unmapped", then waits up to // five seconds for ".release", so that a reader thread can reach the window every time. #ifdef X2W_XMEM_TEST_CONTROLS void hold_window() diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index be07ade9db..b722875fbd 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -20,6 +20,10 @@ // `next-break-control` the handler is not held, so it reads break A while A is open: that order passes even when // the handler names the breaks wrongly, which shows the hold is what this case depends on. // +// A fault whose handler reads the breaks only after a later break on another run has begun (two_runs: break B on a +// disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) +// must be retried as well: the handler keeps the ranges of the recent breaks, not only of the last one. +// // A break that begins while x2w_xmem_stable_call's fn runs (break_during_fn): fn itself starts the unmap, waits until // the window is open and queries a page of the run (reserved). stable_call must see the generation change and run fn // again under memory.mutex: 2 calls, the last one committed. @@ -29,7 +33,10 @@ // `lazy` (X2W_XMEM_SHARED_VIEWS=1, X2W_XMEM_LAZY_COMMIT=1): XMemVirtualQuery and VirtualQueryEx wait for a break // with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. // -// Usage: xmem_run_break_readers_check [control|next-break-control|default|lazy] +// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process). +// +// Usage: xmem_run_break_readers_check +// [control|next-break-control|default|lazy|two-runs|mirror] #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include @@ -376,16 +383,140 @@ void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) CloseHandle(second_read); if (!hold_retry) std::printf("next-break control: the handler read break A while it was open\n"); } +// Break A takes apart run 1, break B (begun after A ended) run 2, a disjoint run. The handler for a fault in A is held +// (X2W_XMEM_TEST_HOLD_RETRY) until B is held open, so it reads the breaks while B is in progress: it must still find +// A and retry the fault. A handler that knew only the last break's ranges passes the fault on, and the process ends +// with an access violation. +void two_runs_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "two_runs"; + unsigned char* const run1 = base; + unsigned char* const run2 = base + 16 * page; + SIZE_T count = 2 * pages, tokens[2 * pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != 2 * pages || shim.map(run1, pages, tokens) != run1 || + shim.map(run2, pages, tokens + pages) != run2) { + check(false, "map_runs", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) { + *reinterpret_cast(run1 + i * page) = 0x54000000u + static_cast(i); + *reinterpret_cast(run2 + i * page) = 0x54100000u + static_cast(i); + } + unsigned char* const target = run1 + 2 * page; + Events window_a("two-a", "unmapped", "release"), window_b("two-b", "unmapped", "release"), retry("two-retry", "faulted", "go"); + std::atomic reads{0}; + std::uint32_t value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_a.name); + std::thread unmap_a([&] { shim.map(run1 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window_a.first, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, + "break_a_held_on_run_1", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + value = *reinterpret_cast(target); // faults in break A + ++reads; + }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(window_a.second); + unmap_a.join(); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_b.name); + std::thread unmap_b([&] { shim.map(run2 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0 && raw_state(run2 + 2 * page) != MEM_COMMIT, + "break_b_held_on_run_2", name); + SetEvent(retry.second); // the handler reads the breaks now, with B in progress + Sleep(100); + SetEvent(window_b.second); + unmap_b.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(reads.load() == 1 && value == 0x54000002u, "fault_in_break_a_retried_during_break_b", name); + check(*reinterpret_cast(run2 + 2 * page) == 0x54100002u, "run_2_data_kept", name); + shim.map(run1, 7, nullptr); + shim.map(run2, 7, nullptr); + shim.release(2 * pages, tokens); +} + +// The owner's configuration (X2W_XMEM_PERMISSIVE=1, X2W_XMEM_GPU_MIRROR=1): one XMemMapPhysicalPages call joins the +// CPU run, then the same pages' GPU mirror run, under one memory.mutex hold; the two breaks follow each other at once. +// A fault on the CPU run in the first break, whose handler is held until the GPU break is held open, must be retried. +// The release event is auto-reset, so each of the call's two holds waits for a release of its own. +void mirror_case(const Shim& shim, unsigned char* cpu) +{ + const char* const name = "mirror"; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", "1"); + auto* const gpu_view = static_cast(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 3, 0x800 | PAGE_NOACCESS)); + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", nullptr); + unsigned char* const at = cpu + page; + SIZE_T count = pages + 1, tokens[pages + 1] = {}; + if (!check(gpu_view != nullptr, "gpu_reservation", name) || + !check(shim.allocate(0x280, &count, tokens) && count == pages + 1 && shim.map(at, pages, tokens) == at, "map_run", name)) { + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + if (gpu_view) VirtualFree(gpu_view, 0, MEM_RELEASE); + return; + } + unsigned char* const twin = at - cpu + gpu_view; + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(at + i * page) = 0x55000000u + static_cast(i); + check(*reinterpret_cast(twin + 2 * page) == 0x55000002u, "gpu_twin_shows_the_cpu_page", name); + unsigned char* const target = at + 2 * page; + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-mirror-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, FALSE, FALSE, event_name); + Events retry("mirror-retry", "faulted", "go"); + std::atomic reads{0}; + std::uint32_t value = 0; + bool mapped = false; + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread mapper([&] { mapped = shim.map(at + pages * page, 1, &tokens[pages]) == at + pages * page; }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, "cpu_merge_held", name); + ResetEvent(unmapped); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + value = *reinterpret_cast(target); // faults in the CPU merge's break + ++reads; + }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(release); // the CPU merge ends; the GPU merge begins and holds + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(twin + 2 * page) != MEM_COMMIT && + raw_state(target) == MEM_COMMIT, "gpu_merge_held_after_the_cpu_merge", name); + SetEvent(retry.second); // the handler reads the breaks now, with the GPU merge in progress + Sleep(100); + SetEvent(release); + mapper.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(mapped, "mapping_call_succeeded", name); + check(reads.load() == 1 && value == 0x55000002u, "fault_in_the_cpu_merge_retried_during_the_gpu_merge", name); + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(at, &info, sizeof(info)) && info.RegionSize == (pages + 1) * page && + VirtualQuery(twin, &info, sizeof(info)) && info.RegionSize == (pages + 1) * page, "both_views_joined", name); + shim.map(at, pages + 1, nullptr); + shim.release(pages + 1, tokens); + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + VirtualFree(gpu_view, 0, MEM_RELEASE); + CloseHandle(unmapped); + CloseHandle(release); +} } // namespace int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); // a case that ends the process with an access violation keeps its lines const bool control = argc > 2 && std::strcmp(argv[2], "control") == 0; const bool next_break_control = argc > 2 && std::strcmp(argv[2], "next-break-control") == 0; const bool default_mode = argc > 2 && std::strcmp(argv[2], "default") == 0; const bool lazy = argc > 2 && std::strcmp(argv[2], "lazy") == 0; - if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy)) { - std::printf("usage: xmem_run_break_readers_check [control|next-break-control|default|lazy]\n"); + const bool two_runs = argc > 2 && std::strcmp(argv[2], "two-runs") == 0; + const bool mirror = argc > 2 && std::strcmp(argv[2], "mirror") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror)) { + std::printf("usage: xmem_run_break_readers_check " + "[control|next-break-control|default|lazy|two-runs|mirror]\n"); return 2; } // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. @@ -412,10 +543,12 @@ int main(int argc, char** argv) return 1; } unsigned char* const at = base + page; - if (next_break_control || default_mode || lazy) { + if (next_break_control || default_mode || lazy || two_runs || mirror) { if (next_break_control) next_break_case(shim, at, false); if (default_mode) default_case(shim, at); if (lazy) lazy_case(shim, at); + if (two_runs) two_runs_case(shim, at); + if (mirror) mirror_case(shim, base); VirtualFree(base, 0, MEM_RELEASE); std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; From 3985646e62cbb18dc2b15f0a3f49509024f08354 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:58:59 +1000 Subject: [PATCH 15/34] xmem: run title ReadFile/WriteFile again after a run break refused the buffer Inside a run break a kernel copy into or out of a page of the run fails at once, with no fault to retry. Measured under Wine with the break held open (xmem_run_break_readers ReadFile_import/WriteFile_import, before this change): ReadFile fails with ERROR_NOACCESS and leaves the file position at 0, WriteFile fails with ERROR_INVALID_USER_BUFFER. With X2W_XMEM_SHARED_VIEWS=1 at load, the main module's ReadFile and WriteFile imports go through a wrapper. A synchronous call that fails with one of those errors while a break was in progress, or began or ended around it, and whose buffer lies in a run, waits for memory.mutex and runs again, at most 4 times in all. Other failures return at once as before: a read into a reserved page in no run fails at once (io_outside_runs). With lazy commit the ReadFile wrapper calls read_file_committed inside (lazy_read_file). Overlapped I/O, a call that a break cuts short after part of the copy, and I/O from other modules stay uncovered. --- docs/startup-runtime.md | 17 +++- src/xmem_mapped_pages.cpp | 84 +++++++++++++++ tests/xmem_run_break_readers_check.cpp | 136 ++++++++++++++++++++++++- 3 files changed, 229 insertions(+), 8 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a46587a89d..15f07d0593 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3184,8 +3184,9 @@ at most one retry for each unmap or join. Shared views are opt-in. The caller chooses before the first mapping call by setting `X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. It also -reads it once when `xmem.dll` loads: with it set then, the main module's `VirtualQueryEx` imports -are wrapped (see below), and the module is pinned at load when one is. +reads it once when `xmem.dll` loads: with it set then, the main module's `VirtualQueryEx`, +`ReadFile` and `WriteFile` imports are wrapped (see below), and the module is pinned at load when +one is. A region query or a kernel copy does not fault, so inside an unmap it would see the pages of the view being taken apart as reserved. With shared views such readers run through the export @@ -3193,13 +3194,21 @@ view being taken apart as reserved. With shared views such readers run through t around it. `XMemVirtualQuery`, the main module's `VirtualQueryEx` imports and the shim's own `VirtualQuery` and `ReadProcessMemory` readers (`src/startup_stubs/local_log.h`, slot 133, the sampler snapshot) use it. Without shared views every page has a view of its own and readers -run once, as before. Title `ReadFile`/`WriteFile` into mapped pages are not covered. +run once, as before. + +Inside an unmap a kernel copy into or out of a page of that view fails at once. Measured under +Wine: `ReadFile` fails with `ERROR_NOACCESS` and leaves the file position as it was, `WriteFile` +with `ERROR_INVALID_USER_BUFFER`. The main module's `ReadFile` and `WriteFile` imports therefore +run again, up to 4 times in all, when a synchronous call fails with one of those errors while an +unmap or join was in progress or began or ended around it, and its buffer lies in a view of a +run; they wait for that one to end first. Overlapped I/O (the copy happens at completion), a call +cut short after part of the copy, and I/O from other modules are not covered. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| | Views | one per page | one per run of adjacent pages | | Fault handler | none | registered by the first mapping call, never removed | -| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends (at load when the main module imports `VirtualQueryEx`, else at the first mapping call) | +| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends (at load when the main module imports `VirtualQueryEx`, `ReadFile` or `WriteFile`, else at the first mapping call) | The handler is process-wide, and Windows has no removal that also waits for a dispatch already under way, so the opt-in keeps the module, the handler and the shim's state in place for the life diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index c20857835b..0989532c41 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -2040,6 +2040,90 @@ const int virtual_query_ex_wrapped = [] { queries); return queries; }(); + +// With X2W_XMEM_SHARED_VIEWS=1 the main module's ReadFile and WriteFile imports also go around run breaks. Inside one, +// a kernel copy into or out of a page of the run being taken apart fails at once, with no fault to retry. Measured +// under Wine (tests/xmem_run_break_readers_check.cpp, ReadFile_import and WriteFile_import): ReadFile fails with +// ERROR_NOACCESS and leaves the file position where it was, WriteFile with ERROR_INVALID_USER_BUFFER. A synchronous +// call (no OVERLAPPED) that fails with one of those while a break was in progress, or began or ended around it, and +// whose buffer lies in a run, waits for memory.mutex (the end of the break) and runs again, at most io_attempts times +// in all. A call that fails that way with no break around it, or outside the runs, fails at once as before. +// Not covered: overlapped I/O (the copy happens at completion, after the call has returned), a call that a break +// cuts short after part of the copy (a short count), and I/O from other modules or through GetProcAddress. +using WriteFileFn = BOOL(WINAPI*)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED); +ReadFileFn next_read_file; // read_file_committed with lazy commit, kernel32's ReadFile without +WriteFileFn kernel_write_file; +constexpr int io_attempts = 4; + +ULONG64 break_generation() +{ + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; +} + +// Whether [buffer, buffer + bytes) holds a page of a run. Takes memory.mutex, so it returns after the break in progress. +bool in_a_run(const void* buffer, DWORD bytes) +{ + const auto first = reinterpret_cast(buffer); + const std::lock_guard guard(memory.mutex); + const auto run = memory.runs.upper_bound(first); + if (run != memory.runs.begin() && first - std::prev(run)->first < std::prev(run)->second) return true; + return run != memory.runs.end() && run->first - first < bytes; +} + +template +BOOL io_outside_breaks(const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, const Call& call) +{ + if (overlapped || !buffer || !bytes || mapping_thread || !shared_views_on.load(std::memory_order_acquire)) return call(); + for (int attempt = 1;; ++attempt) { + const ULONG64 before = break_generation(); + if (call()) return TRUE; + const DWORD error = GetLastError(); + const bool broken = (before & 1) || break_generation() != before; + if ((error != ERROR_NOACCESS && error != ERROR_INVALID_USER_BUFFER) || !broken || attempt == io_attempts || + !in_a_run(buffer, bytes)) { + SetLastError(error); + return FALSE; + } + } +} + +BOOL WINAPI read_file_stable(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) +{ + return io_outside_breaks(buffer, bytes, overlapped, [&] { return next_read_file(file, buffer, bytes, read, overlapped); }); +} + +BOOL WINAPI write_file_stable(HANDLE file, LPCVOID buffer, DWORD bytes, LPDWORD written, LPOVERLAPPED overlapped) +{ + return io_outside_breaks(buffer, bytes, overlapped, [&] { return kernel_write_file(file, buffer, bytes, written, overlapped); }); +} + +const int file_io_wrapped = [] { + if (!x2w_local::env_on("X2W_XMEM_SHARED_VIEWS")) return 0; + const HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); + const auto kernel_read_file = reinterpret_cast(GetProcAddress(kernel32, "ReadFile")); + kernel_write_file = reinterpret_cast(GetProcAddress(kernel32, "WriteFile")); + if (!kernel_read_file || !kernel_write_file) return 0; + // With lazy commit the ReadFile imports already point at read_file_committed, which stays the inner call. + next_read_file = lazy_commit_installed && real_read_file ? &read_file_committed : kernel_read_file; + int wrapped = patch_main_import("ReadFile", reinterpret_cast(&read_file_stable)); + wrapped += patch_main_import("WriteFile", reinterpret_cast(&write_file_stable)); + HMODULE self = nullptr; + if (wrapped && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&read_file_stable), &self)) { + const DWORD error = GetLastError(); + const int restored = patch_main_import("ReadFile", reinterpret_cast(next_read_file)) + + patch_main_import("WriteFile", reinterpret_cast(kernel_write_file)); + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): xmem.dll could not be pinned (error %lu); " + "%d of %d ReadFile/WriteFile import(s) restored", static_cast(error), restored, wrapped); + wrapped = 0; + } + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d ReadFile/WriteFile import(s) run again after a run " + "break that refused their buffer", wrapped); + return wrapped; +}(); } // namespace // Experimental export: writes bytes into physical pages named by the title's diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index b722875fbd..ce2ba3c15d 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -7,8 +7,9 @@ // and then checks the reader's answer: the neighbour page is committed, mapped and holds its data. // // Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, this program's VirtualQueryEx import (wrapped by -// xmem.dll when it loads with the switch), x2w_local::writable, x2w_startup::measure_placed_buffer and -// x2w_startup::snapshot_samplers. +// xmem.dll when it loads with the switch), this program's ReadFile and WriteFile imports (synchronous, into and out +// of the page; wrapped the same way), x2w_local::writable, x2w_startup::measure_placed_buffer and +// x2w_startup::snapshot_samplers. Then io_outside_runs: a ReadFile into a reserved page in no run fails at once. // // With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run // directly) the three header readers answer inside the window: the check expects that, and fails if they wait. @@ -31,7 +32,8 @@ // `default` (X2W_XMEM_SHARED_VIEWS unset): every page has a view of its own, and readers that overlap an unmap // answer inside it, without waiting for memory.mutex, as before x2w_xmem_stable_call. // `lazy` (X2W_XMEM_SHARED_VIEWS=1, X2W_XMEM_LAZY_COMMIT=1): XMemVirtualQuery and VirtualQueryEx wait for a break -// with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. +// with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. Then a +// ReadFile into another such slot, with no break: the lazy-commit ReadFile wrapper still runs inside the run-break one. // // `two-runs` and `mirror` run those two cases alone (an access violation there ends the process). // @@ -191,6 +193,101 @@ void break_during_fn(const Shim& shim, unsigned char* base) CloseHandle(c.release); } +// Kernel I/O into or out of a page of the run: this program's ReadFile and WriteFile imports (wrapped by xmem.dll +// when it loads with the switch). Synchronous calls on a file opened without FILE_FLAG_OVERLAPPED. +constexpr DWORD io_bytes = 4096; + +struct TempFile { + char path[MAX_PATH] = {}; + explicit TempFile(const char* stem) + { + char dir[MAX_PATH]; + GetTempPathA(sizeof(dir), dir); + std::snprintf(path, sizeof(path), "%sx2w-run-break-%s-%lu.bin", dir, stem, GetCurrentProcessId()); + } + ~TempFile() { DeleteFileA(path); } + HANDLE open(DWORD access, DWORD disposition) const + { + return CreateFileA(path, access, 0, nullptr, disposition, FILE_ATTRIBUTE_NORMAL, nullptr); + } +}; + +// The file's bytes: the neighbour page's mark, then 0xa5. +void io_pattern(unsigned char* out) +{ + std::memset(out, 0xa5, io_bytes); + const std::uint32_t mark = 0x51000000u + neighbour; + std::memcpy(out, &mark, sizeof(mark)); +} + +bool read_file_into(unsigned char* target) +{ + TempFile file("read"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE, CREATE_ALWAYS); + DWORD done = 0; + const bool written = h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && done == io_bytes; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + if (!written) return false; + h = file.open(GENERIC_READ, OPEN_EXISTING); + if (h == INVALID_HANDLE_VALUE) return false; + done = 0; + const BOOL ok = ReadFile(h, target, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + LARGE_INTEGER position{}; + SetFilePointerEx(h, LARGE_INTEGER{}, &position, FILE_CURRENT); + CloseHandle(h); + std::printf("ReadFile into the run: ok=%d bytes=%lu error=%lu position=%lld\n", ok, done, error, position.QuadPart); + return ok && done == io_bytes && std::memcmp(target, data, io_bytes) == 0; +} + +bool write_file_from(unsigned char* target) +{ + TempFile file("write"); + HANDLE h = file.open(GENERIC_WRITE, CREATE_ALWAYS); + if (h == INVALID_HANDLE_VALUE) return false; + DWORD done = 0; + const BOOL ok = WriteFile(h, target, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + CloseHandle(h); + std::printf("WriteFile from the run: ok=%d bytes=%lu error=%lu\n", ok, done, error); + if (!ok || done != io_bytes) return false; + unsigned char data[io_bytes]; + h = file.open(GENERIC_READ, OPEN_EXISTING); + const bool read = h != INVALID_HANDLE_VALUE && ReadFile(h, data, io_bytes, &done, nullptr) && done == io_bytes; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + return read && std::memcmp(data, target, io_bytes) == 0; +} + +// A read into a reserved page that is in no run fails at once, as without the wrapper: nothing waits for it. +void io_outside_runs() +{ + const char* const name = "io_outside_runs"; + auto* const reserved = static_cast(VirtualAlloc(nullptr, page, MEM_RESERVE, PAGE_NOACCESS)); + if (!check(reserved != nullptr, "reserve", name)) return; + TempFile file("outside"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS); + DWORD done = 0; + if (!check(h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && + SetFilePointer(h, 0, nullptr, FILE_BEGIN) == 0, "temp_file", name)) { + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + VirtualFree(reserved, 0, MEM_RELEASE); + return; + } + const ULONGLONG from = GetTickCount64(); + const BOOL ok = ReadFile(h, reserved, io_bytes, &done, nullptr); + const DWORD error = GetLastError(); + const ULONGLONG took = GetTickCount64() - from; + CloseHandle(h); + VirtualFree(reserved, 0, MEM_RELEASE); + std::printf("ReadFile into a reserved page outside the runs: ok=%d error=%lu %llu ms\n", ok, error, took); + check(!ok && error == ERROR_NOACCESS, "read_into_reserved_page_fails_with_ERROR_NOACCESS", name); + check(took < 1000, "read_into_reserved_page_fails_at_once", name); +} + // Default mode: eight single-page views; the unmap of page 5 is held open while readers query page 2. void default_case(const Shim& shim, unsigned char* base) { @@ -305,6 +402,31 @@ void lazy_case(const Shim& shim, unsigned char* base) CloseHandle(release); } +// Lazy commit and shared views: the ReadFile import goes through both wrappers. A read into a mapped slot that is not +// committed yet (no break around it) commits the slot first and succeeds, as with lazy commit alone. +void lazy_read_file(const Shim& shim, unsigned char* at) +{ + const char* const name = "lazy_read_file"; + SIZE_T count = 1, token = 0; + if (!check(shim.allocate(0x20400000, &count, &token) && shim.map(at, 1, &token) == at, "map", name)) return; + if (check(raw_state(at) != MEM_COMMIT, "slot_not_committed_yet", name)) { + TempFile file("lazy"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS); + DWORD done = 0; + const bool ready = h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && + SetFilePointer(h, 0, nullptr, FILE_BEGIN) == 0; + const BOOL ok = ready && ReadFile(h, at, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + std::printf("lazy: ReadFile into an uncommitted mapped slot: ok=%d error=%lu\n", ok, error); + check(ok && done == io_bytes && std::memcmp(at, data, io_bytes) == 0, "read_into_the_slot", name); + } + shim.map(at, 1, nullptr); + shim.release(1, &token); +} + struct Events { char name[64]; HANDLE first, second; @@ -546,7 +668,10 @@ int main(int argc, char** argv) if (next_break_control || default_mode || lazy || two_runs || mirror) { if (next_break_control) next_break_case(shim, at, false); if (default_mode) default_case(shim, at); - if (lazy) lazy_case(shim, at); + if (lazy) { + lazy_case(shim, at); + lazy_read_file(shim, at + 40 * page); + } if (two_runs) two_runs_case(shim, at); if (mirror) mirror_case(shim, base); VirtualFree(base, 0, MEM_RELEASE); @@ -573,6 +698,9 @@ int main(int argc, char** argv) MEMORY_BASIC_INFORMATION info{}; return VirtualQueryEx(GetCurrentProcess(), target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_COMMIT; }); + window_case(shim, at, index++, "ReadFile_import", true, read_file_into); + window_case(shim, at, index++, "WriteFile_import", true, write_file_from); + io_outside_runs(); } // The header readers: waiting with the export, answering inside the window without it (control). const bool waits = !control; From f415ffcd227d6f4998e56e988f995a688f712e68 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:02:34 +1000 Subject: [PATCH 16/34] xmem: write back only what XMemVirtualQuery's query writes, and pass lines at the end XMemVirtualQuery copied all 64 bytes of the caller's buffer before the query and wrote all 64 back after it. era_query writes 49 (the MBI and the tail byte at 0x30), so bytes 49-63 were read and rewritten where they never were before, and a buffer of 49-63 bytes that ends at a page end could fault. The caller's buffer is no longer read; on success tail_offset + 1 bytes go back, on failure none. xmem_run_break_readers_default prints its pass line at the end of main, only with no failed check, so a crash after the cases does not read as a pass. xmem_page_runs_device_check prints a check_failed line before the map-order returns, which were silent and looked like a refused device. --- src/xmem_shim.cpp | 10 +++++----- tests/xmem_page_runs_device_check.cpp | 14 +++++++++++--- tests/xmem_run_break_readers_check.cpp | 3 ++- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index a198c3f256..61f64e716f 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -107,9 +107,10 @@ extern "C" void XMemFree(void* allocation, ULONGLONG attributes) extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context); // The answer for a page of a shared-view run is taken outside a run break (x2w_xmem_stable_call): inside one the -// page would read as reserved. era_query writes a copy of the caller's buffer, which goes back after the call: on -// stable_call's mutex path the lazy-commit handler passes faults on, so an uncommitted mapped slot is not written -// there. +// page would read as reserved. era_query writes a local buffer, and on success its tail_offset + 1 bytes (the MBI and +// the tail byte, all that era_query writes) go to the caller's after the call: on stable_call's mutex path the +// lazy-commit handler passes faults on, so an uncommitted mapped slot is not written there. The caller's buffer is +// not read, and nothing is written to it on failure. extern "C" BOOL XMemVirtualQuery(HANDLE process, LPCVOID address, void* buffer) { struct Query { @@ -119,12 +120,11 @@ extern "C" BOOL XMemVirtualQuery(HANDLE process, LPCVOID address, void* buffer) unsigned char copy[query_buffer_bytes]; std::size_t result; } query{process, address, static_cast(buffer), {}, 0}; - if (query.buffer) std::memcpy(query.copy, query.buffer, query_buffer_bytes); x2w_xmem_stable_call([](void* context) { auto& q = *static_cast(context); q.result = era_query::query(q.process, q.address, q.buffer ? q.copy : nullptr, query_buffer_bytes); }, &query); - if (query.buffer) std::memcpy(query.buffer, query.copy, query_buffer_bytes); + if (query.buffer && query.result) std::memcpy(query.buffer, query.copy, era_query::tail_offset + 1); return query.result != 0; } diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index 991284af35..81481437a4 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -92,8 +92,10 @@ int main(int argc, char** argv) // call joins only a view that ends at its address (merge_with_previous), never one that starts after it. const auto a = pages(8), b = pages(8); if (a.empty() || b.empty() || XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page || - XMemMapPhysicalPages(first, 8, a.data()) != first) + XMemMapPhysicalPages(first, 8, a.data()) != first) { + std::printf("check_failed: allocate or map the two 8-page calls (error %lu)\n", GetLastError()); return 1; + } place("inside one view", wrapper.Get(), first + 4 * page, 1); place("across two mapping calls", wrapper.Get(), first + 8 * page, 2); @@ -112,9 +114,15 @@ int main(int argc, char** argv) // go in reverse order, so that no call continues the slot before it and joins its view (merge_with_previous). unsigned char* const third = second + 8192 * page; const auto single = pages(8); - if (single.empty()) return 1; + if (single.empty()) { + std::printf("check_failed: allocate 8 single pages (error %lu)\n", GetLastError()); + return 1; + } for (int i = 0; i < 8; ++i) - if (XMemMapPhysicalPages(third + i * page, 1, &single[7 - i]) != third + i * page) return 1; + if (XMemMapPhysicalPages(third + i * page, 1, &single[7 - i]) != third + i * page) { + std::printf("check_failed: single-page call %d (error %lu)\n", i, GetLastError()); + return 1; + } place("across two single-page views", wrapper.Get(), third + 4 * page, 2); if (failures) { diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index ce2ba3c15d..8c7b3d330c 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -336,7 +336,6 @@ void default_case(const Shim& shim, unsigned char* base) shim.release(pages, tokens); CloseHandle(unmapped); CloseHandle(release); - std::printf("default mode: readers answer inside an unmap\n"); } // Lazy commit: the output buffers lie in a mapped page whose slot is not committed until it is touched. @@ -675,6 +674,8 @@ int main(int argc, char** argv) if (two_runs) two_runs_case(shim, at); if (mirror) mirror_case(shim, base); VirtualFree(base, 0, MEM_RELEASE); + // The default mode's pass line, at the end and only with no failed check (ctest matches it). + if (default_mode && !failures) std::printf("default mode: readers answer inside an unmap\n"); std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); return failures ? 1 : 0; } From 4a43a1730af1fabe385d34aabd4c802a04d618e3 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:32:37 +1000 Subject: [PATCH 17/34] xmem: say the run cap bounds joined runs only, and test the break ring's edge The cap of 64 pages (max_merged_run_pages) is checked only where a page joins the run before it (merge_with_previous). A run mapped by one call (map_run in map_pages_locked) is not capped, and neither are the survivors map_recorded maps again after an unmap inside such a run. Both are as long as before the cap; a single large call is the title's own choice and was not the regression. The comment above the cap and docs/startup-runtime.md said the cap bounds every later break of a run; they now say it bounds the runs that joining builds, and name the two uncapped paths. xmem_run_break_readers_ring_edge holds a fault in break A before its handler reads the breaks, ends A, then makes 63 or 64 later breaks (map and unmap a lone page). After 63, A is still recorded and the fault is retried; after 64, A's slot (RemapWindow::kept) holds the newest break and the fault is passed on, which the reader's own __except catches. --- CMakeLists.txt | 5 +- docs/startup-runtime.md | 6 +- src/xmem_mapped_pages.cpp | 6 +- tests/xmem_run_break_readers_check.cpp | 87 ++++++++++++++++++++++++-- 4 files changed, 94 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index aff3e2c46c..33f3c12266 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -354,11 +354,14 @@ add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_chec add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) # A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint # run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR). +# ring-edge: a held fault whose break has 63 later breaks is retried; with 64 its break is no longer recorded +# (RemapWindow::kept) and the fault is passed on. add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$" mirror) +add_test(NAME xmem_run_break_readers_ring_edge COMMAND xmem_run_break_readers_check "$" ring-edge) set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs - xmem_run_break_readers_mirror PROPERTIES TIMEOUT 60) + xmem_run_break_readers_mirror xmem_run_break_readers_ring_edge PROPERTIES TIMEOUT 60) set_tests_properties(xmem_run_break_readers_default PROPERTIES PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") # Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 15f07d0593..a81f3e9b69 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3167,8 +3167,10 @@ that view: the view is unmapped, its placeholder is joined with the new pages' p view is mapped over both. It is taken apart the same way as in an unmap (below), and if a step is refused the view is mapped again as it was and the new pages get a view of their own. A joined view stops at 64 pages (`max_merged_run_pages`): a page that would make it longer starts a view of -its own, which the next pages join. Every later unmap inside a view takes the whole view apart, so -the cap bounds that work too. Measured under Wine with every byte of the view written +its own, which the next pages join. Every later unmap inside a joined view takes the whole view +apart, so the cap bounds that work too. Only joined views are capped: a view mapped by one call +covers as many of its pages as follow each other in address and in their section, and an unmap inside it maps the surviving pages again +with one view per contiguous stretch, as long as before the cap. Measured under Wine with every byte of the view written (`xmem_cross_call_merge_check timing`): an unmap inside a view of 64 pages took 0.28 ms, of 512 pages 2.1 ms and of 4096 pages 13 ms; joining a page to a view of 63 took 1.5 ms, about what a page mapped on its own costs (1.4 ms). diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 0989532c41..15364200aa 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -796,8 +796,10 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu // the caller maps the new pages on their own. lost: R could not be mapped again; the pages that have // no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 turns the merge off (tests only). // A joined run stops at max_merged_run_pages: a page that would make R longer starts a run of its own, which the -// next pages join. An unmap inside a run takes the whole run apart and maps its other pages again, so the cap bounds -// the work of every later break of the run as well as of each join. +// next pages join. The cap bounds the runs that joining builds: the work of each join, and of a later break of such a +// run (an unmap inside a run takes the whole run apart and maps its other pages again). A run mapped by one call +// (map_run in map_pages_locked) is not capped, and neither are the survivors map_recorded maps again after an unmap +// inside such a run; both are as long as they were before the cap. enum class Merge { joined, separate, lost }; constexpr SIZE_T max_merged_run_pages = 64; diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index 8c7b3d330c..f4c78ce9cc 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -25,6 +25,9 @@ // disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) // must be retried as well: the handler keeps the ranges of the recent breaks, not only of the last one. // +// The ring's edge (ring_edge): a held fault in break A whose handler reads the breaks after 63 later breaks is retried; +// after 64 later breaks, A is no longer recorded and the fault is passed on (the reader's own __except catches it). +// // A break that begins while x2w_xmem_stable_call's fn runs (break_during_fn): fn itself starts the unmap, waits until // the window is open and queries a page of the run (reserved). stable_call must see the generation change and run fn // again under memory.mutex: 2 calls, the last one committed. @@ -35,10 +38,11 @@ // with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. Then a // ReadFile into another such slot, with no break: the lazy-commit ReadFile wrapper still runs inside the run-break one. // -// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process). +// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process); `ring-edge` runs +// ring_edge with 63 and then 64 later breaks. // // Usage: xmem_run_break_readers_check -// [control|next-break-control|default|lazy|two-runs|mirror] +// [control|next-break-control|default|lazy|two-runs|mirror|ring-edge] #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include @@ -624,6 +628,73 @@ void mirror_case(const Shim& shim, unsigned char* cpu) CloseHandle(unmapped); CloseHandle(release); } + +// Reads *address into value; false when the access violation reaches this frame (the handler passed it on). No C++ +// objects in the __try frame, and not inlined: inlined into the reader's lambda (clang-cl, under Wine), the code after +// the __except wrote through a null pointer. +__declspec(noinline) bool guarded_read(const volatile std::uint32_t* address, std::uint32_t* value) +{ + __try { + *value = *address; + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +// The edge of the ring of recorded breaks (RemapWindow::kept, 64). Break A takes apart run 1; a fault in it is held +// before its handler reads the breaks (X2W_XMEM_TEST_HOLD_RETRY). A ends, then `later` breaks follow, each the unmap +// of a lone page mapped by a call of its own (one break per unmap call; the lone page joins no run). The k-th break +// after A is recorded in A's slot when k is a multiple of 64. With 63 later breaks A is still recorded and the fault +// is retried (the reader reads its page); with 64, A's slot holds the newest break, no recorded break holds the +// address, and the handler passes the fault on, which the reader's own __except catches. +void ring_edge_case(const Shim& shim, unsigned char* run1, SIZE_T later, bool retried) +{ + char name[32], stem[32]; + std::snprintf(name, sizeof(name), "ring_edge_%zu", later); + std::snprintf(stem, sizeof(stem), "ring-%zu", later); + unsigned char* const lone = run1 + 32 * page; + SIZE_T count = pages + 1, tokens[pages + 1] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages + 1 || shim.map(run1, pages, tokens) != run1) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(run1 + i * page) = 0x56000000u + static_cast(i); + unsigned char* const target = run1 + 2 * page; + Events window(stem, "unmapped", "release"), retry(stem, "faulted", "go"); + std::atomic outcome{0}; // 0: the reader has not finished; 1: it read its page; 2: the fault was passed on + std::uint32_t value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window.name); + std::thread unmap_a([&] { shim.map(run1 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window.first, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, "break_a_held", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { outcome = guarded_read(reinterpret_cast(target), &value) ? 1 : 2; }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(window.second); + unmap_a.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + // The handler waits at most five seconds for "go" (hold_retry): the later breaks must all end inside that wait. + const ULONGLONG started = GetTickCount64(); + SIZE_T made = 0; + for (SIZE_T k = 0; k < later; ++k) { + if (shim.map(lone, 1, &tokens[pages]) != lone || raw_state(lone) != MEM_COMMIT) break; + if (shim.map(lone, 1, nullptr) != lone || raw_state(lone) == MEM_COMMIT) break; + ++made; + } + check(made == later, "later_breaks_made", name); + check(outcome.load() == 0 && GetTickCount64() - started < 4000, "handler_still_held_after_the_later_breaks", name); + SetEvent(retry.second); // the handler reads the breaks now + reader.join(); + if (retried) + check(outcome.load() == 1 && value == 0x56000002u, "fault_retried_with_break_a_still_recorded", name); + else + check(outcome.load() == 2, "fault_passed_on_with_break_a_evicted", name); + shim.map(run1, 7, nullptr); + shim.release(pages + 1, tokens); +} } // namespace int main(int argc, char** argv) @@ -635,9 +706,11 @@ int main(int argc, char** argv) const bool lazy = argc > 2 && std::strcmp(argv[2], "lazy") == 0; const bool two_runs = argc > 2 && std::strcmp(argv[2], "two-runs") == 0; const bool mirror = argc > 2 && std::strcmp(argv[2], "mirror") == 0; - if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror)) { + const bool ring_edge = argc > 2 && std::strcmp(argv[2], "ring-edge") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror && + !ring_edge)) { std::printf("usage: xmem_run_break_readers_check " - "[control|next-break-control|default|lazy|two-runs|mirror]\n"); + "[control|next-break-control|default|lazy|two-runs|mirror|ring-edge]\n"); return 2; } // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. @@ -664,7 +737,7 @@ int main(int argc, char** argv) return 1; } unsigned char* const at = base + page; - if (next_break_control || default_mode || lazy || two_runs || mirror) { + if (next_break_control || default_mode || lazy || two_runs || mirror || ring_edge) { if (next_break_control) next_break_case(shim, at, false); if (default_mode) default_case(shim, at); if (lazy) { @@ -673,6 +746,10 @@ int main(int argc, char** argv) } if (two_runs) two_runs_case(shim, at); if (mirror) mirror_case(shim, base); + if (ring_edge) { + ring_edge_case(shim, at, 63, true); + ring_edge_case(shim, at + 64 * page, 64, false); + } VirtualFree(base, 0, MEM_RELEASE); // The default mode's pass line, at the end and only with no failed check (ctest matches it). if (default_mode && !failures) std::printf("default mode: readers answer inside an unmap\n"); From ad1980cb3ca05bba32821c65b0a3e02215f62601 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:11:44 +1000 Subject: [PATCH 18/34] tests: map single-page XMem views from high to low Same change as f6020249 in #2918. --- tests/xmem_page_runs_device_check.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index 81481437a4..c1f1ec807a 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -110,15 +110,15 @@ int main(int argc, char** argv) } place("across two backing sections", wrapper.Get(), second + info.RegionSize, 2); - // Pages mapped one call at a time get a view each: the layout every page had before views were shared. The slots - // go in reverse order, so that no call continues the slot before it and joins its view (merge_with_previous). + // Map the single pages from high to low addresses. Each call then has no adjacent view below it to join, + // regardless of the order in which the allocator assigned the backing slots. unsigned char* const third = second + 8192 * page; const auto single = pages(8); if (single.empty()) { std::printf("check_failed: allocate 8 single pages (error %lu)\n", GetLastError()); return 1; } - for (int i = 0; i < 8; ++i) + for (int i = 7; i >= 0; --i) if (XMemMapPhysicalPages(third + i * page, 1, &single[7 - i]) != third + i * page) { std::printf("check_failed: single-page call %d (error %lu)\n", i, GetLastError()); return 1; From 238ed78ac9405ccc7ebeb91d88931b10e7deded1 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:21:15 +1000 Subject: [PATCH 19/34] tests: preserve the XMem linear buffer view boundary Same change as 27778f4f in #2918. --- tests/linear_buffer_backing_check.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index a735c1ef8d..98ceaf1681 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -345,7 +345,7 @@ struct Pool { write(previous.cpu, 0, D, alloc_pages * page / 4); return release(previous); } - bool map(Memory& out, unsigned pages) + bool map(Memory& out, unsigned pages, bool split_last_page = false) { out.cpu = base + cursor; if (cursor + pages * page > bytes) return false; @@ -353,8 +353,13 @@ struct Pool { if (!xmem) return true; out.tokens.assign(pages, 0); ULONG_PTR got = pages; - return XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) && got == pages && - XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + if (!XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) || got != pages) return false; + if (!split_last_page) return XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + + // Map the upper page first so neither call can join across the boundary inside the buffer. + auto* const last_page = out.cpu + (pages - 1) * page; + return XMemMapPhysicalPages(last_page, 1, &out.tokens.back()) == last_page && + XMemMapPhysicalPages(out.cpu, pages - 1, out.tokens.data()) == out.cpu; } // One allocation in the case layout: neighbour pages, then the buffer filled with `fill`. bool allocate(Memory& out, Tag fill, bool* zero = nullptr) @@ -370,11 +375,7 @@ struct Pool { // Two pages of the buffer in two mapping calls (two views): the buffer crosses a view boundary. bool allocate_split(Memory& out, Tag fill) { - Memory first, second; - if (!xmem || !map(first, alloc_pages - 1) || !map(second, 1)) return false; - out.cpu = first.cpu; - out.tokens = first.tokens; - out.tokens.insert(out.tokens.end(), second.tokens.begin(), second.tokens.end()); + if (!xmem || !map(out, alloc_pages, true)) return false; write(out.cpu, 0, neighbour, buffer_offset / 4); write(out.buffer(), 0, fill, buffer_bytes / 4); return true; From 14a9589ff00fd8ffb0614399e205543d3a787a30 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:51:32 +1000 Subject: [PATCH 20/34] tests: move the XMem page-run registrations to tests/cmake/xmem_page_runs.cmake The three blocks this branch added to CMakeLists.txt move verbatim into a fragment (tests/cmake/README.md), so CMakeLists.txt is main's again. The fragment is included after every target and helper it names. The configured tests (names, commands, properties) and the compile and link commands of the moved targets are the same before and after. The break-window fixture's comment names the fragment for its negative control. --- CMakeLists.txt | 118 ----------------- tests/cmake/xmem_page_runs.cmake | 122 ++++++++++++++++++ tests/startup_dstorage_break_window_check.cpp | 3 +- 3 files changed, 124 insertions(+), 119 deletions(-) create mode 100644 tests/cmake/xmem_page_runs.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 33f3c12266..8d9886fdfc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -324,65 +324,6 @@ set_tests_properties(xmem_lazy_imports PROPERTIES TIMEOUT 60) add_test(NAME xmem_lazy_handler_failure COMMAND xmem_lazy_imports_check "$" handler-failure) set_tests_properties(xmem_lazy_handler_failure PROPERTIES TIMEOUT 60) -# Readers that do not fault, inside a run break held open by the test-controls build: x2w_xmem_stable_call, -# XMemVirtualQuery, the VirtualQueryEx import wrapper and the stand-in readers that go through -# x2w_local::outside_run_breaks must answer after the break. Control: a copy of local_log.h that asks xmem.dll for -# a missing export, so the stand-in readers run directly and answer inside the window. -foreach(variant check control) - add_executable(xmem_run_break_readers_${variant} tests/xmem_run_break_readers_check.cpp) - target_compile_features(xmem_run_break_readers_${variant} PRIVATE cxx_std_17) - add_dependencies(xmem_run_break_readers_${variant} xmem_shim_test_controls) -endforeach() -target_include_directories(xmem_run_break_readers_check PRIVATE src) -file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/local_log.h" local_log_text) -string(REPLACE "\"x2w_xmem_stable_call\"" "\"x2w_xmem_stable_call_control\"" local_log_control_text "${local_log_text}") -if(local_log_control_text STREQUAL local_log_text) - message(FATAL_ERROR "local_log.h lost the anchor used by xmem_run_break_readers_control") -endif() -file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control/startup_stubs/local_log.h" "${local_log_control_text}") -set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/local_log.h) -target_include_directories(xmem_run_break_readers_control BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control") -target_include_directories(xmem_run_break_readers_control PRIVATE src) -add_test(NAME xmem_run_break_readers COMMAND xmem_run_break_readers_check "$") -add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_control - "$" control) -add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_readers_check - "$" next-break-control) -# Default mode (no X2W_XMEM_SHARED_VIEWS): readers that overlap an unmap answer inside it, as before. Lazy commit: -# the readers' output buffer in a mapped slot not yet committed. -add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) -add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) -# A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint -# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR). -# ring-edge: a held fault whose break has 63 later breaks is retried; with 64 its break is no longer recorded -# (RemapWindow::kept) and the fault is passed on. -add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) -add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$" mirror) -add_test(NAME xmem_run_break_readers_ring_edge COMMAND xmem_run_break_readers_check "$" ring-edge) -set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control - xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs - xmem_run_break_readers_mirror xmem_run_break_readers_ring_edge PROPERTIES TIMEOUT 60) -set_tests_properties(xmem_run_break_readers_default PROPERTIES - PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") -# Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and -# the steps around it (an unmap inside, slots out of order, a reader inside the held window, refused steps, two -# reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test build only); the deployed shim -# ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its own. -add_executable(xmem_cross_call_merge_check tests/xmem_cross_call_merge_check.cpp) -target_compile_features(xmem_cross_call_merge_check PRIVATE cxx_std_17) -add_dependencies(xmem_cross_call_merge_check xmem_shim xmem_shim_test_controls) -add_test(NAME xmem_cross_call_merge COMMAND xmem_cross_call_merge_check "$" check) -add_test(NAME xmem_cross_call_merge_control COMMAND xmem_cross_call_merge_check "$" control) -add_test(NAME xmem_cross_call_merge_deployed COMMAND xmem_cross_call_merge_check "$" deployed) -add_test(NAME xmem_cross_call_merge_default COMMAND xmem_cross_call_merge_check "$" default) -set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed - xmem_cross_call_merge_default PROPERTIES TIMEOUT 60) -set_tests_properties(xmem_cross_call_merge_control PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" - PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") -set_tests_properties(xmem_cross_call_merge_deployed PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" - PASS_REGULAR_EXPRESSION "merge: 1 view of 32 pages" FAIL_REGULAR_EXPRESSION "check_failed") -set_tests_properties(xmem_cross_call_merge_default PROPERTIES - PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") add_executable(xmem_section_lease_check tests/xmem_section_lease_check.cpp tests/desktop_gpu.cpp) target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) @@ -398,32 +339,6 @@ foreach(adapter warp hardware) add_test(NAME xmem_section_lease_vertex_${adapter} COMMAND xmem_section_lease_check ${adapter} "$" vertex) set_tests_properties(xmem_section_lease_vertex_${adapter} xmem_section_lease_mesh_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endforeach() -# Slot 31 placeholder split inside an XMem reservation. The control disables the fallback used where the OS does -# not report placeholders (Wine), so the split fails there; where the OS reports them, the control skips (77). -add_executable(xmem_placeholder_split_check tests/xmem_placeholder_split_check.cpp) -target_include_directories(xmem_placeholder_split_check PRIVATE src) -target_compile_features(xmem_placeholder_split_check PRIVATE cxx_std_17) -target_link_libraries(xmem_placeholder_split_check PRIVATE OneCore) -add_dependencies(xmem_placeholder_split_check xmem_shim) -set(xmem_placeholder_env "X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") -add_test(NAME xmem_placeholder_split COMMAND xmem_placeholder_split_check "$") -set_tests_properties(xmem_placeholder_split PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") -# The control passes only when the split itself fails, not on an earlier setup failure. -add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check "$" control) -set_tests_properties(xmem_placeholder_split_control PROPERTIES - ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1" - PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) -add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) -target_include_directories(xmem_map_split_first_check PRIVATE src) -target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) -add_dependencies(xmem_map_split_first_check xmem_shim) -add_test(NAME xmem_map_split_first COMMAND xmem_map_split_first_check "$") -add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check "$" control) -set_tests_properties(xmem_map_split_first PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") -# The control passes only when the map-first order is measured (2 maps per page), not on a setup failure. -set_tests_properties(xmem_map_split_first_control PROPERTIES - ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_MAP_FIRST=1" - PASS_REGULAR_EXPRESSION "map-first control: maps=2N" 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) @@ -1028,39 +943,6 @@ target_compile_features(startup_dstorage_destination_check PRIVATE cxx_std_17) add_dependencies(startup_dstorage_destination_check startup_stub_xcrdapi) add_test(NAME startup_dstorage_destination COMMAND startup_dstorage_destination_check "$") set_tests_properties(startup_dstorage_destination PROPERTIES TIMEOUT 60) -# A request whose destination page an XMem run break holds unmapped (the xmem test-controls build's -# X2W_XMEM_TEST_HOLD_WINDOW) must not complete within the 1000 ms hold, then land after the release. -# Control: XCRDAPI without the x2w_xmem_copy_to_destination lookup judges the destination with its own VirtualQuery -# inside the window and refuses it. -add_executable(startup_dstorage_break_window_check tests/startup_dstorage_break_window_check.cpp) -target_compile_features(startup_dstorage_break_window_check PRIVATE cxx_std_17) -add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi xmem_shim_test_controls) -add_test(NAME startup_dstorage_break_window COMMAND startup_dstorage_break_window_check - "$" "$") -set_tests_properties(startup_dstorage_break_window PROPERTIES TIMEOUT 60) -set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) -file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) -string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text - "${xcrdapi_text}") -if(xcrdapi_control_text STREQUAL xcrdapi_text) - message(FATAL_ERROR "xcrdapi.cpp lost the anchor used by startup_dstorage_break_window_control") -endif() -set(xcrdapi_control "${CMAKE_CURRENT_BINARY_DIR}/xcrdapi_break_window_control/xcrdapi.cpp") -file(WRITE "${xcrdapi_control}" "${xcrdapi_control_text}") -add_library(startup_stub_xcrdapi_break_window_control SHARED "${xcrdapi_control}" src/startup_stubs/xcrdapi.def) -set_target_properties(startup_stub_xcrdapi_break_window_control PROPERTIES OUTPUT_NAME XCRDAPI - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -target_include_directories(startup_stub_xcrdapi_break_window_control PRIVATE src) -target_compile_features(startup_stub_xcrdapi_break_window_control PRIVATE cxx_std_17) -target_link_libraries(startup_stub_xcrdapi_break_window_control PRIVATE psapi) -add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi_break_window_control) -add_test(NAME startup_dstorage_break_window_control COMMAND startup_dstorage_break_window_check - "$" "$") -set_tests_properties(startup_dstorage_break_window_control PROPERTIES TIMEOUT 60 - PASS_REGULAR_EXPRESSION "FAIL break window: refused while the run was broken") add_executable(startup_storage_worker_start tests/startup_storage_worker_start.cpp) target_compile_features(startup_storage_worker_start PRIVATE cxx_std_17) target_include_directories(startup_storage_worker_start PRIVATE src) diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake new file mode 100644 index 0000000000..2604e517bb --- /dev/null +++ b/tests/cmake/xmem_page_runs.cmake @@ -0,0 +1,122 @@ +# XMem page-run fixtures (#2911): readers inside a run break, the cross-call merge of shared views, the slot 31 +# placeholder split, split-before-map inside a placeholder, and a DirectStorage destination inside a run break. +# Readers that do not fault, inside a run break held open by the test-controls build: x2w_xmem_stable_call, +# XMemVirtualQuery, the VirtualQueryEx import wrapper and the stand-in readers that go through +# x2w_local::outside_run_breaks must answer after the break. Control: a copy of local_log.h that asks xmem.dll for +# a missing export, so the stand-in readers run directly and answer inside the window. +foreach(variant check control) + add_executable(xmem_run_break_readers_${variant} tests/xmem_run_break_readers_check.cpp) + target_compile_features(xmem_run_break_readers_${variant} PRIVATE cxx_std_17) + add_dependencies(xmem_run_break_readers_${variant} xmem_shim_test_controls) +endforeach() +target_include_directories(xmem_run_break_readers_check PRIVATE src) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/local_log.h" local_log_text) +string(REPLACE "\"x2w_xmem_stable_call\"" "\"x2w_xmem_stable_call_control\"" local_log_control_text "${local_log_text}") +if(local_log_control_text STREQUAL local_log_text) + message(FATAL_ERROR "local_log.h lost the anchor used by xmem_run_break_readers_control") +endif() +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control/startup_stubs/local_log.h" "${local_log_control_text}") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/local_log.h) +target_include_directories(xmem_run_break_readers_control BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control") +target_include_directories(xmem_run_break_readers_control PRIVATE src) +add_test(NAME xmem_run_break_readers COMMAND xmem_run_break_readers_check "$") +add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_control + "$" control) +add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_readers_check + "$" next-break-control) +# Default mode (no X2W_XMEM_SHARED_VIEWS): readers that overlap an unmap answer inside it, as before. Lazy commit: +# the readers' output buffer in a mapped slot not yet committed. +add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) +add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) +# A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint +# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR). +# ring-edge: a held fault whose break has 63 later breaks is retried; with 64 its break is no longer recorded +# (RemapWindow::kept) and the fault is passed on. +add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) +add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$" mirror) +add_test(NAME xmem_run_break_readers_ring_edge COMMAND xmem_run_break_readers_check "$" ring-edge) +set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control + xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs + xmem_run_break_readers_mirror xmem_run_break_readers_ring_edge PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_run_break_readers_default PROPERTIES + PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") +# Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and +# the steps around it (an unmap inside, slots out of order, a reader inside the held window, refused steps, two +# reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test build only); the deployed shim +# ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its own. +add_executable(xmem_cross_call_merge_check tests/xmem_cross_call_merge_check.cpp) +target_compile_features(xmem_cross_call_merge_check PRIVATE cxx_std_17) +add_dependencies(xmem_cross_call_merge_check xmem_shim xmem_shim_test_controls) +add_test(NAME xmem_cross_call_merge COMMAND xmem_cross_call_merge_check "$" check) +add_test(NAME xmem_cross_call_merge_control COMMAND xmem_cross_call_merge_check "$" control) +add_test(NAME xmem_cross_call_merge_deployed COMMAND xmem_cross_call_merge_check "$" deployed) +add_test(NAME xmem_cross_call_merge_default COMMAND xmem_cross_call_merge_check "$" default) +set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed + xmem_cross_call_merge_default PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_cross_call_merge_control PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_deployed PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "merge: 1 view of 32 pages" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_default PROPERTIES + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") + +# Slot 31 placeholder split inside an XMem reservation. The control disables the fallback used where the OS does +# not report placeholders (Wine), so the split fails there; where the OS reports them, the control skips (77). +add_executable(xmem_placeholder_split_check tests/xmem_placeholder_split_check.cpp) +target_include_directories(xmem_placeholder_split_check PRIVATE src) +target_compile_features(xmem_placeholder_split_check PRIVATE cxx_std_17) +target_link_libraries(xmem_placeholder_split_check PRIVATE OneCore) +add_dependencies(xmem_placeholder_split_check xmem_shim) +set(xmem_placeholder_env "X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") +add_test(NAME xmem_placeholder_split COMMAND xmem_placeholder_split_check "$") +set_tests_properties(xmem_placeholder_split PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the split itself fails, not on an earlier setup failure. +add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check "$" control) +set_tests_properties(xmem_placeholder_split_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1" + PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) +add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) +target_include_directories(xmem_map_split_first_check PRIVATE src) +target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) +add_dependencies(xmem_map_split_first_check xmem_shim) +add_test(NAME xmem_map_split_first COMMAND xmem_map_split_first_check "$") +add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check "$" control) +set_tests_properties(xmem_map_split_first PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the map-first order is measured (2 maps per page), not on a setup failure. +set_tests_properties(xmem_map_split_first_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_MAP_FIRST=1" + PASS_REGULAR_EXPRESSION "map-first control: maps=2N" TIMEOUT 60) + +# A request whose destination page an XMem run break holds unmapped (the xmem test-controls build's +# X2W_XMEM_TEST_HOLD_WINDOW) must not complete within the 1000 ms hold, then land after the release. +# Control: XCRDAPI without the x2w_xmem_copy_to_destination lookup judges the destination with its own VirtualQuery +# inside the window and refuses it. +add_executable(startup_dstorage_break_window_check tests/startup_dstorage_break_window_check.cpp) +target_compile_features(startup_dstorage_break_window_check PRIVATE cxx_std_17) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi xmem_shim_test_controls) +add_test(NAME startup_dstorage_break_window COMMAND startup_dstorage_break_window_check + "$" "$") +set_tests_properties(startup_dstorage_break_window PROPERTIES TIMEOUT 60) +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) +string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text + "${xcrdapi_text}") +if(xcrdapi_control_text STREQUAL xcrdapi_text) + message(FATAL_ERROR "xcrdapi.cpp lost the anchor used by startup_dstorage_break_window_control") +endif() +set(xcrdapi_control "${CMAKE_CURRENT_BINARY_DIR}/xcrdapi_break_window_control/xcrdapi.cpp") +file(WRITE "${xcrdapi_control}" "${xcrdapi_control_text}") +add_library(startup_stub_xcrdapi_break_window_control SHARED "${xcrdapi_control}" src/startup_stubs/xcrdapi.def) +set_target_properties(startup_stub_xcrdapi_break_window_control PROPERTIES OUTPUT_NAME XCRDAPI + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +target_include_directories(startup_stub_xcrdapi_break_window_control PRIVATE src) +target_compile_features(startup_stub_xcrdapi_break_window_control PRIVATE cxx_std_17) +target_link_libraries(startup_stub_xcrdapi_break_window_control PRIVATE psapi) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi_break_window_control) +add_test(NAME startup_dstorage_break_window_control COMMAND startup_dstorage_break_window_check + "$" "$") +set_tests_properties(startup_dstorage_break_window_control PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "FAIL break window: refused while the run was broken") diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp index d04d329bac..c1cd980e2c 100644 --- a/tests/startup_dstorage_break_window_check.cpp +++ b/tests/startup_dstorage_break_window_check.cpp @@ -13,7 +13,8 @@ // - break held: while an unmap holds page 2's run apart (page 2 reads MEM_RESERVE), a request into page 2 must not // complete for the whole hold window (1000 ms, polled every 10 ms); after the release it completes with S_OK and // every byte landed. An XCRDAPI that judges the destination with its own VirtualQuery instead refuses inside the -// window: "FAIL break window: refused while the run was broken" (the negative control in CMakeLists.txt). +// window: "FAIL break window: refused while the run was broken" (the negative control in +// tests/cmake/xmem_page_runs.cmake). #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif From e9e0b4419ed2eb6d1a9c5783551dffbcb469f7aa Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:52:52 +1000 Subject: [PATCH 21/34] xmem: put the slab accounting comment back above x2w_xmem_slab_stats The #1199 comment had ended up above x2w_xmem_map_counts. The cross-call merge fixture's comments now say what the timing mode prints instead of pointing at notes outside the repository. Comments only. --- src/xmem_mapped_pages.cpp | 6 +++--- tests/xmem_cross_call_merge_check.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 15364200aa..9a3b0e872a 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1761,9 +1761,6 @@ extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context) return TRUE; } -// Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free -// in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs -// are closed when all of their slots are freed and unpinned. // Test export: MapViewOfFile3 and placeholder-split attempts made by the physical-page map path so far. extern "C" BOOL WINAPI x2w_xmem_map_counts(ULONGLONG* maps, ULONGLONG* splits) { @@ -1773,6 +1770,9 @@ extern "C" BOOL WINAPI x2w_xmem_map_counts(ULONGLONG* maps, ULONGLONG* splits) return TRUE; } +// Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free +// in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs +// are closed when all of their slots are freed and unpinned. extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in_use, ULONGLONG* slots_free) { if (!slabs || !slots_in_use || !slots_free) return FALSE; diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp index 3d0aa09cf2..bb8a59d975 100644 --- a/tests/xmem_cross_call_merge_check.cpp +++ b/tests/xmem_cross_call_merge_check.cpp @@ -10,7 +10,7 @@ // deployed (deployed xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) the deployed shim ignores the test switch and merges. // default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own. // timing (test-controls xmem.dll; not a ctest case) ms of a join, of a break and of an own-view map against the -// run length R (X2W_XMEM_TEST_MERGE_CAP), for the cap's table in the review notes. +// run length R (X2W_XMEM_TEST_MERGE_CAP): a table of "timing:" lines, one row per R from 16 to 4096. // The pass line of control, deployed and default is printed at the end of main, only when no check failed. // // Cases of `check`: @@ -326,7 +326,7 @@ void capped(const Shim& shim, unsigned char* base) shim.release(n, tokens.data()), "capped: unmap and release"); } -// timing (not a ctest case; ready.md's table): for a run of R pages, the ms of the call that joins page R to a run of +// timing (not a ctest case; one row per R): for a run of R pages, the ms of the call that joins page R to a run of // R - 1 (X2W_XMEM_TEST_MERGE_CAP=R), of the unmap of page R/2 (one break of the whole run) and, for comparison, of a // single-page call that maps a view of its own (X2W_XMEM_TEST_NO_MERGE=1). Every byte of the run is written before // the join and before the break, as a title's use of the pages would (a run that is mostly untouched unmaps much From d4f1344e986124d99c06bfac74db474de929cf58 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:06:38 +1000 Subject: [PATCH 22/34] xmem: put joins across mapping calls behind X2W_XMEM_JOIN_CALLS A mapping call joins the shared view that ends at its address only with X2W_XMEM_JOIN_CALLS=1, read once with X2W_XMEM_SHARED_VIEWS by the first mapping call; without shared views it does nothing. It is off by default, so the layout with shared views alone is main's again (one view per call). run.sh sets it beside X2W_XMEM_SHARED_VIEWS, where the joins were measured; run.ps1 -LazyMemory does not. With the switch off and no test changes, these fail under Wine and now set it: xmem_cross_call_merge, xmem_cross_call_merge_deployed and xmem_run_break_readers_mirror; xmem_shim_page_runs is main's check again (three views). Every mode of the branch's fixtures sets or clears the switch itself. New: xmem_cross_call_merge_no_join (deployed shim, shared views, no join switch: one view per call) and xmem_page_runs_device_join_warp (the view boundaries hold with joins on). startup_run_sh_check checks the export. --- docs/startup-runtime.md | 6 ++- docs/wine.md | 1 + src/xmem_mapped_pages.cpp | 38 ++++++++++++------- tests/cmake/xmem_page_runs.cmake | 26 ++++++++++--- tests/linear_buffer_backing_check.cpp | 4 +- tests/startup_dstorage_break_window_check.cpp | 1 + tests/startup_run_sh_check.py | 7 ++-- tests/xmem_cross_call_merge_check.cpp | 26 ++++++++----- tests/xmem_page_runs_check.py | 6 +-- tests/xmem_page_runs_device_check.cpp | 20 ++++++---- tests/xmem_run_break_readers_check.cpp | 13 ++++--- tools/startup/run.sh | 3 ++ 12 files changed, 100 insertions(+), 51 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a81f3e9b69..1c1ef5247f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1466,6 +1466,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `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` (`run.ps1 -LazyMemory`, which also sets `X2W_XMEM_LAZY_COMMIT=1` and `X2W_XMEM_SHARED_VIEWS=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 of 32 MiB and up placed below 2^40 by `X2W_XMEM_STARTUP_BELOW_40` are also reserved lazily. See [Startup blocks committed on first touch](experiments.md#startup-blocks-committed-on-first-touch) | +| `X2W_XMEM_JOIN_CALLS=1` (with `X2W_XMEM_SHARED_VIEWS=1`; `tools/startup/run.sh` sets both, `run.ps1 -LazyMemory` only `X2W_XMEM_SHARED_VIEWS`) | experimental: a mapping call whose pages continue the shared view that ends at its address joins that view instead of mapping a view of its own ([Physical pages in shared sections](#physical-pages-in-shared-sections)). Read once, with `X2W_XMEM_SHARED_VIEWS`, by the first mapping call; without shared views it does nothing | | `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; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) | | `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 | @@ -3161,7 +3162,8 @@ slow for a start-up batch of about 100,000 pages (measured under Wine: 42.9 s fo 82 ms with shared sections and views). Start-up maps nearly every page with a call of its own, and under Wine each map costs more the -more views the process has. So a mapping call whose pages all continue the view that ends at its +more views the process has. With `X2W_XMEM_JOIN_CALLS=1` as well (off by default; `tools/startup/run.sh` +sets it, `run.ps1 -LazyMemory` does not), a mapping call whose pages all continue the view that ends at its address, on the next slots of the same section and inside the same reservation of the shim, joins that view: the view is unmapped, its placeholder is joined with the new pages' placeholder, and one view is mapped over both. It is taken apart the same way as in an unmap (below), and if a step is @@ -3208,7 +3210,7 @@ cut short after part of the copy, and I/O from other modules are not covered. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| -| Views | one per page | one per run of adjacent pages | +| Views | one per page | one per run of adjacent pages of one call; with `X2W_XMEM_JOIN_CALLS=1` a call can also join the view that ends at its address | | Fault handler | none | registered by the first mapping call, never removed | | `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends (at load when the main module imports `VirtualQueryEx`, `ReadFile` or `WriteFile`, else at the first mapping call) | diff --git a/docs/wine.md b/docs/wine.md index 3864e71290..d7bf05c84f 100644 --- a/docs/wine.md +++ b/docs/wine.md @@ -57,6 +57,7 @@ set yourself stays, except `XDG_RUNTIME_DIR`, which it always unsets: |---|---| | The `run.ps1` set: `X2W_AUDIO_PERMISSIVE`, `X2W_D3D12_DEVICE_NOOP`, `X2W_D3D12_LIST_NOOP`, `X2W_D3D12_PERMISSIVE`, `X2W_XMEM_PERMISSIVE`, `X2W_RUNTIME_PROXY` (all `=1`) | The same stand-in behaviour as a Windows run. `run.sh` sets the variables behind `--render`, `--fake-user`, `--gpu-mirror` and `--host-cpu` as [Switches](startup-runtime.md#switches) lists them | | `X2W_XMEM_SHARED_VIEWS=1` | With one section and view per page, a start-up batch of about 100,000 pages took 42.9 s under Wine. With shared views it took 82 ms ([Physical pages in shared sections](startup-runtime.md#physical-pages-in-shared-sections)). Without it, the measured runs did not get past start-up | +| `X2W_XMEM_JOIN_CALLS=1` | Start-up maps nearly every page with a call of its own. With it, such a call joins the shared view that ends at its address instead of adding a view, and under Wine each map costs more the more views the process has ([Behaviour seen only under Wine](#behaviour-seen-only-under-wine)). It needs `X2W_XMEM_SHARED_VIEWS=1` | | `XDG_RUNTIME_DIR` unset | Wine then backs sections in `/tmp`, not on a small tmpfs ([Startup debugger under Wine](non-windows-hosts.md#startup-debugger-under-wine)). This also breaks audio; see the next section | | `PULSE_SERVER=unix:/run/user/$(id -u)/pulse/native` | Restores audio while `XDG_RUNTIME_DIR` stays unset. `run.sh` sets it only when that socket exists | | `WINEDLLOVERRIDES=d3d12,d3d12core,dxgi,d3d11=n`, `WINEFSYNC=1` | Wine's built-in D3D12 is not enough; the prefix holds vkd3d-proton and DXVK | diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 9a3b0e872a..a5dc045445 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -517,6 +517,9 @@ RemapWindow remap_window; // generation), but then a page has a view of its own and no break takes a neighbour away, so x2w_xmem_stable_call // does not wait for them. std::atomic shared_views_on{false}; +// Set once, with shared views, when X2W_XMEM_JOIN_CALLS=1 is set as well (FaultRetry::ready): only then does a run +// mapped by a call of its own join the recorded run that ends at its address (merge_with_previous). +std::atomic joins_on{false}; void begin_break(const std::map& broken) { @@ -611,6 +614,9 @@ struct MappingThread { // place until the process ends, also across a host's FreeLibrary and LoadLibrary. Nothing is // waited for or torn down at DLL detach. If the handler cannot be registered or the module cannot // be pinned, the opt-in is refused and pages get a view each. +// +// X2W_XMEM_JOIN_CALLS=1 is read at the same time and only counts with shared views on: a mapping call may then join +// the run that ends at its address (merge_with_previous). Without it every call maps views of its own. struct FaultRetry { SRWLOCK lock = SRWLOCK_INIT; bool tried = false; @@ -625,6 +631,7 @@ struct FaultRetry { // Test build only: shared views without the handler, to show that a reader then faults. if (x2w_local::env_on("X2W_XMEM_NO_FAULT_RETRY")) { guaranteed = true; + joins_on.store(x2w_local::env_on("X2W_XMEM_JOIN_CALLS"), std::memory_order_release); ReleaseSRWLockExclusive(&lock); return true; } @@ -637,6 +644,10 @@ struct FaultRetry { AddVectoredExceptionHandler(1, retry_remapped_page)) { guaranteed = true; x2w_local::logf("x2w-xmem shared views are on (X2W_XMEM_SHARED_VIEWS): xmem.dll stays loaded until the process ends"); + if (x2w_local::env_on("X2W_XMEM_JOIN_CALLS")) { + joins_on.store(true, std::memory_order_release); + x2w_local::logf("x2w-xmem joins across mapping calls are on (X2W_XMEM_JOIN_CALLS)"); + } } else x2w_local::logf("x2w-xmem shared views are off: the fault handler could not be set up (error %lu)", GetLastError()); } @@ -785,16 +796,16 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } -// Shared views only. Startup maps nearly every page with a call of its own, and under Wine each map -// costs more the more views the process has. A run mapped by a call of its own therefore joins the -// recorded run R that ends at its address, when its first page is the next slot of the section behind -// R's last page and R and the new pages lie in one reservation of the shim: the new pages' range is -// split to a placeholder of its own, R is unmapped, the two placeholders are joined and one view is -// mapped over both. R is taken apart as in an unmap (begin_break), so a thread that touches R in -// between is retried and x2w_xmem_stable_call readers wait. On a refused step before R is unmapped -// nothing changed; after it, R is mapped again as it was (map_recorded). Both return separate, and -// the caller maps the new pages on their own. lost: R could not be mapped again; the pages that have -// no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 turns the merge off (tests only). +// Shared views with X2W_XMEM_JOIN_CALLS=1 only (joins_on). Startup maps nearly every page with a call of its own, +// and under Wine each map costs more the more views the process has. With the switch, a run mapped by a call of its +// own therefore joins the recorded run R that ends at its address, when its first page is the next slot of the +// section behind R's last page and R and the new pages lie in one reservation of the shim: the new pages' range is +// split to a placeholder of its own, R is unmapped, the two placeholders are joined and one view is mapped over +// both. R is taken apart as in an unmap (begin_break), so a thread that touches R in between is retried and +// x2w_xmem_stable_call readers wait. On a refused step before R is unmapped nothing changed; after it, R is mapped +// again as it was (map_recorded). Both return separate, and the caller maps the new pages on their own. lost: R +// could not be mapped again; the pages that have no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 +// turns the merge off (tests only). // A joined run stops at max_merged_run_pages: a page that would make R longer starts a run of its own, which the // next pages join. The cap bounds the runs that joining builds: the work of each join, and of a later break of such a // run (an unmap inside a run takes the whole run apart and maps its other pages again). A run mapped by one call @@ -905,9 +916,10 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& const Backing& b = memory.backings.at(last->second); if (last->first != first->first + bytes || b.section != head.section || b.offset != head.offset + bytes) break; } - // Only a run that is the whole batch joins an earlier one: a later run of the batch that - // fails unmaps everything in made, which a joined run is not. - const Merge merge = share_views && first == batch.begin() && last == batch.end() + // Only with X2W_XMEM_JOIN_CALLS, and only a run that is the whole batch joins an earlier one: a + // later run of the batch that fails unmaps everything in made, which a joined run is not. + const bool whole_batch = first == batch.begin() && last == batch.end(); + const Merge merge = share_views && joins_on.load(std::memory_order_acquire) && whole_batch ? merge_with_previous(first->first, head, bytes, failure) : Merge::separate; if (merge == Merge::lost) { diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index 2604e517bb..77ee1d3fab 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -29,7 +29,8 @@ add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_r add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) # A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint -# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR). +# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR; the program +# sets X2W_XMEM_JOIN_CALLS=1 for `mirror` only). # ring-edge: a held fault whose break has 63 later breaks is retried; with 64 its break is no longer recorded # (RemapWindow::kept) and the fault is passed on. add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) @@ -40,10 +41,11 @@ set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_ xmem_run_break_readers_mirror xmem_run_break_readers_ring_edge PROPERTIES TIMEOUT 60) set_tests_properties(xmem_run_break_readers_default PROPERTIES PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") -# Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and -# the steps around it (an unmap inside, slots out of order, a reader inside the held window, refused steps, two -# reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test build only); the deployed shim -# ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its own. +# Cross-call merge of shared views (merge_with_previous, X2W_XMEM_JOIN_CALLS=1 set by the program): single-page calls +# on consecutive slots join one view, and the steps around it (an unmap inside, slots out of order, a reader inside the +# held window, refused steps, two reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test +# build only); the deployed shim ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its +# own. no_join: the deployed shim with shared views and without X2W_XMEM_JOIN_CALLS keeps a view per call. add_executable(xmem_cross_call_merge_check tests/xmem_cross_call_merge_check.cpp) target_compile_features(xmem_cross_call_merge_check PRIVATE cxx_std_17) add_dependencies(xmem_cross_call_merge_check xmem_shim xmem_shim_test_controls) @@ -51,14 +53,26 @@ add_test(NAME xmem_cross_call_merge COMMAND xmem_cross_call_merge_check "$" control) add_test(NAME xmem_cross_call_merge_deployed COMMAND xmem_cross_call_merge_check "$" deployed) add_test(NAME xmem_cross_call_merge_default COMMAND xmem_cross_call_merge_check "$" default) +add_test(NAME xmem_cross_call_merge_no_join COMMAND xmem_cross_call_merge_check "$" no-join) set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed - xmem_cross_call_merge_default PROPERTIES TIMEOUT 60) + xmem_cross_call_merge_default xmem_cross_call_merge_no_join PROPERTIES TIMEOUT 60) set_tests_properties(xmem_cross_call_merge_control PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") set_tests_properties(xmem_cross_call_merge_deployed PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" PASS_REGULAR_EXPRESSION "merge: 1 view of 32 pages" FAIL_REGULAR_EXPRESSION "check_failed") set_tests_properties(xmem_cross_call_merge_default PROPERTIES PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_no_join PROPERTIES + PASS_REGULAR_EXPRESSION "no-join: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +# Placed buffers at view boundaries (tests/xmem_page_runs_device_check.cpp, registered in CMakeLists.txt) with joins +# across mapping calls on: the order of the mapping calls keeps every boundary. +add_test(NAME xmem_page_runs_device_join_warp COMMAND xmem_page_runs_device_check warp join) +set_tests_properties(xmem_page_runs_device_join_warp PROPERTIES TIMEOUT 120) +# tests/xmem_page_runs_check.py expects one view per mapping call: an X2W_XMEM_JOIN_CALLS=1 inherited from the +# caller's environment must not reach it. +if(TEST xmem_shim_page_runs) + set_property(TEST xmem_shim_page_runs APPEND PROPERTY ENVIRONMENT "X2W_XMEM_JOIN_CALLS=") +endif() # Slot 31 placeholder split inside an XMem reservation. The control disables the fallback used where the OS does # not report placeholders (Wine), so the split fails there; where the OS reports them, the control skips (77). diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 98ceaf1681..cadc63aace 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -356,7 +356,8 @@ struct Pool { if (!XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) || got != pages) return false; if (!split_last_page) return XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; - // Map the upper page first so neither call can join across the boundary inside the buffer. + // Map the upper page first so that, with X2W_XMEM_JOIN_CALLS=1, neither call can join across the boundary + // inside the buffer. auto* const last_page = out.cpu + (pages - 1) * page; return XMemMapPhysicalPages(last_page, 1, &out.tokens.back()) == last_page && XMemMapPhysicalPages(out.cpu, pages - 1, out.tokens.data()) == out.cpu; @@ -1767,6 +1768,7 @@ int main(int argc, char** argv) SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", nullptr); // no joins across mapping calls (the default) SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention || path == Path::lease ? L"copy" : L"1"); diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp index c1cd980e2c..15ce2ba285 100644 --- a/tests/startup_dstorage_break_window_check.cpp +++ b/tests/startup_dstorage_break_window_check.cpp @@ -126,6 +126,7 @@ int main(int argc, char** argv) char hold_name[64]; std::snprintf(hold_name, sizeof(hold_name), "x2w-dstorage-break-window-%lu", GetCurrentProcessId()); SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", nullptr); // the run is mapped by one call; no join is needed SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold_name); // xmem first: XCRDAPI finds it by module name (GetModuleHandleW(L"xmem.dll")). diff --git a/tests/startup_run_sh_check.py b/tests/startup_run_sh_check.py index beab30d418..b7a0b8e0f9 100644 --- a/tests/startup_run_sh_check.py +++ b/tests/startup_run_sh_check.py @@ -28,8 +28,8 @@ CHECKED = PERMISSIVE + [ "X2W_FAKE_USER", "X2W_XMEM_GPU_MIRROR", "X2W_HOST_CPU", "X2W_XMEM_STARTUP_BELOW_40", "X2W_HIDE_TITLE_WINDOW", "X2W_D3D12_RENDER", "X2W_DRAW_NULL_IDENTITY", "X2W_SHADER_CACHE", "X2W_TITLE_ID", "X2W_STORAGE_MB", - "X2W_STORAGE_PATH", "X2W_INPUT_SCRIPT", "X2W_XMEM_SHARED_VIEWS", "WINEDLLOVERRIDES", "WINEFSYNC", "WINEDEBUG", - "WINEPREFIX", "XDG_RUNTIME_DIR", "PULSE_SERVER", "X2W_FXC"] + "X2W_STORAGE_PATH", "X2W_INPUT_SCRIPT", "X2W_XMEM_SHARED_VIEWS", "X2W_XMEM_JOIN_CALLS", "WINEDLLOVERRIDES", + "WINEFSYNC", "WINEDEBUG", "WINEPREFIX", "XDG_RUNTIME_DIR", "PULSE_SERVER", "X2W_FXC"] GAME_OVERRIDES = "d3d12,d3d12core,dxgi,d3d11=n" # docs/wine.md FAKE_USER_WARNING = ("WARNING: Without --fake-user, user API calls go to the host gaming runtime " "(docs/startup-runtime.md).") @@ -272,7 +272,7 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d found.append(f"{label}: the debugger received {got}, expected {want}") seen = read_json(startup / "env.json") or {} expected = {name: "1" for name in PERMISSIVE} - expected.update(X2W_XMEM_SHARED_VIEWS="1", X2W_TITLE_ID="X2WTEST", X2W_STORAGE_MB="123", + expected.update(X2W_XMEM_SHARED_VIEWS="1", X2W_XMEM_JOIN_CALLS="1", X2W_TITLE_ID="X2WTEST", X2W_STORAGE_MB="123", WINEDLLOVERRIDES=GAME_OVERRIDES, WINEFSYNC="1", WINEDEBUG="-all", WINEPREFIX=str(prefix)) if translate: expected.update(X2W_D3D12_RENDER="1", X2W_DRAW_NULL_IDENTITY="1", X2W_SHADER_CACHE=win(root / "cache"), @@ -384,6 +384,7 @@ def mutants_of(script): "no FakeUser warning": replace(script, ' echo "WARNING: Without --fake-user', ' : "WARNING: Without --fake-user'), "short DLL list": replace(script, " xg_xs GameInput; do", " xg_xs; do"), "no shared views": drop_line(script, "export X2W_XMEM_SHARED_VIEWS="), + "no join calls": drop_line(script, "export X2W_XMEM_JOIN_CALLS="), "watcher without --render": replace(script, 'if [ -n "$translate" ] && [ -n "$render" ]; then', 'if [ -n "$translate" ]; then'), "config not read": replace(script, 'if [ -f "$config" ]; then', "if false; then"), diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp index bb8a59d975..55cc6869eb 100644 --- a/tests/xmem_cross_call_merge_check.cpp +++ b/tests/xmem_cross_call_merge_check.cpp @@ -1,17 +1,21 @@ -// Cross-call merge of shared views (X2W_XMEM_SHARED_VIEWS=1, src/xmem_mapped_pages.cpp, merge_with_previous). A run -// mapped by a call of its own joins the recorded run that ends at its address when its first page is the next slot of -// the section behind that run's last page and both lie in one reservation of the shim. What a view is, is measured -// with VirtualQuery: inside a view AllocationBase is the view's base and RegionSize the bytes to the view's end. +// Cross-call merge of shared views (X2W_XMEM_SHARED_VIEWS=1 and X2W_XMEM_JOIN_CALLS=1, src/xmem_mapped_pages.cpp, +// merge_with_previous). A run mapped by a call of its own joins the recorded run that ends at its address when its +// first page is the next slot of the section behind that run's last page and both lie in one reservation of the shim. +// What a view is, is measured with VirtualQuery: inside a view AllocationBase is the view's base and RegionSize the +// bytes to the view's end. // -// Modes: +// Modes (each sets X2W_XMEM_SHARED_VIEWS and X2W_XMEM_JOIN_CALLS itself; JOIN_CALLS=1 in every mode but no-join): // check (test-controls xmem.dll) every case below. // control (test-controls xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) single-page calls keep a view each: the layout // before the merge. Prints "no-merge control: 32 views". // deployed (deployed xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) the deployed shim ignores the test switch and merges. -// default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own. +// default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own; the join +// switch alone does nothing. +// no-join (deployed xmem.dll, X2W_XMEM_JOIN_CALLS unset) single-page calls keep a view each: joins are opt-in. +// Prints "no-join: 32 views". // timing (test-controls xmem.dll; not a ctest case) ms of a join, of a break and of an own-view map against the // run length R (X2W_XMEM_TEST_MERGE_CAP): a table of "timing:" lines, one row per R from 16 to 4096. -// The pass line of control, deployed and default is printed at the end of main, only when no check failed. +// The pass line of control, deployed, default and no-join is printed at the end of main, only when no check failed. // // Cases of `check`: // joined 32 single-page calls on consecutive slots: one view of 32 pages; each page keeps the mark written @@ -414,13 +418,14 @@ int main(int argc, char** argv) const char* const mode = argc == 3 ? argv[2] : ""; const bool all = std::strcmp(mode, "check") == 0, control = std::strcmp(mode, "control") == 0, deployed = std::strcmp(mode, "deployed") == 0, plain = std::strcmp(mode, "default") == 0, - timed = std::strcmp(mode, "timing") == 0; - if (!all && !control && !deployed && !plain && !timed) { - std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default|timing\n"); + timed = std::strcmp(mode, "timing") == 0, no_join = std::strcmp(mode, "no-join") == 0; + if (!all && !control && !deployed && !plain && !timed && !no_join) { + std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default|no-join|timing\n"); return 2; } // The mode is read by the first mapping call. SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", plain ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", no_join ? nullptr : "1"); const HMODULE xmem = LoadLibraryA(argv[1]); if (!xmem) { std::printf("check_failed: load (error %lu)\n", GetLastError()); @@ -449,6 +454,7 @@ int main(int argc, char** argv) return failures ? 1 : 0; } single_page_calls(shim, base, all || deployed, all); + if (no_join && token) token = "no-join: 32 views"; if (all) { reversed(shim, base + 64 * page, base + 128 * page); window(shim, base + 192 * page); diff --git a/tests/xmem_page_runs_check.py b/tests/xmem_page_runs_check.py index b9bf799cd8..afb878d74f 100644 --- a/tests/xmem_page_runs_check.py +++ b/tests/xmem_page_runs_check.py @@ -153,11 +153,9 @@ def view(page, first, last): assert view(i, 4, 7), f"upper piece, page {i}: {shim.query(base + i * PAGE)}" hole = shim.query(base + 3 * PAGE) assert hole[1] == base + 3 * PAGE and hole[2] == PAGE and hole[3] == MEM_RESERVE, hole - # Mapping the page again on its own call joins the lower piece, which ends at it on the slot before - # (merge_with_previous): two views. It never joins the upper piece. One view per call without the merge is - # asserted by xmem_cross_call_merge_control (tests/xmem_cross_call_merge_check.cpp). + # Mapping the page again does not join the pieces: three views. assert shim.contiguous(base + 3 * PAGE, 1, C.byref(shim.number(tokens[3]))) == base + 3 * PAGE - assert view(3, 0, 3) and view(2, 0, 3) and view(4, 4, 7), (shim.query(base + 3 * PAGE), shim.query(base + 4 * PAGE)) + assert view(3, 3, 3) and view(2, 0, 2) and view(4, 4, 7) assert shim.contiguous(base, 8, None) == base and shim.release(8, tokens) diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index c1f1ec807a..16071992de 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -2,8 +2,10 @@ // Adjacent pages of one mapping call share a view, so a buffer can lie inside one view or across // two: two mapping calls next to each other, the boundary between two backing sections inside one // call, or pages that each have a view of their own. The device wrapper's placed-resource entry -// (slot 133) must accept all of them alike and leave the memory as it was. -// usage: xmem_page_runs_device_check warp|hardware +// (slot 133) must accept all of them alike and leave the memory as it was. With `join`, X2W_XMEM_JOIN_CALLS=1 as +// well: a mapping call may then join the view that ends at its address, and the mapping order below keeps every +// boundary in place all the same. Without it the switch is cleared. +// usage: xmem_page_runs_device_check warp|hardware [join] #include "xmem_test_device.h" #include @@ -76,11 +78,13 @@ void place(const char* name, ID3D12Device* wrapper, unsigned char* boundary, int int main(int argc, char** argv) { - if (argc != 2) return 1; + if (argc != 2 && !(argc == 3 && std::strcmp(argv[2], "join") == 0)) return 1; const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool join = argc == 3; bool unmatched = false; SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); // the mode under test; read by the first mapping call + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", join ? L"1" : nullptr); auto wrapper = create_device(warp, unmatched, create_wrapper); if (!wrapper) return warp || unmatched ? 1 : 77; @@ -88,8 +92,9 @@ int main(int argc, char** argv) if (!whole) return 1; unsigned char* const first = whole + page; - // Two mapping calls next to each other: two views that meet at first + 8 pages. The upper one is mapped first: a - // call joins only a view that ends at its address (merge_with_previous), never one that starts after it. + // Two mapping calls next to each other: two views that meet at first + 8 pages. The upper one is mapped first: with + // X2W_XMEM_JOIN_CALLS=1 a call joins only a view that ends at its address (merge_with_previous), never one that + // starts after it. const auto a = pages(8), b = pages(8); if (a.empty() || b.empty() || XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page || XMemMapPhysicalPages(first, 8, a.data()) != first) { @@ -110,8 +115,9 @@ int main(int argc, char** argv) } place("across two backing sections", wrapper.Get(), second + info.RegionSize, 2); - // Map the single pages from high to low addresses. Each call then has no adjacent view below it to join, - // regardless of the order in which the allocator assigned the backing slots. + // Pages mapped one call at a time get a view each. They are mapped from high to low addresses: with + // X2W_XMEM_JOIN_CALLS=1 no call then has an adjacent view below it to join, regardless of the order in which the + // allocator assigned the backing slots. unsigned char* const third = second + 8192 * page; const auto single = pages(8); if (single.empty()) { diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index f4c78ce9cc..b455b076e1 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -23,7 +23,8 @@ // // A fault whose handler reads the breaks only after a later break on another run has begun (two_runs: break B on a // disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) -// must be retried as well: the handler keeps the ranges of the recent breaks, not only of the last one. +// must be retried as well: the handler keeps the ranges of the recent breaks, not only of the last one. Joins across +// calls need X2W_XMEM_JOIN_CALLS=1: main sets it for `mirror` and clears it for every other mode. // // The ring's edge (ring_edge): a held fault in break A whose handler reads the breaks after 63 later breaks is retried; // after 64 later breaks, A is no longer recorded and the fault is passed on (the reader's own __except catches it). @@ -563,10 +564,11 @@ void two_runs_case(const Shim& shim, unsigned char* base) shim.release(2 * pages, tokens); } -// The owner's configuration (X2W_XMEM_PERMISSIVE=1, X2W_XMEM_GPU_MIRROR=1): one XMemMapPhysicalPages call joins the -// CPU run, then the same pages' GPU mirror run, under one memory.mutex hold; the two breaks follow each other at once. -// A fault on the CPU run in the first break, whose handler is held until the GPU break is held open, must be retried. -// The release event is auto-reset, so each of the call's two holds waits for a release of its own. +// The owner's configuration (X2W_XMEM_PERMISSIVE=1, X2W_XMEM_GPU_MIRROR=1, X2W_XMEM_JOIN_CALLS=1 from main): one +// XMemMapPhysicalPages call joins the CPU run, then the same pages' GPU mirror run, under one memory.mutex hold; the +// two breaks follow each other at once. A fault on the CPU run in the first break, whose handler is held until the GPU +// break is held open, must be retried. The release event is auto-reset, so each of the call's two holds waits for a +// release of its own. void mirror_case(const Shim& shim, unsigned char* cpu) { const char* const name = "mirror"; @@ -715,6 +717,7 @@ int main(int argc, char** argv) } // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", default_mode ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", mirror ? "1" : nullptr); // only `mirror` joins across calls if (lazy) SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); const HMODULE xmem = LoadLibraryA(argv[1]); if (!xmem) { diff --git a/tools/startup/run.sh b/tools/startup/run.sh index 01a32d4872..802e12c9c5 100755 --- a/tools/startup/run.sh +++ b/tools/startup/run.sh @@ -100,6 +100,9 @@ export X2W_AUDIO_PERMISSIVE=1 X2W_D3D12_DEVICE_NOOP=1 X2W_D3D12_LIST_NOOP=1 export X2W_D3D12_PERMISSIVE=1 X2W_XMEM_PERMISSIVE=1 X2W_RUNTIME_PROXY=1 # Under Wine, one section and view per page did not get past start-up (docs/wine.md). export X2W_XMEM_SHARED_VIEWS=${X2W_XMEM_SHARED_VIEWS:-1} +# Mapping calls join the shared view that ends at their address: fewer views, and under Wine each map costs more +# the more views there are (docs/wine.md). +export X2W_XMEM_JOIN_CALLS=${X2W_XMEM_JOIN_CALLS:-1} export WINEDEBUG=${WINEDEBUG:--all} WINEFSYNC=${WINEFSYNC:-1} # Wine's built-in D3D12 is not enough (docs/wine.md); the prefix holds vkd3d-proton and DXVK. export WINEDLLOVERRIDES=${WINEDLLOVERRIDES:-d3d12,d3d12core,dxgi,d3d11=n} From cb8cc808f8cd50fe892941da66661765818d50c2 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:12:49 +1000 Subject: [PATCH 23/34] xmem: honour the two split test switches only in the test-controls build X2W_XMEM_TEST_MAP_FIRST and X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK are read only under X2W_XMEM_TEST_CONTROLS; the deployed xmem.dll no longer contains either name and behaves as if both were unset. xmem_map_split_first_control and xmem_placeholder_split_control now run against xmem_shim_test_controls. New xmem_map_split_first_deployed and xmem_placeholder_split_deployed set the switch for the deployed shim and must give the default result (the placeholder one skips with 77 where the OS reports the placeholder bit, as its control does). Each mode of both check programs sets or clears its switch itself, so the CTest entries no longer pass it. --- docs/experiments.md | 2 +- src/xmem_mapped_pages.cpp | 17 ++++++++++++--- tests/cmake/xmem_page_runs.cmake | 29 ++++++++++++++++++-------- tests/xmem_map_split_first_check.cpp | 18 +++++++++++----- tests/xmem_placeholder_split_check.cpp | 20 ++++++++++++------ 5 files changed, 62 insertions(+), 24 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index e1d91e855c..86a5cb2d15 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10494,7 +10494,7 @@ Command queue slot 31 resolves 64 KiB pool pages against the views XMem currentl The `xmem_page_batch_inflight_{warp,hardware}` fixture holds a submitted GPU read behind an unsignaled fence, remaps the same virtual address, then releases the fence. The held read must see the old pattern. A second read binds the new section, writes a different pattern through its CPU pool after recording, and checks every byte across a 64 KiB boundary. Run `ctest --preset release --no-tests=error -R '^xmem_page_batch_inflight_' -V`. -`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. It skips (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. Both skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. `vm_page_provenance_warp` and `vm_page_provenance_hardware` test the source side independently. Two pagefile sections hold distinct data and are mapped into adjacent CPU addresses in reverse creation order. D3D12 reopens those same sections as heaps. The test copies a 4 KiB span centered on the page boundary into a GPU buffer using the logical page order, then compares its readback with the two expected token patterns. It writes new data through the CPU aliases and reads the GPU buffer again before uploading, which must still return the old data. A second upload must produce all the updated words. The tests skip (77) if the requested adapter or section-backed D3D12 buffers are unavailable. [Opening a D3D12 heap from a file mapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index a5dc045445..2d53ba8f36 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -387,12 +387,17 @@ bool exact_placeholder(void* target, SIZE_T bytes) // a map into the middle of a larger placeholder always fails, and under Wine every failed map is another // server round trip whose cost grows with the number of views (one 64 KiB page per call at startup). // The query and the split are not atomic, so if the split or the map after it fails, the map-first -// path below runs as before. X2W_XMEM_TEST_MAP_FIRST=1 skips the split-first step (tests only). +// path below runs as before. Test build only (X2W_XMEM_TEST_CONTROLS): X2W_XMEM_TEST_MAP_FIRST=1 skips the +// split-first step; the deployed build ignores it. // Once a split succeeds, report the retry's result even if it fails for a different reason. template bool map_split(void* target, SIZE_T bytes, Map map) { +#ifdef X2W_XMEM_TEST_CONTROLS static const bool map_first = x2w_local::env_on("X2W_XMEM_TEST_MAP_FIRST"); +#else + constexpr bool map_first = false; +#endif const auto address = reinterpret_cast(target); const auto reservation = owned_reservation(address); const bool owned = reservation != memory.reservations.end() && @@ -1328,10 +1333,16 @@ constexpr ULONG placeholder_reservation = 0x100; // Measured once: whether the region query reports placeholder_reservation for a fresh placeholder, and, when it does // not, whether VirtualFree(MEM_PRESERVE_PLACEHOLDER) refuses a plain reservation and leaves it whole. Windows reports // the bit. Wine (Proton Experimental, 2026-11) leaves Flags 0 for placeholders but refuses the plain case with -// ERROR_INVALID_ADDRESS. X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 skips the second probe (tests only). +// ERROR_INVALID_ADDRESS. Test build only (X2W_XMEM_TEST_CONTROLS): X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 skips the +// second probe; the deployed build ignores it. bool placeholder_fallback() { static const bool fallback = [] { +#ifdef X2W_XMEM_TEST_CONTROLS + const bool skip_probe = x2w_local::env_on("X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK"); +#else + constexpr bool skip_probe = false; +#endif bool bit_reported = false, refuses_plain = false; if (void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)) { @@ -1341,7 +1352,7 @@ bool placeholder_fallback() (info.Flags & placeholder_reservation); VirtualFree(probe, 0, MEM_RELEASE); } - if (!bit_reported && !x2w_local::env_on("X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK")) { + if (!bit_reported && !skip_probe) { if (auto* plain = static_cast(VirtualAlloc(nullptr, 2 * page_bytes, MEM_RESERVE, PAGE_NOACCESS))) { MEMORY_BASIC_INFORMATION after{}; refuses_plain = !VirtualFree(plain + page_bytes, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) && diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index 77ee1d3fab..7c9500f915 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -74,32 +74,43 @@ if(TEST xmem_shim_page_runs) set_property(TEST xmem_shim_page_runs APPEND PROPERTY ENVIRONMENT "X2W_XMEM_JOIN_CALLS=") endif() -# Slot 31 placeholder split inside an XMem reservation. The control disables the fallback used where the OS does -# not report placeholders (Wine), so the split fails there; where the OS reports them, the control skips (77). +# Slot 31 placeholder split inside an XMem reservation. The control (test-controls build) disables the fallback used +# where the OS does not report placeholders (Wine), so the split fails there; where the OS reports them, the control +# skips (77). The check program sets each mode's test switch itself. add_executable(xmem_placeholder_split_check tests/xmem_placeholder_split_check.cpp) target_include_directories(xmem_placeholder_split_check PRIVATE src) target_compile_features(xmem_placeholder_split_check PRIVATE cxx_std_17) target_link_libraries(xmem_placeholder_split_check PRIVATE OneCore) -add_dependencies(xmem_placeholder_split_check xmem_shim) +add_dependencies(xmem_placeholder_split_check xmem_shim xmem_shim_test_controls) set(xmem_placeholder_env "X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") add_test(NAME xmem_placeholder_split COMMAND xmem_placeholder_split_check "$") set_tests_properties(xmem_placeholder_split PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") # The control passes only when the split itself fails, not on an earlier setup failure. -add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check "$" control) +add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check + "$" control) set_tests_properties(xmem_placeholder_split_control PROPERTIES - ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1" + ENVIRONMENT "${xmem_placeholder_env}" PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) +# The deployed shim with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1: the switch is ignored and the split succeeds. +add_test(NAME xmem_placeholder_split_deployed COMMAND xmem_placeholder_split_check "$" deployed) +set_tests_properties(xmem_placeholder_split_deployed PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" SKIP_RETURN_CODE 77 TIMEOUT 60) add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) target_include_directories(xmem_map_split_first_check PRIVATE src) target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) -add_dependencies(xmem_map_split_first_check xmem_shim) +add_dependencies(xmem_map_split_first_check xmem_shim xmem_shim_test_controls) add_test(NAME xmem_map_split_first COMMAND xmem_map_split_first_check "$") -add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check "$" control) +add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check + "$" control) set_tests_properties(xmem_map_split_first PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") -# The control passes only when the map-first order is measured (2 maps per page), not on a setup failure. +# The control (test-controls build, X2W_XMEM_TEST_MAP_FIRST=1) passes only when the map-first order is measured +# (2 maps per page), not on a setup failure. set_tests_properties(xmem_map_split_first_control PROPERTIES - ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_MAP_FIRST=1" + ENVIRONMENT "${xmem_placeholder_env}" PASS_REGULAR_EXPRESSION "map-first control: maps=2N" TIMEOUT 60) +# The deployed shim with X2W_XMEM_TEST_MAP_FIRST=1: the switch is ignored, so the split-first counts hold. +add_test(NAME xmem_map_split_first_deployed COMMAND xmem_map_split_first_check "$" deployed) +set_tests_properties(xmem_map_split_first_deployed PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") # A request whose destination page an XMem run break holds unmapped (the xmem test-controls build's # X2W_XMEM_TEST_HOLD_WINDOW) must not complete within the 1000 ms hold, then land after the release. diff --git a/tests/xmem_map_split_first_check.cpp b/tests/xmem_map_split_first_check.cpp index 4514fc6f3b..f2c6e56ec3 100644 --- a/tests/xmem_map_split_first_check.cpp +++ b/tests/xmem_map_split_first_check.cpp @@ -1,10 +1,14 @@ // XMemMapPhysicalPages into an owned XMem reservation: when the target is in the middle of a larger placeholder, xmem // splits first and maps once (one MapViewOfFile3 per page). Under Wine each failed map is a server round trip whose // cost grows with the number of views, and the title maps one 64 KiB page per call at startup. -// xmem_map_split_first_check N single-page maps take N map attempts; an exact placeholder -// (left by an unmap) is mapped without a split -// xmem_map_split_first_check control run by CTest with X2W_XMEM_TEST_MAP_FIRST=1: the old order takes -// 2N map attempts and prints "map-first control: maps=2N" +// xmem_map_split_first_check N single-page maps take N map attempts; an exact placeholder +// (left by an unmap) is mapped without a split +// xmem_map_split_first_check control test-controls build (X2W_XMEM_TEST_CONTROLS) with +// X2W_XMEM_TEST_MAP_FIRST=1: the old order takes 2N map attempts and +// prints "map-first control: maps=2N" +// xmem_map_split_first_check deployed deployed build with X2W_XMEM_TEST_MAP_FIRST=1: the build ignores +// the switch, so the checks of the first mode pass +// Each mode sets or clears X2W_XMEM_TEST_MAP_FIRST itself, so an inherited value cannot change the result. #include #include #include @@ -27,7 +31,10 @@ bool require(bool ok, const char* step) int wmain(int argc, wchar_t** argv) { const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; - if (argc != 2 && !control) return 2; + const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; + if (argc != 2 && !control && !deployed) return 2; + // xmem reads the switch on first use and keeps the value; set it before any map. + SetEnvironmentVariableW(L"X2W_XMEM_TEST_MAP_FIRST", control || deployed ? L"1" : nullptr); const HMODULE xmem = LoadLibraryW(argv[1]); if (!require(xmem != nullptr, "load xmem.dll")) return 1; const auto reserve = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); @@ -89,5 +96,6 @@ int wmain(int argc, wchar_t** argv) !require(first[0] == 0x40, "the remapped page reads its bytes")) return 1; std::puts("split-first: maps=N; exact placeholder mapped without a split"); + if (deployed) std::puts("deployed build: X2W_XMEM_TEST_MAP_FIRST=1 was ignored"); return 0; } diff --git a/tests/xmem_placeholder_split_check.cpp b/tests/xmem_placeholder_split_check.cpp index 767c3a6579..fcedcfd8da 100644 --- a/tests/xmem_placeholder_split_check.cpp +++ b/tests/xmem_placeholder_split_check.cpp @@ -1,10 +1,14 @@ // Queue slot 31 (X2WMapPageBatch) into the middle of an XMem reservation needs a placeholder split. Where the region // query does not report placeholders (Wine), xmem probes whether a placeholder release refuses a plain reservation // and then offers reserved regions to the split (xmem placeholder_fallback). -// xmem_placeholder_split_check split succeeds; a committed target still fails and stays intact -// xmem_placeholder_split_check control the same checks, run with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 -// by CTest, which expects the split step to fail; exits 77 where -// the OS reports the bit, because there the fallback is never used +// xmem_placeholder_split_check split succeeds; a committed target still fails and stays intact +// xmem_placeholder_split_check control the same checks in the test-controls build (X2W_XMEM_TEST_CONTROLS) +// with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1; CTest expects the +// split step to fail +// xmem_placeholder_split_check deployed the same checks in the deployed build with the same switch, which +// that build ignores, so they pass +// control and deployed exit 77 where the OS reports the bit, because there the fallback is never used. Each mode sets +// or clears X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK itself, so an inherited value cannot change the result. #include #include "xmem_page_batch.h" #include @@ -47,10 +51,13 @@ MEMORY_BASIC_INFORMATION query(const BYTE* pointer) int wmain(int argc, wchar_t** argv) { const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; - if (argc != 2 && !control) return 2; + const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; + if (argc != 2 && !control && !deployed) return 2; + // xmem reads the switch once, in its first placeholder probe; set it before loading xmem.dll. + SetEnvironmentVariableW(L"X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK", control || deployed ? L"1" : nullptr); const bool bit = os_reports_placeholder_bit(); std::printf("placeholder bit reported=%d\n", bit); - if (control && bit) { + if ((control || deployed) && bit) { std::puts("SKIP: the OS reports the placeholder bit, so the fallback is never used"); return 77; } @@ -105,5 +112,6 @@ int wmain(int argc, wchar_t** argv) window[page_bytes] = 0x60; if (!require(pool[page_bytes] == 0x60, "a write through the destination reaches the pool page")) return 1; std::puts("slot31 split inside an XMem reservation matched; a committed target was refused and kept"); + if (deployed) std::puts("deployed build: X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 was ignored"); return 0; } From 1615efc5a158cfbe7a834f12575c4f8d8eb47837 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:21:44 +1000 Subject: [PATCH 24/34] xmem: check every region of a view the placeholder fallback accepts Where the region query does not report the placeholder bit (Wine), alias_placeholders accepted a view after one VirtualQuery at the start of each allocation and then skipped to the allocation's end. It now walks every VirtualQuery region the view covers and requires each to be reserved. New xmem_placeholder_split_partial (test-controls build, shared views): two pages of the XMem reservation become a private reservation whose second page is committed and tagged, and a batch maps a two-page view there. With the old walk under Wine (Proton Experimental) the batch succeeded: alias refusals 0, one placeholder release tried, and the committed page became a mapped view reading the pool page (0x53 instead of the 0x7a tag). With the new walk the view is refused (alias refusals 2, one release: the per-page retry maps the reserved page alone and the rollback unmaps it), the batch fails with 0x80070057 and the committed page keeps its tag. The new x2w_xmem_alias_counts export (@27) counts alias_placeholders refusals and placeholder releases on the X2WMapPageBatch path in the test-controls build; the deployed build returns FALSE. Where the OS reports the bit the case skips (77). --- docs/experiments.md | 2 +- src/xmem_mapped_pages.cpp | 58 +++++++++++++++++++++----- src/xmem_shim.def | 1 + tests/cmake/xmem_page_runs.cmake | 7 ++++ tests/xmem_placeholder_split_check.cpp | 58 ++++++++++++++++++++++++-- 5 files changed, 110 insertions(+), 16 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 86a5cb2d15..1813796a36 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10494,7 +10494,7 @@ Command queue slot 31 resolves 64 KiB pool pages against the views XMem currentl The `xmem_page_batch_inflight_{warp,hardware}` fixture holds a submitted GPU read behind an unsignaled fence, remaps the same virtual address, then releases the fence. The held read must see the old pattern. A second read binds the new section, writes a different pattern through its CPU pool after recording, and checks every byte across a 64 KiB boundary. Run `ctest --preset release --no-tests=error -R '^xmem_page_batch_inflight_' -V`. -`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. Both skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. `vm_page_provenance_warp` and `vm_page_provenance_hardware` test the source side independently. Two pagefile sections hold distinct data and are mapped into adjacent CPU addresses in reverse creation order. D3D12 reopens those same sections as heaps. The test copies a 4 KiB span centered on the page boundary into a GPU buffer using the logical page order, then compares its readback with the two expected token patterns. It writes new data through the CPU aliases and reads the GPU buffer again before uploading, which must still return the old data. A second upload must produce all the updated words. The tests skip (77) if the requested adapter or section-backed D3D12 buffers are unavailable. [Opening a D3D12 heap from a file mapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 2d53ba8f36..f26a67a240 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -372,6 +372,11 @@ auto owned_reservation(ULONG_PTR address) // MapViewOfFile3 and placeholder-split attempts made by map_split (x2w_xmem_map_counts). volatile LONG64 map_attempts, split_attempts; +#ifdef X2W_XMEM_TEST_CONTROLS +// Test build only (x2w_xmem_alias_counts): views install_alias_view could not map in place inside an owned +// reservation, split by whether alias_placeholders refused the range or a placeholder release was tried. +volatile LONG64 alias_refusals, alias_splits; +#endif // True when [target, target + bytes) is a whole reserved region of its own: a placeholder that // MEM_REPLACE_PLACEHOLDER can take as it is, so no split is needed first. @@ -1373,8 +1378,10 @@ bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) { // VirtualQuery alone cannot distinguish a reserved private allocation from a placeholder, and on Windows // PRESERVE_PLACEHOLDER can silently release that allocation. Where the region query does not report the bit - // and the OS refuses that release (placeholder_fallback), any reserved region may be offered: a plain one - // fails the split instead of being released. + // and the OS refuses that release for a plain reservation (placeholder_fallback), reserved regions may be + // offered. Every region the view covers must be reserved, not only the first one of each allocation: Wine + // (Proton Experimental, 2026-11) released a private allocation made in place of a placeholder together with + // its committed second page, and the view then replaced that page (xmem_placeholder_split_partial). const bool fallback = placeholder_fallback(); const auto end = address + bytes; while (address < end) { @@ -1382,15 +1389,21 @@ bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) if (!QueryVirtualMemoryInformation(GetCurrentProcess(), reinterpret_cast(address), MemoryRegionInfo, &info, sizeof(info), nullptr)) return false; - if (!(info.Flags & placeholder_reservation)) { - MEMORY_BASIC_INFORMATION region{}; - if (!fallback || VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) != sizeof(region) || - region.State != MEM_RESERVE) - return false; - } const auto base = reinterpret_cast(info.AllocationBase); if (address - base >= info.RegionSize) return false; - address += info.RegionSize - (address - base); + const auto allocation_end = base + info.RegionSize; + if (!(info.Flags & placeholder_reservation)) { + if (!fallback) return false; + const auto stop = end < allocation_end ? end : allocation_end; + for (auto at = address; at < stop;) { + MEMORY_BASIC_INFORMATION region{}; + if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region)) != sizeof(region) || + region.State != MEM_RESERVE || !region.RegionSize) + return false; + at = reinterpret_cast(region.BaseAddress) + region.RegionSize; + } + } + address = allocation_end; } return true; } @@ -1408,8 +1421,13 @@ bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, if (!map()) { const DWORD original_error = GetLastError(); const auto reservation = owned_reservation(address); - if (reservation == memory.reservations.end() || - bytes > reservation->second - (address - reservation->first) || !alias_placeholders(address, bytes)) { + const bool inside = reservation != memory.reservations.end() && + bytes <= reservation->second - (address - reservation->first); + const bool accepted = inside && alias_placeholders(address, bytes); +#ifdef X2W_XMEM_TEST_CONTROLS + if (inside) InterlockedIncrement64(accepted ? &alias_splits : &alias_refusals); +#endif + if (!accepted) { SetLastError(original_error); return false; } @@ -1793,6 +1811,24 @@ extern "C" BOOL WINAPI x2w_xmem_map_counts(ULONGLONG* maps, ULONGLONG* splits) return TRUE; } +// Test export, counted in the test-controls build only: views X2WMapPageBatch could not map in place inside an +// owned reservation whose range alias_placeholders refused, and those for which it tried a placeholder release. +// The deployed build returns FALSE with ERROR_NOT_SUPPORTED. +extern "C" BOOL WINAPI x2w_xmem_alias_counts(ULONGLONG* refusals, ULONGLONG* splits) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (!refusals || !splits) return FALSE; + *refusals = static_cast(alias_refusals); + *splits = static_cast(alias_splits); + return TRUE; +#else + (void)refusals; + (void)splits; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; +#endif +} + // Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free // in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs // are closed when all of their slots are freed and unpinned. diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 06c581eb0c..78c0607009 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -25,3 +25,4 @@ EXPORTS x2w_xmem_copy_to_destination @23 x2w_xmem_map_counts @25 x2w_xmem_stable_call @26 + x2w_xmem_alias_counts @27 diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index 7c9500f915..5b5a5fc166 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -95,6 +95,13 @@ set_tests_properties(xmem_placeholder_split_control PROPERTIES add_test(NAME xmem_placeholder_split_deployed COMMAND xmem_placeholder_split_check "$" deployed) set_tests_properties(xmem_placeholder_split_deployed PROPERTIES ENVIRONMENT "${xmem_placeholder_env}" SKIP_RETURN_CODE 77 TIMEOUT 60) +# A two-page view over a reserved page and a committed page of one private allocation: the fallback checks every +# region of the view and refuses it (test-controls build: x2w_xmem_alias_counts), and the committed page keeps its +# bytes. The program turns shared views on for this mode. +add_test(NAME xmem_placeholder_split_partial COMMAND xmem_placeholder_split_check + "$" partial) +set_tests_properties(xmem_placeholder_split_partial PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" SKIP_RETURN_CODE 77 TIMEOUT 60) add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) target_include_directories(xmem_map_split_first_check PRIVATE src) target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) diff --git a/tests/xmem_placeholder_split_check.cpp b/tests/xmem_placeholder_split_check.cpp index fcedcfd8da..092a5f2ecc 100644 --- a/tests/xmem_placeholder_split_check.cpp +++ b/tests/xmem_placeholder_split_check.cpp @@ -7,8 +7,12 @@ // split step to fail // xmem_placeholder_split_check deployed the same checks in the deployed build with the same switch, which // that build ignores, so they pass -// control and deployed exit 77 where the OS reports the bit, because there the fallback is never used. Each mode sets -// or clears X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK itself, so an inherited value cannot change the result. +// xmem_placeholder_split_check partial test-controls build with shared views: a two-page view over a +// private reservation whose second page is committed is refused +// by the region walk (x2w_xmem_alias_counts), and the committed +// page keeps its bytes +// control, deployed and partial exit 77 where the OS reports the bit, because there the fallback is never used. Each +// mode sets or clears X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK itself, so an inherited value cannot change the result. #include #include "xmem_page_batch.h" #include @@ -21,6 +25,7 @@ constexpr UINT pool_pages = 4; using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); using Scatter = BOOL (WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); +using AliasCounts = BOOL (WINAPI*)(ULONGLONG*, ULONGLONG*); bool require(bool ok, const char* step) { @@ -46,18 +51,62 @@ MEMORY_BASIC_INFORMATION query(const BYTE* pointer) VirtualQuery(pointer, &info, sizeof(info)); return info; } + +// partial: two pages of the reservation become a private reservation whose second page is committed and tagged. Its +// first region is reserved, so a check of that region alone would accept the whole two-page view. +int partial_case(HMODULE xmem, BYTE* pool, decltype(&X2WMapPageBatch) batch_map) +{ + const auto counts = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_alias_counts")); + ULONGLONG refusals0 = 0, splits0 = 0, refusals1 = 0, splits1 = 0; + if (!require(counts && counts(&refusals0, &splits0), "read the alias counts (test-controls build)")) return 1; + BYTE* const piece = pool + 192 * page_bytes; + if (!require(VirtualFree(piece, 2 * page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split out two pages") || + !require(VirtualAlloc2(GetCurrentProcess(), piece, 2 * page_bytes, MEM_RESERVE | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == piece, "reserve the two pages privately") || + !require(VirtualAlloc(piece + page_bytes, page_bytes, MEM_COMMIT, PAGE_READWRITE) == piece + page_bytes, + "commit the second page")) + return 1; + std::memset(piece + page_bytes, 0x7a, page_bytes); + const X2WPageRange two{0, 1, 2}; + const X2WPageBatch onto_partial{reinterpret_cast(piece), 1, &two}; + const HRESULT hr = batch_map(1, &onto_partial, reinterpret_cast(pool), pool_pages, 0, nullptr); + if (!require(counts(&refusals1, &splits1), "read the alias counts")) return 1; + const MEMORY_BASIC_INFORMATION first = query(piece), second = query(piece + page_bytes); + std::printf("batch onto a reserved page and a committed one -> 0x%08lx; alias refusals %llu, placeholder " + "releases tried %llu; after: state 0x%lx type 0x%lx, then state 0x%lx type 0x%lx byte 0x%02x\n", + static_cast(hr), refusals1 - refusals0, splits1 - splits0, first.State, first.Type, + second.State, second.Type, second.State == MEM_COMMIT ? piece[page_bytes] : 0u); + // The walk refuses the two-page view. The batch then retries each page on its own (install_alias_plan): the + // reserved page alone may be released and mapped, and the rollback unmaps it again; the committed page alone is + // refused. A walk that checks only the first region of each allocation accepts the view, and under Wine the + // release then succeeds and the view replaces the committed page (measured 2026-11-27 before the fix). + if (!require(refusals1 - refusals0 >= 1, "the region walk refuses the two-page view") || + !require(FAILED(hr), "the partly committed target is refused") || + !require(first.State == MEM_RESERVE && second.State == MEM_COMMIT && second.Type == MEM_PRIVATE && + piece[page_bytes] == 0x7a && piece[2 * page_bytes - 1] == 0x7a, + "the committed page keeps its bytes and the reserved page stays reserved")) + return 1; + std::puts("partial: a view over a reserved and a committed page was refused; the committed page kept its bytes"); + return 0; +} } // namespace int wmain(int argc, wchar_t** argv) { const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; - if (argc != 2 && !control && !deployed) return 2; + const bool partial = argc == 3 && std::wcscmp(argv[2], L"partial") == 0; + if (argc != 2 && !control && !deployed && !partial) return 2; // xmem reads the switch once, in its first placeholder probe; set it before loading xmem.dll. SetEnvironmentVariableW(L"X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK", control || deployed ? L"1" : nullptr); + if (partial) { + // A two-page view needs shared views (one view per run of pool pages); joins across calls stay off. + SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", nullptr); + } const bool bit = os_reports_placeholder_bit(); std::printf("placeholder bit reported=%d\n", bit); - if ((control || deployed) && bit) { + if ((control || deployed || partial) && bit) { std::puts("SKIP: the OS reports the placeholder bit, so the fallback is never used"); return 77; } @@ -78,6 +127,7 @@ int wmain(int argc, wchar_t** argv) !require(scatter(addresses, pool_pages, grants), "map the pool")) return 1; for (UINT i = 0; i < pool_pages; ++i) std::memset(addresses[i], 0x51 + i, page_bytes); + if (partial) return partial_case(xmem, pool, batch_map); // Negative control: a committed page inside the reservation is not a placeholder. The batch must fail and leave // the page committed with its bytes. From c839170941be280878aceb21355c1df384edba1d Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:34:28 +1000 Subject: [PATCH 25/34] xmem: stamp each run with the break that mapped it instead of a 64-break history retry_remapped_page retried a fault only while the break that took the page apart was among the last 64 recorded. A handler that ran after 64 later breaks on other runs passed the fault on although the page was mapped again, which xmem_run_break_readers_ring_edge asserted. Each recorded view now keeps the id of the break inside which it was mapped (0 outside breaks): the survivors map_recorded maps again after an unmap, a joined run, and the views of a page batch. The handler reads that stamp under memory.mutex, after the break in progress, and retries once per page and stamp per thread, so the id never expires while the view lasts. The ring and its ranges are gone; the generation stays for x2w_xmem_stable_call and the ReadFile/WriteFile retry. Because the handler is registered first and now needs the mutex for the lookup, faults that cannot be the transient one skip it: with the generation even before and unchanged after a VirtualQuery of the page and no mapped view there, the fault is passed on at once (faults on lazily committed memory take this path). Any other fault waits for the mapping call, as the ring lookup's hits did. xmem_run_break_readers_ring_edge becomes xmem_run_break_readers_stamps: 63, 64 and 200 later breaks (under Wine 3, 4 and 10 ms), all retried; the 64th used to be passed on. New in the same mode: a page made no-access faults once on a run no break mapped (passed on at once) and twice after a break mapped it (one retry), counted by a first-chance handler. --- docs/startup-runtime.md | 16 ++- src/xmem_mapped_pages.cpp | 175 ++++++++++++------------- tests/cmake/xmem_page_runs.cmake | 9 +- tests/xmem_run_break_readers_check.cpp | 109 +++++++++++---- 4 files changed, 178 insertions(+), 131 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 1c1ef5247f..8ed158ffad 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3178,13 +3178,15 @@ pages 2.1 ms and of 4096 pages 13 ms; joining a page to a view of 63 took 1.5 ms mapped on its own costs (1.4 ms). Unmapping a page inside a shared view unmaps that view and maps its other pages again. A thread -that touches one of those pages in between takes an access violation. A vectored handler retries -it only when the address is inside a view that one of the last 64 unmaps or joins (the one in -progress included) took apart, the page is recorded and covered by a view once that one is over, -and the thread has not already retried that page for the newest such unmap or join. A handler that -runs late, after a later unmap or join of another view has begun (one call joins a CPU view and -then its GPU mirror), still finds the one its fault came from. Any other fault is passed on, after -at most one retry for each unmap or join. +that touches one of those pages in between takes an access violation. Each view mapped inside an +unmap, a join or a page batch keeps that one's id. A vectored handler retries the fault only when, +once the one in progress (if any) is over, the page is recorded, covered by a view, and that view +carries such an id, and the thread has not already retried that page for that id. A handler that +runs late, after any number of later unmaps or joins of other views (one call joins a CPU view and +then its GPU mirror), still finds the one that mapped the page again. Any other fault is passed on, +after at most one retry for each unmap or join that mapped the page's view. A fault with none in +progress or beginning or ending around a region query of the page, and no mapped view there, is +passed on without waiting for the mapping lock. Shared views are opt-in. The caller chooses before the first mapping call by setting `X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. It also diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index f26a67a240..7e2460737d 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -57,7 +57,13 @@ struct PhysicalMemory { ULONG_PTR mirror_cpu = 0, mirror_gpu = 0; SIZE_T mirror_bytes = 0; std::set explicit_mirror_pages; - std::map runs; // OS views: base -> bytes + // OS views: base -> bytes, and the id of the run break inside which the view was mapped (0: mapped outside any + // break). retry_remapped_page reads the id; it never expires while the view lasts. + struct Run { + SIZE_T bytes = 0; + ULONG64 stamp = 0; + }; + std::map runs; // The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together // are adjacent slots again. x2w_xmem::SlabSlots slots{era_physical::page_bytes}; @@ -441,8 +447,8 @@ bool map_view(ULONG_PTR address, const Backing& backing) } // Maps bytes of one section at address as a single view; falls back to one view per page when the -// range is not inside a single placeholder. -bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, +// range is not inside a single placeholder. stamp: the run break in progress, or 0 (PhysicalMemory::Run). +bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, ULONG64 stamp, std::vector>& made, ULONG_PTR& failed_address) { auto* target = reinterpret_cast(address); @@ -451,7 +457,7 @@ bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; }; if (map_split(target, bytes, map)) { - memory.runs[address] = bytes; + memory.runs[address] = {bytes, stamp}; made.emplace_back(address, bytes); return true; } @@ -464,7 +470,7 @@ bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, failed_address = address + done; return false; } - memory.runs[address + done] = page_bytes; + memory.runs[address + done] = {page_bytes, stamp}; made.emplace_back(address + done, page_bytes); } return true; @@ -491,36 +497,16 @@ void coalesce_unused(const Pages& batch) } } -// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages), and so does a -// cross-call merge (merge_with_previous) for the run it joins. A thread that touches one of those pages in between -// faults. Each break records the address ranges of the runs it takes apart, and a generation that is odd while it -// is in progress; the break's id is that odd value. The last `kept` breaks stay recorded, so that a fault handler -// that runs late, after later breaks on other runs have begun (a merge of the CPU view and then of its GPU mirror -// in one call, or the next call's merge), still finds the break its fault came from. +// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages), and so do a +// cross-call merge (merge_with_previous) for the run it joins and a page batch (remap_alias_pages) for the runs it +// changes. A thread that touches one of those pages in between faults. Such a run break has a generation that is odd +// while it is in progress; the break's id is that odd value. Every view mapped inside a break records the id +// (PhysicalMemory::Run::stamp, under memory.mutex), so a fault handler that runs late, after any number of later +// breaks on other runs (a merge of the CPU view and then of its GPU mirror in one call, or the next calls), still +// finds the break that mapped the page again. struct RemapWindow { - static constexpr std::size_t kept = 64; - struct Break { - ULONG64 id = 0; // 0: no break recorded in this slot yet - std::vector> ranges; - }; SRWLOCK lock = SRWLOCK_INIT; - Break recent[kept]; // break id i in recent[(i / 2) % kept] ULONG64 generation = 0; - - // The newest recorded break whose ranges hold address, or 0. Caller holds lock (shared). - ULONG64 newest_holding(ULONG_PTR address) const - { - ULONG64 found = 0; - for (const Break& b : recent) { - if (b.id <= found) continue; - for (const auto& [base, size] : b.ranges) - if (address - base < size) { - found = b.id; - break; - } - } - return found; - } }; RemapWindow remap_window; // Set once shared views are on (FaultRetry::ready). Breaks also begin without them (every unmap counts in the @@ -531,15 +517,13 @@ std::atomic shared_views_on{false}; // mapped by a call of its own join the recorded run that ends at its address (merge_with_previous). std::atomic joins_on{false}; -void begin_break(const std::map& broken) +// Caller holds memory.mutex. Returns the break's id, the stamp of the views mapped until end_break. +ULONG64 begin_break() { - std::vector> ranges(broken.begin(), broken.end()); AcquireSRWLockExclusive(&remap_window.lock); const ULONG64 id = ++remap_window.generation; - auto& slot = remap_window.recent[(id / 2) % RemapWindow::kept]; - slot.id = id; - slot.ranges.swap(ranges); // the old slot's ranges are freed after the lock ReleaseSRWLockExclusive(&remap_window.lock); + return id; } void end_break() { @@ -550,6 +534,14 @@ void end_break() struct EndBreak { ~EndBreak() { end_break(); } }; +ULONG64 break_generation() +{ + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; +} + // Test build only: X2W_XMEM_TEST_HOLD_RETRY= holds the fault handler before it reads the break: it sets // ".faulted", then waits up to five seconds for ".go", so that a test can end the break first. #ifdef X2W_XMEM_TEST_CONTROLS @@ -574,11 +566,15 @@ void hold_retry() void hold_retry() {} #endif -// Retries an access violation only when all of this holds: the address is inside a run that one of the recorded -// breaks (the one in progress or the last RemapWindow::kept) took apart; after that break has finished (the mutex) -// the page is recorded and covered by a view; and this thread has not already retried this page for the newest -// such break. Everything else is passed on, so a fault that is not the transient one is reported after at most one -// retry per break. +// Retries an access violation only when all of this holds: after the break in progress, if any, has finished (the +// mutex), the page is recorded, covered by a view, and in a run mapped inside a break (a nonzero Run::stamp); and +// this thread has not already retried this page for that stamp. Everything else is passed on, so a fault that is not +// the transient one is reported after at most one retry per break that mapped the page again. +// Faults that cannot be the transient one do not wait for memory.mutex, which a mapping call holds for all of its +// work: when no break is in progress or begins or ends around a region query of the page (the generation is even +// before and unchanged after) and the query shows no mapped view there, the fault is passed on at once. Outside +// breaks only a break takes away a view mapped inside one, so the check below would pass it on as well. Faults on +// lazily committed memory and other faults outside the runs take that path. LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -587,24 +583,27 @@ LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) const ULONG_PTR address = record->ExceptionInformation[1]; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); hold_retry(); - AcquireSRWLockShared(&remap_window.lock); - // The newest break that took the page apart, in progress or finished; a later break on another run does not - // hide it. A fault in a later break of the same page names that break, so it is retried again. - const ULONG64 break_id = remap_window.newest_holding(address); - ReleaseSRWLockShared(&remap_window.lock); - if (!break_id) return EXCEPTION_CONTINUE_SEARCH; - thread_local ULONG_PTR retried_page = 0; - thread_local ULONG64 retried_break = 0; - if (retried_page == page && retried_break == break_id) return EXCEPTION_CONTINUE_SEARCH; - bool mapped = false; + const ULONG64 before = break_generation(); + MEMORY_BASIC_INFORMATION info{}; + const bool mapped_now = VirtualQuery(reinterpret_cast(page), &info, sizeof(info)) == sizeof(info) && + info.State == MEM_COMMIT && info.Type == MEM_MAPPED; + if (!(before & 1) && break_generation() == before && !mapped_now) return EXCEPTION_CONTINUE_SEARCH; + // The break that last mapped the page's run, however many breaks on other runs came after it. A later break of + // the same run stamps it again, so a fault in that break is retried again. + ULONG64 stamp = 0; { const std::lock_guard guard(memory.mutex); // held by the mapping thread until its break is over - auto run = memory.runs.upper_bound(page); - mapped = memory.views.count(page) && run != memory.runs.begin() && page - std::prev(run)->first < std::prev(run)->second; + const auto run = memory.runs.upper_bound(page); + if (memory.views.count(page) && run != memory.runs.begin() && + page - std::prev(run)->first < std::prev(run)->second.bytes) + stamp = std::prev(run)->second.stamp; } - if (!mapped) return EXCEPTION_CONTINUE_SEARCH; + if (!stamp) return EXCEPTION_CONTINUE_SEARCH; + thread_local ULONG_PTR retried_page = 0; + thread_local ULONG64 retried_stamp = 0; + if (retried_page == page && retried_stamp == stamp) return EXCEPTION_CONTINUE_SEARCH; retried_page = page; - retried_break = break_id; + retried_stamp = stamp; return EXCEPTION_CONTINUE_EXECUTION; } struct MappingThread { @@ -742,7 +741,7 @@ void forget_page(ULONG_PTR address) // Maps every recorded page of [base, base + size) that has no view: neighbours on adjacent slots // together, one page at a time when a group is refused. A page that cannot be mapped is forgotten -// and counted. fail is true when the test control refuses this range. +// and counted. fail is true when the test control refuses this range. stamp: the break in progress. struct MapFailure { const char* stage = nullptr; ULONG_PTR address = 0; @@ -764,7 +763,7 @@ struct MapFailure { } }; -ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failure) +ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, ULONG64 stamp, bool fail, MapFailure* failure) { ULONG_PTR lost = 0; ULONG_PTR at = base; @@ -784,14 +783,14 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu } std::vector> made; ULONG_PTR failed_address; - if (fail || !map_run(at, head, bytes, made, failed_address)) { + if (fail || !map_run(at, head, bytes, stamp, made, failed_address)) { // map_run may have mapped some pages one at a time before it stopped; keep those. for (SIZE_T done = 0; done < bytes; done += page_bytes) { if (memory.runs.count(at + done)) continue; Backing one = head; one.offset += done; if (!fail && map_view(at + done, one)) { - memory.runs[at + done] = page_bytes; + memory.runs[at + done] = {page_bytes, stamp}; } else { if (failure) failure->record("restore-view", at + done, memory.views.at(at + done), @@ -843,7 +842,8 @@ Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, #endif const auto next = memory.runs.lower_bound(address); if (next == memory.runs.begin()) return Merge::separate; - const auto [base, size] = *std::prev(next); + const ULONG_PTR base = std::prev(next)->first; + const SIZE_T size = std::prev(next)->second.bytes; if (base + size != address) return Merge::separate; if ((size + bytes) / page_bytes > merged_run_cap()) return Merge::separate; const auto tail = memory.views.find(address - page_bytes); @@ -860,7 +860,7 @@ Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, if (!VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return Merge::separate; } TestFault test; - begin_break({{base, size}}); + const ULONG64 stamp = begin_break(); const EndBreak end; if (!unmap_view(base)) return Merge::separate; memory.runs.erase(base); @@ -870,12 +870,12 @@ Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, InterlockedIncrement64(&map_attempts); if (!test.hit(4) && MapViewOfFile3(start.section, GetCurrentProcess(), whole, start.offset, size + bytes, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) { - memory.runs[base] = size + bytes; + memory.runs[base] = {size + bytes, stamp}; return Merge::joined; } } // map_recorded splits the joined placeholder back to R's size (map_split: the reservation is the shim's). - const ULONG_PTR lost = map_recorded(base, size, false, failure); + const ULONG_PTR lost = map_recorded(base, size, stamp, false, failure); if (!lost) return Merge::separate; x2w_local::logf("x2w-xmem merge of a run with the next mapping call failed: %llu page(s) of the run could not be " "mapped again and were forgotten", static_cast(lost)); @@ -938,7 +938,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& return FALSE; } ULONG_PTR failed_address; - if (merge == Merge::separate && !map_run(first->first, head, bytes, made, failed_address)) { + if (merge == Merge::separate && !map_run(first->first, head, bytes, 0, made, failed_address)) { const DWORD error = GetLastError(); if (failure) failure->record("map-view", failed_address, batch.at(failed_address), error); for (const auto& [base, size] : made) { @@ -966,10 +966,10 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& auto run = memory.runs.upper_bound(address); if (run == memory.runs.begin()) continue; --run; - if (address - run->first < run->second) broken.insert(*run); + if (address - run->first < run->second.bytes) broken.emplace(run->first, run->second.bytes); } TestFault test; - begin_break(broken); + const ULONG64 stamp = begin_break(); const EndBreak end; DWORD error = ERROR_SUCCESS; std::vector> unmapped; @@ -993,7 +993,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& if (!refused && !unmapped.empty()) hold_window(); ULONG_PTR lost = 0; for (const auto& [base, size] : unmapped) - lost += map_recorded(base, size, refused ? test.stage == 3 && test.hit(3) : test.hit(2), failure); + lost += map_recorded(base, size, stamp, refused ? test.stage == 3 && test.hit(3) : test.hit(2), failure); if (!refused) coalesce_unused(batch); if (refused || lost) { x2w_local::logf("x2w-xmem unmap of %llu page(s) failed (error %lu): %s; %llu surviving page(s) could not be mapped " @@ -1330,7 +1330,7 @@ struct AliasEdit { }; using AliasPlan = std::map; -using ViewRuns = std::map; +using ViewRuns = std::map; // The region query exposes the placeholder reservation flag in Flags even though the SDK does not name that bit. constexpr ULONG placeholder_reservation = 0x100; @@ -1410,7 +1410,8 @@ bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) // Both maps have the same node type. The node for each possible run base was reserved before // unmapping anything, so recording a successful OS call cannot fail for lack of C++ heap memory. -bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, +// stamp: the page batch's break (PhysicalMemory::Run). +bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, ULONG64 stamp, ViewRuns& nodes, X2WPageBatchStats& stats) { auto* target = reinterpret_cast(address); @@ -1441,13 +1442,13 @@ bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, if (!map()) return false; } auto node = nodes.extract(address); - node.mapped() = bytes; + node.mapped() = {bytes, stamp}; memory.runs.insert(std::move(node)); ++stats.mapCalls; return true; } -DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, bool restoring, +DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, bool restoring, ULONG64 stamp, std::vector& made, X2WPageBatchStats& stats) { DWORD error = ERROR_SUCCESS; @@ -1467,7 +1468,7 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo const auto& next = memory.backings.at(token(end->second)); if (next.section != head.section || next.offset != head.offset + bytes) break; } - if (install_alias_view(address, head, bytes, nodes, stats)) { + if (install_alias_view(address, head, bytes, stamp, nodes, stats)) { made.push_back(address); for (auto page = it; page != end; ++page) page->second.actual = token(page->second); @@ -1478,7 +1479,7 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo // A grouped view may cross placeholder boundaries. Retry each page once. for (auto page = it; page != end; ++page) { if (install_alias_view(page->first, memory.backings.at(token(page->second)), - page_bytes, nodes, stats)) { + page_bytes, stamp, nodes, stats)) { made.push_back(page->first); page->second.actual = token(page->second); } else { @@ -1494,13 +1495,13 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& stats) { - ViewRuns broken; + std::map broken; for (const auto& [address, edit] : plan) { if (!edit.old) continue; const auto run = memory.runs.upper_bound(address); - if (run == memory.runs.begin() || address - std::prev(run)->first >= std::prev(run)->second) + if (run == memory.runs.begin() || address - std::prev(run)->first >= std::prev(run)->second.bytes) return E_UNEXPECTED; - broken.insert(*std::prev(run)); + broken.emplace(std::prev(run)->first, std::prev(run)->second.bytes); } for (const auto& [base, size] : broken) { // Surviving neighbours of a shared view are part of the transaction as well. @@ -1516,7 +1517,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& std::vector made; made.reserve(plan.size()); for (const auto& [address, edit] : plan) { - run_nodes.emplace(address, page_bytes); + run_nodes.emplace(address, PhysicalMemory::Run{page_bytes, 0}); view_nodes.emplace(address, 0); } auto clear_run = [&](ULONG_PTR address, SIZE_T size) { @@ -1525,7 +1526,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& it->second.actual = 0; }; - begin_break(broken); + const ULONG64 stamp = begin_break(); const EndBreak end; DWORD error = ERROR_SUCCESS; for (const auto& [base, size] : broken) { @@ -1537,7 +1538,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& clear_run(base, size); } if (!error) - error = install_alias_plan(plan, run_nodes, share_views, false, made, stats); + error = install_alias_plan(plan, run_nodes, share_views, false, stamp, made, stats); bool restore_failed = false; if (error) { for (const auto address : made) { @@ -1546,11 +1547,11 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& continue; } auto run = memory.runs.extract(address); - clear_run(address, run.mapped()); + clear_run(address, run.mapped().bytes); run_nodes.insert(std::move(run)); } made.clear(); - if (install_alias_plan(plan, run_nodes, share_views, true, made, stats)) + if (install_alias_plan(plan, run_nodes, share_views, true, stamp, made, stats)) restore_failed = true; } // Publish the OS state, including any views left over if Windows refused rollback. @@ -2116,21 +2117,13 @@ ReadFileFn next_read_file; // read_file_committed with lazy commit, kernel32's WriteFileFn kernel_write_file; constexpr int io_attempts = 4; -ULONG64 break_generation() -{ - AcquireSRWLockShared(&remap_window.lock); - const ULONG64 value = remap_window.generation; - ReleaseSRWLockShared(&remap_window.lock); - return value; -} - // Whether [buffer, buffer + bytes) holds a page of a run. Takes memory.mutex, so it returns after the break in progress. bool in_a_run(const void* buffer, DWORD bytes) { const auto first = reinterpret_cast(buffer); const std::lock_guard guard(memory.mutex); const auto run = memory.runs.upper_bound(first); - if (run != memory.runs.begin() && first - std::prev(run)->first < std::prev(run)->second) return true; + if (run != memory.runs.begin() && first - std::prev(run)->first < std::prev(run)->second.bytes) return true; return run != memory.runs.end() && run->first - first < bytes; } diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index 5b5a5fc166..0e14dd3181 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -31,14 +31,15 @@ add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check " # A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint # run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR; the program # sets X2W_XMEM_JOIN_CALLS=1 for `mirror` only). -# ring-edge: a held fault whose break has 63 later breaks is retried; with 64 its break is no longer recorded -# (RemapWindow::kept) and the fault is passed on. +# stamps: a held fault whose break is followed by 63, 64 or 200 later breaks on another page is retried each time +# (the run keeps the stamp of the break that mapped it again); a fault that stays is passed on at once on a run no +# break mapped, and after one retry on a run a break mapped. add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$" mirror) -add_test(NAME xmem_run_break_readers_ring_edge COMMAND xmem_run_break_readers_check "$" ring-edge) +add_test(NAME xmem_run_break_readers_stamps COMMAND xmem_run_break_readers_check "$" stamps) set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs - xmem_run_break_readers_mirror xmem_run_break_readers_ring_edge PROPERTIES TIMEOUT 60) + xmem_run_break_readers_mirror xmem_run_break_readers_stamps PROPERTIES TIMEOUT 60) set_tests_properties(xmem_run_break_readers_default PROPERTIES PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") # Cross-call merge of shared views (merge_with_previous, X2W_XMEM_JOIN_CALLS=1 set by the program): single-page calls diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index b455b076e1..8f7b52bc9f 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -23,11 +23,14 @@ // // A fault whose handler reads the breaks only after a later break on another run has begun (two_runs: break B on a // disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) -// must be retried as well: the handler keeps the ranges of the recent breaks, not only of the last one. Joins across -// calls need X2W_XMEM_JOIN_CALLS=1: main sets it for `mirror` and clears it for every other mode. +// must be retried as well: the page's run keeps the stamp of the break that mapped it again, whatever breaks follow on +// other runs. Joins across calls need X2W_XMEM_JOIN_CALLS=1: main sets it for `mirror` and clears it for every other +// mode. // -// The ring's edge (ring_edge): a held fault in break A whose handler reads the breaks after 63 later breaks is retried; -// after 64 later breaks, A is no longer recorded and the fault is passed on (the reader's own __except catches it). +// Many later breaks (later_breaks): a held fault in break A whose handler runs after 63, 64 or 200 later breaks on +// another page is retried each time (the reader's own __except would catch a fault passed on). A fault that stays +// (persistent_fault, a page of a run made no-access): passed on at once when no break mapped the run, and after one +// retry when one did; a first-chance handler of the test counts the faults. // // A break that begins while x2w_xmem_stable_call's fn runs (break_during_fn): fn itself starts the unmap, waits until // the window is open and queries a page of the run (reserved). stable_call must see the generation change and run fn @@ -39,11 +42,11 @@ // with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. Then a // ReadFile into another such slot, with no break: the lazy-commit ReadFile wrapper still runs inside the run-break one. // -// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process); `ring-edge` runs -// ring_edge with 63 and then 64 later breaks. +// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process); `stamps` runs +// later_breaks with 63, 64 and 200 later breaks, then persistent_fault. // // Usage: xmem_run_break_readers_check -// [control|next-break-control|default|lazy|two-runs|mirror|ring-edge] +// [control|next-break-control|default|lazy|two-runs|mirror|stamps] #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include @@ -644,17 +647,16 @@ __declspec(noinline) bool guarded_read(const volatile std::uint32_t* address, st } } -// The edge of the ring of recorded breaks (RemapWindow::kept, 64). Break A takes apart run 1; a fault in it is held -// before its handler reads the breaks (X2W_XMEM_TEST_HOLD_RETRY). A ends, then `later` breaks follow, each the unmap -// of a lone page mapped by a call of its own (one break per unmap call; the lone page joins no run). The k-th break -// after A is recorded in A's slot when k is a multiple of 64. With 63 later breaks A is still recorded and the fault -// is retried (the reader reads its page); with 64, A's slot holds the newest break, no recorded break holds the -// address, and the handler passes the fault on, which the reader's own __except catches. -void ring_edge_case(const Shim& shim, unsigned char* run1, SIZE_T later, bool retried) +// Break A takes apart run 1; a fault in it is held before its handler looks the page up (X2W_XMEM_TEST_HOLD_RETRY). +// A ends, then `later` breaks follow, each the unmap of a lone page mapped by a call of its own (one break per unmap +// call; the lone page joins no run). Run 1's views keep the stamp of break A, which mapped them again, however many +// breaks follow, so the fault is retried and the reader reads its page. A fault passed on would reach the reader's +// own __except. +void later_breaks_case(const Shim& shim, unsigned char* run1, SIZE_T later) { char name[32], stem[32]; - std::snprintf(name, sizeof(name), "ring_edge_%zu", later); - std::snprintf(stem, sizeof(stem), "ring-%zu", later); + std::snprintf(name, sizeof(name), "later_breaks_%zu", later); + std::snprintf(stem, sizeof(stem), "later-%zu", later); unsigned char* const lone = run1 + 32 * page; SIZE_T count = pages + 1, tokens[pages + 1] = {}; if (!shim.allocate(0x20400000, &count, tokens) || count != pages + 1 || shim.map(run1, pages, tokens) != run1) { @@ -686,17 +688,64 @@ void ring_edge_case(const Shim& shim, unsigned char* run1, SIZE_T later, bool re if (shim.map(lone, 1, nullptr) != lone || raw_state(lone) == MEM_COMMIT) break; ++made; } + const ULONGLONG elapsed = GetTickCount64() - started; + std::printf("%s: %zu later breaks in %llu ms\n", name, made, static_cast(elapsed)); check(made == later, "later_breaks_made", name); - check(outcome.load() == 0 && GetTickCount64() - started < 4000, "handler_still_held_after_the_later_breaks", name); - SetEvent(retry.second); // the handler reads the breaks now + check(outcome.load() == 0 && elapsed < 4000, "handler_still_held_after_the_later_breaks", name); + SetEvent(retry.second); // the handler looks the page up now reader.join(); - if (retried) - check(outcome.load() == 1 && value == 0x56000002u, "fault_retried_with_break_a_still_recorded", name); - else - check(outcome.load() == 2, "fault_passed_on_with_break_a_evicted", name); + check(outcome.load() == 1 && value == 0x56000002u, "fault_retried_after_the_later_breaks", name); shim.map(run1, 7, nullptr); shim.release(pages + 1, tokens); } + +std::atomic first_chance_faults{0}; +ULONG_PTR counted_page = 0; + +// Added after xmem's handler with FirstHandler=1, so it sees each access violation first, also one xmem retries. +LONG CALLBACK count_fault(EXCEPTION_POINTERS* e) +{ + const EXCEPTION_RECORD* record = e->ExceptionRecord; + if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2 && + (record->ExceptionInformation[1] & ~(ULONG_PTR{page} - 1)) == counted_page) + ++first_chance_faults; + return EXCEPTION_CONTINUE_SEARCH; +} + +// A fault that stays: page 2 of a run made no-access, read once by a new thread. On a run no break has mapped (stamp +// 0) the handler passes the fault on at once: one fault. After a break maps the run again (the unmap of page 7), it +// retries once and then passes it on: two faults. Both reach the reader's __except. +void persistent_fault_case(const Shim& shim, unsigned char* run1) +{ + const char* const name = "persistent_fault"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(run1, pages, tokens) != run1) { + check(false, "map_run", name); + return; + } + unsigned char* const target = run1 + 2 * page; + const auto faults = [&](const char* step) { + DWORD old = 0; + if (!check(VirtualProtect(target, page, PAGE_NOACCESS, &old) != FALSE, step, name)) return -1; + counted_page = reinterpret_cast(target); + first_chance_faults = 0; + void* const counter = AddVectoredExceptionHandler(1, count_fault); + std::uint32_t value = 0; + bool read = true; + std::thread reader([&] { read = guarded_read(reinterpret_cast(target), &value); }); + reader.join(); + if (counter) RemoveVectoredExceptionHandler(counter); + VirtualProtect(target, page, PAGE_READWRITE, &old); + const int counted = first_chance_faults.load(); + std::printf("%s: %s -> read %d, first-chance faults %d\n", name, step, read, counted); + return counter && !read ? counted : -1; + }; + check(faults("no_break_mapped_the_run") == 1, "passed_on_at_once_without_a_stamp", name); + check(shim.map(run1 + 7 * page, 1, nullptr) == run1 + 7 * page, "unmap_page_7", name); + check(faults("a_break_mapped_the_run") == 2, "retried_once_with_a_stamp", name); + shim.map(run1, 7, nullptr); + shim.release(pages, tokens); +} } // namespace int main(int argc, char** argv) @@ -708,11 +757,11 @@ int main(int argc, char** argv) const bool lazy = argc > 2 && std::strcmp(argv[2], "lazy") == 0; const bool two_runs = argc > 2 && std::strcmp(argv[2], "two-runs") == 0; const bool mirror = argc > 2 && std::strcmp(argv[2], "mirror") == 0; - const bool ring_edge = argc > 2 && std::strcmp(argv[2], "ring-edge") == 0; + const bool stamps = argc > 2 && std::strcmp(argv[2], "stamps") == 0; if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror && - !ring_edge)) { + !stamps)) { std::printf("usage: xmem_run_break_readers_check " - "[control|next-break-control|default|lazy|two-runs|mirror|ring-edge]\n"); + "[control|next-break-control|default|lazy|two-runs|mirror|stamps]\n"); return 2; } // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. @@ -740,7 +789,7 @@ int main(int argc, char** argv) return 1; } unsigned char* const at = base + page; - if (next_break_control || default_mode || lazy || two_runs || mirror || ring_edge) { + if (next_break_control || default_mode || lazy || two_runs || mirror || stamps) { if (next_break_control) next_break_case(shim, at, false); if (default_mode) default_case(shim, at); if (lazy) { @@ -749,9 +798,11 @@ int main(int argc, char** argv) } if (two_runs) two_runs_case(shim, at); if (mirror) mirror_case(shim, base); - if (ring_edge) { - ring_edge_case(shim, at, 63, true); - ring_edge_case(shim, at + 64 * page, 64, false); + if (stamps) { + later_breaks_case(shim, at, 63); + later_breaks_case(shim, at + 64 * page, 64); + later_breaks_case(shim, at + 128 * page, 200); + persistent_fault_case(shim, at + 192 * page); } VirtualFree(base, 0, MEM_RELEASE); // The default mode's pass line, at the end and only with no failed check (ctest matches it). From 4f7d47defe83efec3f106a3dc12107b77da5938e Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:38:14 +1000 Subject: [PATCH 26/34] xmem: run a failed ReadFile/WriteFile again only on a disk file The ReadFile/WriteFile wrappers ran a synchronous call again after a run break whenever it failed with ERROR_NOACCESS or ERROR_INVALID_USER_BUFFER into or out of a run. On a pipe, socket or console the failed call may already have consumed or sent data, so they now do that only when GetFileType reports FILE_TYPE_DISK, asked only on that failure path. New window case ReadFile_pipe in xmem_run_break_readers: an anonymous pipe with two 4096-byte messages queued, read into the unmapped page. Under Wine (Proton Experimental) the read fails there with ERROR_NOACCESS and leaves both messages queued. Before this change the wrapper waited for the break and ran the read again, which failed as well: under Wine a pipe read into a mapped page of a run fails with ERROR_INVALID_USER_BUFFER even outside a break (into a VirtualAlloc buffer it reads the first message). Now the read fails inside the window; the case also checks that its error is one the wrapper retries on a disk file, so answering at once is not vacuous. --- docs/startup-runtime.md | 11 ++++--- src/xmem_mapped_pages.cpp | 16 +++++----- tests/xmem_run_break_readers_check.cpp | 43 ++++++++++++++++++++++++-- 3 files changed, 57 insertions(+), 13 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8ed158ffad..8bd31797e7 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3205,10 +3205,13 @@ run once, as before. Inside an unmap a kernel copy into or out of a page of that view fails at once. Measured under Wine: `ReadFile` fails with `ERROR_NOACCESS` and leaves the file position as it was, `WriteFile` with `ERROR_INVALID_USER_BUFFER`. The main module's `ReadFile` and `WriteFile` imports therefore -run again, up to 4 times in all, when a synchronous call fails with one of those errors while an -unmap or join was in progress or began or ended around it, and its buffer lies in a view of a -run; they wait for that one to end first. Overlapped I/O (the copy happens at completion), a call -cut short after part of the copy, and I/O from other modules are not covered. +run again, up to 4 times in all, when a synchronous call on a disk file fails with one of those +errors while an unmap or join was in progress or began or ended around it, and its buffer lies in +a view of a run; they wait for that one to end first. A call on a pipe, socket or console is not +run again, because the failed call may already have consumed or sent data (measured under Wine: an +anonymous pipe read inside an unmap fails with `ERROR_NOACCESS` and leaves its data queued). +Overlapped I/O (the copy happens at completion), a call cut short after part of the copy, and I/O +from other modules are not covered. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 7e2460737d..e2ef15eee3 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -2107,9 +2107,11 @@ const int virtual_query_ex_wrapped = [] { // a kernel copy into or out of a page of the run being taken apart fails at once, with no fault to retry. Measured // under Wine (tests/xmem_run_break_readers_check.cpp, ReadFile_import and WriteFile_import): ReadFile fails with // ERROR_NOACCESS and leaves the file position where it was, WriteFile with ERROR_INVALID_USER_BUFFER. A synchronous -// call (no OVERLAPPED) that fails with one of those while a break was in progress, or began or ended around it, and -// whose buffer lies in a run, waits for memory.mutex (the end of the break) and runs again, at most io_attempts times -// in all. A call that fails that way with no break around it, or outside the runs, fails at once as before. +// call (no OVERLAPPED) on a disk file that fails with one of those while a break was in progress, or began or ended +// around it, and whose buffer lies in a run, waits for memory.mutex (the end of the break) and runs again, at most +// io_attempts times in all. A call that fails that way with no break around it, outside the runs, or on a handle that +// is not a disk file, fails at once as before: a pipe, socket or console may have consumed or sent data in the failed +// call, so running it again could lose or repeat that data. GetFileType is asked only on that failure path. // Not covered: overlapped I/O (the copy happens at completion, after the call has returned), a call that a break // cuts short after part of the copy (a short count), and I/O from other modules or through GetProcAddress. using WriteFileFn = BOOL(WINAPI*)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED); @@ -2128,7 +2130,7 @@ bool in_a_run(const void* buffer, DWORD bytes) } template -BOOL io_outside_breaks(const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, const Call& call) +BOOL io_outside_breaks(HANDLE file, const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, const Call& call) { if (overlapped || !buffer || !bytes || mapping_thread || !shared_views_on.load(std::memory_order_acquire)) return call(); for (int attempt = 1;; ++attempt) { @@ -2137,7 +2139,7 @@ BOOL io_outside_breaks(const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, const DWORD error = GetLastError(); const bool broken = (before & 1) || break_generation() != before; if ((error != ERROR_NOACCESS && error != ERROR_INVALID_USER_BUFFER) || !broken || attempt == io_attempts || - !in_a_run(buffer, bytes)) { + GetFileType(file) != FILE_TYPE_DISK || !in_a_run(buffer, bytes)) { SetLastError(error); return FALSE; } @@ -2146,12 +2148,12 @@ BOOL io_outside_breaks(const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, BOOL WINAPI read_file_stable(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) { - return io_outside_breaks(buffer, bytes, overlapped, [&] { return next_read_file(file, buffer, bytes, read, overlapped); }); + return io_outside_breaks(file, buffer, bytes, overlapped, [&] { return next_read_file(file, buffer, bytes, read, overlapped); }); } BOOL WINAPI write_file_stable(HANDLE file, LPCVOID buffer, DWORD bytes, LPDWORD written, LPOVERLAPPED overlapped) { - return io_outside_breaks(buffer, bytes, overlapped, [&] { return kernel_write_file(file, buffer, bytes, written, overlapped); }); + return io_outside_breaks(file, buffer, bytes, overlapped, [&] { return kernel_write_file(file, buffer, bytes, written, overlapped); }); } const int file_io_wrapped = [] { diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index 8f7b52bc9f..d7761cefb7 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -8,8 +8,9 @@ // // Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, this program's VirtualQueryEx import (wrapped by // xmem.dll when it loads with the switch), this program's ReadFile and WriteFile imports (synchronous, into and out -// of the page; wrapped the same way), x2w_local::writable, x2w_startup::measure_placed_buffer and -// x2w_startup::snapshot_samplers. Then io_outside_runs: a ReadFile into a reserved page in no run fails at once. +// of the page; wrapped the same way), a ReadFile from an anonymous pipe into the page (not run again: it fails inside +// the window), x2w_local::writable, x2w_startup::measure_placed_buffer and x2w_startup::snapshot_samplers. Then +// io_outside_runs: a ReadFile into a reserved page in no run fails at once. // // With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run // directly) the three header readers answer inside the window: the check expects that, and fails if they wait. @@ -268,6 +269,41 @@ bool write_file_from(unsigned char* target) return read && std::memcmp(data, target, io_bytes) == 0; } +// An anonymous pipe with two 4096-byte messages queued, read into the page inside the window. The wrapper runs a +// failed call again only on a disk file, so this one fails inside the window instead of waiting for the break. Its +// error must be one the wrapper retries on a disk file, or answering at once would show nothing. Measured under Wine +// (Proton Experimental, 2026-11): ERROR_NOACCESS inside the window, both messages still queued. A pipe read into a +// mapped page of a run fails there even outside a break (ERROR_INVALID_USER_BUFFER), while one into a VirtualAlloc +// buffer reads the first message, so a retry after the break would not have read it either. +struct PipeRead { + BOOL ok = FALSE; + DWORD bytes = 0, error = 0, queued_before = 0, queued_after = 0; + bool second_message = false; // the bytes read are the second message's +} pipe_read; + +bool read_pipe_into(unsigned char* target) +{ + HANDLE r = nullptr, w = nullptr; + if (!CreatePipe(&r, &w, nullptr, 16 * io_bytes)) return false; + unsigned char first[io_bytes], second[io_bytes]; + io_pattern(first); + std::memset(second, 0x5a, io_bytes); + DWORD done = 0; + const bool queued = WriteFile(w, first, io_bytes, &done, nullptr) && done == io_bytes && + WriteFile(w, second, io_bytes, &done, nullptr) && done == io_bytes; + PipeRead& p = pipe_read; + PeekNamedPipe(r, nullptr, 0, nullptr, &p.queued_before, nullptr); + p.ok = queued && ReadFile(r, target, io_bytes, &p.bytes, nullptr); + p.error = p.ok ? 0 : GetLastError(); + PeekNamedPipe(r, nullptr, 0, nullptr, &p.queued_after, nullptr); + p.second_message = p.ok && std::memcmp(target, second, io_bytes) == 0; + CloseHandle(r); + CloseHandle(w); + std::printf("ReadFile from a pipe into the run: ok=%d bytes=%lu error=%lu queued before %lu after %lu, second " + "message %d\n", p.ok, p.bytes, p.error, p.queued_before, p.queued_after, p.second_message); + return p.ok && p.bytes == io_bytes && std::memcmp(target, first, io_bytes) == 0; +} + // A read into a reserved page that is in no run fails at once, as without the wrapper: nothing waits for it. void io_outside_runs() { @@ -832,6 +868,9 @@ int main(int argc, char** argv) }); window_case(shim, at, index++, "ReadFile_import", true, read_file_into); window_case(shim, at, index++, "WriteFile_import", true, write_file_from); + window_case(shim, at, index++, "ReadFile_pipe", false, read_pipe_into); + check(!pipe_read.ok && (pipe_read.error == ERROR_NOACCESS || pipe_read.error == ERROR_INVALID_USER_BUFFER), + "fails_with_an_error_the_wrapper_retries_for_disk_files", "ReadFile_pipe"); io_outside_runs(); } // The header readers: waiting with the export, answering inside the window without it (control). From f19890e4b3a77511e98d30c1f8297ab081e04756 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:43:53 +1000 Subject: [PATCH 27/34] xmem: take the mapping mutex for a DirectStorage copy only when it touches a run x2w_xmem_copy_to_destination held memory.mutex for every copy and judged the destination with the region walk alone, so with xmem.dll loaded the working-set check from #2685 never ran and every copy waited for, and blocked, the mapping calls. With shared views on, a short hold of the mutex now looks up whether the destination or the source overlaps a recorded run. Only then do the check and the copy run under the mutex, as before. Otherwise, and always with shared views off (each page has a view of its own and no unmap takes a neighbour away), both run without it. Both paths check resident read-write pages first and fall back to the region walk, as XCRDAPI does without xmem.dll; resident_read_write moves from xcrdapi.cpp to src/startup_stubs/resident_pages.h, which both include. A run can appear over a range only through a mapping call on those addresses during the copy, which is the caller's race. New x2w_xmem_copy_counts (@24) counts copies made with and without the mutex in the test-controls build; the deployed build returns FALSE. New startup_dstorage_break_window_plain: a VirtualAlloc destination copies without the mutex (0 with, 1 without) and a destination in the run with it (1, 0); startup_dstorage_break_window_views_off: with shared views off a destination in an XMem page copies without it (0, 1). The break-window case and its control are unchanged. --- src/startup_stubs/resident_pages.h | 31 +++++++ src/startup_stubs/xcrdapi.cpp | 32 ++----- src/xmem_mapped_pages.cpp | 86 ++++++++++++++++--- src/xmem_shim.def | 1 + tests/cmake/xmem_page_runs.cmake | 7 ++ tests/startup_dstorage_break_window_check.cpp | 55 +++++++++++- 6 files changed, 171 insertions(+), 41 deletions(-) create mode 100644 src/startup_stubs/resident_pages.h diff --git a/src/startup_stubs/resident_pages.h b/src/startup_stubs/resident_pages.h new file mode 100644 index 0000000000..6cae74c59e --- /dev/null +++ b/src/startup_stubs/resident_pages.h @@ -0,0 +1,31 @@ +#pragma once +// Shared by XCRDAPI's destination check (src/startup_stubs/xcrdapi.cpp) and xmem's copy into a destination +// (x2w_xmem_copy_to_destination, src/xmem_mapped_pages.cpp). +#include +#include + +#include + +namespace x2w_local { +// True when every page of [start, end) is resident and plain read-write: valid in the working set, PAGE_READWRITE +// or PAGE_EXECUTE_READWRITE, no guard bit. One QueryWorkingSetEx per 512 pages, so the cost follows the +// destination's size, not the region's. Reads attributes only; no page is touched. +inline bool resident_read_write(std::uintptr_t start, std::uintptr_t end) noexcept +{ + PSAPI_WORKING_SET_EX_INFORMATION pages[512]; + std::uintptr_t page = start & ~std::uintptr_t{0xFFF}; + while (page < end) { + DWORD count = 0; + for (; count < 512 && page < end; ++count, page += 0x1000) pages[count].VirtualAddress = reinterpret_cast(page); + if (!QueryWorkingSetEx(GetCurrentProcess(), pages, count * sizeof(pages[0]))) return false; + for (DWORD i = 0; i < count; ++i) { + const auto& page_info = pages[i].VirtualAttributes; + const DWORD protect = static_cast(page_info.Win32Protection); + if (!page_info.Valid || page_info.Bad || (protect & PAGE_GUARD) || + ((protect & 0xFF) != PAGE_READWRITE && (protect & 0xFF) != PAGE_EXECUTE_READWRITE)) + return false; + } + } + return true; +} +} // namespace x2w_local diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index ac6df58902..2b3084b88c 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -10,6 +10,7 @@ #include "startup_stubs/trap.h" #include "startup_stubs/profile_zone.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/resident_pages.h" #include "startup_stubs/inflate.h" #include "startup_stubs/dstorage_error_record.h" #include "startup_stubs/dstorage_file_read.h" @@ -175,28 +176,6 @@ static bool has_zlib_header(const unsigned char* bytes, std::size_t size) return true; } -// True when every page of [start, end) is resident and plain read-write: valid in the working set, PAGE_READWRITE -// or PAGE_EXECUTE_READWRITE, no guard bit. One QueryWorkingSetEx per 512 pages, so the cost follows the -// destination's size, not the region's. Reads attributes only; no page is touched. -static bool resident_read_write(std::uintptr_t start, std::uintptr_t end) -{ - PSAPI_WORKING_SET_EX_INFORMATION pages[512]; - std::uintptr_t page = start & ~std::uintptr_t{0xFFF}; - while (page < end) { - DWORD count = 0; - for (; count < 512 && page < end; ++count, page += 0x1000) pages[count].VirtualAddress = reinterpret_cast(page); - if (!QueryWorkingSetEx(GetCurrentProcess(), pages, count * sizeof(pages[0]))) return false; - for (DWORD i = 0; i < count; ++i) { - const auto& page_info = pages[i].VirtualAttributes; - const DWORD protect = static_cast(page_info.Win32Protection); - if (!page_info.Valid || page_info.Bad || (protect & PAGE_GUARD) || - ((protect & 0xFF) != PAGE_READWRITE && (protect & 0xFF) != PAGE_EXECUTE_READWRITE)) - return false; - } - } - return true; -} - // True when every byte of [destination, destination + bytes) is committed and writable, with no guard or // no-access page in between. Nothing is written or touched. Resident read-write pages are accepted from // their working-set attributes; any other page (not resident, copy-on-write, guard, no access) sends the @@ -209,14 +188,15 @@ static bool destination_writable(const void* destination, std::size_t bytes) const auto start = reinterpret_cast(destination); if (!destination || bytes > UINTPTR_MAX - start) return false; x2w_local::commit_lazy(destination, bytes); - if (resident_read_write(start, start + bytes)) return true; + if (x2w_local::resident_read_write(start, start + bytes)) return true; return x2w_local::committed_writable(destination, bytes); } // Copies bytes of data into a plain-memory destination whose whole declared capacity must be writable. With -// xmem.dll loaded, x2w_xmem_copy_to_destination makes the check and the copy under XMem's mapping mutex, so an -// XMem run break (the pages of a shared view unmapped and mapped again) can neither make a mapped destination -// look reserved nor take it away during the copy. Without xmem.dll the check and the copy run here. +// xmem.dll loaded, x2w_xmem_copy_to_destination makes the check and the copy, under XMem's mapping mutex when +// either range overlaps one of its runs, so an XMem run break (the pages of a shared view unmapped and mapped again) +// can neither make a mapped destination look reserved nor take it away during the copy. Without xmem.dll the check +// and the copy run here. // ERROR_SUCCESS; ERROR_NOACCESS when the destination is not writable (nothing written); another error when the // copy faulted. static DWORD copy_to_destination(void* destination, std::size_t capacity, const void* data, std::size_t bytes) diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index e2ef15eee3..fde65d5c3c 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -11,6 +11,7 @@ #include #include #include "startup_stubs/local_log.h" +#include "startup_stubs/resident_pages.h" #include "startup_stubs/profile_zone.h" #include @@ -1892,14 +1893,43 @@ bool copy_guarded(void* destination, const void* data, SIZE_T bytes) noexcept // The longest hold of memory.mutex by a destination copy, and the largest copy, so far (under memory.mutex). double copy_hold_max_ms = 0; SIZE_T copy_bytes_max = 0; +#ifdef X2W_XMEM_TEST_CONTROLS +// Test build only (x2w_xmem_copy_counts): destination copies made under memory.mutex and without it. +volatile LONG64 locked_copies, unlocked_copies; +#endif + +// Whether [address, address + bytes) overlaps a recorded run. Caller holds memory.mutex. +bool overlaps_run(ULONG_PTR address, SIZE_T bytes) +{ + if (!bytes) return false; + const auto run = memory.runs.upper_bound(address); + if (run != memory.runs.begin() && address - std::prev(run)->first < std::prev(run)->second.bytes) return true; + return run != memory.runs.end() && run->first - address < bytes; +} + +// [destination, destination + capacity) committed and writable: resident read-write pages from their working-set +// attributes, any other page through the region walk (as XCRDAPI's destination check without xmem.dll). +bool destination_writable(void* destination, SIZE_T capacity) +{ + const auto start = reinterpret_cast(destination); + if (capacity && destination && capacity <= ~ULONG_PTR{0} - start && + x2w_local::resident_read_write(start, start + capacity)) + return true; + return x2w_local::committed_writable(destination, capacity); +} } // namespace -// The DirectStorage stand-in's copy into a plain-memory destination (XCRDAPI). The check that all of -// [destination, destination + capacity) is committed and writable and the copy of bytes from data both run under -// memory.mutex. Unmapping a page of a shared run takes the whole run away until its other pages are mapped again -// (map_pages_locked, remap_alias_pages), all under that mutex, so neither the check nor the copy can fall into that -// window, and no such window can open while the copy runs. Lazily mapped pages of both ranges are committed first, -// before the mutex is taken: a fault under it is passed on (mapping_thread), not served. +// The DirectStorage stand-in's copy into a plain-memory destination (XCRDAPI): the check that all of +// [destination, destination + capacity) is committed and writable, then the copy of bytes from data. Unmapping a page +// of a shared run takes the whole run away until its other pages are mapped again (map_pages_locked, +// remap_alias_pages, merge_with_previous), all under memory.mutex. With shared views on (shared_views_on), a short +// hold of that mutex first looks up whether either range overlaps a recorded run. If one does, the check and the +// copy run under the mutex, so neither can fall into that window and no such window can open while the copy runs. +// Otherwise, and always with shared views off (every page then has a view of its own, and no unmap takes a +// neighbour away), both run without the mutex, as in XCRDAPI without xmem.dll. A run can then appear over either +// range only through a mapping call on those addresses during the copy, which is the caller's race. Lazily mapped +// pages of both ranges are committed first, before any mutex: a fault under it is passed on (mapping_thread), not +// served. // TRUE when the bytes were copied. FALSE with ERROR_NOACCESS when the destination is not writable (nothing is // written), ERROR_INVALID_ADDRESS when the copy faulted (a source page not readable; part of the destination may be // written), or ERROR_INVALID_PARAMETER for more bytes than capacity or null data. @@ -1913,15 +1943,34 @@ extern "C" BOOL WINAPI x2w_xmem_copy_to_destination(void* destination, SIZE_T ca if (capacity && destination && capacity <= ~ULONG_PTR{0} - start) x2w_xmem_commit_range(destination, capacity); if (bytes) x2w_xmem_commit_range(data, bytes); DWORD error = ERROR_SUCCESS; + bool in_runs = false; + if (shared_views_on.load(std::memory_order_acquire)) { + const std::lock_guard guard(memory.mutex); + in_runs = overlaps_run(start, capacity) || overlaps_run(reinterpret_cast(data), bytes); + } + if (!in_runs) { +#ifdef X2W_XMEM_TEST_CONTROLS + InterlockedIncrement64(&unlocked_copies); +#endif + if (!destination_writable(destination, capacity)) + error = ERROR_NOACCESS; + else if (bytes && !copy_guarded(destination, data, bytes)) + error = ERROR_INVALID_ADDRESS; + SetLastError(error); + return error == ERROR_SUCCESS; + } double held_ms = 0; bool longest = false, largest = false; { const MappingThread marker; const std::lock_guard guard(memory.mutex); +#ifdef X2W_XMEM_TEST_CONTROLS + InterlockedIncrement64(&locked_copies); +#endif LARGE_INTEGER frequency{}, begin{}, end{}; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&begin); - if (!x2w_local::committed_writable(destination, capacity)) + if (!destination_writable(destination, capacity)) error = ERROR_NOACCESS; else if (bytes && !copy_guarded(destination, data, bytes)) error = ERROR_INVALID_ADDRESS; @@ -1946,6 +1995,24 @@ extern "C" BOOL WINAPI x2w_xmem_copy_to_destination(void* destination, SIZE_T ca return error == ERROR_SUCCESS; } +// Test export, counted in the test-controls build only: destination copies (x2w_xmem_copy_to_destination) made under +// memory.mutex because a range overlapped a run, and those made without it. The deployed build returns FALSE with +// ERROR_NOT_SUPPORTED. +extern "C" BOOL WINAPI x2w_xmem_copy_counts(ULONGLONG* locked, ULONGLONG* unlocked) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (!locked || !unlocked) return FALSE; + *locked = static_cast(locked_copies); + *unlocked = static_cast(unlocked_copies); + return TRUE; +#else + (void)locked; + (void)unlocked; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; +#endif +} + // 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 @@ -2122,11 +2189,8 @@ constexpr int io_attempts = 4; // Whether [buffer, buffer + bytes) holds a page of a run. Takes memory.mutex, so it returns after the break in progress. bool in_a_run(const void* buffer, DWORD bytes) { - const auto first = reinterpret_cast(buffer); const std::lock_guard guard(memory.mutex); - const auto run = memory.runs.upper_bound(first); - if (run != memory.runs.begin() && first - std::prev(run)->first < std::prev(run)->second.bytes) return true; - return run != memory.runs.end() && run->first - first < bytes; + return overlaps_run(reinterpret_cast(buffer), bytes); } template diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 78c0607009..5ff7b8500d 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -23,6 +23,7 @@ EXPORTS x2w_xmem_match_section @21 X2WMapPageBatch @22 x2w_xmem_copy_to_destination @23 + x2w_xmem_copy_counts @24 x2w_xmem_map_counts @25 x2w_xmem_stable_call @26 x2w_xmem_alias_counts @27 diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index 0e14dd3181..8e73cd6a7e 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -130,6 +130,13 @@ add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi xmem_s add_test(NAME startup_dstorage_break_window COMMAND startup_dstorage_break_window_check "$" "$") set_tests_properties(startup_dstorage_break_window PROPERTIES TIMEOUT 60) +# Which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared views, a VirtualAlloc destination copies +# without it and one in a run with it (plain); with shared views off, an XMem page destination copies without it. +add_test(NAME startup_dstorage_break_window_plain COMMAND startup_dstorage_break_window_check + "$" "$" plain) +add_test(NAME startup_dstorage_break_window_views_off COMMAND startup_dstorage_break_window_check + "$" "$" views-off) +set_tests_properties(startup_dstorage_break_window_plain startup_dstorage_break_window_views_off PROPERTIES TIMEOUT 60) set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp index 15ce2ba285..3a0ae81432 100644 --- a/tests/startup_dstorage_break_window_check.cpp +++ b/tests/startup_dstorage_break_window_check.cpp @@ -6,7 +6,7 @@ // surviving page reads as reserved. The xmem build with its test controls holds an unmap in that window // (X2W_XMEM_TEST_HOLD_WINDOW=: it sets ".unmapped" and waits up to five seconds for ".release"). // -// usage: startup_dstorage_break_window_check +// usage: startup_dstorage_break_window_check [plain|views-off] // Cases, each against the real stand-in's queue with a memory source: // - no break: a request into a mapped page of the run lands; // - read-only destination: refused, nothing written (the writability check also runs on the xmem path); @@ -15,6 +15,9 @@ // every byte landed. An XCRDAPI that judges the destination with its own VirtualQuery instead refuses inside the // window: "FAIL break window: refused while the run was broken" (the negative control in // tests/cmake/xmem_page_runs.cmake). +// `plain` and `views-off` instead check which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared +// views, a request into a VirtualAlloc destination copies without it and one into the run with it; with +// X2W_XMEM_SHARED_VIEWS unset (`views-off`), a request into an XMem page copies without it as well. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -42,6 +45,7 @@ using VirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); using AllocatePagesFn = BOOL(WINAPI*)(ULONG_PTR, PULONG_PTR, PULONG_PTR); using MapPagesFn = void*(WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); using ScatterFn = BOOL(WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); +using CopyCountsFn = BOOL(WINAPI*)(ULONGLONG*, ULONGLONG*); constexpr SIZE_T page = 65536; constexpr unsigned run_pages = 8; @@ -115,17 +119,59 @@ DWORD WINAPI unmap_one(void* context) unmap->result = unmap->scatter(&unmap->address, 1, nullptr); // no pages: unmap return 0; } + +// One request per row; the change of xmem's copy counts across it names the path the copy took. +int copy_rows(HMODULE xmem, unsigned char* run_page, bool views_off) +{ + const auto counts = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_copy_counts")); + ULONGLONG locked = 0, unlocked = 0; + if (!counts || !counts(&locked, &unlocked)) { + std::printf("FAIL setup: x2w_xmem_copy_counts (needs the test-controls build)\n"); + return 1; + } + const auto row = [&](const char* name, unsigned char* destination, ULONGLONG want_locked, ULONGLONG want_unlocked) { + ULONGLONG locked0 = 0, unlocked0 = 0, locked1 = 0, unlocked1 = 0; + counts(&locked0, &unlocked0); + std::memset(destination, 0xAA, bytes); + long hr = -1; + const bool done = completed_within(submit(destination, bytes, bytes), 5000, hr); + counts(&locked1, &unlocked1); + std::printf("%s: completed %d hr 0x%08lx; copies under the mapping mutex %llu, without it %llu\n", name, done, + static_cast(hr), locked1 - locked0, unlocked1 - unlocked0); + if (!done || hr != 0 || std::memcmp(destination, source, bytes) != 0) fail(name, "the request did not land"); + else if (locked1 - locked0 != want_locked || unlocked1 - unlocked0 != want_unlocked) fail(name, "wrong copy path"); + else std::printf("ok: %s\n", name); + }; + if (views_off) { + row("views off, XMem page destination", run_page, 0, 1); + } else { + auto* plain = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!plain) { + fail("plain destination", "VirtualAlloc"); + } else { + row("plain destination", plain, 0, 1); + VirtualFree(plain, 0, MEM_RELEASE); + } + row("run destination", run_page, 1, 0); + } + if (failures) return 1; + std::printf("dstorage copy paths: %s\n", views_off ? "views off: no mutex" : "the mutex only for the run"); + return 0; +} } // namespace int main(int argc, char** argv) { - if (argc != 3) { - std::printf("usage: startup_dstorage_break_window_check \n"); + const bool plain_mode = argc == 4 && std::strcmp(argv[3], "plain") == 0; + const bool views_off = argc == 4 && std::strcmp(argv[3], "views-off") == 0; + if (argc != 3 && !plain_mode && !views_off) { + std::printf("usage: startup_dstorage_break_window_check " + "[plain|views-off]\n"); return 2; } char hold_name[64]; std::snprintf(hold_name, sizeof(hold_name), "x2w-dstorage-break-window-%lu", GetCurrentProcessId()); - SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", views_off ? nullptr : "1"); SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", nullptr); // the run is mapped by one call; no join is needed SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold_name); @@ -167,6 +213,7 @@ int main(int argc, char** argv) std::printf("FAIL setup: could not map %u pages (err %lu)\n", run_pages, GetLastError()); return 1; } + if (plain_mode || views_off) return copy_rows(xmem, base + 2 * page, views_off); MEMORY_BASIC_INFORMATION run{}; if (!VirtualQuery(base, &run, sizeof(run)) || run.Type != MEM_MAPPED || run.RegionSize < run_pages * page) { std::printf("FAIL setup: the %u pages are not one view (region 0x%zx), so no unmap takes a run apart\n", run_pages, From 302618bd04d12937cf01fc1dfe00f5e69eb9285f Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:46:27 +1000 Subject: [PATCH 28/34] dstorage: log the destination copy's outcome by its error code A copy that x2w_xmem_copy_to_destination did not complete was logged as "copy faulted (source not readable)" for every error but ERROR_NOACCESS. XCRDAPI now names each: ERROR_NOACCESS "destination not writable", ERROR_INVALID_ADDRESS "copy faulted (part of the destination may be written)", ERROR_INVALID_PARAMETER "invalid copy request", any other "copy failed (error N)". The StorageFailure causes are unchanged. The export's comment says that ERROR_INVALID_ADDRESS also covers a destination page that stopped being writable during the copy. New startup_dstorage_break_window_outcomes: the test-controls build's X2W_XMEM_TEST_COPY_ERROR= fails the copy with that code before anything is written; for 998, 487, 87 and 31 the request fails, its destination keeps its bytes and the logged line carries the text above (the check points the standard error handle at a temporary file). --- src/startup_stubs/xcrdapi.cpp | 20 ++++- src/xmem_mapped_pages.cpp | 14 +++- tests/cmake/xmem_page_runs.cmake | 6 +- tests/startup_dstorage_break_window_check.cpp | 75 ++++++++++++++++++- 4 files changed, 106 insertions(+), 9 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 2b3084b88c..74c33c8061 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -197,8 +197,8 @@ static bool destination_writable(const void* destination, std::size_t bytes) // either range overlaps one of its runs, so an XMem run break (the pages of a shared view unmapped and mapped again) // can neither make a mapped destination look reserved nor take it away during the copy. Without xmem.dll the check // and the copy run here. -// ERROR_SUCCESS; ERROR_NOACCESS when the destination is not writable (nothing written); another error when the -// copy faulted. +// ERROR_SUCCESS; ERROR_NOACCESS when the destination is not writable (nothing written); ERROR_INVALID_ADDRESS when +// the copy faulted (part of the destination may be written); ERROR_INVALID_PARAMETER for an invalid request. static DWORD copy_to_destination(void* destination, std::size_t capacity, const void* data, std::size_t bytes) { using CopyToDestination = BOOL(WINAPI*)(void*, SIZE_T, const void*, SIZE_T); @@ -212,6 +212,19 @@ static DWORD copy_to_destination(void* destination, std::size_t capacity, const return ERROR_SUCCESS; } +// The outcome logged for a copy that copy_to_destination did not complete, by its error. text holds the last case. +static const char* copy_outcome(DWORD error, char (&text)[40]) +{ + switch (error) { + case ERROR_NOACCESS: return "destination not writable"; + case ERROR_INVALID_ADDRESS: return "copy faulted (part of the destination may be written)"; + case ERROR_INVALID_PARAMETER: return "invalid copy request"; + default: + std::snprintf(text, sizeof(text), "copy failed (error %lu)", static_cast(error)); + return text; + } +} + // Return the exact queued requests that continue this stream in this submission, in queue order. // Status entries and requests for unrelated files are skipped. In the same file, any non-matching // size, non-consecutive offset, or submission boundary ends the continuation chain (Refs #1136, #1144, #1198, #1214). @@ -742,6 +755,7 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR const unsigned page_offset = static_cast(*reinterpret_cast(request + 0x10) & 0xFFFF); const u64 known = 1 | (0xFull << 1) | (1ull << 21) | 0x400000; const char* outcome = "done"; + char copy_failure[40]; // copy_outcome's text for an error it does not name StorageFailure failure = StorageFailure::other; // the heartbeat's cause, if the request fails std::vector packed, output; const unsigned char* input = nullptr; @@ -931,7 +945,7 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR // byte is written, so a refusal leaves every page untouched. const DWORD copied = copy_to_destination(destination, destination_capacity, data, decode_length); if (copied != ERROR_SUCCESS) { - outcome = copied == ERROR_NOACCESS ? "destination not writable" : "copy faulted (source not readable)"; + outcome = copy_outcome(copied, copy_failure); failure = copied == ERROR_NOACCESS ? StorageFailure::destination_not_writable : StorageFailure::other; data = nullptr; written = false; diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index fde65d5c3c..59214c2776 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1931,14 +1931,24 @@ bool destination_writable(void* destination, SIZE_T capacity) // pages of both ranges are committed first, before any mutex: a fault under it is passed on (mapping_thread), not // served. // TRUE when the bytes were copied. FALSE with ERROR_NOACCESS when the destination is not writable (nothing is -// written), ERROR_INVALID_ADDRESS when the copy faulted (a source page not readable; part of the destination may be -// written), or ERROR_INVALID_PARAMETER for more bytes than capacity or null data. +// written), ERROR_INVALID_ADDRESS when the copy faulted (a source page not readable, or a destination page that +// stopped being writable during the copy; part of the destination may be written), or ERROR_INVALID_PARAMETER for +// more bytes than capacity or null data. +// Test build only: X2W_XMEM_TEST_COPY_ERROR= fails every copy with that error before anything is written +// (startup_dstorage_break_window_check outcomes: XCRDAPI's logged outcome per error). extern "C" BOOL WINAPI x2w_xmem_copy_to_destination(void* destination, SIZE_T capacity, const void* data, SIZE_T bytes) { if (bytes > capacity || (bytes && !data)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } +#ifdef X2W_XMEM_TEST_CONTROLS + char forced[16]; + if (GetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", forced, sizeof(forced)) && forced[0]) { + SetLastError(static_cast(std::strtoul(forced, nullptr, 10))); + return FALSE; + } +#endif const auto start = reinterpret_cast(destination); if (capacity && destination && capacity <= ~ULONG_PTR{0} - start) x2w_xmem_commit_range(destination, capacity); if (bytes) x2w_xmem_commit_range(data, bytes); diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index 8e73cd6a7e..db9220e9f0 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -136,7 +136,11 @@ add_test(NAME startup_dstorage_break_window_plain COMMAND startup_dstorage_break "$" "$" plain) add_test(NAME startup_dstorage_break_window_views_off COMMAND startup_dstorage_break_window_check "$" "$" views-off) -set_tests_properties(startup_dstorage_break_window_plain startup_dstorage_break_window_views_off PROPERTIES TIMEOUT 60) +# XCRDAPI's logged outcome for each copy error, forced by the test-controls build (X2W_XMEM_TEST_COPY_ERROR). +add_test(NAME startup_dstorage_break_window_outcomes COMMAND startup_dstorage_break_window_check + "$" "$" outcomes) +set_tests_properties(startup_dstorage_break_window_plain startup_dstorage_break_window_views_off + startup_dstorage_break_window_outcomes PROPERTIES TIMEOUT 60) set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp index 3a0ae81432..9fc6467d43 100644 --- a/tests/startup_dstorage_break_window_check.cpp +++ b/tests/startup_dstorage_break_window_check.cpp @@ -6,7 +6,8 @@ // surviving page reads as reserved. The xmem build with its test controls holds an unmap in that window // (X2W_XMEM_TEST_HOLD_WINDOW=: it sets ".unmapped" and waits up to five seconds for ".release"). // -// usage: startup_dstorage_break_window_check [plain|views-off] +// usage: startup_dstorage_break_window_check +// [plain|views-off|outcomes] // Cases, each against the real stand-in's queue with a memory source: // - no break: a request into a mapped page of the run lands; // - read-only destination: refused, nothing written (the writability check also runs on the xmem path); @@ -18,6 +19,9 @@ // `plain` and `views-off` instead check which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared // views, a request into a VirtualAlloc destination copies without it and one into the run with it; with // X2W_XMEM_SHARED_VIEWS unset (`views-off`), a request into an XMem page copies without it as well. +// `outcomes` forces each copy error in turn (the test-controls build's X2W_XMEM_TEST_COPY_ERROR) and checks the +// outcome XCRDAPI logs for the request: the DLLs log to the standard error handle, which this mode points at a +// temporary file. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -158,15 +162,79 @@ int copy_rows(HMODULE xmem, unsigned char* run_page, bool views_off) std::printf("dstorage copy paths: %s\n", views_off ? "views off: no mutex" : "the mutex only for the run"); return 0; } + +// Waits up to two seconds for text to appear in the log file (the request's line follows its completion). +bool logged(HANDLE log, const char* text) +{ + static char all[1 << 16]; + for (int waited = 0; waited <= 2000; waited += 20) { + DWORD size = 0; + SetFilePointer(log, 0, nullptr, FILE_BEGIN); + if (ReadFile(log, all, sizeof(all) - 1, &size, nullptr)) { + all[size] = 0; + if (std::strstr(all, text)) return true; + } + Sleep(20); + } + return false; +} + +int outcome_rows() +{ + char dir[MAX_PATH], path[MAX_PATH]; + GetTempPathA(sizeof(dir), dir); + std::snprintf(path, sizeof(path), "%sx2w-dstorage-outcomes-%lu.log", dir, GetCurrentProcessId()); + const HANDLE log = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + auto* plain = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (log == INVALID_HANDLE_VALUE || !plain) { + std::printf("FAIL setup: log file or destination\n"); + return 1; + } + const HANDLE saved = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_ERROR_HANDLE, log); + const struct { + DWORD error; + const char* text; + } rows[] = { + {ERROR_NOACCESS, "-> destination not writable"}, + {ERROR_INVALID_ADDRESS, "-> copy faulted (part of the destination may be written)"}, + {ERROR_INVALID_PARAMETER, "-> invalid copy request"}, + {ERROR_GEN_FAILURE, "-> copy failed (error 31)"}, + }; + for (const auto& row : rows) { + char code[16]; + std::snprintf(code, sizeof(code), "%lu", row.error); + SetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", code); + std::memset(plain, 0xAA, bytes); + long hr = 0; + const bool done = completed_within(submit(plain, bytes, bytes), 5000, hr); + SetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", nullptr); + const bool found = logged(log, row.text); + std::printf("error %lu: completed %d hr 0x%08lx, logged \"%s\" %d\n", row.error, done, + static_cast(hr), row.text, found); + if (!done || hr == 0) fail(row.text, "the request did not fail"); + else if (!filled(plain, 0xAA, bytes)) fail(row.text, "bytes were written"); + else if (!found) fail(row.text, "outcome not logged"); + else std::printf("ok: error %lu logged %s\n", row.error, row.text); + } + SetStdHandle(STD_ERROR_HANDLE, saved); + CloseHandle(log); + VirtualFree(plain, 0, MEM_RELEASE); + if (failures) return 1; + std::printf("dstorage outcomes: one text per copy error\n"); + return 0; +} } // namespace int main(int argc, char** argv) { const bool plain_mode = argc == 4 && std::strcmp(argv[3], "plain") == 0; const bool views_off = argc == 4 && std::strcmp(argv[3], "views-off") == 0; - if (argc != 3 && !plain_mode && !views_off) { + const bool outcomes = argc == 4 && std::strcmp(argv[3], "outcomes") == 0; + if (argc != 3 && !plain_mode && !views_off && !outcomes) { std::printf("usage: startup_dstorage_break_window_check " - "[plain|views-off]\n"); + "[plain|views-off|outcomes]\n"); return 2; } char hold_name[64]; @@ -204,6 +272,7 @@ int main(int argc, char** argv) status = static_cast(status_pointer); queue = static_cast(queue_pointer); for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast(i % 251 + 1); + if (outcomes) return outcome_rows(); // Eight physical pages mapped as one run at the start of a startup reservation (as xmem_page_runs_check.py). auto* whole = static_cast(virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); From 0cfdd607ed985178e4ab4a73201030a173710164 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:50:14 +1000 Subject: [PATCH 29/34] docs, ci: move the page-run note to docs/experiments/ and add the fixtures to the pr preset docs/experiments.md is main's again. Its xmem_placeholder_split paragraph moves unchanged to docs/experiments/xmem-page-runs.md, with short sections for the split-first, cross-call join, run-break and DirectStorage fixtures and the X2W_XMEM_JOIN_CALLS switch, each with what was measured under Wine and its ctest command. The README row keeps its -R line and links the note next to the command. The pr build preset also builds xmem_shim_test_controls, the two XCRDAPI builds and the fixtures' check programs, including xmem_page_runs_device_check and linear_buffer_backing_check. Its test include adds the xmem_run_break_readers, xmem_cross_call_merge, xmem_placeholder_split, xmem_map_split_first and startup_dstorage_break_window families, xmem_page_runs_device(_join)_warp and linear_buffer_backing_share_warp: 28 tests that the pr include did not match before, every add_test of tests/cmake/xmem_page_runs.cmake plus the two named outside it. startup_run_sh stays out: it skips on Windows, and the Linux Python job runs tests/startup_run_sh_check.py. --- CMakePresets.json | 8 +++- README.md | 2 +- docs/experiments.md | 2 - docs/experiments/xmem-page-runs.md | 63 ++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 docs/experiments/xmem-page-runs.md diff --git a/CMakePresets.json b/CMakePresets.json index 19a646b004..f782f2316e 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,7 +29,11 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", - "startup_indirect_dispatch", "startup_indirect_draw_indexed" + "startup_indirect_dispatch", "startup_indirect_draw_indexed", + "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", + "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", + "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", + "xmem_page_runs_device_check", "linear_buffer_backing_check" ] }, { "name": "release", "configurePreset": "release" } @@ -42,7 +46,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp)$" } } }, diff --git a/README.md b/README.md index fc23d1a64f..8206517494 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | PE 32/64-bit base fixups against Windows | `ctest --preset dev --no-tests=error -R '^cpu_native_highlow$' -V` · [scope and controls](docs/experiments.md#highlow-and-mixed-width-base-relocations) | | [CPU counted cache-line zero loops](docs/experiments.md#counted-cache-line-zero-loops) | `ctest --preset release --no-tests=error -R '^cpu_counted_clzero$' -V` | | [Experimental startup stand-ins and debugger (trap-by-default DLLs)](docs/startup-runtime.md) | `ctest --preset release --no-tests=error -R '^startup_stubs$' -V` | -| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` | +| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` · [page runs](docs/experiments/xmem-page-runs.md) | | [Sample a texture by address in a translated draw](docs/startup-runtime.md#textures-published-by-address-device-slot-70) | `ctest --preset release --no-tests=error -R '^startup_address_console_' -V` | | [Desktop audio render sink and its three-case fixture (WASAPI)](docs/experiments.md#desktop-audio-render-sink) | `ctest --preset release --no-tests=error -R '^startup_audio_output$' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 1813796a36..f9fb98d4ec 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10494,8 +10494,6 @@ Command queue slot 31 resolves 64 KiB pool pages against the views XMem currentl The `xmem_page_batch_inflight_{warp,hardware}` fixture holds a submitted GPU read behind an unsignaled fence, remaps the same virtual address, then releases the fence. The held read must see the old pattern. A second read binds the new section, writes a different pattern through its CPU pool after recording, and checks every byte across a 64 KiB boundary. Run `ctest --preset release --no-tests=error -R '^xmem_page_batch_inflight_' -V`. -`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. - `vm_page_provenance_warp` and `vm_page_provenance_hardware` test the source side independently. Two pagefile sections hold distinct data and are mapped into adjacent CPU addresses in reverse creation order. D3D12 reopens those same sections as heaps. The test copies a 4 KiB span centered on the page boundary into a GPU buffer using the logical page order, then compares its readback with the two expected token patterns. It writes new data through the CPU aliases and reads the GPU buffer again before uploading, which must still return the old data. A second upload must produce all the updated words. The tests skip (77) if the requested adapter or section-backed D3D12 buffers are unavailable. [Opening a D3D12 heap from a file mapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping) Run `ctest --preset dev --no-tests=error -R '^vm_page_provenance_' -V`. diff --git a/docs/experiments/xmem-page-runs.md b/docs/experiments/xmem-page-runs.md new file mode 100644 index 0000000000..476c7b7657 --- /dev/null +++ b/docs/experiments/xmem-page-runs.md @@ -0,0 +1,63 @@ +# XMem page runs: placeholder splits, joins and run breaks + +Refs [#2911](https://github.com/R0Y00/Xbox2Windows/pull/2911). The fixtures below cover the shim's mapping of +physical pages into XMem reservations with shared views (`X2W_XMEM_SHARED_VIEWS=1`). The results quoted here were +measured under Wine (Proton Experimental, November 2026) on Linux x64, with a clang-cl cross build and each CTest +entry's command run through Wine in one prefix. They are not Windows results. The D3D12 fixtures at the end have no +result there. + +## Placeholder split for queue slot 31 + +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. + +## Split before map + +`xmem_map_split_first` maps eight single pages with `XMemMapPhysicalPages`, each into the middle of the +reservation's placeholder. xmem splits first and maps once, so the eight pages take eight `MapViewOfFile3` attempts +and eight splits, and an exact placeholder left by an unmap is mapped without a split. `xmem_map_split_first_control` +runs the old map-first order in the test-controls build (`X2W_XMEM_TEST_MAP_FIRST=1`) and must measure 16 attempts. +`xmem_map_split_first_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must measure +8. Measured under Wine: 8, 16 and 8. Run `ctest --preset dev --no-tests=error -R '^xmem_map_split_first' -V`. + +## Joins across mapping calls + +With shared views, the pages of one call that are adjacent slots of one section share a view. A call joins the run +that ends at its address only with `X2W_XMEM_JOIN_CALLS=1`, which counts only with shared views on. It is off by +default; `tools/startup/run.sh` sets it, and `tools/startup/run.ps1 -LazyMemory` does not. `xmem_cross_call_merge` +checks the joined layout (32 single-page calls on consecutive slots give one view of 32 pages) and the cases around +it. `xmem_cross_call_merge_no_join` checks that the deployed shim with shared views and no join switch keeps a view +per call (32 views). `xmem_cross_call_merge_control` turns the merge off in the test-controls build +(`X2W_XMEM_TEST_NO_MERGE=1`) and must also show 32 views; `xmem_cross_call_merge_deployed` sets that switch for the +deployed shim, which ignores it and joins. All passed under Wine. Run +`ctest --preset dev --no-tests=error -R '^xmem_cross_call_merge' -V`. + +## Run breaks and the fault handler + +Unmapping a page of a shared view unmaps the whole view and maps its other pages again; a join and a slot 31 batch do +the same for the runs they change. `xmem_run_break_readers` holds that window open (the test-controls build's +`X2W_XMEM_TEST_HOLD_WINDOW`) and checks that each reader either waits for it or, for a pipe `ReadFile`, fails inside +it without being run again (under Wine with `ERROR_NOACCESS`, both queued messages kept). The access-violation +handler retries a fault on a page whose view was mapped inside a break, once per break and thread. +`xmem_run_break_readers_stamps` holds a fault's handler while 63, 64 and 200 later breaks run on another page; each +fault is retried (under Wine the later breaks took 3, 4 and 10 ms). In the same mode, a page made no-access faults +once on a run no break has mapped (passed on at once) and twice after a break mapped it (one retry), counted by a +first-chance handler of the test. Run `ctest --preset dev --no-tests=error -R '^xmem_run_break_readers' -V`. + +## DirectStorage copies into runs + +`startup_dstorage_break_window` submits a memory-source request into a page of a run while an unmap holds the run +apart: the request must not complete during the 1000 ms hold, then lands; its control, an XCRDAPI that judges the +destination with its own query, refuses inside the window. The copy takes xmem's mapping mutex only when the +destination or source overlaps a run: `startup_dstorage_break_window_plain` measures a `VirtualAlloc` destination +copied without it and a run destination with it, and `startup_dstorage_break_window_views_off` an XMem page +destination copied without it when shared views are off (`x2w_xmem_copy_counts`, test-controls build). +`startup_dstorage_break_window_outcomes` forces each copy error (`X2W_XMEM_TEST_COPY_ERROR`) and checks the outcome +XCRDAPI logs for it. All passed under Wine. Run +`ctest --preset dev --no-tests=error -R '^startup_dstorage_break_window' -V`. + +## D3D12 fixtures (not run here) + +`xmem_page_runs_device_warp`, `xmem_page_runs_device_join_warp` and `linear_buffer_backing_share_warp` check view +boundaries through D3D12 placed resources. They need D3D12 with WARP, which the Wine prefix above does not provide: +they fail there (`linear_buffer_backing_share_warp`: "WARP device not created"), so this note has no result for +them. From f9391ccaf509e99a43e1e5dc65d400becd80cc72 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:11:24 +1000 Subject: [PATCH 30/34] gh #2911 review round 1: state the placeholder fallback's limit for MEM_REPLACE_PLACEHOLDER allocations xmem_placeholder_split_partial now checks that the two pages start as one allocation, prints where each page's allocation starts after the batch, and asserts that the first page is still one reserved page whose allocation base is its own address. Under Wine (Proton Experimental) the batch's per-page retry releases the reserved first page and the rollback unmaps it again, which cuts that page out of the caller's allocation: the committed page's allocation starts at +0 pages before the batch and at +1 after it. The fallback cannot tell a reserved page of a private allocation made with VirtualAlloc2(MEM_REPLACE_PLACEHOLDER) from a placeholder, because Wine does not refuse the release for that kind of allocation. The comment above alias_placeholders said the OS refuses the release for a plain reservation. That holds for VirtualAlloc and not for this kind, so it now names both and the limit, and so does the note in docs/experiments/xmem-page-runs.md. --- docs/experiments/xmem-page-runs.md | 2 +- src/xmem_mapped_pages.cpp | 11 ++++++--- tests/xmem_placeholder_split_check.cpp | 34 +++++++++++++++++++++----- 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/docs/experiments/xmem-page-runs.md b/docs/experiments/xmem-page-runs.md index 476c7b7657..148b3fb9b2 100644 --- a/docs/experiments/xmem-page-runs.md +++ b/docs/experiments/xmem-page-runs.md @@ -8,7 +8,7 @@ result there. ## Placeholder split for queue slot 31 -`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. Limit: the fallback cannot tell a reserved page of a private allocation made with `VirtualAlloc2(MEM_REPLACE_PLACEHOLDER)` from a placeholder, because Wine does not refuse the release for that kind of allocation. After the refused view, the batch retries each page on its own and releases the reserved first page, which cuts it out of the caller's allocation: under Wine the committed page's allocation then starts one page later. The fixture prints where that allocation starts and asserts only that the first page is still one reserved page at its own address. Where the OS reports the bit, the fallback is not used. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. ## Split before map diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 59214c2776..7dfde73a20 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1379,10 +1379,13 @@ bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) { // VirtualQuery alone cannot distinguish a reserved private allocation from a placeholder, and on Windows // PRESERVE_PLACEHOLDER can silently release that allocation. Where the region query does not report the bit - // and the OS refuses that release for a plain reservation (placeholder_fallback), reserved regions may be - // offered. Every region the view covers must be reserved, not only the first one of each allocation: Wine - // (Proton Experimental, 2026-11) released a private allocation made in place of a placeholder together with - // its committed second page, and the view then replaced that page (xmem_placeholder_split_partial). + // and the OS refuses that release for a reservation made by VirtualAlloc (placeholder_fallback), reserved + // regions may be offered. Every region the view covers must be reserved, not only the first one of each + // allocation: Wine (Proton Experimental, 2026-11) released a private allocation made in place of a placeholder + // (VirtualAlloc2 MEM_REPLACE_PLACEHOLDER) together with its committed second page, and the view then replaced + // that page (xmem_placeholder_split_partial). Limit: Wine does not refuse the release for that kind of + // allocation either, so its reserved pages are still offered, and releasing one cuts it out of the caller's + // allocation. const bool fallback = placeholder_fallback(); const auto end = address + bytes; while (address < end) { diff --git a/tests/xmem_placeholder_split_check.cpp b/tests/xmem_placeholder_split_check.cpp index 092a5f2ecc..e1ce8d7dae 100644 --- a/tests/xmem_placeholder_split_check.cpp +++ b/tests/xmem_placeholder_split_check.cpp @@ -10,7 +10,8 @@ // xmem_placeholder_split_check partial test-controls build with shared views: a two-page view over a // private reservation whose second page is committed is refused // by the region walk (x2w_xmem_alias_counts), and the committed -// page keeps its bytes +// page keeps its bytes; prints where its allocation starts after +// the batch (the limit in alias_placeholders) // control, deployed and partial exit 77 where the OS reports the bit, because there the fallback is never used. Each // mode sets or clears X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK itself, so an inherited value cannot change the result. #include @@ -52,6 +53,12 @@ MEMORY_BASIC_INFORMATION query(const BYTE* pointer) return info; } +// Where the region's allocation starts, in pages from `at` (negative: before it). +long long base_pages(const MEMORY_BASIC_INFORMATION& info, const BYTE* at) +{ + return (static_cast(info.AllocationBase) - at) / static_cast(page_bytes); +} + // partial: two pages of the reservation become a private reservation whose second page is committed and tagged. Its // first region is reserved, so a check of that region alone would accept the whole two-page view. int partial_case(HMODULE xmem, BYTE* pool, decltype(&X2WMapPageBatch) batch_map) @@ -67,6 +74,8 @@ int partial_case(HMODULE xmem, BYTE* pool, decltype(&X2WMapPageBatch) batch_map) "commit the second page")) return 1; std::memset(piece + page_bytes, 0x7a, page_bytes); + const MEMORY_BASIC_INFORMATION before = query(piece + page_bytes); + if (!require(before.AllocationBase == piece, "the two pages are one allocation")) return 1; const X2WPageRange two{0, 1, 2}; const X2WPageBatch onto_partial{reinterpret_cast(piece), 1, &two}; const HRESULT hr = batch_map(1, &onto_partial, reinterpret_cast(pool), pool_pages, 0, nullptr); @@ -76,16 +85,29 @@ int partial_case(HMODULE xmem, BYTE* pool, decltype(&X2WMapPageBatch) batch_map) "releases tried %llu; after: state 0x%lx type 0x%lx, then state 0x%lx type 0x%lx byte 0x%02x\n", static_cast(hr), refusals1 - refusals0, splits1 - splits0, first.State, first.Type, second.State, second.Type, second.State == MEM_COMMIT ? piece[page_bytes] : 0u); + std::printf("allocation base in pages from the first page: first page %+lld (region %llu pages); committed page " + "%+lld before the batch, %+lld after\n", + base_pages(first, piece), static_cast(first.RegionSize / page_bytes), + base_pages(before, piece), base_pages(second, piece)); // The walk refuses the two-page view. The batch then retries each page on its own (install_alias_plan): the - // reserved page alone may be released and mapped, and the rollback unmaps it again; the committed page alone is - // refused. A walk that checks only the first region of each allocation accepts the view, and under Wine the + // reserved page alone is accepted, released and mapped, and the rollback unmaps it again; the committed page alone + // is refused. A walk that checks only the first region of each allocation accepts the view, and under Wine the // release then succeeds and the view replaces the committed page (measured 2026-11-27 before the fix). + // Limit: the fallback cannot tell a reserved page of a private allocation made in place of a placeholder + // (MEM_REPLACE_PLACEHOLDER) from a placeholder. Under Wine the per-page release cuts that page out of the caller's + // allocation: afterwards the committed page's allocation starts one page later (measured 2026-11-27). The row + // asserts only that the first page is still one reserved page with its own address as its allocation base, and + // prints where the committed page's allocation starts. if (!require(refusals1 - refusals0 >= 1, "the region walk refuses the two-page view") || !require(FAILED(hr), "the partly committed target is refused") || - !require(first.State == MEM_RESERVE && second.State == MEM_COMMIT && second.Type == MEM_PRIVATE && - piece[page_bytes] == 0x7a && piece[2 * page_bytes - 1] == 0x7a, - "the committed page keeps its bytes and the reserved page stays reserved")) + !require(first.State == MEM_RESERVE && first.AllocationBase == piece && first.RegionSize == page_bytes && + second.State == MEM_COMMIT && second.Type == MEM_PRIVATE && piece[page_bytes] == 0x7a && + piece[2 * page_bytes - 1] == 0x7a, + "the committed page keeps its bytes and the first page stays one reserved page at its address")) return 1; + if (second.AllocationBase != piece) + std::puts("limit: the per-page retry cut the reserved page out of the caller's allocation " + "(docs/experiments/xmem-page-runs.md)"); std::puts("partial: a view over a reserved and a committed page was refused; the committed page kept its bytes"); return 0; } From f4cc29004648c055309666d6b2f8f027e63ebc07 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:12:05 +1000 Subject: [PATCH 31/34] gh #2911 review round 1: say which half of the pipe retry reason is measured docs/startup-runtime.md gave "the failed call may already have consumed or sent data" as the reason a pipe, socket or console call is not run again, followed by a Wine measurement that shows the data was left queued. It now states the Wine result on its own and says that whether Windows consumes or sends data in such a failed call is unmeasured. The comment above the ReadFile/WriteFile wrappers gets the same sentence. --- docs/startup-runtime.md | 5 +++-- src/xmem_mapped_pages.cpp | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8bd31797e7..ac36996e09 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3208,8 +3208,9 @@ with `ERROR_INVALID_USER_BUFFER`. The main module's `ReadFile` and `WriteFile` i run again, up to 4 times in all, when a synchronous call on a disk file fails with one of those errors while an unmap or join was in progress or began or ended around it, and its buffer lies in a view of a run; they wait for that one to end first. A call on a pipe, socket or console is not -run again, because the failed call may already have consumed or sent data (measured under Wine: an -anonymous pipe read inside an unmap fails with `ERROR_NOACCESS` and leaves its data queued). +run again. Under Wine an anonymous pipe read inside an unmap fails with `ERROR_NOACCESS` and leaves +its data queued (measured). Whether Windows consumes or sends any data in a call that fails this way +is unmeasured, and if it does, running the call again would lose or repeat that data. Overlapped I/O (the copy happens at completion), a call cut short after part of the copy, and I/O from other modules are not covered. diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 7dfde73a20..de4dee155d 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -2191,7 +2191,8 @@ const int virtual_query_ex_wrapped = [] { // around it, and whose buffer lies in a run, waits for memory.mutex (the end of the break) and runs again, at most // io_attempts times in all. A call that fails that way with no break around it, outside the runs, or on a handle that // is not a disk file, fails at once as before: a pipe, socket or console may have consumed or sent data in the failed -// call, so running it again could lose or repeat that data. GetFileType is asked only on that failure path. +// call, so running it again could lose or repeat that data. Under Wine a pipe read that fails this way leaves its data +// queued; whether Windows consumes it is unmeasured. GetFileType is asked only on that failure path. // Not covered: overlapped I/O (the copy happens at completion, after the call has returned), a call that a break // cuts short after part of the copy (a short count), and I/O from other modules or through GetProcAddress. using WriteFileFn = BOOL(WINAPI*)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED); From 863c04596735aa3555ea264e476b51836c680465 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:13:42 +1000 Subject: [PATCH 32/34] gh #2911 review round 1: describe the readers fixture's handler by its stamp lookup The header of tests/xmem_run_break_readers_check.cpp and the comments in next_break_case, two_runs_case and mirror still said the handler "reads the generation" or "the breaks", the wording from when it looked breaks up in a history of recent ones. They now say what it does: it finds the page mapped again and looks up the stamp the break left on the run. The next-break-control line printed by the fixture and one comment in tests/cmake/xmem_page_runs.cmake follow. Comments and one log line only. --- tests/cmake/xmem_page_runs.cmake | 2 +- tests/xmem_run_break_readers_check.cpp | 29 +++++++++++++------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake index db9220e9f0..fe8e94aa56 100644 --- a/tests/cmake/xmem_page_runs.cmake +++ b/tests/cmake/xmem_page_runs.cmake @@ -28,7 +28,7 @@ add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_r # the readers' output buffer in a mapped slot not yet committed. add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) -# A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint +# A fault handler that looks the page up after a later break on another run has begun: a second unmap on a disjoint # run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR; the program # sets X2W_XMEM_JOIN_CALLS=1 for `mirror` only). # stamps: a held fault whose break is followed by 63, 64 or 200 later breaks on another page is retried each time diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp index d7761cefb7..3f1767ab66 100644 --- a/tests/xmem_run_break_readers_check.cpp +++ b/tests/xmem_run_break_readers_check.cpp @@ -17,12 +17,13 @@ // // Then a page that faults in two breaks in a row (retry_remapped_page): a thread faults on a page of a run taken // apart by break A, and the test build's X2W_XMEM_TEST_HOLD_RETRY holds the handler until break A has ended, so the -// handler reads the generation after it; the thread is retried and reads its page. Break B then takes the same page -// apart, and the thread faults on it again: that fault must be retried as well (a different break). With -// `next-break-control` the handler is not held, so it reads break A while A is open: that order passes even when -// the handler names the breaks wrongly, which shows the hold is what this case depends on. +// handler finds the page mapped again and looks up the stamp break A left on the run; the thread is retried and reads +// its page. Break B then takes the same page apart and stamps the run again, and the thread faults on it again: that +// fault must be retried as well (a different stamp). With `next-break-control` the handler is not held, so it sees +// break A in progress and waits for memory.mutex before the lookup: that order passes even when the handler's check +// of a fault after its break has ended is wrong, which shows the hold is what this case depends on. // -// A fault whose handler reads the breaks only after a later break on another run has begun (two_runs: break B on a +// A fault whose handler looks the page up only after a later break on another run has begun (two_runs: break B on a // disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) // must be retried as well: the page's run keeps the stamp of the break that mapped it again, whatever breaks follow on // other runs. Joins across calls need X2W_XMEM_JOIN_CALLS=1: main sets it for `mirror` and clears it for every other @@ -490,7 +491,7 @@ struct Events { }; // Break A: unmap page 7 of a run of eight; break B: unmap page 6 of what is left, [0, 7). The reader's page 2 is in -// both. hold_retry: the handler for the fault in break A reads the break only after A has ended. +// both. hold_retry: the handler for the fault in break A looks the page up only after A has ended. void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) { const char* const name = hold_retry ? "next_break" : "next_break_control"; @@ -522,12 +523,12 @@ void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_break", name); SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); } else { - Sleep(100); // the handler reads break A while it is open, then waits for it + Sleep(100); // the handler sees break A in progress and waits for memory.mutex } SetEvent(window_a.second); unmap_a.join(); check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); - if (hold_retry) SetEvent(retry.second); // the handler now reads the generation after break A + if (hold_retry) SetEvent(retry.second); // the handler now looks the page up after break A for (int i = 0; i < 200 && reads.load() < 1; ++i) Sleep(10); check(reads.load() == 1 && first_value == 0x52000002u, "first_fault_retried", name); @@ -546,12 +547,12 @@ void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) shim.map(base, 6, nullptr); shim.release(pages, tokens); CloseHandle(second_read); - if (!hold_retry) std::printf("next-break control: the handler read break A while it was open\n"); + if (!hold_retry) std::printf("next-break control: the handler ran while break A was open\n"); } // Break A takes apart run 1, break B (begun after A ended) run 2, a disjoint run. The handler for a fault in A is held -// (X2W_XMEM_TEST_HOLD_RETRY) until B is held open, so it reads the breaks while B is in progress: it must still find -// A and retry the fault. A handler that knew only the last break's ranges passes the fault on, and the process ends -// with an access violation. +// (X2W_XMEM_TEST_HOLD_RETRY) until B is held open, so it looks the page up while B is in progress: it must still find +// the stamp of A on run 1 and retry the fault. A handler that knew only the last break's ranges passes the fault on, +// and the process ends with an access violation. void two_runs_case(const Shim& shim, unsigned char* base) { const char* const name = "two_runs"; @@ -590,7 +591,7 @@ void two_runs_case(const Shim& shim, unsigned char* base) std::thread unmap_b([&] { shim.map(run2 + 7 * page, 1, nullptr); }); check(WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0 && raw_state(run2 + 2 * page) != MEM_COMMIT, "break_b_held_on_run_2", name); - SetEvent(retry.second); // the handler reads the breaks now, with B in progress + SetEvent(retry.second); // the handler looks the page up now, with B in progress Sleep(100); SetEvent(window_b.second); unmap_b.join(); @@ -651,7 +652,7 @@ void mirror_case(const Shim& shim, unsigned char* cpu) SetEvent(release); // the CPU merge ends; the GPU merge begins and holds check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(twin + 2 * page) != MEM_COMMIT && raw_state(target) == MEM_COMMIT, "gpu_merge_held_after_the_cpu_merge", name); - SetEvent(retry.second); // the handler reads the breaks now, with the GPU merge in progress + SetEvent(retry.second); // the handler looks the page up now, with the GPU merge in progress Sleep(100); SetEvent(release); mapper.join(); From bf9e448f0d5e977ac7619300ad6d3887e598eeb1 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:13:53 +1000 Subject: [PATCH 33/34] gh #2911 review round 1: list no-join in the cross-call merge fixture's usage comment The Usage comment at the top of tests/xmem_cross_call_merge_check.cpp lacked the no-join mode that the header describes and the usage line printed by main lists. Comment only. --- tests/xmem_cross_call_merge_check.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp index 55cc6869eb..981608bb05 100644 --- a/tests/xmem_cross_call_merge_check.cpp +++ b/tests/xmem_cross_call_merge_check.cpp @@ -34,7 +34,7 @@ // capped 192 single-page calls make three runs of 64 pages (max_merged_run_pages); an unmap held in its window // inside the middle run takes apart at most 64 pages, and the outer runs stay mapped. // -// Usage: xmem_cross_call_merge_check check|control|deployed|default|timing +// Usage: xmem_cross_call_merge_check check|control|deployed|default|no-join|timing #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include From 0c6be9713d0ec9f47dee956d7da1462de3ab0a6a Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:14:15 +1000 Subject: [PATCH 34/34] gh #2911 review round 1: put the page-run note link next to the row's first link The README row for queue slot 31 carried the link to docs/experiments/xmem-page-runs.md after the ctest command in its second column. It now sits next to the experiments.md link in the first column. Layout only. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8206517494..707d7b9402 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | PE 32/64-bit base fixups against Windows | `ctest --preset dev --no-tests=error -R '^cpu_native_highlow$' -V` · [scope and controls](docs/experiments.md#highlow-and-mixed-width-base-relocations) | | [CPU counted cache-line zero loops](docs/experiments.md#counted-cache-line-zero-loops) | `ctest --preset release --no-tests=error -R '^cpu_counted_clzero$' -V` | | [Experimental startup stand-ins and debugger (trap-by-default DLLs)](docs/startup-runtime.md) | `ctest --preset release --no-tests=error -R '^startup_stubs$' -V` | -| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` · [page runs](docs/experiments/xmem-page-runs.md) | +| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) · [page runs](docs/experiments/xmem-page-runs.md) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` | | [Sample a texture by address in a translated draw](docs/startup-runtime.md#textures-published-by-address-device-slot-70) | `ctest --preset release --no-tests=error -R '^startup_address_console_' -V` | | [Desktop audio render sink and its three-case fixture (WASAPI)](docs/experiments.md#desktop-audio-render-sink) | `ctest --preset release --no-tests=error -R '^startup_audio_output$' -V` |