From 12fcf6b2382d124db34be33bb9326800faff97c0 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 06:06:19 +0100 Subject: [PATCH 01/18] gpu: back slot 133 linear buffers by sharing or a submit-time copy (opt-in) X2W_D3D12_LINEAR_BUFFERS=1 (or =copy) gives device slot 133 buffers in COMMON state (row-major or unknown layout) a backing that keeps the title's bytes visible to the GPU. Unset, slot 133 is unchanged. - Share only after D3D12_FEATURE_EXISTING_HEAPS reports support (queried once, before any open), for a buffer inside one committed private allocation at a 64 KiB-aligned offset. The heap is cached by base, which the open heap keeps from being released. - An XMem view is not shared: a heap opened from a view makes XMem's unmap of those pages fail with error 87 (measured), and desktop resources live for the process. Sharing reports 0x80070032 and the buffer is copied. - Copy into a committed default buffer at each submission through the queue wrapper, before the title's lists run, never at bind or record. Only changed bytes are copied, through staging buffers that are reused only after their submission's queue fence completes. - Refuse with a defined HRESULT where the copy cannot keep the guarantees: a GPU-written use returns the sharing HRESULT (or DXGI_ERROR_UNSUPPORTED when sharing was not attempted), no submit fence returns E_NOT_VALID_STATE, and a submission whose refresh cannot be staged is not executed. tests/linear_buffer_backing_check.cpp drives slot 133, wrapper lists and the queue wrapper in d3d12_xs.dll over XMem pages and a private range with the #1942 cases and sentinels: default (old behaviour asserted), share, copy, host sharing refusal (EXISTING_HEAPS forced to 0) and a copy without a submit fence, plus four mutants that each remove one guarantee inside the DLL and must fail their case. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 23 + docs/experiments.md | 40 + docs/startup-runtime.md | 27 + src/startup_stubs/d3d12_xs_device.cpp | 123 ++- src/startup_stubs/linear_buffer_backing.h | 650 +++++++++++++++ src/startup_stubs/linear_buffer_report.h | 28 + tests/linear_buffer_backing_check.cpp | 952 ++++++++++++++++++++++ 7 files changed, 1818 insertions(+), 25 deletions(-) create mode 100644 src/startup_stubs/linear_buffer_backing.h create mode 100644 src/startup_stubs/linear_buffer_report.h create mode 100644 tests/linear_buffer_backing_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b85216ccf6..8f30436e0c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2585,6 +2585,29 @@ foreach(mutant IN ITEMS skip_refresh skip_copy_back reuse_early) set_tests_properties(unified_buffer_paths_${mutant}_control PROPERTIES WILL_FAIL TRUE TIMEOUT 90 SKIP_RETURN_CODE 77) endforeach() +# The production slice (#1914): slot 133's opt-in linear-buffer backing (X2W_D3D12_LINEAR_BUFFERS, +# src/startup_stubs/linear_buffer_backing.h) through the device and queue wrappers of d3d12_xs.dll, over +# XMem pages and a private range: the default, real sharing, forced copying, host sharing refusal and +# a copy without a submit fence. Each mutant removes one guarantee in the DLL and must fail its case. +add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) +target_include_directories(linear_buffer_backing_check PRIVATE tests) +target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) +target_link_libraries(linear_buffer_backing_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(adapter IN ITEMS warp hardware) + foreach(path IN ITEMS default share copy refusal untracked) + add_test(NAME linear_buffer_backing_${path}_${adapter} COMMAND linear_buffer_backing_check ${adapter} ${path}) + set_tests_properties(linear_buffer_backing_${path}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endforeach() +foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature) + string(REPLACE ":" ";" parts "${control}") + list(GET parts 0 path) + list(GET parts 1 mutant) + string(REPLACE "_" "-" flag "${mutant}") + add_test(NAME linear_buffer_backing_${mutant}_control COMMAND linear_buffer_backing_check warp ${path} --mutate ${flag}) + set_tests_properties(linear_buffer_backing_${mutant}_control PROPERTIES WILL_FAIL TRUE TIMEOUT 120 + SKIP_RETURN_CODE 77) +endforeach() # The configured range's windows and GPU addresses (src/d3d12_xs_range.h) with a fake device and fake # windows. The mutated run is the negative control. add_executable(d3d12_xs_range_check tests/d3d12_xs_range_check.cpp src/d3d12_xs_range.cpp) diff --git a/docs/experiments.md b/docs/experiments.md index f47b5d13d2..954ba5ec7b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9657,6 +9657,46 @@ cmake --build --preset release --target startup_indirect_draw_indexed startup_li ctest --preset release --no-tests=error -j1 -R '^(xmem_section_lease_|xmem_shim_(exports|mapped_pages|page_runs)$|startup_(mesh_xmem_writer|mesh86_srv_proof|list_copy|list_resubmit.*_warp$))' --output-on-failure ``` +#### Production slice: slot 133 linear buffers (#1914) + +The first production change wires the #1942 comparison to one buffer kind in `d3d12_xs.dll`: device slot 133 (`CreatePlacedResourceX`) with a buffer description and initial state `COMMON`. The title writes such a buffer with the CPU and the GPU reads it as vertex, index, constant, shader-resource or indirect-argument data. The behaviour is opt-in through `X2W_D3D12_LINEAR_BUFFERS`; unset, slot 133 keeps its backing (see [Linear buffer backing](startup-runtime.md#linear-buffer-backing-device-slot-133-opt-in)). `src/startup_stubs/linear_buffer_backing.h` shares a buffer in a private allocation after `D3D12_FEATURE_EXISTING_HEAPS`. It copies any other buffer from title memory at each submission through the queue wrapper, and refuses with a defined HRESULT where the copy cannot keep the guarantees. + +`tests/linear_buffer_backing_check.cpp` drives the production entry points: slot 133 on the device wrapper, list Reset (139) and Close (9) on wrapper lists recorded on their desktop lists, and `ExecuteCommandLists` (queue slot 10) on the queue wrapper, in render mode. It reuses #1942's sentinels and cases. The GPU reads the buffer through a root SRV and writes it through a root UAV. Title memory is either `xmem.dll` physical pages (64 KiB slots of 256 MiB sections, `X2W_XMEM_SHARED_VIEWS=1`) or one committed private range. The buffer sits at offset `0x30000` behind three neighbour pages, and the first XMem buffer lands on slots that a previous user freed, which must read zero. Each run sets its own environment. The path is one of `default` (unset), `share` (`=1`), `copy` (`=copy`), `refusal` (`=1` with `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1`, as on an adapter with `EXISTING_HEAPS = 0`) and `untracked` (`=copy` with `X2W_TEST_SUBMIT_FENCE_FAIL=1`). + +| Case | Sequence and oracle | +|---|---| +| a | Slot 133 and a list that reads the buffer are recorded over A; the CPU writes B before `ExecuteCommandLists`. The GPU must read B in all 1,024 words. | +| a2 | 16 words then change to E. The next submission must read them, and a copy must move only those 64 bytes. | +| b | A GPU-written use (`ALLOW_UNORDERED_ACCESS`). The GPU writes G ^ key; after the fence the CPU alias must hold it and the rest of the buffer its filler. A copy must refuse. | +| c | Three submissions (B, C, D, each its own buffer) are held on a gate fence; each must read its own sentinel. Sharing: the title releases X while it is held, and after the fence places E at X's address. Copying: no staging buffer may be handed out twice while held, and after the fence the next refresh must take one of them again. | +| d1 | After a refreshed submission of A the CPU writes B, and the list runs on the desktop queue directly, past the wrapper. A copy must expose the stale A; sharing reads B. Through the wrapper, B. | +| d2 | As b, held on the gate. Before it opens, the fence must be incomplete and the alias must hold P in every word; after it, G ^ key. | +| split | `share` only: a buffer across two XMem views is copied, and must read B. | +| gate | `refusal` only: one feature query and no heap open. | +| off | `default` only: none of the linear-buffer code ran. | + +On Windows 11 build 26300 at `19e04be9` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All five paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. + +| Path | Pool | Backing | Slot 133 / sharing HRESULT | Bytes copied | Results | +|---|---|---|---|---|---| +| `default` | XMem | committed default buffer, not aliased (old behaviour) | `S_OK` / not attempted | 0 | a reads zero in all words; b leaves P | +| `default` | private | aliased through the cached heap (old behaviour) | `S_OK` / not attempted | 0 | a B; b G ^ key; no linear-buffer code ran | +| `share` | private | title memory, one heap opened for the range (generation 1, 7 cache hits) | `S_OK` / `S_OK` | 0 | a B; a2 E; b G ^ key; c B, C, D, then E at X's address on the same heap; d1 B both ways; d2 P before the fence, then G ^ key | +| `share` | XMem | copied | `S_OK` / `0x80070032` (view), `0x80070057` (split) | a 131,072; a2 64; split 131,072; c 4 × 131,072; d1 131,072 + 4,096 | as `copy`; b and d2 refused with `0x80070032` | +| `copy` | XMem, private | committed default buffer refreshed at submit | `S_OK` / not attempted | a 131,072; a2 64; c 4 × 131,072; d1 131,072 + 4,096 | a B; a2 E; c B, C, D on staging 1, 2, 3, then staging 1 again after the fence; d1 stale A past the wrapper, B through it; b and d2 refused with `0x887A0004` | +| `refusal` | XMem, private | as `copy` | `S_OK` / `0x887A0004` from the feature gate, no heap opened | as `copy` | as `copy`; b and d2 refused with `0x887A0004` | +| `untracked` | XMem, private | none | `0x8007139F` (`E_NOT_VALID_STATE`) for a; `0x887A0004` for b and d2 | 0 | refused, no resource created | + +The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. + +Four negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: +- `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. +- `reuse-early` hands out staging buffers without their fence. All three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). +- `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). +- `ignore-feature` opens a heap although the feature query reports no support. gate sees one heap open (1 of 1), and the private buffers are shared. + +Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. + #### Xbox frame events and token wait semantics (#874) The source-built frame events fixture (`tests/cpu/frame_events_caller.asm`, `tests/cpu/frame_events_provider.cpp`, `tests/cpu/frame_events_check.py`, CTest `cpu_native_frame_events`) models the scheduling and wait semantics of the Xbox frame-pacing extensions in `d3d12_xs.dll`: diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d57babc3c6..2011485208 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1332,6 +1332,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `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 | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | +| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it, otherwise copied from title memory at each submission, otherwise refused with a defined HRESULT; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | @@ -2903,6 +2904,32 @@ layouts"): - `ctest --preset release --no-tests=error -R '^startup_gfx10_layout' -V` - `ctest --preset release --no-tests=error -j 1 -R '^startup_address_console_' -V` +## Linear buffer backing (device slot 133, opt-in) + +By default slot 133 aliases a buffer only in private memory, through an existing heap cached by +allocation base and opened without a `D3D12_FEATURE_EXISTING_HEAPS` query. Anything else gets a +committed default buffer that does not alias the title memory, holds zeros and is reported as +success (`not aliased` in the log). `X2W_D3D12_LINEAR_BUFFERS` changes this for one buffer kind: a +buffer description with row-major or unknown layout and initial state `COMMON` +(`src/startup_stubs/linear_buffer_backing.h`, [#1914](https://github.com/R0Y00/Xbox2Windows/issues/1914)). +Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, keep the default backing. + +| Value | Backing | +|---|---| +| unset or `0` | the default above; none of the linear-buffer code runs | +| `1` | shared when the adapter reports `D3D12_FEATURE_EXISTING_HEAPS` (queried once, before any open) and the buffer lies in one committed private allocation at a 64 KiB-aligned offset; otherwise copied; otherwise refused | +| `copy` | copied; otherwise refused | + +- Shared: a cross-adapter buffer placed on the private allocation's heap, cached by base. The GPU reads and writes title memory; nothing is copied. +- An XMem view is never shared. A heap opened from a view keeps it mapped, and XMem's unmap of those pages then fails with error 87. Sharing reports `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)` (`0x80070032`) and the buffer is copied. A buffer across several allocations, or at an unaligned offset, reports `E_INVALIDARG`. Both are decided before any D3D12 call. +- Copied: a committed default buffer that the command-queue wrapper refreshes from title memory just before the title's lists run on that queue, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. A staging buffer is reused only after the queue fence of the submission that read it has completed. +- Refused, and no resource is created: a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared returns the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory. Without a submit fence (`X2W_TEST_SUBMIT_FENCE_FAIL=1`), slot 133 returns `E_NOT_VALID_STATE` (`0x8007139f`). +- A submission whose refresh cannot be staged is not executed. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. The HRESULT is logged (`x2w-d3d12 linear buffers: submission refused`). + +Each placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit|refused`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). + +Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. + ## Buffer memory SRVs (device slot 70) Device slot 70 (`src/startup_stubs/d3d12_memory_srv.inl`, validation in diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0c2a5caae3..1fd57873dd 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -39,6 +39,7 @@ #include "startup_stubs/resource_address_index.h" #include "startup_stubs/placed_build.h" #include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/linear_buffer_backing.h" #include "startup_stubs/memory_srv_report.h" #include "startup_stubs/memory_srv_census.h" #include "startup_stubs/memory_srv_as.h" @@ -925,6 +926,13 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) return hr; } ULONG __stdcall add_ref(Wrapper* self) { return static_cast(InterlockedIncrement(&self->own().refs)); } +// X2W_D3D12_LINEAR_BUFFERS (opt-in): the shared or copied backing of slot 133's linear buffers +// (src/startup_stubs/linear_buffer_backing.h). Unused while the switch is off. +x2w_startup::LinearBuffers& linear_buffers() +{ + static x2w_startup::LinearBuffers buffers; + return buffers; +} // The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is // X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. // The wrapper stays. @@ -954,6 +962,8 @@ ULONG __stdcall release(Wrapper* self) drop_mesh_lease_owner(self); retire_placement(self); if (self->own().retire_when_idle) retire_note_title_release(self); + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { discard_mesh_lease_recording(static_cast(self->own().real)); @@ -1550,6 +1560,23 @@ extern "C" __declspec(dllexport) void x2w_d3d12_render_target_stats(unsigned* bi if (unresolved) *unresolved = static_cast(InterlockedCompareExchange(&render_target_unresolved, 0, 0)); } +// Fixtures (X2W_D3D12_LINEAR_BUFFERS): how slot 133 backed a linear buffer (false: the default backing, or +// not a placed buffer), and the totals since the process started. +extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_info(void* resource, X2wLinearBufferInfo* info) +{ + Wrapper* w = as_wrapper(resource); + if (!info || !w || w->own().kind != resource_kind || + x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + return false; + return linear_buffers().info(static_cast(w->own().real), info); +} +extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals* totals) +{ + if (!totals) return; + *totals = X2wLinearBufferTotals{}; + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); +} + // Fixtures: the number of desktop allocators a title allocator stands for (0 if it has none yet). extern "C" __declspec(dllexport) unsigned x2w_d3d12_allocator_pool_size(void* allocator) { @@ -3484,6 +3511,19 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" +// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the queue +// just before the title's lists. False: they could not be (logged), and the lists must not run. +bool linear_refresh(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) +{ + return x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off || + SUCCEEDED(linear_buffers().before_submit(queue, submission)); +} +void linear_submitted(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) +{ + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().after_submit(queue, submission); +} + // Queue slot 10, desktop ExecuteCommandLists(count, lists). void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) { @@ -3507,6 +3547,8 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) auto* queue = static_cast(self->own().real); bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { + x2w_startup::LinearBuffers::Submission linear_submission; + if (!linear_refresh(queue, linear_submission)) return; const UINT ready_count = static_cast(native_lists.size()); red_producers().execute(queue, native_lists, [&] { if (draw_dump_frame()) { @@ -3517,6 +3559,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } }); retire_address_uploads(queue, native_lists); + linear_submitted(queue, linear_submission); retire_draw_sampler_heaps(queue, native_lists); note_submits(queue, wrappers); retire_note_submission(queue, wrappers); @@ -3554,7 +3597,11 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) // No hold or flight is recorded here: the copy handlers that create holds exist only in render mode. std::vector real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); - static_cast(self->own().real)->ExecuteCommandLists(count, real.data()); + auto* queue = static_cast(self->own().real); + x2w_startup::LinearBuffers::Submission linear; + if (!linear_refresh(queue, linear)) return; + queue->ExecuteCommandLists(count, real.data()); + linear_submitted(queue, linear); if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); } @@ -4193,6 +4240,39 @@ IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 by } volatile LONG64 placed_buffer_calls, placed_buffer_region_info, placed_buffer_queries; // five-second totals +// Wraps a placed buffer's desktop resource and publishes it in the placement index. aliased: the +// resource reads and writes the title memory itself, placed on a heap whose budget is backing_budget +// (or none); otherwise it is a committed default buffer. +HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, + ID3D12Resource* resource, bool aliased, x2w_budget::Ticket* backing_budget, void** out) +{ + Wrapper* w = wrap(resource, resource_kind); + w->own().title_memory = address; + const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; + auto& group = placement_group(desc->Width); + const HRESULT hr = x2w_startup::publish_placement(note_lock, resource_infos, group.by_start, group.max_width, + static_cast(w), reinterpret_cast(address), record, [&] { index_resource(w, record); }); + if (FAILED(hr)) { + // The caller has never received this wrapper; release its desktop resource and storage. + AcquireSRWLockExclusive(®istry_lock); + registry().erase(w); + ReleaseSRWLockExclusive(®istry_lock); + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().discard(resource); + resource->Release(); + _aligned_free(&w->own()); + return hr; + } + if (aliased) { + w->own().budget = x2w_budget::resource(device_of(self), resource, x2w_budget::placed); + w->own().backing_budget = backing_budget; + if (backing_budget) backing_budget->begin_use(); + } else { + w->own().budget = x2w_budget::committed(device_of(self), resource, D3D12_HEAP_TYPE_DEFAULT); + } + *out = w; + return S_OK; +} + HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3D12_RESOURCE_DESC* desc, UINT state, const void* clear, const GUID* iid, void** out) { @@ -4265,6 +4345,22 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (initial_state != D3D12_RESOURCE_STATE_COMMON && !(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return E_INVALIDARG; const UINT64 offset = static_cast(address) - static_cast(base); + if (x2w_startup::LinearBuffers::eligible(*desc, initial_state)) { + // X2W_D3D12_LINEAR_BUFFERS=1 or copy: shared, copied at submit, or refused (linear_buffer_backing.h). + const bool uav = (sanitized(*desc).Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; + X2wLinearBufferInfo report{}; + ID3D12Resource* resource = nullptr; + bool shared = false; + const HRESULT hr = linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, &shared, &report); + log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer address=%p base=%p type=0x%lx offset=0x%llx " + "width=0x%llx flags=0x%x use=%s existing-heaps=0x%08lx share=0x%08lx -> 0x%08lx %s gpuva=0x%llx", address, base, + static_cast(range.type), offset, desc->Width, desc->Flags, uav ? "gpu-written" : "gpu-read", + static_cast(report.feature_hr), static_cast(report.share_hr), + static_cast(hr), FAILED(hr) ? "refused" : shared ? "shared" : "copied at submit", + resource ? resource->GetGPUVirtualAddress() : 0ull); + if (FAILED(hr)) return hr; + return publish_placed_buffer(self, address, desc, initial_state, resource, shared, nullptr, out); + } ID3D12Heap* heap = nullptr; x2w_budget::Ticket* backing_budget = nullptr; HRESULT hr = S_OK; @@ -4316,30 +4412,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx", address, base, offset, desc->Width, desc->Flags, state, clear, text, static_cast(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); if (FAILED(hr)) return hr; - Wrapper* w = wrap(resource, resource_kind); - w->own().title_memory = address; - const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; - auto& group = placement_group(desc->Width); - hr = x2w_startup::publish_placement(note_lock, resource_infos, group.by_start, group.max_width, - static_cast(w), reinterpret_cast(address), record, [&] { index_resource(w, record); }); - if (FAILED(hr)) { - // The caller has never received this wrapper; release its desktop resource and storage. - AcquireSRWLockExclusive(®istry_lock); - registry().erase(w); - ReleaseSRWLockExclusive(®istry_lock); - resource->Release(); - _aligned_free(&w->own()); - return hr; - } - if (aliased) { - w->own().budget = x2w_budget::resource(device_of(self), resource, x2w_budget::placed); - w->own().backing_budget = backing_budget; - if (backing_budget) backing_budget->begin_use(); - } else { - w->own().budget = x2w_budget::committed(device_of(self), resource, D3D12_HEAP_TYPE_DEFAULT); - } - *out = w; - return S_OK; + return publish_placed_buffer(self, address, desc, initial_state, resource, aliased, backing_budget, out); } #include "d3d12_memory_srv.inl" diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h new file mode 100644 index 0000000000..c642b45d8b --- /dev/null +++ b/src/startup_stubs/linear_buffer_backing.h @@ -0,0 +1,650 @@ +#pragma once + +// Opt-in backing for one ordinary linear buffer kind placed at a title address (#1914, #874): +// device slot 133 (CreatePlacedResourceX) with a buffer description, row-major or unknown layout, +// and initial state COMMON. The title writes it with the CPU and the GPU reads it (vertex, index, +// constant, shader-resource or indirect-argument data). X2W_D3D12_LINEAR_BUFFERS selects it: +// +// unset or 0 the default: slot 133 keeps its backing (an existing heap cached by allocation +// base for a private range, otherwise a committed default buffer that does not alias +// the title memory and holds zeros). Nothing in this file runs. +// 1 share when the adapter, the extent and the use allow it, else copy, else refuse. +// copy never share; copy, else refuse. +// +// XMem owns the title memory (identity, mapping, offsets, lifetime); this file owns the desktop +// backing and the fences that say when the GPU is done with it. +// +// Share. Only when D3D12_FEATURE_EXISTING_HEAPS reports support (queried once per device, before +// any open), the whole buffer lies in one committed private allocation (MEM_PRIVATE) at a 64 KiB- +// aligned offset, and the opened heap covers it. The heap is cached by allocation base, as the +// default backing caches it: while it is open the range cannot be released or decommitted +// (VirtualFree fails with error 87, measured in #1942), so a later allocation cannot appear at that +// base under it. Each opened heap gets a generation. The GPU reads and writes the title memory +// itself; nothing is copied. +// +// An XMem view (MEM_MAPPED) is not shared: a heap opened from a view keeps it mapped, and XMem's +// unmap of those pages then fails with error 87 (tests/linear_buffer_backing_check.cpp measures it). +// Desktop resources live for the process, so the title could never unmap or free those pages again. +// Sharing reports HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) for a view and the buffer is copied. A +// buffer across several allocations, or at an unaligned offset, reports E_INVALIDARG. Both are +// decided without a D3D12 call. +// +// Copy. A committed default-heap buffer whose bytes are refreshed from the title memory at each +// submission through the command-queue wrapper, before the title's lists execute on that queue, +// never at bind or record. Only the bytes that differ from the last upload are copied, through an +// upload staging buffer. A staging buffer is reused only after the queue fence of the submission +// that read it has completed. The default buffer itself is rewritten in queue order, after every +// earlier submission on that queue; a title write to bytes that an incomplete submission still reads +// is an unsynchronized concurrent write, outside the contract. +// +// Refuse, with a defined HRESULT, when the copy cannot keep the guarantees sharing would give: +// - a GPU-written use (ALLOW_UNORDERED_ACCESS): the copy has no point at which GPU writes reach the +// title memory. Slot 133 returns the sharing HRESULT, or DXGI_ERROR_UNSUPPORTED when sharing was +// not attempted (X2W_D3D12_LINEAR_BUFFERS=copy). +// - no submit fence (X2W_TEST_SUBMIT_FENCE_FAIL=1, or the fence cannot be created): staging reuse +// cannot wait for completion. Slot 133 returns E_NOT_VALID_STATE. +// - a submission whose refresh cannot be staged (the pool stays full past a 5 s wait, or creating a +// staging buffer or refresh list fails): the title's lists are not executed, and the HRESULT +// (DXGI_ERROR_WAS_STILL_DRAWING for the wait) is logged and kept in the totals. +// +// Fixtures only: +// X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1 the feature query reports no support (an adapter such as +// Intel Gen9 reports EXISTING_HEAPS = 0). +// X2W_TEST_LINEAR_BUFFER_MUTANT= removes one guarantee, for negative controls: +// skip-refresh the copy is taken at placement (bind) and never refreshed at submit +// reuse-early a staging buffer is reused without waiting for its fence +// copy-gpu-writes the copy path accepts a GPU-written use +// ignore-feature sharing is attempted although the feature query reports no support + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stubs/linear_buffer_report.h" +#include "startup_stubs/local_log.h" +#include "startup_stubs/placed_buffer_range.h" + +namespace x2w_startup { + +enum class LinearBufferMode { off, automatic, copy }; + +inline LinearBufferMode linear_buffer_mode() +{ + static const LinearBufferMode mode = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_LINEAR_BUFFERS", value, sizeof(value)); + SetLastError(saved); + if (!n || n >= sizeof(value)) return LinearBufferMode::off; + if (std::strcmp(value, "1") == 0) return LinearBufferMode::automatic; + if (_stricmp(value, "copy") == 0) return LinearBufferMode::copy; + return LinearBufferMode::off; + }(); + return mode; +} + +namespace linear_detail { +inline bool mutant(const char* name) +{ + static char value[32] = {}; + static const bool read = [] { + const DWORD saved = GetLastError(); + const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", value, sizeof(value)); + if (n >= sizeof(value)) value[0] = 0; + SetLastError(saved); + return true; + }(); + (void)read; + return value[0] && std::strcmp(value, name) == 0; +} +inline bool existing_heaps_forced_off() +{ + static const bool on = x2w_local::env_on("X2W_TEST_EXISTING_HEAPS_UNSUPPORTED"); + return on; +} +inline bool submit_fence_forced_off() +{ + static const bool on = GetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", nullptr, 0) != 0; + return on; +} +inline D3D12_RESOURCE_DESC buffer(UINT64 width, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = width; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} +} // namespace linear_detail + +class LinearBuffers { + struct Staging; + struct RefreshList; + +public: + enum Path : std::uint32_t { shared_path = 1, copied_path = 2 }; + enum Use : std::uint32_t { gpu_read = 1, gpu_written = 2 }; + + // The kind this file handles. Anything else keeps the default backing. + static bool eligible(const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES initial_state) + { + return linear_buffer_mode() != LinearBufferMode::off && desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + (desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR || desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN) && + desc.Width && initial_state == D3D12_RESOURCE_STATE_COMMON; + } + + // Slot 133 for an eligible buffer. range is measure_placed_buffer's answer for (address, width) and + // uav says whether the desktop flags keep ALLOW_UNORDERED_ACCESS. On success *out holds the + // desktop resource and *shared whether it aliases the title memory. + HRESULT place(ID3D12Device* device, void* address, UINT64 width, bool uav, const PlacedBufferRange& range, + ID3D12Resource** out, bool* shared, X2wLinearBufferInfo* report) + { + *out = nullptr; + *shared = false; + std::lock_guard lock(mutex_); + ++totals_.placements; + Record record{}; + record.info.use = uav ? gpu_written : gpu_read; + record.info.feature_hr = S_FALSE; + record.info.share_hr = S_FALSE; + const UINT64 offset = static_cast(static_cast(address) - static_cast(range.base)); + ID3D12Resource* resource = nullptr; + if (linear_buffer_mode() == LinearBufferMode::automatic) { + record.info.feature_hr = feature(device); + const bool allowed = SUCCEEDED(record.info.feature_hr) || linear_detail::mutant("ignore-feature"); + if (!allowed) + record.info.share_hr = record.info.feature_hr; + else if (!range.covered || (offset & 0xFFFF)) + record.info.share_hr = E_INVALIDARG; // decided without D3D12: each failed open throws in D3D12Core + else if (range.type == MEM_MAPPED) + record.info.share_hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); // an open heap would pin the view + else if (range.type != MEM_PRIVATE) + record.info.share_hr = E_INVALIDARG; + else + record.info.share_hr = share(device, range, offset, width, uav, &resource, &record.info.heap_generation); + } + HRESULT hr = S_OK; + if (SUCCEEDED(record.info.share_hr) && record.info.share_hr != S_FALSE) { + record.info.path = shared_path; + ++totals_.shared; + } else if (uav && !linear_detail::mutant("copy-gpu-writes")) { + hr = record.info.share_hr == S_FALSE ? DXGI_ERROR_UNSUPPORTED : record.info.share_hr; + } else if (linear_detail::submit_fence_forced_off() || FAILED(fence_check(device))) { + hr = E_NOT_VALID_STATE; + } else { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = linear_detail::buffer(width, uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + : D3D12_RESOURCE_FLAG_NONE); + hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&resource)); + if (SUCCEEDED(hr)) { + try { + record.copy = std::make_unique(); + record.copy->title = static_cast(address); + record.copy->bytes = width; + if (linear_detail::mutant("skip-refresh")) { + // Mutant: the bytes at placement are what every submission gets. + const std::size_t readable = x2w_local::probe_readable(reinterpret_cast(address), + static_cast(width)); + record.copy->bound.assign(record.copy->title, record.copy->title + readable); + record.copy->bound.resize(static_cast(width)); + } + } catch (const std::bad_alloc&) { + resource->Release(); + resource = nullptr; + hr = E_OUTOFMEMORY; + } + } + if (SUCCEEDED(hr)) { + record.info.path = copied_path; + ++totals_.copied; + } + } + if (FAILED(hr)) { + ++totals_.refused; + totals_.last_refusal_hr = hr; + if (resource) resource->Release(); + if (report) *report = record.info; + return hr; + } + record.info.backing = resource; + if (report) *report = record.info; + const bool is_shared = record.info.path == shared_path; + try { + records_.emplace(resource, std::move(record)); + } catch (const std::bad_alloc&) { + resource->Release(); + return E_OUTOFMEMORY; + } + *out = resource; + *shared = is_shared; + return S_OK; + } + + // The resource never reached the title and is about to be released. + void discard(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + records_.erase(resource); + } + + // The title released the resource: its memory is not read again. The desktop backing stays (as + // every wrapper's does); a shared one keeps its heap. + void retire(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + if (found == records_.end() || !found->second.copy) return; + found->second.copy->live = false; + std::vector().swap(found->second.copy->uploaded); + } + + // What one submission used: released by the queue fence value that after_submit signals. + struct Submission { + std::vector staging; + RefreshList* list = nullptr; + }; + + // Before the title's lists are executed on queue (the contract's copy point): records and + // executes the refresh of every live copied buffer whose title bytes changed. A failure means the + // submission must not run; the HRESULT says why. + HRESULT before_submit(ID3D12CommandQueue* queue, Submission& submission) + { + std::lock_guard lock(mutex_); + ++totals_.submissions; + bool any = false; + for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; + if (!any) return S_OK; + QueueState* state = nullptr; + HRESULT hr = queue_state(queue, &state); + if (FAILED(hr)) return refuse_submit(submission, hr); + struct Op { + ID3D12Resource* dest; + Copied* copy; + UINT64 offset; + Staging* source; + UINT64 bytes; + }; + std::vector ops; + for (auto& [resource, record] : records_) { + Copied* copy = record.copy.get(); + if (!copy || !copy->live) continue; + const std::size_t bytes = static_cast(copy->bytes); + const unsigned char* source = copy->bound.empty() ? copy->title : copy->bound.data(); + if (copy->bound.empty() && x2w_local::probe_readable(reinterpret_cast(source), bytes) < bytes) { + if (x2w_local::first_calls(unreadable_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffer %p: title memory %p is no longer readable; its backing " + "keeps the last upload", static_cast(resource), static_cast(source)); + ++totals_.unreadable; + continue; + } + std::size_t first = 0, last = bytes; + if (copy->uploaded.size() == bytes) { + if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) continue; + while (first < bytes && copy->uploaded[first] == source[first]) ++first; + while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; + first &= ~std::size_t{3}; + last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); + } else { + try { + copy->uploaded.assign(bytes, 0); + } catch (const std::bad_alloc&) { + return refuse_submit(submission, E_OUTOFMEMORY); + } + } + const UINT64 span = last - first; + Staging* staging = nullptr; + hr = take_staging(queue, span, submission, &staging); + if (FAILED(hr)) return refuse_submit(submission, hr); + try { + submission.staging.push_back(staging); + ops.push_back({resource, copy, first, staging, span}); + } catch (const std::bad_alloc&) { + staging->value = 0; + return refuse_submit(submission, E_OUTOFMEMORY); + } + std::memcpy(staging->mapped, source + first, static_cast(span)); + std::memcpy(copy->uploaded.data() + first, staging->mapped, static_cast(span)); + } + if (ops.empty()) return S_OK; + RefreshList* list = nullptr; + hr = take_list(queue, *state, &list); + if (FAILED(hr)) return refuse_submit(submission, hr); + // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST, and it decays to + // COMMON again when this ExecuteCommandLists completes, before the title's lists use it. + for (const Op& op : ops) list->list->CopyBufferRegion(op.dest, op.offset, op.source->buffer, 0, op.bytes); + hr = list->list->Close(); + if (FAILED(hr)) { + list->value = 0; + return refuse_submit(submission, hr); + } + ID3D12CommandList* lists[] = {list->list}; + queue->ExecuteCommandLists(1, lists); + submission.list = list; + for (const Op& op : ops) { + ++op.copy->refreshes; + op.copy->bytes_copied += op.bytes; + op.copy->last_staging = op.source->id; + ++totals_.refreshes; + totals_.bytes_copied += op.bytes; + } + return S_OK; + } + + // After the title's lists were executed on queue: the fence value that completes them also releases + // the staging buffers and refresh list used for this submission. + void after_submit(ID3D12CommandQueue* queue, Submission& submission) + { + std::lock_guard lock(mutex_); + const auto found = queues_.find(queue); + if (found == queues_.end()) return; + QueueState& state = found->second; + UINT64 value = 0; + if (SUCCEEDED(queue->Signal(state.fence, state.value + 1))) value = ++state.value; + // Without a signalled value nothing used here can be proven complete: it stays in use. + for (Staging* staging : submission.staging) { + staging->fence = state.fence; + staging->value = value ? value : ~UINT64{0}; + } + if (submission.list) submission.list->value = value ? value : ~UINT64{0}; + submission = {}; + if (!value) { + if (x2w_local::first_calls(signal_logged_, 2)) + x2w_local::logf("x2w-d3d12 linear buffers: the submit fence could not be signalled; its staging stays in use"); + return; + } + for (auto& [resource, record] : records_) + if (record.copy && record.copy->live) record.copy->last_fence = value; + } + + bool info(ID3D12Resource* resource, X2wLinearBufferInfo* out) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + if (found == records_.end()) return false; + *out = found->second.info; + if (const Copied* copy = found->second.copy.get()) { + out->refreshes = copy->refreshes; + out->bytes_copied = copy->bytes_copied; + out->last_staging = copy->last_staging; + out->last_fence = copy->last_fence; + } + return true; + } + + void totals(X2wLinearBufferTotals* out) + { + std::lock_guard lock(mutex_); + *out = totals_; + } + +private: + struct Copied { + const unsigned char* title = nullptr; + UINT64 bytes = 0; + bool live = true; + std::vector uploaded; // what the backing holds (empty before the first refresh) + std::vector bound; // skip-refresh mutant: the bytes at placement + UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, last_fence = 0; + }; + struct Record { + X2wLinearBufferInfo info{}; + std::unique_ptr copy; + }; + struct Staging { + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + UINT64 bytes = 0, id = 0; + ID3D12Fence* fence = nullptr; // the queue fence whose value completes its last use + UINT64 value = 0; // 0: free; ~0: in use with no signalled value + }; + struct RefreshList { + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + UINT64 value = 0; + }; + struct QueueState { + ID3D12Fence* fence = nullptr; + UINT64 value = 0; + std::vector> lists; + }; + struct Heap { + void* base; + ID3D12Heap* heap; + UINT64 generation, bytes; + }; + static constexpr std::size_t staging_limit = 256; + + HRESULT feature(ID3D12Device* device) + { + if (feature_device_ != device) { + feature_device_ = device; + ++totals_.feature_queries; + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + const HRESULT hr = device->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps)); + feature_hr_ = FAILED(hr) ? hr + : heaps.Supported && !linear_detail::existing_heaps_forced_off() ? S_OK : DXGI_ERROR_UNSUPPORTED; + x2w_local::logf("x2w-d3d12 linear buffers (X2W_D3D12_LINEAR_BUFFERS=%s): D3D12_FEATURE_EXISTING_HEAPS -> 0x%08lx " + "supported=%d%s", linear_buffer_mode() == LinearBufferMode::copy ? "copy" : "1", + static_cast(hr), heaps.Supported ? 1 : 0, + linear_detail::existing_heaps_forced_off() ? " (reported as unsupported: X2W_TEST_EXISTING_HEAPS_UNSUPPORTED)" : ""); + } + return feature_hr_; + } + + // A private range only (place() decides the rest). Its heap is opened once per allocation base and + // cached: the open heap keeps the range from being released, so the base cannot name other memory. + HRESULT share(ID3D12Device* device, const PlacedBufferRange& range, UINT64 offset, UINT64 width, bool uav, + ID3D12Resource** out, UINT64* generation) + { + const Heap* entry = nullptr; + for (const Heap& known : heaps_) + if (known.base == range.base) entry = &known; + if (entry) { + ++totals_.heap_cache_hits; + } else { + ID3D12Device3* device3 = nullptr; + ID3D12Heap* heap = nullptr; + HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device3)); + if (SUCCEEDED(hr)) { + ++totals_.heap_opens; + hr = device3->OpenExistingHeapFromAddress(range.base, IID_PPV_ARGS(&heap)); + device3->Release(); + if (FAILED(hr)) ++totals_.heap_open_failures; + } + if (FAILED(hr)) return hr; + try { + heaps_.push_back({range.base, heap, ++generation_, heap->GetDesc().SizeInBytes}); + } catch (const std::bad_alloc&) { + heap->Release(); + return E_OUTOFMEMORY; + } + entry = &heaps_.back(); + } + *generation = entry->generation; + if (entry->bytes < offset || width > entry->bytes - offset) return E_INVALIDARG; + const auto desc = linear_detail::buffer(width, static_cast( + (uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER)); + const HRESULT hr = device->CreatePlacedResource(entry->heap, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(out)); + if (FAILED(hr)) ++totals_.place_failures; + return hr; + } + + // Whether a fence can be created for this device at all (the copy path's lifetime guarantee needs one). + HRESULT fence_check(ID3D12Device* device) + { + if (fence_check_device_ != device) { + fence_check_device_ = device; + ID3D12Fence* fence = nullptr; + fence_check_hr_ = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + if (fence) fence->Release(); + } + return fence_check_hr_; + } + + HRESULT queue_state(ID3D12CommandQueue* queue, QueueState** out) + { + auto found = queues_.find(queue); + if (found == queues_.end()) { + if (linear_detail::submit_fence_forced_off()) return E_NOT_VALID_STATE; + ID3D12Device* device = nullptr; + HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); + ID3D12Fence* fence = nullptr; + if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + if (device) device->Release(); + if (FAILED(hr)) return hr; + try { + found = queues_.emplace(queue, QueueState{}).first; + } catch (const std::bad_alloc&) { + fence->Release(); + return E_OUTOFMEMORY; + } + found->second.fence = fence; + } + *out = &found->second; + return S_OK; + } + + static bool complete(const Staging& staging) + { + return staging.value == 0 || + (staging.value != ~UINT64{0} && staging.fence && staging.fence->GetCompletedValue() >= staging.value); + } + + HRESULT take_staging(ID3D12CommandQueue* queue, UINT64 bytes, const Submission& submission, Staging** out) + { + const bool early = linear_detail::mutant("reuse-early"); + for (int attempt = 0; attempt < 2; ++attempt) { + Staging* best = nullptr; + for (const auto& staging : staging_) { + if (staging->bytes < bytes || (!early && !complete(*staging))) continue; + const auto& taken = submission.staging; + if (std::find(taken.begin(), taken.end(), staging.get()) != taken.end()) continue; + // The reuse-early mutant takes the most recently used buffer, in flight or not. + if (!best || (early ? staging->id > best->id : staging->bytes < best->bytes)) best = staging.get(); + } + if (best) { + ++totals_.staging_reused; + best->value = ~UINT64{0}; + *out = best; + return S_OK; + } + if (staging_.size() < staging_limit) break; + // The pool is full of buffers in flight: wait (once, bounded) for the oldest. + Staging* oldest = nullptr; + for (const auto& staging : staging_) + if (staging->value != ~UINT64{0} && staging->fence && (!oldest || staging->value < oldest->value)) + oldest = staging.get(); + HANDLE event = oldest ? CreateEventW(nullptr, FALSE, FALSE, nullptr) : nullptr; + const bool reached = event && SUCCEEDED(oldest->fence->SetEventOnCompletion(oldest->value, event)) && + WaitForSingleObject(event, 5000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + if (!reached) return DXGI_ERROR_WAS_STILL_DRAWING; + } + if (staging_.size() >= staging_limit) return DXGI_ERROR_WAS_STILL_DRAWING; + ID3D12Device* device = nullptr; + HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); + if (FAILED(hr)) return hr; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; + const UINT64 rounded = (bytes + 0xFFFF) & ~UINT64{0xFFFF}; + const UINT64 size = rounded ? rounded : 0x10000; + const auto desc = linear_detail::buffer(size, D3D12_RESOURCE_FLAG_NONE); + auto staging = std::make_unique(); + hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&staging->buffer)); + device->Release(); + if (FAILED(hr)) return hr; + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + hr = staging->buffer->Map(0, &none, &mapped); + if (FAILED(hr)) { + staging->buffer->Release(); + return hr; + } + staging->mapped = static_cast(mapped); + staging->bytes = size; + staging->id = ++staging_ids_; + staging->value = ~UINT64{0}; + ++totals_.staging_created; + *out = staging.get(); + staging_.push_back(std::move(staging)); + return S_OK; + } + + HRESULT take_list(ID3D12CommandQueue* queue, QueueState& state, RefreshList** out) + { + const UINT64 completed = state.fence->GetCompletedValue(); + for (const auto& list : state.lists) { + if (list->value == ~UINT64{0} || list->value > completed) continue; + HRESULT hr = list->allocator->Reset(); + if (SUCCEEDED(hr)) hr = list->list->Reset(list->allocator, nullptr); + if (FAILED(hr)) return hr; + list->value = ~UINT64{0}; + *out = list.get(); + return S_OK; + } + ID3D12Device* device = nullptr; + HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); + if (FAILED(hr)) return hr; + const D3D12_COMMAND_LIST_TYPE type = queue->GetDesc().Type; + auto list = std::make_unique(); + hr = device->CreateCommandAllocator(type, IID_PPV_ARGS(&list->allocator)); + if (SUCCEEDED(hr)) + hr = device->CreateCommandList(0, type, list->allocator, nullptr, IID_PPV_ARGS(&list->list)); + device->Release(); + if (FAILED(hr)) { + if (list->allocator) list->allocator->Release(); + return hr; + } + list->value = ~UINT64{0}; + *out = list.get(); + state.lists.push_back(std::move(list)); + return S_OK; + } + + HRESULT refuse_submit(Submission& submission, HRESULT hr) + { + // Staging taken for this submission was not used on the GPU: free it again. + for (Staging* staging : submission.staging) staging->value = 0; + submission = {}; + if (x2w_local::first_calls(refusal_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffers: submission refused 0x%08lx: the copied buffers could not be " + "refreshed; the title's lists are not executed", static_cast(hr)); + ++totals_.submissions_refused; + totals_.last_submit_hr = hr; + // The bytes recorded as uploaded were not: the next submission copies the whole buffer again. + for (auto& [resource, record] : records_) + if (record.copy) record.copy->uploaded.clear(); + return hr; + } + + std::mutex mutex_; + std::unordered_map records_; + std::unordered_map queues_; + std::vector> staging_; + std::vector heaps_; + ID3D12Device* feature_device_ = nullptr; + HRESULT feature_hr_ = S_FALSE; + ID3D12Device* fence_check_device_ = nullptr; + HRESULT fence_check_hr_ = S_OK; + UINT64 generation_ = 0, staging_ids_ = 0; + X2wLinearBufferTotals totals_{}; + volatile LONG unreadable_logged_ = 0, signal_logged_ = 0, refusal_logged_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h new file mode 100644 index 0000000000..90e15206cc --- /dev/null +++ b/src/startup_stubs/linear_buffer_report.h @@ -0,0 +1,28 @@ +#pragma once + +// What d3d12_xs.dll reports about slot 133's opt-in linear buffers (X2W_D3D12_LINEAR_BUFFERS, +// src/startup_stubs/linear_buffer_backing.h) to fixtures through x2w_d3d12_linear_buffer_info and +// x2w_d3d12_linear_buffer_totals. Plain layouts: the DLL and the fixtures include this file alike. + +#include + +struct X2wLinearBufferInfo { + std::uint32_t path; // 1 shared, 2 copied (a refused placement creates no resource) + std::uint32_t use; // 1 GPU-read, 2 GPU-written + std::int32_t feature_hr; // S_OK supported, DXGI_ERROR_UNSUPPORTED not, other: query failed; S_FALSE not queried + std::int32_t share_hr; // result of the sharing attempt; S_FALSE when not attempted + std::uint64_t heap_generation; // shared: generation of the opened heap + void* backing; // the desktop ID3D12Resource + std::uint64_t refreshes; // copied: submissions that copied bytes into the backing + std::uint64_t bytes_copied; // copied: bytes copied from title memory into the backing + std::uint64_t last_staging; // copied: id of the staging buffer of the last refresh (0: none) + std::uint64_t last_fence; // copied: queue fence value after the last submission (0: none) +}; + +struct X2wLinearBufferTotals { + std::uint64_t placements, shared, copied, refused; + std::uint64_t feature_queries, heap_opens, heap_open_failures, heap_cache_hits, place_failures; + std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; + std::uint64_t submissions_refused; + std::int32_t last_refusal_hr, last_submit_hr; +}; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp new file mode 100644 index 0000000000..3594a25c20 --- /dev/null +++ b/tests/linear_buffer_backing_check.cpp @@ -0,0 +1,952 @@ +// Production slice of #1914 (Refs #874): one ordinary linear buffer, written by the CPU and read by +// the GPU, placed at a title address through the device wrapper's slot 133 (CreatePlacedResourceX) +// and submitted through the command-queue wrapper's ExecuteCommandLists, in d3d12_xs.dll. The cases +// and sentinels are those of tests/unified_buffer_paths_check.cpp (#1942); here they run against the +// production backing instead of a model of it. +// +// linear_buffer_backing_check [--mutate ] +// +// path selects the backing (the process environment is set here, before d3d12_xs.dll reads it): +// default X2W_D3D12_LINEAR_BUFFERS unset: slot 133 as before (the old behaviour, asserted) +// share X2W_D3D12_LINEAR_BUFFERS=1: real sharing where the adapter, extent and memory allow it +// (a private range); an XMem view is refused for sharing by the host rule and copied +// copy X2W_D3D12_LINEAR_BUFFERS=copy: forced copying at submit +// refusal X2W_D3D12_LINEAR_BUFFERS=1 with X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1: the host refuses +// sharing (as an adapter reporting D3D12_FEATURE_EXISTING_HEAPS = 0 does) +// untracked X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_SUBMIT_FENCE_FAIL=1: no submit fence, so +// the copy cannot keep its lifetime guarantee and must refuse +// +// Title memory comes from two pools. "xmem": xmem.dll physical pages (64 KiB slots of 256 MiB +// pagefile sections) mapped with X2W_XMEM_SHARED_VIEWS=1, five pages per mapping call (one view): +// three neighbour pages, then the two-page buffer at view offset 0x30000. A previous user's pages are +// freed first, so the first buffer lands on reused slots that must read zero. "private": one +// committed 4 MiB VirtualAlloc range, five pages per allocation in the same layout. +// +// Cases (sentinels A, B, C, D, E, G, P, filler and neighbour differ in every word): +// a bind A: slot 133 and a list that reads the buffer are recorded over A. The CPU writes B +// before ExecuteCommandLists. The GPU must read B. +// a2 then 16 words change to E: the next submission reads them, and a copy moves only those 64 bytes. +// b a GPU-written use (ALLOW_UNORDERED_ACCESS): the GPU writes G ^ key; after the fence the CPU +// alias holds it and the words around keep theirs. The copy cannot give this: it must refuse, +// with the sharing HRESULT. +// c a submission is held in flight on a gate fence, then two more (other buffers, C and D). Each +// held submission reads its own sentinel. Sharing: the title releases X while it is held, and +// after the fence places a new buffer (E) at X's address, on the same cached heap generation. +// Copying: no staging buffer is handed out again while its submission is held; after the fence +// the next refresh takes one of them again. +// d1 missing refresh: after a refreshed submission of A the CPU writes B, and the list is +// executed on the desktop queue directly, past the wrapper. Copying must expose the stale A +// (the oracle sees a missing refresh); sharing reads B. Through the wrapper the copy reads B. +// d2 readback before the fence: the GPU write of b is held on the gate. Before the gate opens the +// fence has not completed and the alias still holds P in every word (the read is ordered +// before the write by the queue's Wait); after it, G ^ key. Copying refuses the use (as b). +// split (share only) a buffer across two XMem views: sharing is refused with E_INVALIDARG, decided +// before any D3D12 call, and the buffer is copied; case a must still read B. +// gate (refusal only) no heap was opened: D3D12_FEATURE_EXISTING_HEAPS gates sharing before any open. +// pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on +// it, then XMem's unmap of those pages, while they live and after their release. +// +// The default path asserts what slot 133 did before: a private range is aliased (a and b pass) and +// an XMem view gets a committed buffer that does not alias it (a reads zero, b leaves P), with no +// linear-buffer bookkeeping at all. +// +// --mutate sets X2W_TEST_LINEAR_BUFFER_MUTANT, which removes one guarantee inside d3d12_xs.dll: +// skip-refresh (copy) case a, reuse-early (copy) case c, copy-gpu-writes (copy) case b, +// ignore-feature (refusal) case gate. +// The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). +// X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. +// Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter +// reports no existing-heap support. +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "xmem_test_device.h" +#include "../src/startup_stubs/linear_buffer_report.h" + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); +extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); +extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR, PULONG_PTR, PULONG_PTR); +extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR); +extern "C" __declspec(dllimport) void* WINAPI XMemMapPhysicalPages(void*, ULONG_PTR, const ULONG_PTR*); + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 64 * 1024; +constexpr unsigned alloc_pages = 5; // three neighbour pages, then the buffer +constexpr UINT64 buffer_offset = 3 * page; +constexpr UINT64 buffer_bytes = 2 * page; +constexpr UINT words = 1024; +constexpr UINT64 region_bytes = words * 4; +constexpr UINT64 r0 = page - region_bytes / 2; // the region the GPU reads; straddles the buffer's two pages +constexpr UINT64 r1 = page + 0x8000; // the region the GPU writes +constexpr std::uint32_t key = 0x5a5a5a5au; + +enum Tag { neighbour, filler, A, B, C, D, E, G, P, tag_count }; +const char* const tag_names[tag_count] = {"neighbour", "filler", "A", "B", "C", "D", "E", "G", "P"}; +constexpr std::uint32_t seeds[tag_count] = {0x6e656967u, 0x66696c6cu, 0xa1a1a1a1u, 0xb2b2b2b2u, 0xc3c3c3c3u, + 0xd4d4d4d4u, 0xe5e5e5e5u, 0x47474747u, 0x50505050u}; +std::uint32_t pattern(Tag tag, UINT64 word) { return seeds[tag] ^ static_cast(word * 0x9e3779b1u); } + +std::string hex(HRESULT hr) +{ + char text[16]; + std::snprintf(text, sizeof(text), "0x%08lx", static_cast(hr)); + return text; +} + +// `count` words of `tag` at byte `offset` of `cpu`; the pattern index is the word's index from `cpu`. +void write(std::uint8_t* cpu, UINT64 offset, Tag tag, UINT64 count) +{ + auto* w = reinterpret_cast(cpu); + for (UINT64 i = 0; i < count; ++i) w[offset / 4 + i] = pattern(tag, offset / 4 + i); +} + +struct Tally { + unsigned count[tag_count]{}; + unsigned zero = 0, other = 0; + std::string text() const + { + std::string out; + for (int t = 0; t < tag_count; ++t) + if (count[t]) out += (out.empty() ? "" : " ") + std::string(tag_names[t]) + "=" + std::to_string(count[t]); + if (zero) out += (out.empty() ? "" : " ") + std::string("zero=") + std::to_string(zero); + if (other) out += (out.empty() ? "" : " ") + std::string("other=") + std::to_string(other); + return out + "/" + std::to_string(words); + } +}; +// Attributes each word to the sentinel it holds after removing `mask`; word i has pattern index first + i. +Tally tally(const std::uint32_t* got, UINT64 first, std::uint32_t mask) +{ + Tally t; + for (UINT i = 0; i < words; ++i) { + const std::uint32_t value = got[i] ^ mask; + bool matched = false; + for (int tag = 0; tag < tag_count && !matched; ++tag) + if (value == pattern(static_cast(tag), first + i)) { + ++t.count[tag]; + matched = true; + } + if (!matched) ++(value == 0 ? t.zero : t.other); + } + return t; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +using Word = std::uint64_t; +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word(WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e); +} +template Word arg(T* value) { return reinterpret_cast(value); } + +// The desktop object behind a wrapper: SetPrivateDataInterface unwraps its argument before the call +// reaches the shared desktop device (as in tests/startup_indirect_dispatch.cpp). +template +ComPtr underlying(ID3D12Device* desktop, ID3D12Device* guest, IUnknown* object) +{ + constexpr GUID slot{0x6c1f0a3e, 0x2b51, 0x4d0e, {0x9b, 0x31, 0x5e, 0x0c, 0x72, 0x14, 0x88, 0x19}}; + ComPtr result; + if (FAILED(guest->SetPrivateDataInterface(slot, object))) return result; + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = desktop->GetPrivateData(slot, &bytes, stored.GetAddressOf()); + guest->SetPrivateDataInterface(slot, nullptr); + if (SUCCEEDED(read)) stored.As(&result); + return result; +} + +constexpr char shader_source[] = R"( +ByteAddressBuffer src : register(t0); +RWByteAddressBuffer dst : register(u0); +cbuffer Key : register(b0) { uint key; }; +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { dst.Store(id.x * 4, src.Load(id.x * 4) ^ key); } +)"; + +enum class Path { default_backing, share, copy, refusal, untracked }; +const char* path_name(Path p) +{ + switch (p) { + case Path::default_backing: return "default"; + case Path::share: return "share"; + case Path::copy: return "copy"; + case Path::refusal: return "refusal"; + default: return "untracked"; + } +} + +// ---- Title memory ---- + +struct Memory { + std::uint8_t* cpu = nullptr; // allocation start; the buffer is at cpu + buffer_offset + std::vector tokens; + std::uint8_t* buffer() const { return cpu + buffer_offset; } +}; + +struct Pool { + bool xmem; + std::uint8_t* base = nullptr; + UINT64 cursor = 0, bytes = 0; + explicit Pool(bool x) : xmem(x) {} + const char* name() const { return xmem ? "xmem" : "private"; } + + bool init() + { + bytes = xmem ? UINT64{16} << 30 : UINT64{4} << 20; // XMem takes the 16 GiB startup reservation shape + base = static_cast(xmem ? XMemVirtualAlloc(nullptr, static_cast(bytes), 0x20402000, 0x21, PAGE_READWRITE) + : VirtualAlloc(nullptr, static_cast(bytes), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!base) return false; + if (!xmem) return true; + // A previous user: its slots are freed, so the next allocation reuses them and must read zero. + Memory previous; + if (!map(previous, alloc_pages)) return false; + write(previous.cpu, 0, D, alloc_pages * page / 4); + return release(previous); + } + bool map(Memory& out, unsigned pages) + { + out.cpu = base + cursor; + if (cursor + pages * page > bytes) return false; + cursor += pages * page; + 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; + } + // One allocation in the case layout: neighbour pages, then the buffer filled with `fill`. + bool allocate(Memory& out, Tag fill, bool* zero = nullptr) + { + if (!map(out, alloc_pages)) return false; + bool clean = true; + for (UINT64 i = 0; i < alloc_pages * page; i += 4) clean &= *reinterpret_cast(out.cpu + i) == 0; + if (zero) *zero = clean; + write(out.cpu, 0, neighbour, buffer_offset / 4); + write(out.buffer(), 0, fill, buffer_bytes / 4); + return true; + } + // 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()); + write(out.cpu, 0, neighbour, buffer_offset / 4); + write(out.buffer(), 0, fill, buffer_bytes / 4); + return true; + } + bool release(Memory& memory) + { + if (!xmem) return true; + const auto count = static_cast(memory.tokens.size()); + return XMemMapPhysicalPages(memory.cpu, count, nullptr) == memory.cpu && + XMemFreePhysicalPages(count, memory.tokens.data()); + } +}; + +// ---- Device, the wrapper's queue, and recording ---- + +struct Gpu { + ComPtr desktop, guest; + ComPtr guest_queue, queue; // the wrapper and the desktop queue behind it + ComPtr done, gate; + ComPtr root; + ComPtr pipeline; + // GPU-read results (one slot per list that may be in flight at once), their CPU copy, the G words. + static constexpr UINT slots = 4; + ComPtr output, readback, source; + ComPtr info; + UINT64 submitted = 0, gate_value = 0; + bool gate_armed = false; + + bool init() + { + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(guest->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&guest_queue)))) return false; + queue = underlying(desktop.Get(), guest.Get(), guest_queue.Get()); + if (!queue || FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate)))) + return false; + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {0, 0, 1}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, code, errors; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(desktop->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root))) || + FAILED(D3DCompile(shader_source, sizeof(shader_source) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code, &errors))) + return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(desktop->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline)))) return false; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + auto desc = buffer_desc(slots * region_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&output)))) + return false; + heap.Type = D3D12_HEAP_TYPE_READBACK; + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback)))) + return false; + heap.Type = D3D12_HEAP_TYPE_UPLOAD; + desc.Width = region_bytes; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&source)))) + return false; + void* mapped = nullptr; + if (FAILED(source->Map(0, nullptr, &mapped))) return false; + // The G words are indexed as the buffer's words at r1, so the alias can be tallied in place. + for (UINT i = 0; i < words; ++i) static_cast(mapped)[i] = pattern(G, r1 / 4 + i); + source->Unmap(0, nullptr); + return true; + } + + // Later submissions wait on the gate until open_gate(). + void hold() + { + if (!gate_armed) ++gate_value; + gate_armed = true; + } + void open_gate() + { + if (gate_armed) gate->Signal(gate_value); + gate_armed = false; + } + bool wait(UINT64 value) + { + if (done->GetCompletedValue() >= value) return true; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool ok = event && SUCCEEDED(done->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return ok; + } + std::vector read_output(UINT slot = 0) + { + std::vector got(words); + void* mapped = nullptr; + const D3D12_RANGE range{slot * region_bytes, (slot + 1) * region_bytes}; + if (SUCCEEDED(readback->Map(0, &range, &mapped))) { + std::memcpy(got.data(), static_cast(mapped) + slot * region_bytes, region_bytes); + const D3D12_RANGE none{0, 0}; + readback->Unmap(0, &none); + } + return got; + } + unsigned debug_errors() + { + if (!info) return 0; + unsigned errors = 0; + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) continue; + if (++errors <= 8) std::printf("debug layer ERROR id %d: %.300s\n", message->ID, message->pDescription); + } + return errors; + } +}; + +// One title command list: a wrapper list on its own wrapper allocator, recorded on its desktop list. +struct TitleList { + ComPtr allocator; + ComPtr list; + ComPtr native; + Gpu* gpu = nullptr; + + bool begin(Gpu& g) + { + gpu = &g; + if (FAILED(g.guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))) return false; + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + auto* create = reinterpret_cast((*reinterpret_cast(g.guest.Get()))[73]); + if (FAILED(create(g.guest.Get(), list_desc, allocator.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(list.GetAddressOf())))) + return false; + if (FAILED(static_cast(invoke(list.Get(), 139, arg(allocator.Get()))))) return false; + native = underlying(g.desktop.Get(), g.guest.Get(), list.Get()); + return native != nullptr; + } + void barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + native->ResourceBarrier(1, &b); + } + void dispatch(D3D12_GPU_VIRTUAL_ADDRESS src, D3D12_GPU_VIRTUAL_ADDRESS dst) + { + native->SetComputeRootSignature(gpu->root.Get()); + native->SetPipelineState(gpu->pipeline.Get()); + native->SetComputeRootShaderResourceView(0, src); + native->SetComputeRootUnorderedAccessView(1, dst); + native->SetComputeRoot32BitConstant(2, key, 0); + native->Dispatch(words / 64, 1, 1); + } + // output[i] = buffer[r0 + 4i] ^ key, then output -> readback, in result slot `slot`. + void read(ID3D12Resource* buffer, UINT slot = 0) + { + const UINT64 at = slot * region_bytes; + barrier(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + dispatch(buffer->GetGPUVirtualAddress() + r0, gpu->output->GetGPUVirtualAddress() + at); + barrier(buffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + native->CopyBufferRegion(gpu->readback.Get(), at, gpu->output.Get(), at, region_bytes); + barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + } + // buffer[r1 + 4i] = G[i] ^ key. + void write_g(ID3D12Resource* buffer) + { + barrier(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + dispatch(gpu->source->GetGPUVirtualAddress(), buffer->GetGPUVirtualAddress() + r1); + barrier(buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + } + bool close() { return SUCCEEDED(static_cast(invoke(list.Get(), 9))); } + // Through the queue wrapper (slot 10, ExecuteCommandLists), behind the gate if it is held. + UINT64 submit() + { + if (gpu->gate_armed) gpu->queue->Wait(gpu->gate.Get(), gpu->gate_value); + void* lists[] = {list.Get()}; + invoke(gpu->guest_queue.Get(), 10, 1, arg(lists)); + gpu->queue->Signal(gpu->done.Get(), ++gpu->submitted); + return gpu->submitted; + } + // Past the wrapper: the desktop list on the desktop queue (a submission without the refresh). + UINT64 submit_bypassing() + { + ID3D12CommandList* lists[] = {native.Get()}; + gpu->queue->ExecuteCommandLists(1, lists); + gpu->queue->Signal(gpu->done.Get(), ++gpu->submitted); + return gpu->submitted; + } +}; + +// ---- Placement through slot 133 ---- + +struct Placed { + HRESULT hr = E_FAIL; + ComPtr wrapper; + ComPtr backing; + X2wLinearBufferInfo info{}; + bool linear = false; +}; + +Placed place(Gpu& gpu, std::uint8_t* address, bool gpu_written) +{ + Placed p; + using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + const auto desc = buffer_desc(buffer_bytes, gpu_written ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE); + auto* slot = reinterpret_cast((*reinterpret_cast(gpu.guest.Get()))[133]); + p.hr = slot(gpu.guest.Get(), address, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), + reinterpret_cast(p.wrapper.GetAddressOf())); + if (SUCCEEDED(p.hr) && p.wrapper) { + p.backing = underlying(gpu.desktop.Get(), gpu.guest.Get(), p.wrapper.Get()); + p.linear = x2w_d3d12_linear_buffer_info(p.wrapper.Get(), &p.info); + } + return p; +} +void refresh_info(Placed& p) +{ + if (p.wrapper) p.linear = x2w_d3d12_linear_buffer_info(p.wrapper.Get(), &p.info); +} + +std::string backing_text(const Placed& p) +{ + if (FAILED(p.hr)) return "refused " + hex(p.hr); + if (!p.linear) return "default"; + char text[160]; + if (p.info.path == 1) + std::snprintf(text, sizeof(text), "shared (heap generation %llu, feature %s)", + static_cast(p.info.heap_generation), hex(p.info.feature_hr).c_str()); + else + std::snprintf(text, sizeof(text), "copied (share %s, feature %s, %llu bytes in %llu refreshes, staging %llu)", + hex(p.info.share_hr).c_str(), hex(p.info.feature_hr).c_str(), + static_cast(p.info.bytes_copied), static_cast(p.info.refreshes), + static_cast(p.info.last_staging)); + return text; +} + +X2wLinearBufferTotals totals() +{ + X2wLinearBufferTotals t{}; + x2w_d3d12_linear_buffer_totals(&t); + return t; +} + +// ---- Cases ---- + +struct Run { + Gpu& gpu; + Path path; + unsigned failures = 0, skips = 0; + std::vector> results; // case name -> passed (for --mutate) + + bool copying() const { return path == Path::copy || path == Path::refusal; } + // The copy backs this pool's buffers: forced, refused by the host, or an XMem view on the share path. + bool copied(const Pool& pool) const { return copying() || (path == Path::share && pool.xmem); } + // The sharing HRESULT a refused sharing attempt reports for a buffer inside one allocation. + HRESULT share_refusal(const Pool& pool) const + { + return path == Path::refusal ? DXGI_ERROR_UNSUPPORTED : path == Path::share && pool.xmem ? HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) : S_FALSE; + } + void row(const Pool& pool, const char* name, bool pass, const std::string& text) + { + std::printf("%-8s %-8s %-6s %s: %s\n", path_name(path), pool.name(), name, pass ? "PASS" : "FAIL", text.c_str()); + results.emplace_back(name, pass); + if (!pass) ++failures; + } + // The path's expected backing for a GPU-read buffer in this pool. + bool backing_ok(const Pool& pool, const Placed& p, bool split = false) const + { + switch (path) { + case Path::default_backing: return SUCCEEDED(p.hr) && !p.linear; + case Path::share: + if (!pool.xmem) return SUCCEEDED(p.hr) && p.linear && p.info.path == 1 && p.info.share_hr == S_OK; + return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.feature_hr == S_OK && + p.info.share_hr == (split ? E_INVALIDARG : HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)); + case Path::copy: return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.share_hr == S_FALSE; + case Path::refusal: return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.share_hr == DXGI_ERROR_UNSUPPORTED && + p.info.feature_hr == DXGI_ERROR_UNSUPPORTED; + default: return p.hr == E_NOT_VALID_STATE; + } + } + // What the GPU must read in case a: B, except on the default path over an XMem view (not aliased, zero). + bool read_ok(const Pool& pool, const Tally& t, Tag want) const + { + if (path == Path::default_backing && pool.xmem) return t.zero == words; + return t.count[want] == words; + } + + void case_a(Pool& pool, bool split = false) + { + const char* name = split ? "split" : "a"; + Memory memory; + if (!(split ? pool.allocate_split(memory, A) : pool.allocate(memory, A))) return row(pool, name, false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + if (path == Path::untracked) { + return row(pool, name, p.hr == E_NOT_VALID_STATE && !p.wrapper, + "slot 133 -> " + hex(p.hr) + " (expected E_NOT_VALID_STATE 0x8007139f: no submit fence to guard staging reuse)"); + } + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, name, false, "slot 133 -> " + hex(p.hr)); + list.read(p.backing.Get()); + if (!list.close()) return row(pool, name, false, "Close failed"); + write(memory.buffer(), r0, B, words); // after bind and record, before ExecuteCommandLists + if (!gpu.wait(list.submit())) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool pass = backing_ok(pool, p, split) && read_ok(pool, t, B) && + (!p.linear || p.info.path != 2 || p.info.bytes_copied == buffer_bytes); + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; GPU read " + t.text(); + if (path == Path::default_backing) text += pool.xmem ? " (old behaviour: not aliased, no copy)" : " (old behaviour: aliased)"; + row(pool, name, pass, text); + if (split || !pass || path == Path::default_backing) return; + + // a2: 16 words change; only they are copied. + TitleList second; + if (!second.begin(gpu)) return row(pool, "a2", false, "list"); + second.read(p.backing.Get()); + second.close(); + const UINT64 before = p.info.bytes_copied; + write(memory.buffer(), r0 + 64 * 4, E, 16); + if (!gpu.wait(second.submit())) return row(pool, "a2", false, "fence timeout"); + const Tally t2 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const UINT64 copied = p.info.bytes_copied - before; + const bool pass2 = t2.count[E] == 16 && t2.count[B] == words - 16 && (p.info.path != 2 || copied == 64); + row(pool, "a2", pass2, "GPU read " + t2.text() + "; bytes copied for this submission " + std::to_string(copied) + + (p.info.path == 2 ? " (expected 64)" : " (shared: none)")); + } + + void case_b(Pool& pool, bool hold) + { + const char* name = hold ? "d2" : "b"; + Memory memory; + if (!pool.allocate(memory, filler)) return row(pool, name, false, "allocation failed"); + write(memory.buffer(), r1, P, words); + Placed p = place(gpu, memory.buffer(), true); + const auto* alias = reinterpret_cast(memory.buffer() + r1); + const bool copy_refuses = copied(pool) || path == Path::untracked; + if (copy_refuses && FAILED(p.hr)) { + // The copy has no point at which a GPU write reaches the title memory: refused, no object. The + // refusal carries the sharing HRESULT (the feature gate's DXGI_ERROR_UNSUPPORTED, or + // ERROR_NOT_SUPPORTED for an XMem view), or DXGI_ERROR_UNSUPPORTED when sharing is not + // attempted (copy, untracked). + const HRESULT want = share_refusal(pool) == S_FALSE ? DXGI_ERROR_UNSUPPORTED : share_refusal(pool); + return row(pool, name, p.hr == want && !p.wrapper, + "GPU-written use: slot 133 -> " + hex(p.hr) + " (expected refusal " + hex(want) + ")"); + } + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, name, false, "slot 133 -> " + hex(p.hr)); + list.write_g(p.backing.Get()); + if (!list.close()) return row(pool, name, false, "Close failed"); + if (hold) gpu.hold(); + const UINT64 value = list.submit(); + std::string early; + bool early_ok = true; + if (hold) { + // Ordered before the GPU write by the queue's Wait on the gate: no timing assumption. + const bool pending = gpu.done->GetCompletedValue() < value; + const Tally before = tally(alias, r1 / 4, 0); + early_ok = pending && before.count[P] == words; + early = std::string("before the fence: ") + (pending ? "in flight" : "COMPLETE") + ", alias " + before.text() + "; "; + gpu.open_gate(); + } + if (!gpu.wait(value)) return row(pool, name, false, "fence timeout"); + const Tally t = tally(alias, r1 / 4, key), raw = tally(alias, r1 / 4, 0); + // The words around the written region keep their filler. + bool around = true; + const auto* buffer = reinterpret_cast(memory.buffer()); + for (UINT64 i = 0; i < buffer_bytes / 4; ++i) + if (i < r1 / 4 || i >= r1 / 4 + words) around &= buffer[i] == pattern(filler, i); + refresh_info(p); + bool pass; + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; " + early + "after the fence alias " + + (t.count[G] ? t.text() + " (G ^ key)" : raw.text()) + (around ? ", neighbours kept" : ", NEIGHBOURS CHANGED"); + if (path == Path::default_backing && pool.xmem) { + pass = SUCCEEDED(p.hr) && !p.linear && raw.count[P] == words && around; + text += " (old behaviour: not aliased, the alias keeps P)"; + } else { + pass = early_ok && around && t.count[G] == words && + (path == Path::default_backing ? SUCCEEDED(p.hr) && !p.linear : p.linear && p.info.path == 1); + if (path == Path::default_backing) text += " (old behaviour: aliased)"; + } + row(pool, name, pass, text); + } + + // c: held submissions and backing reuse only after completion. + void case_c(Pool& pool) + { + if (path == Path::default_backing || path == Path::untracked) return; + const bool copying = copied(pool); + struct Held { + Memory memory; + Placed placed; + TitleList list; + UINT64 value = 0; + Tag tag; + }; + const Tag tags[3] = {B, C, D}; + Held held[3]; + const X2wLinearBufferTotals start = totals(); + gpu.hold(); + for (int i = 0; i < 3; ++i) { + Held& h = held[i]; + h.tag = tags[i]; + if (!pool.allocate(h.memory, h.tag)) return row(pool, "c", false, "allocation failed"); + h.placed = place(gpu, h.memory.buffer(), false); + if (FAILED(h.placed.hr) || !h.placed.backing || !h.list.begin(gpu)) return row(pool, "c", false, "slot 133 -> " + hex(h.placed.hr)); + h.list.read(h.placed.backing.Get(), static_cast(i + 1)); + h.list.close(); + h.value = h.list.submit(); + refresh_info(h.placed); + // The title is done with X once it is submitted: on the shared path it releases it now. + if (i == 0 && !copying) h.placed.wrapper.Reset(); + } + const X2wLinearBufferTotals during = totals(); + const bool pending = gpu.done->GetCompletedValue() < held[0].value; + // Each held submission reads its own buffer into its own result slot. + gpu.open_gate(); + if (!gpu.wait(held[2].value)) return row(pool, "c", false, "fence timeout"); + std::string reads = "held reads"; + bool reads_ok = true; + for (int i = 0; i < 3; ++i) { + const Tally t = tally(gpu.read_output(static_cast(i + 1)).data(), r0 / 4, key); + reads_ok &= t.count[held[i].tag] == words; + reads += std::string(" ") + "XYZ"[i] + "=[" + t.text() + "]"; + } + std::string text; + bool pass = pending && reads_ok; + if (copying) { + const UINT64 s0 = held[0].placed.info.last_staging, s1 = held[1].placed.info.last_staging, + s2 = held[2].placed.info.last_staging; + const bool distinct = s0 && s1 && s2 && s0 != s1 && s0 != s2 && s1 != s2; + // After completion the next refresh takes one of those buffers again. + Memory memory; + Placed w; + TitleList list; + if (!pool.allocate(memory, E)) return row(pool, "c", false, "allocation failed"); + w = place(gpu, memory.buffer(), false); + if (FAILED(w.hr) || !list.begin(gpu)) return row(pool, "c", false, "slot 133 -> " + hex(w.hr)); + list.read(w.backing.Get()); + list.close(); + if (!gpu.wait(list.submit())) return row(pool, "c", false, "fence timeout"); + const Tally after = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(w); + const X2wLinearBufferTotals end = totals(); + const bool reused_after = w.info.last_staging == s0 || w.info.last_staging == s1 || w.info.last_staging == s2; + pass &= distinct && reused_after && after.count[E] == words && end.staging_reused > during.staging_reused; + char line[320]; + std::snprintf(line, sizeof(line), + "held: staging %llu/%llu/%llu (%s; %llu created, %llu completed ones reused during the hold); after the fence the next refresh " + "took staging %llu (%s) and read %s", + static_cast(s0), static_cast(s1), static_cast(s2), + distinct ? "distinct" : "SHARED", static_cast(during.staging_created - start.staging_created), + static_cast(during.staging_reused - start.staging_reused), + static_cast(w.info.last_staging), reused_after ? "reused" : "NOT REUSED", after.text().c_str()); + text = line; + } else { + // Shared (a private range): after the fence the title places a new buffer Z at X's address. + const std::string reuse = "after the fence Z is placed at X's address"; + Memory z = held[0].memory; + write(z.buffer(), 0, E, buffer_bytes / 4); + Placed zp = place(gpu, z.buffer(), false); + TitleList list; + if (FAILED(zp.hr) || !list.begin(gpu)) return row(pool, "c", false, "slot 133 -> " + hex(zp.hr)); + list.read(zp.backing.Get()); + list.close(); + if (!gpu.wait(list.submit())) return row(pool, "c", false, "fence timeout"); + const Tally after = tally(gpu.read_output().data(), r0 / 4, key); + const UINT64 gx = held[0].placed.info.heap_generation, gz = zp.info.heap_generation; + pass &= zp.linear && zp.info.path == 1 && gz == gx && after.count[E] == words; + text = reuse + "; heap generation " + std::to_string(gx) + " -> " + std::to_string(gz) + + " (the range's cached heap); Z read " + after.text(); + } + row(pool, "c", pass, std::string(pending ? "held in flight" : "NOT HELD") + "; " + reads + "; " + text); + } + + // Measured, not asserted (share path, XMem): why slot 133 does not share a view. A heap opened from + // the view, with a buffer placed on it, and XMem's unmap of the view's pages, before and after the + // heap and buffer are released. + void probe_view_pin(Pool& pool) + { + if (path != Path::share || !pool.xmem) return; + Memory memory; + ComPtr device3; + if (!pool.allocate(memory, A) || FAILED(gpu.desktop.As(&device3))) return; + ComPtr heap; + ComPtr buffer; + HRESULT hr = device3->OpenExistingHeapFromAddress(memory.cpu, IID_PPV_ARGS(&heap)); + const auto desc = buffer_desc(buffer_bytes, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); + if (SUCCEEDED(hr)) hr = gpu.desktop->CreatePlacedResource(heap.Get(), buffer_offset, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&buffer)); + const auto count = static_cast(memory.tokens.size()); + const bool held_unmap = XMemMapPhysicalPages(memory.cpu, count, nullptr) == memory.cpu; + const DWORD held_error = held_unmap ? 0 : GetLastError(); + buffer.Reset(); + heap.Reset(); + const bool unmap = held_unmap || XMemMapPhysicalPages(memory.cpu, count, nullptr) == memory.cpu; + const DWORD error = unmap ? 0 : GetLastError(); + const bool freed = unmap && XMemFreePhysicalPages(count, memory.tokens.data()); + std::printf("%-8s %-8s %-6s measured: heap from the view and placed buffer %s; XMem unmap while they live %s (error %lu); " + "after their release %s (error %lu), pages %s\n", path_name(path), pool.name(), "pin", hex(hr).c_str(), + held_unmap ? "succeeded" : "failed", held_error, unmap ? "succeeded" : "failed", error, + freed ? "freed" : "not freed"); + } + + void case_d1(Pool& pool) + { + if (path == Path::default_backing || path == Path::untracked) return; + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "d1", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList first, bypass, through; + if (FAILED(p.hr) || !first.begin(gpu) || !bypass.begin(gpu) || !through.begin(gpu)) + return row(pool, "d1", false, "slot 133 -> " + hex(p.hr)); + first.read(p.backing.Get()); + first.close(); + if (!gpu.wait(first.submit())) return row(pool, "d1", false, "fence timeout"); + write(memory.buffer(), r0, B, words); + bypass.read(p.backing.Get()); + bypass.close(); + if (!gpu.wait(bypass.submit_bypassing())) return row(pool, "d1", false, "fence timeout"); + const Tally missing = tally(gpu.read_output().data(), r0 / 4, key); + through.read(p.backing.Get()); + through.close(); + if (!gpu.wait(through.submit())) return row(pool, "d1", false, "fence timeout"); + const Tally refreshed = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool shared = !copied(pool); + const bool pass = (shared ? missing.count[B] == words : missing.count[A] == words) && refreshed.count[B] == words && + p.linear && p.info.path == (shared ? 1u : 2u); + row(pool, "d1", pass, std::string("past the wrapper (no refresh) ") + missing.text() + + (shared ? " (shared: no refresh needed)" : " (stale A expected: the oracle sees the missing refresh)") + + "; through the wrapper " + refreshed.text()); + } +}; +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) { + std::puts("usage: linear_buffer_backing_check [--mutate ]"); + return 2; + } + const bool warp = std::strcmp(argv[1], "warp") == 0; + if (!warp && std::strcmp(argv[1], "hardware") != 0) return 2; + Path path; + const std::string p = argv[2]; + if (p == "default") path = Path::default_backing; + else if (p == "share") path = Path::share; + else if (p == "copy") path = Path::copy; + else if (p == "refusal") path = Path::refusal; + else if (p == "untracked") path = Path::untracked; + else return 2; + std::string mutant; + if (argc == 5 && std::strcmp(argv[3], "--mutate") == 0) mutant = argv[4]; + else if (argc != 3) return 2; + + // The switches are read once, by the first call that needs them: set them before any. + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + 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_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr + : path == Path::copy || path == Path::untracked ? L"copy" : L"1"); + SetEnvironmentVariableW(L"X2W_TEST_EXISTING_HEAPS_UNSUPPORTED", path == Path::refusal ? L"1" : nullptr); + SetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", path == Path::untracked ? L"1" : nullptr); + SetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", mutant.empty() ? nullptr : mutant.c_str()); + + char debug_env[4]{}; + const bool debug_layer = GetEnvironmentVariableA("X2W_TEST_DEBUG_LAYER", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_layer) { + ComPtr debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) { + std::puts("X2W_TEST_DEBUG_LAYER=1 but the debug layer is not installed"); + return 1; + } + debug->EnableDebugLayer(); + } + + Gpu gpu; + static ComPtr* desktop_out = &gpu.desktop; + static DXGI_ADAPTER_DESC1 adapter_desc{}; + static LARGE_INTEGER driver{}; + const auto create = [](IUnknown* adapter, REFIID iid, void** out) -> HRESULT { + ComPtr a; + if (SUCCEEDED(adapter->QueryInterface(IID_PPV_ARGS(&a)))) { + a->GetDesc1(&adapter_desc); + a->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + } + const HRESULT hr = D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(desktop_out->ReleaseAndGetAddressOf())); + if (FAILED(hr)) return hr; + unsigned char parameters[64]{}; + return D3D12XboxCreateDevice(adapter, parameters, iid, out); + }; + bool unmatched = false; + gpu.guest = create_device(warp, unmatched, create); + if (!gpu.guest || !gpu.desktop) { + std::puts(warp ? "WARP device not created" : "no D3D12 hardware adapter"); + return warp || unmatched ? 1 : 77; + } + if (debug_layer) gpu.desktop.As(&gpu.info); + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + const HRESULT heaps_hr = gpu.desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps)); + std::printf("adapter %04x:%04x %ls, driver %u.%u.%u.%u, D3D12_FEATURE_EXISTING_HEAPS %s supported=%d, debug layer %s, path %s%s%s\n", + adapter_desc.VendorId, adapter_desc.DeviceId, adapter_desc.Description, HIWORD(driver.HighPart), + LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart), hex(heaps_hr).c_str(), + heaps.Supported ? 1 : 0, debug_layer ? "on" : "off", path_name(path), mutant.empty() ? "" : ", mutant ", + mutant.c_str()); + if (!gpu.init()) { + std::puts("FAIL: fixture setup (queue, fences, pipeline)"); + return 1; + } + if (path == Path::share && (FAILED(heaps_hr) || !heaps.Supported)) { + std::puts("SKIP share: the adapter reports no existing-heap support; the refusal path covers it"); + return 77; + } + + Run run{gpu, path}; + for (const bool xmem : {true, false}) { + Pool pool(xmem); + if (!pool.init()) { + run.row(pool, "pool", false, "title memory could not be set up"); + continue; + } + run.case_a(pool); + if (path == Path::share && xmem) run.case_a(pool, true); + run.case_b(pool, false); + run.case_c(pool); + run.case_d1(pool); + if (path != Path::default_backing) run.case_b(pool, true); + run.probe_view_pin(pool); + } + const X2wLinearBufferTotals t = totals(); + std::printf("totals: placements %llu (shared %llu, copied %llu, refused %llu), feature queries %llu, heap opens %llu " + "(failed %llu, cache hits %llu), placements failed %llu, submissions %llu, refreshes %llu, bytes copied %llu, " + "staging created %llu reused %llu, unreadable %llu, submissions refused %llu, last refusal %s\n", + static_cast(t.placements), static_cast(t.shared), + static_cast(t.copied), static_cast(t.refused), + static_cast(t.feature_queries), static_cast(t.heap_opens), + static_cast(t.heap_open_failures), static_cast(t.heap_cache_hits), + static_cast(t.place_failures), static_cast(t.submissions), + static_cast(t.refreshes), static_cast(t.bytes_copied), + static_cast(t.staging_created), static_cast(t.staging_reused), + static_cast(t.unreadable), static_cast(t.submissions_refused), + hex(t.last_refusal_hr).c_str()); + { + Pool none(false); + if (path == Path::default_backing) { + // Opt-in off: no linear-buffer bookkeeping at all. + const bool untouched = !t.placements && !t.submissions && !t.feature_queries && !t.heap_opens; + run.row(none, "off", untouched, untouched ? "no linear-buffer code ran (all totals zero)" : "LINEAR-BUFFER CODE RAN"); + } else if (path == Path::refusal) { + run.row(none, "gate", t.feature_queries == 1 && t.heap_opens == 0, + "feature queries " + std::to_string(t.feature_queries) + ", heap opens " + std::to_string(t.heap_opens) + + " (expected 1 and 0: no open is attempted when D3D12_FEATURE_EXISTING_HEAPS reports no support)"); + } + } + const HRESULT removed = gpu.desktop->GetDeviceRemovedReason(); + if (FAILED(removed)) { + std::printf("FAIL: device removed %s\n", hex(removed).c_str()); + ++run.failures; + } + const unsigned errors = gpu.debug_errors(); + if (errors) { + std::printf("FAIL: %u debug-layer errors\n", errors); + run.failures += errors; + } + + if (!mutant.empty()) { + const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" + : mutant == "ignore-feature" ? "gate" : nullptr; + if (!target) return 2; + unsigned targeted = 0, failed = 0; + for (const auto& [name, pass] : run.results) + if (name == target) { + ++targeted; + failed += !pass; + } + std::printf("mutant %s: %u of %u targeted '%s' rows failed\n", mutant.c_str(), failed, targeted, target); + return targeted && failed == targeted ? 1 : 0; + } + std::printf("linear_buffer_backing %s %s: %s (%u failed)\n", argv[1], path_name(path), run.failures ? "FAIL" : "PASS", run.failures); + return run.failures ? 1 : 0; +} From 180820ce4d10bec0a7862b3baabbb1501cf2b7bf Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 06:30:24 +0100 Subject: [PATCH 02/18] gpu: keep slot 133's default backing where the linear path refuses A title run with X2W_D3D12_LINEAR_BUFFERS=1 faulted at 1.76 s: the first eligible placement, a GPU-written buffer across XMem views, was refused with 0x80070057, and the title, for which CreatePlacedResourceX never fails on the console, used the null object. - Where neither sharing nor the copy keeps its guarantees (a GPU-written use that is not shared, no submit fence, no copy buffer), slot 133 now keeps the default backing and returns what it returns with the switch off. The refusal HRESULT is appended to the slot 133 log line, kept in x2w_d3d12_linear_buffer_info (path 3, refusal_hr) and counted in the totals (kept_default, last_refusal_hr). - A submission whose refresh cannot be staged now runs. The buffer keeps its last upload and is reported stale (info: stale, refresh_failures, last_refresh_hr; totals: refresh_failures, last_refresh_hr) until a later refresh succeeds; the first failures are logged. The fixture asserts the old behaviour and the reported refusal for every kept default (the log line read back through X2W_TRAP_LOG), adds a stale path (X2W_TEST_LINEAR_REFRESH_FAIL) and a refusal-silent mutant that drops the report and must fail. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 11 +- docs/experiments.md | 29 ++- docs/startup-runtime.md | 15 +- src/startup_stubs/d3d12_xs_device.cpp | 47 +++-- src/startup_stubs/linear_buffer_backing.h | 214 ++++++++++++++------- src/startup_stubs/linear_buffer_report.h | 13 +- tests/linear_buffer_backing_check.cpp | 224 +++++++++++++++++----- 7 files changed, 389 insertions(+), 164 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f30436e0c..0039ce991b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2587,19 +2587,22 @@ foreach(mutant IN ITEMS skip_refresh skip_copy_back reuse_early) endforeach() # The production slice (#1914): slot 133's opt-in linear-buffer backing (X2W_D3D12_LINEAR_BUFFERS, # src/startup_stubs/linear_buffer_backing.h) through the device and queue wrappers of d3d12_xs.dll, over -# XMem pages and a private range: the default, real sharing, forced copying, host sharing refusal and -# a copy without a submit fence. Each mutant removes one guarantee in the DLL and must fail its case. +# XMem pages and a private range: the default, real sharing, forced copying, host sharing refusal, a +# copy without a submit fence (the default backing is kept and the refusal reported) and a refresh +# that cannot be staged (the submission runs, the buffer is reported stale). Each mutant removes one +# guarantee in the DLL and must fail its case. add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) target_include_directories(linear_buffer_backing_check PRIVATE tests) target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) target_link_libraries(linear_buffer_backing_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi d3dcompiler) foreach(adapter IN ITEMS warp hardware) - foreach(path IN ITEMS default share copy refusal untracked) + foreach(path IN ITEMS default share copy refusal untracked stale) add_test(NAME linear_buffer_backing_${path}_${adapter} COMMAND linear_buffer_backing_check ${adapter} ${path}) set_tests_properties(linear_buffer_backing_${path}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() endforeach() -foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature) +foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature + copy:refusal_silent) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/docs/experiments.md b/docs/experiments.md index 954ba5ec7b..f90410ebcf 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9659,43 +9659,52 @@ ctest --preset release --no-tests=error -j1 -R '^(xmem_section_lease_|xmem_shim_ #### Production slice: slot 133 linear buffers (#1914) -The first production change wires the #1942 comparison to one buffer kind in `d3d12_xs.dll`: device slot 133 (`CreatePlacedResourceX`) with a buffer description and initial state `COMMON`. The title writes such a buffer with the CPU and the GPU reads it as vertex, index, constant, shader-resource or indirect-argument data. The behaviour is opt-in through `X2W_D3D12_LINEAR_BUFFERS`; unset, slot 133 keeps its backing (see [Linear buffer backing](startup-runtime.md#linear-buffer-backing-device-slot-133-opt-in)). `src/startup_stubs/linear_buffer_backing.h` shares a buffer in a private allocation after `D3D12_FEATURE_EXISTING_HEAPS`. It copies any other buffer from title memory at each submission through the queue wrapper, and refuses with a defined HRESULT where the copy cannot keep the guarantees. +The first production change wires the #1942 comparison to one buffer kind in `d3d12_xs.dll`: device slot 133 (`CreatePlacedResourceX`) with a buffer description and initial state `COMMON`. The title writes such a buffer with the CPU and the GPU reads it as vertex, index, constant, shader-resource or indirect-argument data. The behaviour is opt-in through `X2W_D3D12_LINEAR_BUFFERS`; unset, slot 133 keeps its backing (see [Linear buffer backing](startup-runtime.md#linear-buffer-backing-device-slot-133-opt-in)). `src/startup_stubs/linear_buffer_backing.h` shares a buffer in a private allocation after `D3D12_FEATURE_EXISTING_HEAPS`. It copies any other buffer from title memory at each submission through the queue wrapper. Where the copy cannot keep the guarantees, slot 133 keeps the default backing and returns what it returns without the switch, and the refusal HRESULT is recorded in the log, the buffer's info and the totals. A refresh that cannot be staged does not hold the submission back; the buffer keeps its last upload and is reported stale. -`tests/linear_buffer_backing_check.cpp` drives the production entry points: slot 133 on the device wrapper, list Reset (139) and Close (9) on wrapper lists recorded on their desktop lists, and `ExecuteCommandLists` (queue slot 10) on the queue wrapper, in render mode. It reuses #1942's sentinels and cases. The GPU reads the buffer through a root SRV and writes it through a root UAV. Title memory is either `xmem.dll` physical pages (64 KiB slots of 256 MiB sections, `X2W_XMEM_SHARED_VIEWS=1`) or one committed private range. The buffer sits at offset `0x30000` behind three neighbour pages, and the first XMem buffer lands on slots that a previous user freed, which must read zero. Each run sets its own environment. The path is one of `default` (unset), `share` (`=1`), `copy` (`=copy`), `refusal` (`=1` with `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1`, as on an adapter with `EXISTING_HEAPS = 0`) and `untracked` (`=copy` with `X2W_TEST_SUBMIT_FENCE_FAIL=1`). +A title run motivated the fallback. An earlier revision returned the refusal from slot 133. On the RX 9070 XT with a warm shader cache and the same input, the run with the switch off stopped at 294 s at the slot 148 builder, as before. With `X2W_D3D12_LINEAR_BUFFERS=1` the title faulted at 1.76 s, reading address `0x18`. Its first eligible placement was a GPU-written buffer of `0xae00000` bytes on an XMem view (`MEM_MAPPED`) across views: sharing `0x80070057`, so slot 133 returned `0x80070057`. On the console `CreatePlacedResourceX` does not fail, and the title used the null object. In the switch-off run, slot 133 placed: +- 2,987 GPU-read buffers (14.2 MiB), not aliased; +- 506 GPU-written buffers (856 MiB), not aliased; +- 61 GPU-written buffers (167 MiB), aliased (private). + +`tests/linear_buffer_backing_check.cpp` drives the production entry points: slot 133 on the device wrapper, list Reset (139) and Close (9) on wrapper lists recorded on their desktop lists, and `ExecuteCommandLists` (queue slot 10) on the queue wrapper, in render mode. It reuses #1942's sentinels and cases. The GPU reads the buffer through a root SRV and writes it through a root UAV. Title memory is either `xmem.dll` physical pages (64 KiB slots of 256 MiB sections, `X2W_XMEM_SHARED_VIEWS=1`) or one committed private range. The buffer sits at offset `0x30000` behind three neighbour pages, and the first XMem buffer lands on slots that a previous user freed, which must read zero. Each run sets its own environment. The path is one of `default` (unset), `share` (`=1`), `copy` (`=copy`), `refusal` (`=1` with `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1`, as on an adapter with `EXISTING_HEAPS = 0`), `untracked` (`=copy` with `X2W_TEST_SUBMIT_FENCE_FAIL=1`) and `stale` (`=copy` with `X2W_TEST_LINEAR_REFRESH_FAIL=3`, so staging requests 2, 5, 8 and so on fail with `E_OUTOFMEMORY`). A kept default must return `S_OK` with an object, behave as before (an XMem view not aliased, a private range aliased on an adapter with existing heaps), and carry the refusal HRESULT in `x2w_d3d12_linear_buffer_info`, in the totals and in its slot 133 log line. The fixture reads that line back from `X2W_TRAP_LOG`. | Case | Sequence and oracle | |---|---| | a | Slot 133 and a list that reads the buffer are recorded over A; the CPU writes B before `ExecuteCommandLists`. The GPU must read B in all 1,024 words. | | a2 | 16 words then change to E. The next submission must read them, and a copy must move only those 64 bytes. | -| b | A GPU-written use (`ALLOW_UNORDERED_ACCESS`). The GPU writes G ^ key; after the fence the CPU alias must hold it and the rest of the buffer its filler. A copy must refuse. | +| b | A GPU-written use (`ALLOW_UNORDERED_ACCESS`). The GPU writes G ^ key; after the fence the CPU alias must hold it and the rest of the buffer its filler. Where the buffer would be copied, slot 133 must keep the default backing and report the refusal. | | c | Three submissions (B, C, D, each its own buffer) are held on a gate fence; each must read its own sentinel. Sharing: the title releases X while it is held, and after the fence places E at X's address. Copying: no staging buffer may be handed out twice while held, and after the fence the next refresh must take one of them again. | | d1 | After a refreshed submission of A the CPU writes B, and the list runs on the desktop queue directly, past the wrapper. A copy must expose the stale A; sharing reads B. Through the wrapper, B. | | d2 | As b, held on the gate. Before it opens, the fence must be incomplete and the alias must hold P in every word; after it, G ^ key. | | split | `share` only: a buffer across two XMem views is copied, and must read B. | | gate | `refusal` only: one feature query and no heap open. | | off | `default` only: none of the linear-buffer code ran. | +| kept | every path with refusals: the totals count as many kept default backings as the run refused. | +| stale | `stale` only: a refreshed submission of A, then the CPU writes B and the refresh fails. The submission must still run and complete and read A (the last upload). The buffer must be reported stale with `E_OUTOFMEMORY` in its info and the log. The next submission must read B and clear it. | -On Windows 11 build 26300 at `19e04be9` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All five paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. +On Windows 11 build 26300 at `ab9a020c` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All six paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. | Path | Pool | Backing | Slot 133 / sharing HRESULT | Bytes copied | Results | |---|---|---|---|---|---| | `default` | XMem | committed default buffer, not aliased (old behaviour) | `S_OK` / not attempted | 0 | a reads zero in all words; b leaves P | | `default` | private | aliased through the cached heap (old behaviour) | `S_OK` / not attempted | 0 | a B; b G ^ key; no linear-buffer code ran | | `share` | private | title memory, one heap opened for the range (generation 1, 7 cache hits) | `S_OK` / `S_OK` | 0 | a B; a2 E; b G ^ key; c B, C, D, then E at X's address on the same heap; d1 B both ways; d2 P before the fence, then G ^ key | -| `share` | XMem | copied | `S_OK` / `0x80070032` (view), `0x80070057` (split) | a 131,072; a2 64; split 131,072; c 4 × 131,072; d1 131,072 + 4,096 | as `copy`; b and d2 refused with `0x80070032` | -| `copy` | XMem, private | committed default buffer refreshed at submit | `S_OK` / not attempted | a 131,072; a2 64; c 4 × 131,072; d1 131,072 + 4,096 | a B; a2 E; c B, C, D on staging 1, 2, 3, then staging 1 again after the fence; d1 stale A past the wrapper, B through it; b and d2 refused with `0x887A0004` | -| `refusal` | XMem, private | as `copy` | `S_OK` / `0x887A0004` from the feature gate, no heap opened | as `copy` | as `copy`; b and d2 refused with `0x887A0004` | -| `untracked` | XMem, private | none | `0x8007139F` (`E_NOT_VALID_STATE`) for a; `0x887A0004` for b and d2 | 0 | refused, no resource created | +| `share` | XMem | copied; b and d2 kept default (not aliased) | `S_OK` / `0x80070032` (view), `0x80070057` (split); b, d2 refusal `0x80070032` | a 131,072; a2 64; split 131,072; c 4 × 131,072; d1 131,072 + 4,096 | as `copy`; b and d2 leave P, as before; 2 kept default backings reported | +| `copy` | XMem, private | committed default buffer refreshed at submit; b and d2 kept default | `S_OK` / not attempted; b, d2 refusal `0x887A0004` | a 131,072; a2 64; c 4 × 131,072; d1 131,072 + 4,096 | a B; a2 E; c B, C, D on staging 1, 2, 3, then staging 1 again after the fence; d1 stale A past the wrapper, B through it; b and d2 as before (XMem leaves P, private G ^ key); 4 kept | +| `refusal` | XMem, private | as `copy` | `S_OK` / `0x887A0004` from the feature gate, no heap opened; b, d2 refusal `0x887A0004` | as `copy` | as `copy`; 4 kept | +| `untracked` | XMem, private | kept default for every placement | `S_OK`; refusal `0x8007139F` (`E_NOT_VALID_STATE`) for a, `0x887A0004` for b and d2 | 0 | a: XMem reads zero, private B; b and d2: XMem leaves P, private G ^ key (as before); 6 kept | +| `stale` | XMem, private | copied | `S_OK` / not attempted | 131,072 + 4,096 per pool; the failed refresh copies 0 | the failed submission completes and reads A, stale reported with `0x8007000E`, then B and stale cleared; 2 refresh failures | The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. -Four negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: +Five negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: - `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. - `reuse-early` hands out staging buffers without their fence. All three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). - `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). - `ignore-feature` opens a heap although the feature query reports no support. gate sees one heap open (1 of 1), and the private buffers are shared. +- `refusal-silent` keeps the default backing without reporting it. b finds no refusal in the info and no log line (2 of 2), and the kept totals stay at 0. -Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. +Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. #### Xbox frame events and token wait semantics (#874) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2011485208..135afdeba9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1332,7 +1332,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `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 | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | -| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it, otherwise copied from title memory at each submission, otherwise refused with a defined HRESULT; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | +| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it, otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | @@ -2917,16 +2917,19 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee | Value | Backing | |---|---| | unset or `0` | the default above; none of the linear-buffer code runs | -| `1` | shared when the adapter reports `D3D12_FEATURE_EXISTING_HEAPS` (queried once, before any open) and the buffer lies in one committed private allocation at a 64 KiB-aligned offset; otherwise copied; otherwise refused | -| `copy` | copied; otherwise refused | +| `1` | shared when the adapter reports `D3D12_FEATURE_EXISTING_HEAPS` (queried once, before any open) and the buffer lies in one committed private allocation at a 64 KiB-aligned offset; otherwise copied; otherwise the default backing, with the refusal recorded | +| `copy` | copied; otherwise the default backing, with the refusal recorded | - Shared: a cross-adapter buffer placed on the private allocation's heap, cached by base. The GPU reads and writes title memory; nothing is copied. - An XMem view is never shared. A heap opened from a view keeps it mapped, and XMem's unmap of those pages then fails with error 87. Sharing reports `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)` (`0x80070032`) and the buffer is copied. A buffer across several allocations, or at an unaligned offset, reports `E_INVALIDARG`. Both are decided before any D3D12 call. - Copied: a committed default buffer that the command-queue wrapper refreshes from title memory just before the title's lists run on that queue, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. A staging buffer is reused only after the queue fence of the submission that read it has completed. -- Refused, and no resource is created: a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared returns the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory. Without a submit fence (`X2W_TEST_SUBMIT_FENCE_FAIL=1`), slot 133 returns `E_NOT_VALID_STATE` (`0x8007139f`). -- A submission whose refresh cannot be staged is not executed. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. The HRESULT is logged (`x2w-d3d12 linear buffers: submission refused`). +- Kept default: where neither path keeps its guarantees, slot 133 keeps the default backing above and returns what it returns without the switch. On the console `CreatePlacedResourceX` does not fail, and a title that received a failure faulted on the null object. The refusal HRESULT is recorded instead: + - a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared records the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory; + - without a submit fence (`X2W_TEST_SUBMIT_FENCE_FAIL=1`), `E_NOT_VALID_STATE` (`0x8007139f`); + - when the copy's default buffer cannot be created, that HRESULT. +- A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. -Each placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit|refused`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 1fd57873dd..2183d8c863 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3512,11 +3512,12 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/list_copy_texture.inl" // X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the queue -// just before the title's lists. False: they could not be (logged), and the lists must not run. -bool linear_refresh(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) +// just before the title's lists. A refresh that fails leaves that buffer stale (logged, counted); +// the lists run either way. +void linear_refresh(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) { - return x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off || - SUCCEEDED(linear_buffers().before_submit(queue, submission)); + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().before_submit(queue, submission); } void linear_submitted(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) { @@ -3548,7 +3549,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { x2w_startup::LinearBuffers::Submission linear_submission; - if (!linear_refresh(queue, linear_submission)) return; + linear_refresh(queue, linear_submission); const UINT ready_count = static_cast(native_lists.size()); red_producers().execute(queue, native_lists, [&] { if (draw_dump_frame()) { @@ -3599,7 +3600,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); auto* queue = static_cast(self->own().real); x2w_startup::LinearBuffers::Submission linear; - if (!linear_refresh(queue, linear)) return; + linear_refresh(queue, linear); queue->ExecuteCommandLists(count, real.data()); linear_submitted(queue, linear); if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); @@ -4345,21 +4346,28 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (initial_state != D3D12_RESOURCE_STATE_COMMON && !(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return E_INVALIDARG; const UINT64 offset = static_cast(address) - static_cast(base); + // X2W_D3D12_LINEAR_BUFFERS=1 or copy: shared or copied at submit (linear_buffer_backing.h). Where + // neither keeps its guarantees, the default backing below is kept and the refusal recorded. + X2wLinearBufferInfo linear{}; + char linear_note[160] = ""; if (x2w_startup::LinearBuffers::eligible(*desc, initial_state)) { - // X2W_D3D12_LINEAR_BUFFERS=1 or copy: shared, copied at submit, or refused (linear_buffer_backing.h). const bool uav = (sanitized(*desc).Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; - X2wLinearBufferInfo report{}; ID3D12Resource* resource = nullptr; bool shared = false; - const HRESULT hr = linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, &shared, &report); - log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer address=%p base=%p type=0x%lx offset=0x%llx " - "width=0x%llx flags=0x%x use=%s existing-heaps=0x%08lx share=0x%08lx -> 0x%08lx %s gpuva=0x%llx", address, base, - static_cast(range.type), offset, desc->Width, desc->Flags, uav ? "gpu-written" : "gpu-read", - static_cast(report.feature_hr), static_cast(report.share_hr), - static_cast(hr), FAILED(hr) ? "refused" : shared ? "shared" : "copied at submit", - resource ? resource->GetGPUVirtualAddress() : 0ull); - if (FAILED(hr)) return hr; - return publish_placed_buffer(self, address, desc, initial_state, resource, shared, nullptr, out); + const HRESULT placed = linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, &shared, &linear); + if (SUCCEEDED(placed)) { + log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer address=%p base=%p type=0x%lx offset=0x%llx " + "width=0x%llx flags=0x%x use=%s existing-heaps=0x%08lx share=0x%08lx -> 0x%08lx %s gpuva=0x%llx", address, base, + static_cast(range.type), offset, desc->Width, desc->Flags, uav ? "gpu-written" : "gpu-read", + static_cast(linear.feature_hr), static_cast(linear.share_hr), + static_cast(placed), shared ? "shared" : "copied at submit", resource->GetGPUVirtualAddress()); + return publish_placed_buffer(self, address, desc, initial_state, resource, shared, nullptr, out); + } + if (x2w_startup::LinearBuffers::report_refusals()) + std::snprintf(linear_note, sizeof(linear_note), + " (kept default backing: linear refusal 0x%08lx, use=%s type=0x%lx existing-heaps=0x%08lx share=0x%08lx)", + static_cast(placed), uav ? "gpu-written" : "gpu-read", static_cast(range.type), + static_cast(linear.feature_hr), static_cast(linear.share_hr)); } ID3D12Heap* heap = nullptr; x2w_budget::Ticket* backing_budget = nullptr; @@ -4409,9 +4417,10 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 placement = "not aliased"; } log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) address=%p base=%p offset=0x%llx width=0x%llx flags=0x%x " - "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx", address, base, offset, desc->Width, desc->Flags, state, - clear, text, static_cast(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); + "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx%s", address, base, offset, desc->Width, desc->Flags, state, + clear, text, static_cast(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull, linear_note); if (FAILED(hr)) return hr; + if (linear.path == x2w_startup::LinearBuffers::kept_default_path) linear_buffers().kept_default(resource, linear); return publish_placed_buffer(self, address, desc, initial_state, resource, aliased, backing_budget, out); } diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index c642b45d8b..e4927533bd 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -8,8 +8,9 @@ // unset or 0 the default: slot 133 keeps its backing (an existing heap cached by allocation // base for a private range, otherwise a committed default buffer that does not alias // the title memory and holds zeros). Nothing in this file runs. -// 1 share when the adapter, the extent and the use allow it, else copy, else refuse. -// copy never share; copy, else refuse. +// 1 share when the adapter, the extent and the use allow it, else copy, else keep the +// default backing and record why. +// copy never share; copy, else keep the default backing and record why. // // XMem owns the title memory (identity, mapping, offsets, lifetime); this file owns the desktop // backing and the fences that say when the GPU is done with it. @@ -37,15 +38,25 @@ // earlier submission on that queue; a title write to bytes that an incomplete submission still reads // is an unsynchronized concurrent write, outside the contract. // -// Refuse, with a defined HRESULT, when the copy cannot keep the guarantees sharing would give: -// - a GPU-written use (ALLOW_UNORDERED_ACCESS): the copy has no point at which GPU writes reach the -// title memory. Slot 133 returns the sharing HRESULT, or DXGI_ERROR_UNSUPPORTED when sharing was -// not attempted (X2W_D3D12_LINEAR_BUFFERS=copy). +// Where neither path can keep its guarantees, slot 133 keeps the default backing and returns what it +// returns without this switch. A title on the console does not see CreatePlacedResourceX fail, so a +// failed call would be a new failure (a title run that took the null object faulted at 1.76 s). The +// refusal is recorded instead: in the slot 133 log line ("kept default backing: linear refusal +// 0x..."), in x2w_d3d12_linear_buffer_info (path 3 and refusal_hr) and in the totals (kept_default, +// last_refusal_hr). The refusals: +// - a GPU-written use (ALLOW_UNORDERED_ACCESS) that cannot be shared: the copy has no point at which +// GPU writes reach the title memory. refusal_hr is the sharing HRESULT, or DXGI_ERROR_UNSUPPORTED +// when sharing was not attempted (X2W_D3D12_LINEAR_BUFFERS=copy). // - no submit fence (X2W_TEST_SUBMIT_FENCE_FAIL=1, or the fence cannot be created): staging reuse -// cannot wait for completion. Slot 133 returns E_NOT_VALID_STATE. -// - a submission whose refresh cannot be staged (the pool stays full past a 5 s wait, or creating a -// staging buffer or refresh list fails): the title's lists are not executed, and the HRESULT -// (DXGI_ERROR_WAS_STILL_DRAWING for the wait) is logged and kept in the totals. +// cannot wait for completion. E_NOT_VALID_STATE. +// - the copy's default buffer cannot be created: that HRESULT. +// +// At submit nothing is refused: holding back a submission can leave a title waiting on its fences. +// When a copied buffer's refresh cannot be staged (a staging buffer or refresh list cannot be +// created, or the pool stays full of buffers in flight past a 5 s wait: DXGI_ERROR_WAS_STILL_DRAWING), +// the title's lists run with the backing's last upload. The buffer is marked stale until a later +// refresh succeeds; the HRESULT is logged (the first few times) and kept in the buffer's info and the +// totals (refresh_failures, last_refresh_hr). // // Fixtures only: // X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1 the feature query reports no support (an adapter such as @@ -55,12 +66,15 @@ // reuse-early a staging buffer is reused without waiting for its fence // copy-gpu-writes the copy path accepts a GPU-written use // ignore-feature sharing is attempted although the feature query reports no support +// refusal-silent a kept default backing is not reported (no log text, info or totals) +// X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY #include #include #include #include +#include #include #include #include @@ -110,6 +124,17 @@ inline bool existing_heaps_forced_off() static const bool on = x2w_local::env_on("X2W_TEST_EXISTING_HEAPS_UNSUPPORTED"); return on; } +inline unsigned refresh_fault_period() +{ + static const unsigned period = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_REFRESH_FAIL", value, sizeof(value)); + SetLastError(saved); + return n && n < sizeof(value) ? static_cast(std::strtoul(value, nullptr, 10)) : 0u; + }(); + return period; +} inline bool submit_fence_forced_off() { static const bool on = GetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", nullptr, 0) != 0; @@ -136,7 +161,7 @@ class LinearBuffers { struct RefreshList; public: - enum Path : std::uint32_t { shared_path = 1, copied_path = 2 }; + enum Path : std::uint32_t { shared_path = 1, copied_path = 2, kept_default_path = 3 }; enum Use : std::uint32_t { gpu_read = 1, gpu_written = 2 }; // The kind this file handles. Anything else keeps the default backing. @@ -147,9 +172,13 @@ class LinearBuffers { desc.Width && initial_state == D3D12_RESOURCE_STATE_COMMON; } + // False under the refusal-silent mutant: a kept default backing is then not reported anywhere. + static bool report_refusals() { return !linear_detail::mutant("refusal-silent"); } + // Slot 133 for an eligible buffer. range is measure_placed_buffer's answer for (address, width) and // uav says whether the desktop flags keep ALLOW_UNORDERED_ACCESS. On success *out holds the - // desktop resource and *shared whether it aliases the title memory. + // desktop resource and *shared whether it aliases the title memory. A failure is a refusal: the + // caller keeps the default backing and passes *report (path kept_default_path) to kept_default(). HRESULT place(ID3D12Device* device, void* address, UINT64 width, bool uav, const PlacedBufferRange& range, ID3D12Resource** out, bool* shared, X2wLinearBufferInfo* report) { @@ -214,27 +243,48 @@ class LinearBuffers { ++totals_.copied; } } + if (SUCCEEDED(hr)) { + record.info.backing = resource; + try { + records_.emplace(resource, std::move(record)); + } catch (const std::bad_alloc&) { + hr = E_OUTOFMEMORY; + --(record.info.path == shared_path ? totals_.shared : totals_.copied); + } + } if (FAILED(hr)) { - ++totals_.refused; - totals_.last_refusal_hr = hr; if (resource) resource->Release(); + record.info.path = kept_default_path; + record.info.refusal_hr = hr; + record.info.backing = nullptr; if (report) *report = record.info; return hr; } - record.info.backing = resource; - if (report) *report = record.info; - const bool is_shared = record.info.path == shared_path; - try { - records_.emplace(resource, std::move(record)); - } catch (const std::bad_alloc&) { - resource->Release(); - return E_OUTOFMEMORY; - } + const auto& stored = records_.at(resource).info; + if (report) *report = stored; + const bool is_shared = stored.path == shared_path; *out = resource; *shared = is_shared; return S_OK; } + // Slot 133 kept the default backing for a refused placement: record why, for this resource. + void kept_default(ID3D12Resource* resource, const X2wLinearBufferInfo& report) + { + if (!report_refusals()) return; + std::lock_guard lock(mutex_); + ++totals_.kept_default; + totals_.last_refusal_hr = report.refusal_hr; + try { + Record record{}; + record.info = report; + record.info.path = kept_default_path; + record.info.backing = resource; + records_.insert_or_assign(resource, std::move(record)); + } catch (const std::bad_alloc&) { + } + } + // The resource never reached the title and is about to be released. void discard(ID3D12Resource* resource) { @@ -260,18 +310,17 @@ class LinearBuffers { }; // Before the title's lists are executed on queue (the contract's copy point): records and - // executes the refresh of every live copied buffer whose title bytes changed. A failure means the - // submission must not run; the HRESULT says why. - HRESULT before_submit(ID3D12CommandQueue* queue, Submission& submission) + // executes the refresh of every live copied buffer whose title bytes changed. Nothing here holds + // the submission back: a buffer whose refresh fails keeps its last upload and is marked stale. + void before_submit(ID3D12CommandQueue* queue, Submission& submission) { std::lock_guard lock(mutex_); ++totals_.submissions; bool any = false; for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; - if (!any) return S_OK; + if (!any) return; QueueState* state = nullptr; - HRESULT hr = queue_state(queue, &state); - if (FAILED(hr)) return refuse_submit(submission, hr); + const HRESULT state_hr = queue_state(queue, &state); struct Op { ID3D12Resource* dest; Copied* copy; @@ -294,55 +343,69 @@ class LinearBuffers { } std::size_t first = 0, last = bytes; if (copy->uploaded.size() == bytes) { - if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) continue; + if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) { + copy->stale = false; + continue; + } while (first < bytes && copy->uploaded[first] == source[first]) ++first; while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; first &= ~std::size_t{3}; last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); - } else { + } + const UINT64 span = last - first; + Staging* staging = nullptr; + HRESULT hr = state_hr; + if (SUCCEEDED(hr)) hr = take_staging(queue, span, submission, &staging); + if (SUCCEEDED(hr)) { try { - copy->uploaded.assign(bytes, 0); + submission.staging.push_back(staging); + ops.push_back({resource, copy, first, staging, span}); } catch (const std::bad_alloc&) { - return refuse_submit(submission, E_OUTOFMEMORY); + hr = E_OUTOFMEMORY; } } - const UINT64 span = last - first; - Staging* staging = nullptr; - hr = take_staging(queue, span, submission, &staging); - if (FAILED(hr)) return refuse_submit(submission, hr); - try { - submission.staging.push_back(staging); - ops.push_back({resource, copy, first, staging, span}); - } catch (const std::bad_alloc&) { - staging->value = 0; - return refuse_submit(submission, E_OUTOFMEMORY); + if (FAILED(hr)) { + if (staging && (submission.staging.empty() || submission.staging.back() != staging)) staging->value = 0; + refresh_failed(resource, *copy, hr); + continue; } std::memcpy(staging->mapped, source + first, static_cast(span)); - std::memcpy(copy->uploaded.data() + first, staging->mapped, static_cast(span)); } - if (ops.empty()) return S_OK; + if (ops.empty()) return; RefreshList* list = nullptr; - hr = take_list(queue, *state, &list); - if (FAILED(hr)) return refuse_submit(submission, hr); - // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST, and it decays to - // COMMON again when this ExecuteCommandLists completes, before the title's lists use it. - for (const Op& op : ops) list->list->CopyBufferRegion(op.dest, op.offset, op.source->buffer, 0, op.bytes); - hr = list->list->Close(); + HRESULT hr = take_list(queue, *state, &list); + if (SUCCEEDED(hr)) { + // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST, and it decays to + // COMMON again when this ExecuteCommandLists completes, before the title's lists use it. + for (const Op& op : ops) list->list->CopyBufferRegion(op.dest, op.offset, op.source->buffer, 0, op.bytes); + hr = list->list->Close(); + if (FAILED(hr)) list->value = 0; + } if (FAILED(hr)) { - list->value = 0; - return refuse_submit(submission, hr); + for (Staging* staging : submission.staging) staging->value = 0; + submission = {}; + for (const Op& op : ops) refresh_failed(op.dest, *op.copy, hr); + return; } ID3D12CommandList* lists[] = {list->list}; queue->ExecuteCommandLists(1, lists); submission.list = list; for (const Op& op : ops) { - ++op.copy->refreshes; - op.copy->bytes_copied += op.bytes; - op.copy->last_staging = op.source->id; + Copied& copy = *op.copy; + // The backing now holds these bytes (the staging buffer keeps them until its fence). + try { + if (copy.uploaded.size() != copy.bytes) copy.uploaded.assign(static_cast(copy.bytes), 0); + std::memcpy(copy.uploaded.data() + op.offset, op.source->mapped, static_cast(op.bytes)); + } catch (const std::bad_alloc&) { + copy.uploaded.clear(); // the next submission copies the whole buffer again + } + copy.stale = false; + ++copy.refreshes; + copy.bytes_copied += op.bytes; + copy.last_staging = op.source->id; ++totals_.refreshes; totals_.bytes_copied += op.bytes; } - return S_OK; } // After the title's lists were executed on queue: the fence value that completes them also releases @@ -382,6 +445,9 @@ class LinearBuffers { out->bytes_copied = copy->bytes_copied; out->last_staging = copy->last_staging; out->last_fence = copy->last_fence; + out->stale = copy->stale ? 1 : 0; + out->refresh_failures = copy->refresh_failures; + out->last_refresh_hr = copy->last_refresh_hr; } return true; } @@ -399,7 +465,9 @@ class LinearBuffers { bool live = true; std::vector uploaded; // what the backing holds (empty before the first refresh) std::vector bound; // skip-refresh mutant: the bytes at placement - UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, last_fence = 0; + UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, last_fence = 0, refresh_failures = 0; + bool stale = false; + HRESULT last_refresh_hr = S_OK; }; struct Record { X2wLinearBufferInfo info{}; @@ -528,6 +596,9 @@ class LinearBuffers { HRESULT take_staging(ID3D12CommandQueue* queue, UINT64 bytes, const Submission& submission, Staging** out) { + if (const unsigned period = linear_detail::refresh_fault_period(); + period && ++staging_requests_ % period == 2 % period) + return E_OUTOFMEMORY; // fixture fault (X2W_TEST_LINEAR_REFRESH_FAIL) const bool early = linear_detail::mutant("reuse-early"); for (int attempt = 0; attempt < 2; ++attempt) { Staging* best = nullptr; @@ -617,20 +688,17 @@ class LinearBuffers { return S_OK; } - HRESULT refuse_submit(Submission& submission, HRESULT hr) + // The submission runs without this buffer's refresh: its backing keeps the last upload. + void refresh_failed(ID3D12Resource* resource, Copied& copy, HRESULT hr) { - // Staging taken for this submission was not used on the GPU: free it again. - for (Staging* staging : submission.staging) staging->value = 0; - submission = {}; - if (x2w_local::first_calls(refusal_logged_, 8)) - x2w_local::logf("x2w-d3d12 linear buffers: submission refused 0x%08lx: the copied buffers could not be " - "refreshed; the title's lists are not executed", static_cast(hr)); - ++totals_.submissions_refused; - totals_.last_submit_hr = hr; - // The bytes recorded as uploaded were not: the next submission copies the whole buffer again. - for (auto& [resource, record] : records_) - if (record.copy) record.copy->uploaded.clear(); - return hr; + copy.stale = true; + ++copy.refresh_failures; + copy.last_refresh_hr = hr; + ++totals_.refresh_failures; + totals_.last_refresh_hr = hr; + if (x2w_local::first_calls(refresh_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffers: refresh of %p failed 0x%08lx; the submission runs with its last " + "upload (stale)", static_cast(resource), static_cast(hr)); } std::mutex mutex_; @@ -642,9 +710,9 @@ class LinearBuffers { HRESULT feature_hr_ = S_FALSE; ID3D12Device* fence_check_device_ = nullptr; HRESULT fence_check_hr_ = S_OK; - UINT64 generation_ = 0, staging_ids_ = 0; + UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; X2wLinearBufferTotals totals_{}; - volatile LONG unreadable_logged_ = 0, signal_logged_ = 0, refusal_logged_ = 0; + volatile LONG unreadable_logged_ = 0, signal_logged_ = 0, refresh_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index 90e15206cc..fae1176e76 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -7,22 +7,27 @@ #include struct X2wLinearBufferInfo { - std::uint32_t path; // 1 shared, 2 copied (a refused placement creates no resource) + std::uint32_t path; // 1 shared, 2 copied, 3 kept the default backing (refusal_hr says why) std::uint32_t use; // 1 GPU-read, 2 GPU-written std::int32_t feature_hr; // S_OK supported, DXGI_ERROR_UNSUPPORTED not, other: query failed; S_FALSE not queried std::int32_t share_hr; // result of the sharing attempt; S_FALSE when not attempted + std::int32_t refusal_hr; // kept default: why the new path could not keep its guarantees; else S_OK + std::uint32_t stale; // copied: 1 while the backing holds an older upload than the title's bytes std::uint64_t heap_generation; // shared: generation of the opened heap void* backing; // the desktop ID3D12Resource std::uint64_t refreshes; // copied: submissions that copied bytes into the backing std::uint64_t bytes_copied; // copied: bytes copied from title memory into the backing std::uint64_t last_staging; // copied: id of the staging buffer of the last refresh (0: none) std::uint64_t last_fence; // copied: queue fence value after the last submission (0: none) + std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh + std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none + std::int32_t reserved; }; struct X2wLinearBufferTotals { - std::uint64_t placements, shared, copied, refused; + std::uint64_t placements, shared, copied, kept_default; std::uint64_t feature_queries, heap_opens, heap_open_failures, heap_cache_hits, place_failures; std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; - std::uint64_t submissions_refused; - std::int32_t last_refusal_hr, last_submit_hr; + std::uint64_t refresh_failures; + std::int32_t last_refusal_hr, last_refresh_hr; }; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 3594a25c20..c525c9a282 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -14,7 +14,17 @@ // refusal X2W_D3D12_LINEAR_BUFFERS=1 with X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1: the host refuses // sharing (as an adapter reporting D3D12_FEATURE_EXISTING_HEAPS = 0 does) // untracked X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_SUBMIT_FENCE_FAIL=1: no submit fence, so -// the copy cannot keep its lifetime guarantee and must refuse +// the copy cannot keep its lifetime guarantee: slot 133 keeps the default backing +// stale X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_LINEAR_REFRESH_FAIL=3: staging requests 2, +// 5, 8 ... fail, so one refresh per pool cannot be staged +// +// Where the new path cannot keep its guarantees (a GPU-written use that is not shared, no submit +// fence), slot 133 must keep the default backing and return what it returns with the switch off: +// S_OK, an XMem view not aliased, a private range aliased (on an adapter with existing heaps). The +// refusal must be reported in x2w_d3d12_linear_buffer_info (path 3, refusal_hr), in the totals +// (kept_default) and in the slot 133 log line ("kept default backing: linear refusal 0x..."), which +// the fixture reads back from X2W_TRAP_LOG (linear_buffer_backing__.log next to the +// executable). // // Title memory comes from two pools. "xmem": xmem.dll physical pages (64 KiB slots of 256 MiB // pagefile sections) mapped with X2W_XMEM_SHARED_VIEWS=1, five pages per mapping call (one view): @@ -27,8 +37,8 @@ // before ExecuteCommandLists. The GPU must read B. // a2 then 16 words change to E: the next submission reads them, and a copy moves only those 64 bytes. // b a GPU-written use (ALLOW_UNORDERED_ACCESS): the GPU writes G ^ key; after the fence the CPU -// alias holds it and the words around keep theirs. The copy cannot give this: it must refuse, -// with the sharing HRESULT. +// alias holds it and the words around keep theirs. The copy cannot give this: slot 133 keeps the +// default backing and reports the sharing HRESULT (DXGI_ERROR_UNSUPPORTED when not attempted). // c a submission is held in flight on a gate fence, then two more (other buffers, C and D). Each // held submission reads its own sentinel. Sharing: the title releases X while it is held, and // after the fence places a new buffer (E) at X's address, on the same cached heap generation. @@ -39,7 +49,10 @@ // (the oracle sees a missing refresh); sharing reads B. Through the wrapper the copy reads B. // d2 readback before the fence: the GPU write of b is held on the gate. Before the gate opens the // fence has not completed and the alias still holds P in every word (the read is ordered -// before the write by the queue's Wait); after it, G ^ key. Copying refuses the use (as b). +// before the write by the queue's Wait); after it, G ^ key. Copying keeps the default (as b). +// stale (stale only) a refreshed submission of A; the CPU writes B and the next refresh fails: the +// submission still runs and completes, reads A (the last upload), and the buffer is reported +// stale with E_OUTOFMEMORY in info, totals and the log; the next submission reads B and clears it. // split (share only) a buffer across two XMem views: sharing is refused with E_INVALIDARG, decided // before any D3D12 call, and the buffer is copied; case a must still read B. // gate (refusal only) no heap was opened: D3D12_FEATURE_EXISTING_HEAPS gates sharing before any open. @@ -52,7 +65,7 @@ // // --mutate sets X2W_TEST_LINEAR_BUFFER_MUTANT, which removes one guarantee inside d3d12_xs.dll: // skip-refresh (copy) case a, reuse-early (copy) case c, copy-gpu-writes (copy) case b, -// ignore-feature (refusal) case gate. +// ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported). // The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). // X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. // Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter @@ -190,7 +203,36 @@ cbuffer Key : register(b0) { uint key; }; void main(uint3 id : SV_DispatchThreadID) { dst.Store(id.x * 4, src.Load(id.x * 4) ^ key); } )"; -enum class Path { default_backing, share, copy, refusal, untracked }; +// The X2W_TRAP_LOG file d3d12_xs.dll appends its log lines to; a line with both needles. +std::wstring log_path; +bool log_has(const std::string& first, const std::string& second) +{ + HANDLE file = CreateFileW(log_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + std::string text; + char chunk[65536]; + DWORD got = 0; + while (ReadFile(file, chunk, sizeof(chunk), &got, nullptr) && got) text.append(chunk, got); + CloseHandle(file); + std::size_t at = 0; + while (at < text.size()) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const std::string line = text.substr(at, end - at); + if (line.find(first) != std::string::npos && line.find(second) != std::string::npos) return true; + at = end + 1; + } + return false; +} +std::string pointer_text(const void* p) +{ + char text[32]; + std::snprintf(text, sizeof(text), "%p", p); + return text; +} + +enum class Path { default_backing, share, copy, refusal, untracked, stale }; const char* path_name(Path p) { switch (p) { @@ -198,7 +240,8 @@ const char* path_name(Path p) case Path::share: return "share"; case Path::copy: return "copy"; case Path::refusal: return "refusal"; - default: return "untracked"; + case Path::untracked: return "untracked"; + default: return "stale"; } } @@ -462,6 +505,7 @@ struct TitleList { struct Placed { HRESULT hr = E_FAIL; + const void* address = nullptr; ComPtr wrapper; ComPtr backing; X2wLinearBufferInfo info{}; @@ -471,6 +515,7 @@ struct Placed { Placed place(Gpu& gpu, std::uint8_t* address, bool gpu_written) { Placed p; + p.address = address; using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); const auto desc = buffer_desc(buffer_bytes, gpu_written ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE); auto* slot = reinterpret_cast((*reinterpret_cast(gpu.guest.Get()))[133]); @@ -492,7 +537,10 @@ std::string backing_text(const Placed& p) if (FAILED(p.hr)) return "refused " + hex(p.hr); if (!p.linear) return "default"; char text[160]; - if (p.info.path == 1) + if (p.info.path == 3) + std::snprintf(text, sizeof(text), "kept default backing (refusal %s, share %s, feature %s)", hex(p.info.refusal_hr).c_str(), + hex(p.info.share_hr).c_str(), hex(p.info.feature_hr).c_str()); + else if (p.info.path == 1) std::snprintf(text, sizeof(text), "shared (heap generation %llu, feature %s)", static_cast(p.info.heap_generation), hex(p.info.feature_hr).c_str()); else @@ -515,7 +563,8 @@ X2wLinearBufferTotals totals() struct Run { Gpu& gpu; Path path; - unsigned failures = 0, skips = 0; + bool adapter_heaps; // the adapter's own D3D12_FEATURE_EXISTING_HEAPS: the default aliases private ranges + unsigned failures = 0, skips = 0, kept_rows = 0; std::vector> results; // case name -> passed (for --mutate) bool copying() const { return path == Path::copy || path == Path::refusal; } @@ -526,6 +575,21 @@ struct Run { { return path == Path::refusal ? DXGI_ERROR_UNSUPPORTED : path == Path::share && pool.xmem ? HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) : S_FALSE; } + // The default backing aliases this pool: a private range on an adapter with existing heaps. + bool default_aliases(const Pool& pool) const { return !pool.xmem && adapter_heaps; } + // A refusal that kept the default backing: slot 133 returned S_OK with an object, and info and the + // slot 133 log line carry the refusal HRESULT. + bool kept_ok(const Placed& p, HRESULT want, std::string& text) + { + char needle[64]; + std::snprintf(needle, sizeof(needle), "kept default backing: linear refusal 0x%08lx", static_cast(want)); + const bool logged = log_has("address=" + pointer_text(p.address), needle); + const bool ok = SUCCEEDED(p.hr) && p.wrapper && p.linear && p.info.path == 3 && p.info.refusal_hr == want && logged; + text += std::string("; refusal ") + (p.linear ? hex(p.info.refusal_hr) : std::string("NOT IN INFO")) + " (expected " + hex(want) + + "), log line " + (logged ? "present" : "MISSING"); + ++kept_rows; + return ok; + } void row(const Pool& pool, const char* name, bool pass, const std::string& text) { std::printf("%-8s %-8s %-6s %s: %s\n", path_name(path), pool.name(), name, pass ? "PASS" : "FAIL", text.c_str()); @@ -544,13 +608,13 @@ struct Run { case Path::copy: return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.share_hr == S_FALSE; case Path::refusal: return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.share_hr == DXGI_ERROR_UNSUPPORTED && p.info.feature_hr == DXGI_ERROR_UNSUPPORTED; - default: return p.hr == E_NOT_VALID_STATE; + default: return false; // untracked: kept_ok decides } } - // What the GPU must read in case a: B, except on the default path over an XMem view (not aliased, zero). + // What the GPU must read in case a: B, except where the default backing does not alias (zero). bool read_ok(const Pool& pool, const Tally& t, Tag want) const { - if (path == Path::default_backing && pool.xmem) return t.zero == words; + if ((path == Path::default_backing || path == Path::untracked) && !default_aliases(pool)) return t.zero == words; return t.count[want] == words; } @@ -560,10 +624,6 @@ struct Run { Memory memory; if (!(split ? pool.allocate_split(memory, A) : pool.allocate(memory, A))) return row(pool, name, false, "allocation failed"); Placed p = place(gpu, memory.buffer(), false); - if (path == Path::untracked) { - return row(pool, name, p.hr == E_NOT_VALID_STATE && !p.wrapper, - "slot 133 -> " + hex(p.hr) + " (expected E_NOT_VALID_STATE 0x8007139f: no submit fence to guard staging reuse)"); - } TitleList list; if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, name, false, "slot 133 -> " + hex(p.hr)); list.read(p.backing.Get()); @@ -572,12 +632,16 @@ struct Run { if (!gpu.wait(list.submit())) return row(pool, name, false, "fence timeout"); const Tally t = tally(gpu.read_output().data(), r0 / 4, key); refresh_info(p); - const bool pass = backing_ok(pool, p, split) && read_ok(pool, t, B) && - (!p.linear || p.info.path != 2 || p.info.bytes_copied == buffer_bytes); std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; GPU read " + t.text(); - if (path == Path::default_backing) text += pool.xmem ? " (old behaviour: not aliased, no copy)" : " (old behaviour: aliased)"; + bool pass = read_ok(pool, t, B) && (!p.linear || p.info.path != 2 || p.info.bytes_copied == buffer_bytes); + if (path == Path::untracked) + pass &= kept_ok(p, E_NOT_VALID_STATE, text); // no submit fence to guard staging reuse + else + pass &= backing_ok(pool, p, split); + if (path == Path::default_backing || path == Path::untracked) + text += default_aliases(pool) ? " (old behaviour: aliased)" : " (old behaviour: not aliased, no copy)"; row(pool, name, pass, text); - if (split || !pass || path == Path::default_backing) return; + if (split || !pass || path == Path::default_backing || path == Path::untracked) return; // a2: 16 words change; only they are copied. TitleList second; @@ -603,16 +667,12 @@ struct Run { write(memory.buffer(), r1, P, words); Placed p = place(gpu, memory.buffer(), true); const auto* alias = reinterpret_cast(memory.buffer() + r1); - const bool copy_refuses = copied(pool) || path == Path::untracked; - if (copy_refuses && FAILED(p.hr)) { - // The copy has no point at which a GPU write reaches the title memory: refused, no object. The - // refusal carries the sharing HRESULT (the feature gate's DXGI_ERROR_UNSUPPORTED, or - // ERROR_NOT_SUPPORTED for an XMem view), or DXGI_ERROR_UNSUPPORTED when sharing is not - // attempted (copy, untracked). - const HRESULT want = share_refusal(pool) == S_FALSE ? DXGI_ERROR_UNSUPPORTED : share_refusal(pool); - return row(pool, name, p.hr == want && !p.wrapper, - "GPU-written use: slot 133 -> " + hex(p.hr) + " (expected refusal " + hex(want) + ")"); - } + // The copy has no point at which a GPU write reaches the title memory: slot 133 keeps the default + // backing and reports the sharing HRESULT (the feature gate's DXGI_ERROR_UNSUPPORTED, or + // ERROR_NOT_SUPPORTED for an XMem view), or DXGI_ERROR_UNSUPPORTED when sharing is not attempted. + const bool kept = copied(pool) || path == Path::untracked; + const bool on_default = kept || path == Path::default_backing; + const HRESULT want = share_refusal(pool) == S_FALSE ? DXGI_ERROR_UNSUPPORTED : share_refusal(pool); TitleList list; if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, name, false, "slot 133 -> " + hex(p.hr)); list.write_g(p.backing.Get()); @@ -640,14 +700,13 @@ struct Run { bool pass; std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; " + early + "after the fence alias " + (t.count[G] ? t.text() + " (G ^ key)" : raw.text()) + (around ? ", neighbours kept" : ", NEIGHBOURS CHANGED"); - if (path == Path::default_backing && pool.xmem) { - pass = SUCCEEDED(p.hr) && !p.linear && raw.count[P] == words && around; - text += " (old behaviour: not aliased, the alias keeps P)"; - } else { - pass = early_ok && around && t.count[G] == words && - (path == Path::default_backing ? SUCCEEDED(p.hr) && !p.linear : p.linear && p.info.path == 1); - if (path == Path::default_backing) text += " (old behaviour: aliased)"; - } + // Visible: shared, or a default backing that aliases this pool. + const bool visible = on_default ? default_aliases(pool) : true; + pass = early_ok && around && (visible ? t.count[G] == words : raw.count[P] == words); + if (path == Path::default_backing) pass &= SUCCEEDED(p.hr) && !p.linear; + else if (kept) pass &= kept_ok(p, want, text); + else pass &= p.linear && p.info.path == 1; + if (on_default) text += visible ? " (old behaviour: aliased)" : " (old behaviour: not aliased, the alias keeps P)"; row(pool, name, pass, text); } @@ -771,6 +830,47 @@ struct Run { freed ? "freed" : "not freed"); } + // stale: a refresh that cannot be staged; the submission still runs, with the last upload. + void case_stale(Pool& pool) + { + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "stale", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList first, second, third; + if (FAILED(p.hr) || !p.backing || !first.begin(gpu) || !second.begin(gpu) || !third.begin(gpu)) + return row(pool, "stale", false, "slot 133 -> " + hex(p.hr)); + first.read(p.backing.Get()); + first.close(); + if (!gpu.wait(first.submit())) return row(pool, "stale", false, "fence timeout (first)"); + const Tally t1 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool fresh1 = p.linear && p.info.path == 2 && !p.info.stale; + write(memory.buffer(), r0, B, words); + second.read(p.backing.Get()); + second.close(); + // The refresh of this submission fails (fixture fault): it must still run and complete. + const bool completed = gpu.wait(second.submit()); + const Tally t2 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + char needle[64]; + std::snprintf(needle, sizeof(needle), "failed 0x%08lx", static_cast(E_OUTOFMEMORY)); + const bool logged = log_has("refresh of " + pointer_text(p.backing.Get()), needle); + const bool stale2 = p.info.stale == 1 && p.info.refresh_failures == 1 && p.info.last_refresh_hr == E_OUTOFMEMORY; + const unsigned stale_flag = p.info.stale; + third.read(p.backing.Get()); + third.close(); + if (!gpu.wait(third.submit())) return row(pool, "stale", false, "fence timeout (third)"); + const Tally t3 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool pass = fresh1 && t1.count[A] == words && completed && t2.count[A] == words && stale2 && logged && + t3.count[B] == words && !p.info.stale; + row(pool, "stale", pass, + "refreshed " + t1.text() + "; failed refresh: submission " + (completed ? "completed" : "DID NOT COMPLETE") + ", read " + + t2.text() + " (last upload), stale=" + std::to_string(stale_flag) + " " + (stale2 ? "reported" : "NOT REPORTED") + + " with " + hex(E_OUTOFMEMORY) + ", log line " + (logged ? "present" : "MISSING") + "; next submission read " + t3.text() + + (p.info.stale ? ", STILL STALE" : ", stale cleared")); + } + void case_d1(Pool& pool) { if (path == Path::default_backing || path == Path::untracked) return; @@ -806,7 +906,7 @@ struct Run { int main(int argc, char** argv) { if (argc < 3) { - std::puts("usage: linear_buffer_backing_check [--mutate ]"); + std::puts("usage: linear_buffer_backing_check [--mutate ]"); return 2; } const bool warp = std::strcmp(argv[1], "warp") == 0; @@ -818,6 +918,7 @@ int main(int argc, char** argv) else if (p == "copy") path = Path::copy; else if (p == "refusal") path = Path::refusal; else if (p == "untracked") path = Path::untracked; + else if (p == "stale") path = Path::stale; else return 2; std::string mutant; if (argc == 5 && std::strcmp(argv[3], "--mutate") == 0) mutant = argv[4]; @@ -829,10 +930,24 @@ int main(int argc, char** argv) SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr - : path == Path::copy || path == Path::untracked ? L"copy" : L"1"); + : path == Path::copy || path == Path::untracked || path == Path::stale ? L"copy" : L"1"); SetEnvironmentVariableW(L"X2W_TEST_EXISTING_HEAPS_UNSUPPORTED", path == Path::refusal ? L"1" : nullptr); SetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", path == Path::untracked ? L"1" : nullptr); + SetEnvironmentVariableW(L"X2W_TEST_LINEAR_REFRESH_FAIL", path == Path::stale ? L"3" : nullptr); SetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", mutant.empty() ? nullptr : mutant.c_str()); + { + // The DLL's log lines go to linear_buffer_backing__[_].log next to this executable. + wchar_t module[MAX_PATH]{}; + const DWORD n = GetModuleFileNameW(nullptr, module, MAX_PATH); + if (!n || n >= MAX_PATH) return 1; + log_path.assign(module, n); + log_path.resize(log_path.find_last_of(L"\\/") + 1); + const std::string name = std::string("linear_buffer_backing_") + path_name(path) + "_" + argv[1] + + (mutant.empty() ? "" : "_" + mutant) + ".log"; + log_path.append(name.begin(), name.end()); + DeleteFileW(log_path.c_str()); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + } char debug_env[4]{}; const bool debug_layer = GetEnvironmentVariableA("X2W_TEST_DEBUG_LAYER", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; @@ -883,13 +998,17 @@ int main(int argc, char** argv) return 77; } - Run run{gpu, path}; + Run run{gpu, path, SUCCEEDED(heaps_hr) && heaps.Supported != FALSE}; for (const bool xmem : {true, false}) { Pool pool(xmem); if (!pool.init()) { run.row(pool, "pool", false, "title memory could not be set up"); continue; } + if (path == Path::stale) { + run.case_stale(pool); + continue; + } run.case_a(pool); if (path == Path::share && xmem) run.case_a(pool, true); run.case_b(pool, false); @@ -899,25 +1018,34 @@ int main(int argc, char** argv) run.probe_view_pin(pool); } const X2wLinearBufferTotals t = totals(); - std::printf("totals: placements %llu (shared %llu, copied %llu, refused %llu), feature queries %llu, heap opens %llu " + std::printf("totals: placements %llu (shared %llu, copied %llu, kept default %llu), feature queries %llu, heap opens %llu " "(failed %llu, cache hits %llu), placements failed %llu, submissions %llu, refreshes %llu, bytes copied %llu, " - "staging created %llu reused %llu, unreadable %llu, submissions refused %llu, last refusal %s\n", + "staging created %llu reused %llu, unreadable %llu, refresh failures %llu, last refusal %s, last refresh failure %s\n", static_cast(t.placements), static_cast(t.shared), - static_cast(t.copied), static_cast(t.refused), + static_cast(t.copied), static_cast(t.kept_default), static_cast(t.feature_queries), static_cast(t.heap_opens), static_cast(t.heap_open_failures), static_cast(t.heap_cache_hits), static_cast(t.place_failures), static_cast(t.submissions), static_cast(t.refreshes), static_cast(t.bytes_copied), static_cast(t.staging_created), static_cast(t.staging_reused), - static_cast(t.unreadable), static_cast(t.submissions_refused), - hex(t.last_refusal_hr).c_str()); + static_cast(t.unreadable), static_cast(t.refresh_failures), + hex(t.last_refusal_hr).c_str(), hex(t.last_refresh_hr).c_str()); { Pool none(false); if (path == Path::default_backing) { // Opt-in off: no linear-buffer bookkeeping at all. const bool untouched = !t.placements && !t.submissions && !t.feature_queries && !t.heap_opens; run.row(none, "off", untouched, untouched ? "no linear-buffer code ran (all totals zero)" : "LINEAR-BUFFER CODE RAN"); - } else if (path == Path::refusal) { + } else if (path == Path::stale) { + run.row(none, "totals", t.refresh_failures == 2 && t.last_refresh_hr == E_OUTOFMEMORY && t.kept_default == 0, + "refresh failures " + std::to_string(t.refresh_failures) + " (expected 2, one per pool), last " + hex(t.last_refresh_hr)); + } + if (path != Path::default_backing && path != Path::stale) { + run.row(none, "kept", t.kept_default == run.kept_rows, + "totals report " + std::to_string(t.kept_default) + " kept default backings for " + std::to_string(run.kept_rows) + + " refused placements, last refusal " + hex(t.last_refusal_hr)); + } + if (path == Path::refusal) { run.row(none, "gate", t.feature_queries == 1 && t.heap_opens == 0, "feature queries " + std::to_string(t.feature_queries) + ", heap opens " + std::to_string(t.heap_opens) + " (expected 1 and 0: no open is attempted when D3D12_FEATURE_EXISTING_HEAPS reports no support)"); @@ -936,7 +1064,7 @@ int main(int argc, char** argv) if (!mutant.empty()) { const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" - : mutant == "ignore-feature" ? "gate" : nullptr; + : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results) From b121bfc9a34028d56308bb08c2ca0ac5666f9d4c Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 07:00:53 +0100 Subject: [PATCH 03/18] gpu: refresh linear buffers without holding their lock across waits Review of #2218: - before_submit snapshots the copied buffers' work under mutex_, then takes, creates or waits for staging (a full pool waits up to 5 s for the oldest fence), fills it, resets and records a refresh list and runs ExecuteCommandLists without the lock, and publishes the result under it again. A release(), the fixture exports or another queue's submission no longer wait behind a fence wait or ExecuteCommandLists. Staging is still reused only after its fence, the refresh still runs at submit, and a buffer whose staging fails is still marked stale. - In render mode the refresh runs before queue_execute takes draw_lock and allocator_lock, so a staging wait does not stall list recording. - x2w_d3d12_linear_buffer_info returns false for a wrapper without a desktop object. The fixture adds a contention path (X2W_TEST_LINEAR_STAGING_LIMIT=1): while a refresh waits for the only staging buffer behind a gate, the info export, release() and a second queue's submission must finish, and a hold-lock mutant that keeps the lock across the wait must fail. The copy path also refreshes on COMPUTE and COPY queues, read by a dispatch and by CopyBufferRegion. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 11 +- docs/experiments.md | 9 +- docs/startup-runtime.md | 5 +- src/startup_stubs/d3d12_xs_device.cpp | 14 +- src/startup_stubs/linear_buffer_backing.h | 350 ++++++++++++++-------- tests/linear_buffer_backing_check.cpp | 203 ++++++++++++- 6 files changed, 436 insertions(+), 156 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0039ce991b..5e0d5caa1a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2588,21 +2588,22 @@ endforeach() # The production slice (#1914): slot 133's opt-in linear-buffer backing (X2W_D3D12_LINEAR_BUFFERS, # src/startup_stubs/linear_buffer_backing.h) through the device and queue wrappers of d3d12_xs.dll, over # XMem pages and a private range: the default, real sharing, forced copying, host sharing refusal, a -# copy without a submit fence (the default backing is kept and the refusal reported) and a refresh -# that cannot be staged (the submission runs, the buffer is reported stale). Each mutant removes one -# guarantee in the DLL and must fail its case. +# copy without a submit fence (the default backing is kept and the refusal reported), a refresh that +# cannot be staged (the submission runs, the buffer is reported stale) and a one-buffer staging pool +# (a waiting refresh must not block release(), the info export or another queue). The copy path also +# refreshes on COMPUTE and COPY queues. Each mutant removes one guarantee in the DLL and must fail its case. add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) target_include_directories(linear_buffer_backing_check PRIVATE tests) target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) target_link_libraries(linear_buffer_backing_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi d3dcompiler) foreach(adapter IN ITEMS warp hardware) - foreach(path IN ITEMS default share copy refusal untracked stale) + foreach(path IN ITEMS default share copy refusal untracked stale contention) add_test(NAME linear_buffer_backing_${path}_${adapter} COMMAND linear_buffer_backing_check ${adapter} ${path}) set_tests_properties(linear_buffer_backing_${path}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() endforeach() foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature - copy:refusal_silent) + copy:refusal_silent contention:hold_lock) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/docs/experiments.md b/docs/experiments.md index f90410ebcf..3ef5cad5bb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9681,8 +9681,10 @@ A title run motivated the fallback. An earlier revision returned the refusal fro | off | `default` only: none of the linear-buffer code ran. | | kept | every path with refusals: the totals count as many kept default backings as the run refused. | | stale | `stale` only: a refreshed submission of A, then the CPU writes B and the refresh fails. The submission must still run and complete and read A (the last upload). The buffer must be reported stale with `E_OUTOFMEMORY` in its info and the log. The next submission must read B and clear it. | +| q.comp, q.copy | `copy` only: the buffer is read on a COMPUTE queue (a dispatch) and on a COPY queue (`CopyBufferRegion`), each through its queue wrapper, so the refresh runs on that queue. The first submission must read B with the whole buffer copied, and a 16-word change must then copy 64 bytes. | +| contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a gate and holds the only staging buffer. S2's refresh of X, on another thread, must wait for S1's fence. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the gate opens, S2 must take the same staging buffer (none created), and S1 and S2 must read B and C with no refresh failure. | -On Windows 11 build 26300 at `ab9a020c` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All six paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. +On Windows 11 build 26300 at `b0669e06` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All seven paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. | Path | Pool | Backing | Slot 133 / sharing HRESULT | Bytes copied | Results | |---|---|---|---|---|---| @@ -9694,15 +9696,18 @@ On Windows 11 build 26300 at `ab9a020c` plus this change, the results were ident | `refusal` | XMem, private | as `copy` | `S_OK` / `0x887A0004` from the feature gate, no heap opened; b, d2 refusal `0x887A0004` | as `copy` | as `copy`; 4 kept | | `untracked` | XMem, private | kept default for every placement | `S_OK`; refusal `0x8007139F` (`E_NOT_VALID_STATE`) for a, `0x887A0004` for b and d2 | 0 | a: XMem reads zero, private B; b and d2: XMem leaves P, private G ^ key (as before); 6 kept | | `stale` | XMem, private | copied | `S_OK` / not attempted | 131,072 + 4,096 per pool; the failed refresh copies 0 | the failed submission completes and reads A, stale reported with `0x8007000E`, then B and stale cleared; 2 refresh failures | +| `copy` (q.comp, q.copy) | XMem, private | copied, refreshed on the COMPUTE or COPY queue | `S_OK` / not attempted | 131,072, then 64 | B in all words, then 16 E; no refresh failure | +| `contention` | XMem, private | copied, one staging buffer | `S_OK` / not attempted | 540,672 for the run | the probes took 0 ms each while S2 waited about 310 ms for the gate; S1 B, S2 C; staging created 1, no refresh failure | The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. -Five negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: +Six negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: - `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. - `reuse-early` hands out staging buffers without their fence. All three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). - `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). - `ignore-feature` opens a heap although the feature query reports no support. gate sees one heap open (1 of 1), and the private buffers are shared. - `refusal-silent` keeps the default backing without reporting it. b finds no refusal in the info and no log line (2 of 2), and the kept totals stay at 0. +- `hold-lock` keeps the backing's lock held while a refresh waits for a staging fence. contention's info probe then blocks for about 4.7 s, until the wait gives up after 5 s. S2 goes stale and reads B (2 of 2). Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 135afdeba9..fa31de7efa 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2923,13 +2923,16 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - Shared: a cross-adapter buffer placed on the private allocation's heap, cached by base. The GPU reads and writes title memory; nothing is copied. - An XMem view is never shared. A heap opened from a view keeps it mapped, and XMem's unmap of those pages then fails with error 87. Sharing reports `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)` (`0x80070032`) and the buffer is copied. A buffer across several allocations, or at an unaligned offset, reports `E_INVALIDARG`. Both are decided before any D3D12 call. - Copied: a committed default buffer that the command-queue wrapper refreshes from title memory just before the title's lists run on that queue, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. A staging buffer is reused only after the queue fence of the submission that read it has completed. + - The refresh runs on the queue that executes: direct, compute or copy. The buffer rests in `COMMON` and is promoted to `COPY_DEST` implicitly on each of them. + - In render mode it runs before the wrapper takes its draw and allocator locks. + - The lock that guards the backing is held only to choose and publish. Waiting for a staging fence (a full pool), creating staging or a refresh list, recording it and `ExecuteCommandLists` all happen without it. A `Release`, the fixture exports and another queue's submission therefore never wait behind them. - Kept default: where neither path keeps its guarantees, slot 133 keeps the default backing above and returns what it returns without the switch. On the console `CreatePlacedResourceX` does not fail, and a title that received a failure faulted on the null object. The refusal HRESULT is recorded instead: - a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared records the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory; - without a submit fence (`X2W_TEST_SUBMIT_FENCE_FAIL=1`), `E_NOT_VALID_STATE` (`0x8007139f`); - when the copy's default buffer cannot be created, that HRESULT. - A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. -A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 2183d8c863..ee173d5efa 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1565,7 +1565,7 @@ extern "C" __declspec(dllexport) void x2w_d3d12_render_target_stats(unsigned* bi extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_info(void* resource, X2wLinearBufferInfo* info) { Wrapper* w = as_wrapper(resource); - if (!info || !w || w->own().kind != resource_kind || + if (!info || !w || w->own().kind != resource_kind || !w->own().real || x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) return false; return linear_buffers().info(static_cast(w->own().real), info); @@ -3531,10 +3531,15 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) X2W_ZONE("ExecuteCommandLists"); static LONG calls; drain_retired_resources(); + x2w_startup::LinearBuffers::Submission linear; if (render_mode()) { // A closed list stays submittable until its next Reset, as on the desktop. std::vector ready; std::vector submitted; + auto* queue = static_cast(self->own().real); + // Before the wrapper's locks: a refresh may wait for a staging fence, and recording must not + // wait with it. + if (count) linear_refresh(queue, linear); // Pin the closed recording and its allocator through submission bookkeeping. AcquireSRWLockExclusive(&draw_lock); AcquireSRWLockExclusive(&allocator_lock); @@ -3545,11 +3550,8 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) submitted.push_back(w); } } - auto* queue = static_cast(self->own().real); bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { - x2w_startup::LinearBuffers::Submission linear_submission; - linear_refresh(queue, linear_submission); const UINT ready_count = static_cast(native_lists.size()); red_producers().execute(queue, native_lists, [&] { if (draw_dump_frame()) { @@ -3560,7 +3562,6 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } }); retire_address_uploads(queue, native_lists); - linear_submitted(queue, linear_submission); retire_draw_sampler_heaps(queue, native_lists); note_submits(queue, wrappers); retire_note_submission(queue, wrappers); @@ -3586,6 +3587,8 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } else if (!ready.empty()) { submit(ready, submitted); } + // Also when no list was ready: an executed refresh still needs its fence value. + linear_submitted(queue, linear); ReleaseSRWLockExclusive(&allocator_lock); ReleaseSRWLockExclusive(&draw_lock); check_device("CommandQueue execute", 35); @@ -3599,7 +3602,6 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) std::vector real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); auto* queue = static_cast(self->own().real); - x2w_startup::LinearBuffers::Submission linear; linear_refresh(queue, linear); queue->ExecuteCommandLists(count, real.data()); linear_submitted(queue, linear); diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index e4927533bd..565bed5a45 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -67,6 +67,8 @@ // copy-gpu-writes the copy path accepts a GPU-written use // ignore-feature sharing is attempted although the feature query reports no support // refusal-silent a kept default backing is not reported (no log text, info or totals) +// hold-lock the wait for a full staging pool keeps mutex_ held (other callers block) +// X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY #include @@ -222,7 +224,7 @@ class LinearBuffers { nullptr, IID_PPV_ARGS(&resource)); if (SUCCEEDED(hr)) { try { - record.copy = std::make_unique(); + record.copy = std::make_shared(); record.copy->title = static_cast(address); record.copy->bytes = width; if (linear_detail::mutant("skip-refresh")) { @@ -312,100 +314,121 @@ class LinearBuffers { // Before the title's lists are executed on queue (the contract's copy point): records and // executes the refresh of every live copied buffer whose title bytes changed. Nothing here holds // the submission back: a buffer whose refresh fails keeps its last upload and is marked stale. + // + // mutex_ is held only to read and publish state: the work is snapshotted under it, then staging + // is taken (and, with the pool full, its fence waited for), filled, recorded and executed without + // it, and the results are published under it again. A release() or another queue's submission + // therefore never waits behind a fence wait or ExecuteCommandLists here. void before_submit(ID3D12CommandQueue* queue, Submission& submission) { - std::lock_guard lock(mutex_); - ++totals_.submissions; - bool any = false; - for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; - if (!any) return; - QueueState* state = nullptr; - const HRESULT state_hr = queue_state(queue, &state); - struct Op { + struct Work { ID3D12Resource* dest; - Copied* copy; - UINT64 offset; - Staging* source; - UINT64 bytes; + std::shared_ptr copy; + const unsigned char* source; + UINT64 offset, bytes; + Staging* staging = nullptr; + HRESULT hr = S_OK; }; - std::vector ops; - for (auto& [resource, record] : records_) { - Copied* copy = record.copy.get(); - if (!copy || !copy->live) continue; - const std::size_t bytes = static_cast(copy->bytes); - const unsigned char* source = copy->bound.empty() ? copy->title : copy->bound.data(); - if (copy->bound.empty() && x2w_local::probe_readable(reinterpret_cast(source), bytes) < bytes) { - if (x2w_local::first_calls(unreadable_logged_, 4)) - x2w_local::logf("x2w-d3d12 linear buffer %p: title memory %p is no longer readable; its backing " - "keeps the last upload", static_cast(resource), static_cast(source)); - ++totals_.unreadable; - continue; - } - std::size_t first = 0, last = bytes; - if (copy->uploaded.size() == bytes) { - if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) { - copy->stale = false; + std::vector work; + QueueState* state = nullptr; + HRESULT state_hr = S_OK; + { + std::lock_guard lock(mutex_); + ++totals_.submissions; + bool any = false; + for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; + if (!any) return; + state_hr = queue_state(queue, &state); + for (auto& [resource, record] : records_) { + const std::shared_ptr& copy = record.copy; + if (!copy || !copy->live) continue; + const std::size_t bytes = static_cast(copy->bytes); + const unsigned char* source = copy->bound.empty() ? copy->title : copy->bound.data(); + if (copy->bound.empty() && x2w_local::probe_readable(reinterpret_cast(source), bytes) < bytes) { + if (x2w_local::first_calls(unreadable_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffer %p: title memory %p is no longer readable; its backing " + "keeps the last upload", static_cast(resource), static_cast(source)); + ++totals_.unreadable; continue; } - while (first < bytes && copy->uploaded[first] == source[first]) ++first; - while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; - first &= ~std::size_t{3}; - last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); - } - const UINT64 span = last - first; - Staging* staging = nullptr; - HRESULT hr = state_hr; - if (SUCCEEDED(hr)) hr = take_staging(queue, span, submission, &staging); - if (SUCCEEDED(hr)) { + std::size_t first = 0, last = bytes; + if (copy->uploaded.size() == bytes) { + if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) { + copy->stale = false; + continue; + } + while (first < bytes && copy->uploaded[first] == source[first]) ++first; + while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; + first &= ~std::size_t{3}; + last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); + } try { - submission.staging.push_back(staging); - ops.push_back({resource, copy, first, staging, span}); + work.push_back({resource, copy, source, first, last - first}); } catch (const std::bad_alloc&) { - hr = E_OUTOFMEMORY; + refresh_failed(resource, *copy, E_OUTOFMEMORY); } } - if (FAILED(hr)) { - if (staging && (submission.staging.empty() || submission.staging.back() != staging)) staging->value = 0; - refresh_failed(resource, *copy, hr); - continue; - } - std::memcpy(staging->mapped, source + first, static_cast(span)); } - if (ops.empty()) return; - RefreshList* list = nullptr; - HRESULT hr = take_list(queue, *state, &list); - if (SUCCEEDED(hr)) { - // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST, and it decays to - // COMMON again when this ExecuteCommandLists completes, before the title's lists use it. - for (const Op& op : ops) list->list->CopyBufferRegion(op.dest, op.offset, op.source->buffer, 0, op.bytes); - hr = list->list->Close(); - if (FAILED(hr)) list->value = 0; + if (work.empty()) return; + + // Without the lock: staging (each one ours alone once taken), the copy into it, the list, the queue. + std::vector taken; + bool any_staged = false; + for (Work& w : work) { + w.hr = state_hr; + if (SUCCEEDED(w.hr)) w.hr = acquire_staging(queue, w.bytes, taken, &w.staging); + if (FAILED(w.hr)) continue; + taken.push_back(w.staging); + std::memcpy(w.staging->mapped, w.source + w.offset, static_cast(w.bytes)); + any_staged = true; } - if (FAILED(hr)) { - for (Staging* staging : submission.staging) staging->value = 0; - submission = {}; - for (const Op& op : ops) refresh_failed(op.dest, *op.copy, hr); - return; + RefreshList* list = nullptr; + HRESULT list_hr = S_OK; + if (any_staged) { + list_hr = acquire_list(queue, *state, &list); + if (SUCCEEDED(list_hr)) { + // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST (on a direct, + // compute or copy queue alike), and it decays to COMMON again when this + // ExecuteCommandLists completes, before the title's lists use it. + for (const Work& w : work) + if (SUCCEEDED(w.hr)) list->list->CopyBufferRegion(w.dest, w.offset, w.staging->buffer, 0, w.bytes); + list_hr = list->list->Close(); + } + if (SUCCEEDED(list_hr)) { + ID3D12CommandList* lists[] = {list->list}; + queue->ExecuteCommandLists(1, lists); + } } - ID3D12CommandList* lists[] = {list->list}; - queue->ExecuteCommandLists(1, lists); - submission.list = list; - for (const Op& op : ops) { - Copied& copy = *op.copy; - // The backing now holds these bytes (the staging buffer keeps them until its fence). - try { - if (copy.uploaded.size() != copy.bytes) copy.uploaded.assign(static_cast(copy.bytes), 0); - std::memcpy(copy.uploaded.data() + op.offset, op.source->mapped, static_cast(op.bytes)); - } catch (const std::bad_alloc&) { - copy.uploaded.clear(); // the next submission copies the whole buffer again + + // Publish under the lock. + std::lock_guard lock(mutex_); + if (list && FAILED(list_hr)) list->value = 0; + for (Work& w : work) { + const HRESULT hr = FAILED(w.hr) ? w.hr : list_hr; + if (FAILED(hr)) { + if (w.staging) w.staging->value = 0; // never reached the GPU + refresh_failed(w.dest, *w.copy, hr); + continue; + } + submission.staging.push_back(w.staging); + Copied& copy = *w.copy; + if (copy.live) { + // The backing now holds these bytes (the staging buffer keeps them until its fence). + try { + if (copy.uploaded.size() != copy.bytes) copy.uploaded.assign(static_cast(copy.bytes), 0); + std::memcpy(copy.uploaded.data() + w.offset, w.staging->mapped, static_cast(w.bytes)); + } catch (const std::bad_alloc&) { + copy.uploaded.clear(); // the next submission copies the whole buffer again + } } copy.stale = false; ++copy.refreshes; - copy.bytes_copied += op.bytes; - copy.last_staging = op.source->id; + copy.bytes_copied += w.bytes; + copy.last_staging = w.staging->id; ++totals_.refreshes; - totals_.bytes_copied += op.bytes; + totals_.bytes_copied += w.bytes; } + if (SUCCEEDED(list_hr) && list) submission.list = list; } // After the title's lists were executed on queue: the fence value that completes them also releases @@ -471,7 +494,7 @@ class LinearBuffers { }; struct Record { X2wLinearBufferInfo info{}; - std::unique_ptr copy; + std::shared_ptr copy; // shared: a submission's snapshot outlives a discard }; struct Staging { ID3D12Resource* buffer = nullptr; @@ -495,7 +518,19 @@ class LinearBuffers { ID3D12Heap* heap; UINT64 generation, bytes; }; - static constexpr std::size_t staging_limit = 256; + // 256 staging buffers; X2W_TEST_LINEAR_STAGING_LIMIT= (fixtures) lowers it, to make the pool fill. + static std::size_t staging_limit() + { + static const std::size_t limit = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_STAGING_LIMIT", value, sizeof(value)); + SetLastError(saved); + const unsigned long parsed = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0; + return parsed ? static_cast(parsed) : std::size_t{256}; + }(); + return limit; + } HRESULT feature(ID3D12Device* device) { @@ -594,80 +629,124 @@ class LinearBuffers { (staging.value != ~UINT64{0} && staging.fence && staging.fence->GetCompletedValue() >= staging.value); } - HRESULT take_staging(ID3D12CommandQueue* queue, UINT64 bytes, const Submission& submission, Staging** out) + // Takes a staging buffer of at least `bytes` that no submission still reads, for this submission + // alone (`taken` are the ones it already holds). Called without mutex_: the lock is taken only to + // choose or publish a buffer; creating one and waiting for a fence happen outside it. + HRESULT acquire_staging(ID3D12CommandQueue* queue, UINT64 bytes, const std::vector& taken, Staging** out) { - if (const unsigned period = linear_detail::refresh_fault_period(); - period && ++staging_requests_ % period == 2 % period) - return E_OUTOFMEMORY; // fixture fault (X2W_TEST_LINEAR_REFRESH_FAIL) const bool early = linear_detail::mutant("reuse-early"); + { + std::lock_guard lock(mutex_); + if (const unsigned period = linear_detail::refresh_fault_period(); + period && ++staging_requests_ % period == 2 % period) + return E_OUTOFMEMORY; // fixture fault (X2W_TEST_LINEAR_REFRESH_FAIL) + } for (int attempt = 0; attempt < 2; ++attempt) { - Staging* best = nullptr; - for (const auto& staging : staging_) { - if (staging->bytes < bytes || (!early && !complete(*staging))) continue; - const auto& taken = submission.staging; - if (std::find(taken.begin(), taken.end(), staging.get()) != taken.end()) continue; - // The reuse-early mutant takes the most recently used buffer, in flight or not. - if (!best || (early ? staging->id > best->id : staging->bytes < best->bytes)) best = staging.get(); - } - if (best) { - ++totals_.staging_reused; - best->value = ~UINT64{0}; - *out = best; - return S_OK; + bool create = false; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; + { + std::lock_guard lock(mutex_); + Staging* best = nullptr; + for (const auto& staging : staging_) { + if (staging->bytes < bytes || (!early && !complete(*staging))) continue; + if (std::find(taken.begin(), taken.end(), staging.get()) != taken.end()) continue; + // The reuse-early mutant takes the most recently used buffer, in flight or not. + if (!best || (early ? staging->id > best->id : staging->bytes < best->bytes)) best = staging.get(); + } + if (best) { + ++totals_.staging_reused; + best->value = ~UINT64{0}; + *out = best; + return S_OK; + } + if (staging_.size() + creating_ < staging_limit()) { + ++creating_; + create = true; + } else { + // The pool is full of buffers in flight: the oldest with a signalled value is waited for. + const Staging* oldest = nullptr; + for (const auto& staging : staging_) + if (staging->value != ~UINT64{0} && staging->fence && (!oldest || staging->value < oldest->value)) + oldest = staging.get(); + if (oldest) { + fence = oldest->fence; + value = oldest->value; + } + } } - if (staging_.size() < staging_limit) break; - // The pool is full of buffers in flight: wait (once, bounded) for the oldest. - Staging* oldest = nullptr; - for (const auto& staging : staging_) - if (staging->value != ~UINT64{0} && staging->fence && (!oldest || staging->value < oldest->value)) - oldest = staging.get(); - HANDLE event = oldest ? CreateEventW(nullptr, FALSE, FALSE, nullptr) : nullptr; - const bool reached = event && SUCCEEDED(oldest->fence->SetEventOnCompletion(oldest->value, event)) && + if (create) return create_staging(queue, bytes, out); + if (!fence || attempt) break; + // The hold-lock mutant waits with mutex_ held, as before the review: other callers block. + std::unique_lock held; + if (linear_detail::mutant("hold-lock")) held = std::unique_lock(mutex_); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool reached = event && SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 5000) == WAIT_OBJECT_0; if (event) CloseHandle(event); if (!reached) return DXGI_ERROR_WAS_STILL_DRAWING; } - if (staging_.size() >= staging_limit) return DXGI_ERROR_WAS_STILL_DRAWING; + return DXGI_ERROR_WAS_STILL_DRAWING; + } + + // Called without mutex_ after acquire_staging reserved a place in the pool (creating_). + HRESULT create_staging(ID3D12CommandQueue* queue, UINT64 bytes, Staging** out) + { + auto staging = std::make_unique(); ID3D12Device* device = nullptr; HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); - if (FAILED(hr)) return hr; - const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; - const UINT64 rounded = (bytes + 0xFFFF) & ~UINT64{0xFFFF}; - const UINT64 size = rounded ? rounded : 0x10000; - const auto desc = linear_detail::buffer(size, D3D12_RESOURCE_FLAG_NONE); - auto staging = std::make_unique(); - hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&staging->buffer)); - device->Release(); - if (FAILED(hr)) return hr; + if (SUCCEEDED(hr)) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; + const UINT64 rounded = (bytes + 0xFFFF) & ~UINT64{0xFFFF}; + const UINT64 size = rounded ? rounded : 0x10000; + const auto desc = linear_detail::buffer(size, D3D12_RESOURCE_FLAG_NONE); + hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&staging->buffer)); + device->Release(); + staging->bytes = size; + } void* mapped = nullptr; const D3D12_RANGE none{0, 0}; - hr = staging->buffer->Map(0, &none, &mapped); + if (SUCCEEDED(hr)) hr = staging->buffer->Map(0, &none, &mapped); + std::lock_guard lock(mutex_); + --creating_; if (FAILED(hr)) { - staging->buffer->Release(); + if (staging->buffer) staging->buffer->Release(); return hr; } staging->mapped = static_cast(mapped); - staging->bytes = size; staging->id = ++staging_ids_; staging->value = ~UINT64{0}; + try { + staging_.push_back(std::move(staging)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; // the unique_ptr releases nothing: the buffer is leaked, not reused + } ++totals_.staging_created; - *out = staging.get(); - staging_.push_back(std::move(staging)); + *out = staging_.back().get(); return S_OK; } - HRESULT take_list(ID3D12CommandQueue* queue, QueueState& state, RefreshList** out) + // A refresh list for queue whose last use has completed, or a new one, reset and ours alone. + // Called without mutex_; the lock covers only the choice and the pool. + HRESULT acquire_list(ID3D12CommandQueue* queue, QueueState& state, RefreshList** out) { - const UINT64 completed = state.fence->GetCompletedValue(); - for (const auto& list : state.lists) { - if (list->value == ~UINT64{0} || list->value > completed) continue; - HRESULT hr = list->allocator->Reset(); - if (SUCCEEDED(hr)) hr = list->list->Reset(list->allocator, nullptr); - if (FAILED(hr)) return hr; - list->value = ~UINT64{0}; - *out = list.get(); - return S_OK; + RefreshList* found = nullptr; + { + std::lock_guard lock(mutex_); + const UINT64 completed = state.fence->GetCompletedValue(); + for (const auto& list : state.lists) { + if (list->value == ~UINT64{0} || list->value > completed) continue; + list->value = ~UINT64{0}; + found = list.get(); + break; + } + } + if (found) { + HRESULT hr = found->allocator->Reset(); + if (SUCCEEDED(hr)) hr = found->list->Reset(found->allocator, nullptr); + *out = found; // on failure the caller frees it again under the lock + return hr; } ID3D12Device* device = nullptr; HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); @@ -679,12 +758,18 @@ class LinearBuffers { hr = device->CreateCommandList(0, type, list->allocator, nullptr, IID_PPV_ARGS(&list->list)); device->Release(); if (FAILED(hr)) { + if (list->list) list->list->Release(); if (list->allocator) list->allocator->Release(); return hr; } list->value = ~UINT64{0}; - *out = list.get(); - state.lists.push_back(std::move(list)); + std::lock_guard lock(mutex_); + try { + state.lists.push_back(std::move(list)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + *out = state.lists.back().get(); return S_OK; } @@ -711,6 +796,7 @@ class LinearBuffers { ID3D12Device* fence_check_device_ = nullptr; HRESULT fence_check_hr_ = S_OK; UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; + std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; volatile LONG unreadable_logged_ = 0, signal_logged_ = 0, refresh_logged_ = 0; }; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index c525c9a282..41106117e0 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -17,6 +17,8 @@ // the copy cannot keep its lifetime guarantee: slot 133 keeps the default backing // stale X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_LINEAR_REFRESH_FAIL=3: staging requests 2, // 5, 8 ... fail, so one refresh per pool cannot be staged +// contention X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_LINEAR_STAGING_LIMIT=1: one staging buffer, +// so a refresh waits for the fence of the submission that holds it // // Where the new path cannot keep its guarantees (a GPU-written use that is not shared, no submit // fence), slot 133 must keep the default backing and return what it returns with the switch off: @@ -56,6 +58,13 @@ // split (share only) a buffer across two XMem views: sharing is refused with E_INVALIDARG, decided // before any D3D12 call, and the buffer is copied; case a must still read B. // gate (refusal only) no heap was opened: D3D12_FEATURE_EXISTING_HEAPS gates sharing before any open. +// q.comp, q.copy (copy only) the buffer is read by a list on a COMPUTE queue (a dispatch) and on a +// COPY queue (CopyBufferRegion) submitted through those queues' wrappers: the refresh runs on +// that queue, the first submission reads B, and a 16-word change then copies 64 bytes. +// contention (contention only) a second queue, a release() and the info export while a submission +// waits for the only staging buffer, which a gate-held submission still reads: all three must +// finish while the wait is still under way. After the gate opens the waiting refresh takes that +// buffer again (none is created), and each submission reads its own bytes. // pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on // it, then XMem's unmap of those pages, while they live and after their release. // @@ -65,7 +74,8 @@ // // --mutate sets X2W_TEST_LINEAR_BUFFER_MUTANT, which removes one guarantee inside d3d12_xs.dll: // skip-refresh (copy) case a, reuse-early (copy) case c, copy-gpu-writes (copy) case b, -// ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported). +// ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported), +// hold-lock (contention) case contention (the wait keeps the backing's lock held). // The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). // X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. // Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter @@ -77,10 +87,13 @@ #include #include +#include +#include #include #include #include #include +#include #include #include "xmem_test_device.h" @@ -232,7 +245,7 @@ std::string pointer_text(const void* p) return text; } -enum class Path { default_backing, share, copy, refusal, untracked, stale }; +enum class Path { default_backing, share, copy, refusal, untracked, stale, contention }; const char* path_name(Path p) { switch (p) { @@ -241,7 +254,8 @@ const char* path_name(Path p) case Path::copy: return "copy"; case Path::refusal: return "refusal"; case Path::untracked: return "untracked"; - default: return "stale"; + case Path::stale: return "stale"; + default: return "contention"; } } @@ -318,6 +332,22 @@ struct Pool { // ---- Device, the wrapper's queue, and recording ---- +// Another queue of the title's device: its wrapper, the desktop queue behind it and a completion fence. +struct Lane { + ComPtr guest, native; + ComPtr fence; + UINT64 value = 0; +}; + +bool wait_fence(ID3D12Fence* fence, UINT64 value) +{ + if (fence->GetCompletedValue() >= value) return true; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool ok = event && SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return ok; +} + struct Gpu { ComPtr desktop, guest; ComPtr guest_queue, queue; // the wrapper and the desktop queue behind it @@ -389,6 +419,13 @@ struct Gpu { if (gate_armed) gate->Signal(gate_value); gate_armed = false; } + bool lane(Lane& out, D3D12_COMMAND_LIST_TYPE type) + { + const D3D12_COMMAND_QUEUE_DESC desc{type}; + if (FAILED(guest->CreateCommandQueue(&desc, IID_PPV_ARGS(&out.guest)))) return false; + out.native = underlying(desktop.Get(), guest.Get(), out.guest.Get()); + return out.native && SUCCEEDED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&out.fence))); + } bool wait(UINT64 value) { if (done->GetCompletedValue() >= value) return true; @@ -433,12 +470,12 @@ struct TitleList { ComPtr native; Gpu* gpu = nullptr; - bool begin(Gpu& g) + bool begin(Gpu& g, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) { gpu = &g; - if (FAILED(g.guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))) return false; + if (FAILED(g.guest->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator)))) return false; using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); - const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + const UINT list_desc[]{static_cast(type), 2, 1, 0}; auto* create = reinterpret_cast((*reinterpret_cast(g.guest.Get()))[73]); if (FAILED(create(g.guest.Get(), list_desc, allocator.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), reinterpret_cast(list.GetAddressOf())))) @@ -474,6 +511,12 @@ struct TitleList { native->CopyBufferRegion(gpu->readback.Get(), at, gpu->output.Get(), at, region_bytes); barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); } + // For a COPY list: buffer[r0 .. r0 + 4 KiB) -> readback slot, unchanged (the buffer is promoted + // from COMMON to COPY_SOURCE implicitly). + void read_copy(ID3D12Resource* buffer, UINT slot = 0) + { + native->CopyBufferRegion(gpu->readback.Get(), slot * region_bytes, buffer, r0, region_bytes); + } // buffer[r1 + 4i] = G[i] ^ key. void write_g(ID3D12Resource* buffer) { @@ -491,6 +534,14 @@ struct TitleList { gpu->queue->Signal(gpu->done.Get(), ++gpu->submitted); return gpu->submitted; } + // Through another queue's wrapper; the lane's fence completes it. + UINT64 submit_on(Lane& lane) + { + void* lists[] = {list.Get()}; + invoke(lane.guest.Get(), 10, 1, arg(lists)); + lane.native->Signal(lane.fence.Get(), ++lane.value); + return lane.value; + } // Past the wrapper: the desktop list on the desktop queue (a submission without the refresh). UINT64 submit_bypassing() { @@ -871,6 +922,130 @@ struct Run { (p.info.stale ? ", STILL STALE" : ", stale cleared")); } + // q.comp, q.copy: the refresh on a COMPUTE and a COPY queue (implicit COMMON -> COPY_DEST there too). + void case_queues(Pool& pool) + { + for (const auto type : {D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY}) { + const bool compute = type == D3D12_COMMAND_LIST_TYPE_COMPUTE; + const char* name = compute ? "q.comp" : "q.copy"; + Lane lane; + Memory memory; + if (!gpu.lane(lane, type)) return row(pool, name, false, "queue wrapper not created"); + if (!pool.allocate(memory, A)) return row(pool, name, false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList first, second; + if (FAILED(p.hr) || !p.backing || !first.begin(gpu, type) || !second.begin(gpu, type)) + return row(pool, name, false, "slot 133 -> " + hex(p.hr) + " or list creation failed"); + const std::uint32_t mask = compute ? key : 0; + compute ? first.read(p.backing.Get()) : first.read_copy(p.backing.Get()); + if (!first.close()) return row(pool, name, false, "Close failed"); + write(memory.buffer(), r0, B, words); + if (!wait_fence(lane.fence.Get(), first.submit_on(lane))) return row(pool, name, false, "fence timeout"); + const Tally t1 = tally(gpu.read_output().data(), r0 / 4, mask); + refresh_info(p); + const UINT64 after_first = p.info.bytes_copied; + compute ? second.read(p.backing.Get()) : second.read_copy(p.backing.Get()); + second.close(); + write(memory.buffer(), r0 + 64 * 4, E, 16); + if (!wait_fence(lane.fence.Get(), second.submit_on(lane))) return row(pool, name, false, "fence timeout"); + const Tally t2 = tally(gpu.read_output().data(), r0 / 4, mask); + refresh_info(p); + const UINT64 delta = p.info.bytes_copied - after_first; + const bool pass = p.linear && p.info.path == 2 && !p.info.stale && p.info.refresh_failures == 0 && t1.count[B] == words && + after_first == buffer_bytes && t2.count[E] == 16 && t2.count[B] == words - 16 && delta == 64; + row(pool, name, pass, + std::string(compute ? "COMPUTE queue, dispatch read: " : "COPY queue, CopyBufferRegion read: ") + "first submission " + + t1.text() + " (" + std::to_string(after_first) + " bytes refreshed), then " + t2.text() + " (" + + std::to_string(delta) + " bytes)" + (p.info.stale ? ", STALE" : "")); + } + } + + // contention: nothing waits behind a submission that waits for the only staging buffer. + void case_contention(Pool& pool) + { + using clock = std::chrono::steady_clock; + const auto ms = [](clock::duration d) { return static_cast(std::chrono::duration_cast(d).count()); }; + Lane second; + Memory mx, mw; + if (!gpu.lane(second, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(mx, A)) + return row(pool, "contention", false, "setup failed"); + Placed x = place(gpu, mx.buffer(), false); + TitleList l0; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu)) return row(pool, "contention", false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, "contention", false, "fence timeout"); // X uploaded: the staging buffer exists + if (!pool.allocate(mw, D)) return row(pool, "contention", false, "allocation failed"); + Placed w = place(gpu, mw.buffer(), false); + TitleList lw; + if (FAILED(w.hr) || !w.backing || !lw.begin(gpu)) return row(pool, "contention", false, "slot 133 -> " + hex(w.hr)); + lw.read(w.backing.Get()); + lw.close(); + if (!wait_fence(second.fence.Get(), lw.submit_on(second))) return row(pool, "contention", false, "fence timeout"); + const X2wLinearBufferTotals before = totals(); + + // S1 reads B and is held on the gate; its refresh holds the only staging buffer. + gpu.hold(); + write(mx.buffer(), r0, B, words); + TitleList s1, s2, probe; + if (!s1.begin(gpu) || !s2.begin(gpu) || !probe.begin(gpu)) return row(pool, "contention", false, "list"); + s1.read(x.backing.Get(), 1); + s1.close(); + s1.submit(); + // S2's refresh (C) must wait for S1's fence: on another thread. + write(mx.buffer(), r0, C, words); + s2.read(x.backing.Get(), 2); + s2.close(); + std::atomic done{false}; + UINT64 s2_value = 0; + const auto t1_start = clock::now(); + clock::duration t1_time{}; + std::thread waiter([&] { + s2_value = s2.submit(); + t1_time = clock::now() - t1_start; + done = true; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + const bool waiting_before = !done; + // Probes, each through mutex_: the info export, the title's release of X, a submission on another queue. + auto* x_wrapper = x.wrapper.Get(); + X2wLinearBufferInfo probe_info{}; + auto t = clock::now(); + x2w_d3d12_linear_buffer_info(w.wrapper.Get(), &probe_info); + const auto info_time = clock::now() - t; + t = clock::now(); + x.wrapper.Reset(); // release(): retire X + const auto release_time = clock::now() - t; + probe.read(w.backing.Get(), 3); + probe.close(); + t = clock::now(); + const bool probe_done = wait_fence(second.fence.Get(), probe.submit_on(second)); + const auto submit_time = clock::now() - t; + const bool waiting_after = !done; + const Tally w_read = tally(gpu.read_output(3).data(), r0 / 4, key); + gpu.open_gate(); + waiter.join(); + if (!gpu.wait(s2_value)) return row(pool, "contention", false, "fence timeout after the gate"); + const Tally r1 = tally(gpu.read_output(1).data(), r0 / 4, key), r2 = tally(gpu.read_output(2).data(), r0 / 4, key); + X2wLinearBufferInfo xi{}; + x2w_d3d12_linear_buffer_info(x_wrapper, &xi); + const X2wLinearBufferTotals after = totals(); + const bool reused = after.staging_created == before.staging_created && after.staging_reused >= before.staging_reused + 2; + const bool pass = waiting_before && waiting_after && probe_done && w_read.count[D] == words && r1.count[B] == words && + r2.count[C] == words && !xi.stale && xi.refresh_failures == 0 && reused && + ms(t1_time) >= ms(info_time + release_time + submit_time); + char text[400]; + std::snprintf(text, sizeof(text), + "while S2's refresh waited (%s before, %s after the probes): info %lld ms, release %lld ms, other-queue submit " + "%lld ms (read %s); S2 returned after %lld ms; S1 read %s, S2 read %s; staging created %llu -> %llu, " + "refresh failures %llu", + waiting_before ? "waiting" : "NOT WAITING", waiting_after ? "waiting" : "DONE", ms(info_time), ms(release_time), + ms(submit_time), w_read.text().c_str(), ms(t1_time), r1.text().c_str(), r2.text().c_str(), + static_cast(before.staging_created), static_cast(after.staging_created), + static_cast(xi.refresh_failures)); + row(pool, "contention", pass, text); + } + void case_d1(Pool& pool) { if (path == Path::default_backing || path == Path::untracked) return; @@ -906,7 +1081,7 @@ struct Run { int main(int argc, char** argv) { if (argc < 3) { - std::puts("usage: linear_buffer_backing_check [--mutate ]"); + std::puts("usage: linear_buffer_backing_check [--mutate ]"); return 2; } const bool warp = std::strcmp(argv[1], "warp") == 0; @@ -919,6 +1094,7 @@ int main(int argc, char** argv) else if (p == "refusal") path = Path::refusal; else if (p == "untracked") path = Path::untracked; else if (p == "stale") path = Path::stale; + else if (p == "contention") path = Path::contention; else return 2; std::string mutant; if (argc == 5 && std::strcmp(argv[3], "--mutate") == 0) mutant = argv[4]; @@ -930,10 +1106,11 @@ int main(int argc, char** argv) SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr - : path == Path::copy || path == Path::untracked || path == Path::stale ? L"copy" : L"1"); + : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention ? L"copy" : L"1"); SetEnvironmentVariableW(L"X2W_TEST_EXISTING_HEAPS_UNSUPPORTED", path == Path::refusal ? L"1" : nullptr); SetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", path == Path::untracked ? L"1" : nullptr); SetEnvironmentVariableW(L"X2W_TEST_LINEAR_REFRESH_FAIL", path == Path::stale ? L"3" : nullptr); + SetEnvironmentVariableW(L"X2W_TEST_LINEAR_STAGING_LIMIT", path == Path::contention ? L"1" : nullptr); SetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", mutant.empty() ? nullptr : mutant.c_str()); { // The DLL's log lines go to linear_buffer_backing__[_].log next to this executable. @@ -1009,12 +1186,17 @@ int main(int argc, char** argv) run.case_stale(pool); continue; } + if (path == Path::contention) { + run.case_contention(pool); + continue; + } run.case_a(pool); if (path == Path::share && xmem) run.case_a(pool, true); run.case_b(pool, false); run.case_c(pool); run.case_d1(pool); if (path != Path::default_backing) run.case_b(pool, true); + if (path == Path::copy) run.case_queues(pool); run.probe_view_pin(pool); } const X2wLinearBufferTotals t = totals(); @@ -1040,7 +1222,7 @@ int main(int argc, char** argv) run.row(none, "totals", t.refresh_failures == 2 && t.last_refresh_hr == E_OUTOFMEMORY && t.kept_default == 0, "refresh failures " + std::to_string(t.refresh_failures) + " (expected 2, one per pool), last " + hex(t.last_refresh_hr)); } - if (path != Path::default_backing && path != Path::stale) { + if (path != Path::default_backing && path != Path::stale && path != Path::contention) { run.row(none, "kept", t.kept_default == run.kept_rows, "totals report " + std::to_string(t.kept_default) + " kept default backings for " + std::to_string(run.kept_rows) + " refused placements, last refusal " + hex(t.last_refusal_hr)); @@ -1064,7 +1246,8 @@ int main(int argc, char** argv) if (!mutant.empty()) { const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" - : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" : nullptr; + : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" + : mutant == "hold-lock" ? "contention" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results) From 96d166bce0fbd8ffedd133e9ed9e99b6f1f1722d Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 07:48:27 +0100 Subject: [PATCH 04/18] gpu: note why concurrent linear-buffer publishes only cost a refresh Two submissions that snapshot the same copied buffer can publish `uploaded` in either order, so it may briefly lag the GPU copy. The next diff is then redundant or larger than needed, never one that misses a change. Comment only (tedin7's review nit on #2218). Refs #1914 Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/linear_buffer_backing.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 565bed5a45..e7af2b111c 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -400,7 +400,11 @@ class LinearBuffers { } } - // Publish under the lock. + // Publish under the lock. Two submissions that snapshot the same buffer concurrently can both + // copy the same changed span and publish `uploaded` in either order, so `uploaded` may briefly + // lag what the GPU already holds. The next submission then compares the title against an older + // upload and copies a span that is redundant or larger than needed, never one that misses a + // change, so the cost is an extra refresh, not stale data. std::lock_guard lock(mutex_); if (list && FAILED(list_hr)) list->value = 0; for (Work& w : work) { From 959cc3a824a45ff55904ad9e65c6c9903f439cb0 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 07:59:45 +0100 Subject: [PATCH 05/18] gpu: refresh linear buffers on an internal queue that consumers wait for Review of #2218 (R0Y00): one copied buffer, one CPU write, then a list on queue 1 behind an unsignalled gate and a list on queue 2. Queue 2 read the old bytes: queue 1's refresh was enqueued behind its gate but recorded as uploaded, so queue 2 skipped its own. - Every refresh now runs on one internal COPY queue per device, which never waits on a title fence, and signals an internal fence value. Each copied buffer remembers the value of its last refresh. - Every submission through a queue wrapper first makes its queue wait for the highest such value among the live copied buffers that has not completed. A consumer on any queue runs after every refresh enqueued before it, and no title queue waits on another, so title-owned cross-queue fences cannot form a cycle with a refresh. - Staging is reused once its copy's internal fence value completes. The per-title-queue fences, after_submit and linear_submitted go. - If the internal queue or fence cannot be created, copied placements keep the default backing with that HRESULT recorded. - x2w_d3d12_linear_buffer_internal_queue lets fixtures hold refreshes. The fixture adds gate2q (both reads see the CPU write), gate2q.held (the second queue waits for a held refresh), xq (queue 1 waits on a fence queue 2 signals: no deadlock, both read the write) and a skip-consumer-wait mutant that must fail gate2q.held. Case c and contention hold the internal queue so staging stays in flight. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 8 +- docs/experiments.md | 16 +- docs/startup-runtime.md | 15 +- src/startup_stubs/d3d12_xs_device.cpp | 32 +- src/startup_stubs/linear_buffer_backing.h | 358 +++++++++++----------- src/startup_stubs/linear_buffer_report.h | 3 +- tests/linear_buffer_backing_check.cpp | 160 +++++++++- 7 files changed, 372 insertions(+), 220 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5e0d5caa1a..97c61ba7db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2590,8 +2590,10 @@ endforeach() # XMem pages and a private range: the default, real sharing, forced copying, host sharing refusal, a # copy without a submit fence (the default backing is kept and the refusal reported), a refresh that # cannot be staged (the submission runs, the buffer is reported stale) and a one-buffer staging pool -# (a waiting refresh must not block release(), the info export or another queue). The copy path also -# refreshes on COMPUTE and COPY queues. Each mutant removes one guarantee in the DLL and must fail its case. +# (a waiting refresh must not block release(), the info export or another queue). Refreshes run on an +# internal copy queue; the copy path also reads on COMPUTE and COPY queues, reads one buffer on two +# queues after one CPU write (both must see it), and follows a title-owned cross-queue fence without +# deadlock. Each mutant removes one guarantee in the DLL and must fail its case. add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) target_include_directories(linear_buffer_backing_check PRIVATE tests) target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) @@ -2603,7 +2605,7 @@ foreach(adapter IN ITEMS warp hardware) endforeach() endforeach() foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature - copy:refusal_silent contention:hold_lock) + copy:refusal_silent contention:hold_lock copy:skip_consumer_wait) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/docs/experiments.md b/docs/experiments.md index 3ef5cad5bb..038774b684 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9659,7 +9659,7 @@ ctest --preset release --no-tests=error -j1 -R '^(xmem_section_lease_|xmem_shim_ #### Production slice: slot 133 linear buffers (#1914) -The first production change wires the #1942 comparison to one buffer kind in `d3d12_xs.dll`: device slot 133 (`CreatePlacedResourceX`) with a buffer description and initial state `COMMON`. The title writes such a buffer with the CPU and the GPU reads it as vertex, index, constant, shader-resource or indirect-argument data. The behaviour is opt-in through `X2W_D3D12_LINEAR_BUFFERS`; unset, slot 133 keeps its backing (see [Linear buffer backing](startup-runtime.md#linear-buffer-backing-device-slot-133-opt-in)). `src/startup_stubs/linear_buffer_backing.h` shares a buffer in a private allocation after `D3D12_FEATURE_EXISTING_HEAPS`. It copies any other buffer from title memory at each submission through the queue wrapper. Where the copy cannot keep the guarantees, slot 133 keeps the default backing and returns what it returns without the switch, and the refusal HRESULT is recorded in the log, the buffer's info and the totals. A refresh that cannot be staged does not hold the submission back; the buffer keeps its last upload and is reported stale. +The first production change wires the #1942 comparison to one buffer kind in `d3d12_xs.dll`: device slot 133 (`CreatePlacedResourceX`) with a buffer description and initial state `COMMON`. The title writes such a buffer with the CPU and the GPU reads it as vertex, index, constant, shader-resource or indirect-argument data. The behaviour is opt-in through `X2W_D3D12_LINEAR_BUFFERS`; unset, slot 133 keeps its backing (see [Linear buffer backing](startup-runtime.md#linear-buffer-backing-device-slot-133-opt-in)). `src/startup_stubs/linear_buffer_backing.h` shares a buffer in a private allocation after `D3D12_FEATURE_EXISTING_HEAPS`. It copies any other buffer from title memory at each submission through the queue wrapper. The copy runs on an internal COPY queue that never waits on a title fence, and every submission through a queue wrapper waits for the internal fence value of every pending refresh of a live copied buffer. A second queue's consumer therefore cannot run ahead of a refresh that another queue enqueued, and no title queue waits on another. Where the copy cannot keep the guarantees, slot 133 keeps the default backing and returns what it returns without the switch, and the refusal HRESULT is recorded in the log, the buffer's info and the totals. A refresh that cannot be staged does not hold the submission back; the buffer keeps its last upload and is reported stale. A title run motivated the fallback. An earlier revision returned the refusal from slot 133. On the RX 9070 XT with a warm shader cache and the same input, the run with the switch off stopped at 294 s at the slot 148 builder, as before. With `X2W_D3D12_LINEAR_BUFFERS=1` the title faulted at 1.76 s, reading address `0x18`. Its first eligible placement was a GPU-written buffer of `0xae00000` bytes on an XMem view (`MEM_MAPPED`) across views: sharing `0x80070057`, so slot 133 returned `0x80070057`. On the console `CreatePlacedResourceX` does not fail, and the title used the null object. In the switch-off run, slot 133 placed: - 2,987 GPU-read buffers (14.2 MiB), not aliased; @@ -9682,9 +9682,11 @@ A title run motivated the fallback. An earlier revision returned the refusal fro | kept | every path with refusals: the totals count as many kept default backings as the run refused. | | stale | `stale` only: a refreshed submission of A, then the CPU writes B and the refresh fails. The submission must still run and complete and read A (the last upload). The buffer must be reported stale with `E_OUTOFMEMORY` in its info and the log. The next submission must read B and clear it. | | q.comp, q.copy | `copy` only: the buffer is read on a COMPUTE queue (a dispatch) and on a COPY queue (`CopyBufferRegion`), each through its queue wrapper, so the refresh runs on that queue. The first submission must read B with the whole buffer copied, and a 16-word change must then copy 64 bytes. | -| contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a gate and holds the only staging buffer. S2's refresh of X, on another thread, must wait for S1's fence. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the gate opens, S2 must take the same staging buffer (none created), and S1 and S2 must read B and C with no refresh failure. | +| gate2q, gate2q.held | `copy` only (review repro): one buffer holding A, read by a list on queue 1 behind a title gate and by a list on queue 2, with one CPU write of B before both submissions. Queue 2 must complete while the gate is still closed and read B, and queue 1 must read B after it. In `.held` the fixture also holds the internal refresh queue, and queue 2 must not complete before the refresh lands. | +| xq | `copy` only: queue 1 waits on a title fence that queue 2 signals after its list. Both read the buffer the CPU changed to B. Both must complete, with no deadlock, and read B. | +| contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a title gate, and its refresh, held on the internal queue, holds the only staging buffer. S2's refresh of X, on another thread, must wait for that copy. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the refreshes land and the gate opens, S2 must have reused the same staging buffer (none created). S1 and S2 must both read C, the CPU's last write before they ran, with no refresh failure. | -On Windows 11 build 26300 at `b0669e06` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All seven paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. +On Windows 11 build 26300 at `793b52b5` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All seven paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. | Path | Pool | Backing | Slot 133 / sharing HRESULT | Bytes copied | Results | |---|---|---|---|---|---| @@ -9697,17 +9699,19 @@ On Windows 11 build 26300 at `b0669e06` plus this change, the results were ident | `untracked` | XMem, private | kept default for every placement | `S_OK`; refusal `0x8007139F` (`E_NOT_VALID_STATE`) for a, `0x887A0004` for b and d2 | 0 | a: XMem reads zero, private B; b and d2: XMem leaves P, private G ^ key (as before); 6 kept | | `stale` | XMem, private | copied | `S_OK` / not attempted | 131,072 + 4,096 per pool; the failed refresh copies 0 | the failed submission completes and reads A, stale reported with `0x8007000E`, then B and stale cleared; 2 refresh failures | | `copy` (q.comp, q.copy) | XMem, private | copied, refreshed on the COMPUTE or COPY queue | `S_OK` / not attempted | 131,072, then 64 | B in all words, then 16 E; no refresh failure | -| `contention` | XMem, private | copied, one staging buffer | `S_OK` / not attempted | 540,672 for the run | the probes took 0 ms each while S2 waited about 310 ms for the gate; S1 B, S2 C; staging created 1, no refresh failure | +| `copy` (gate2q, gate2q.held, xq) | XMem, private | copied | `S_OK` / not attempted | 131,072 for A, then 4,096 for B | queue 2 completes with queue 1 still gated and reads B; queue 1 then reads B; `.held`: queue 2 waits for the held refresh; xq: both complete and read B | +| `contention` | XMem, private | copied, one staging buffer | `S_OK` / not attempted | 540,672 for the run | the probes took 0 ms each while S2 waited about 310 ms for the held copy; S1 C, S2 C; staging created 1, no refresh failure | The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. -Six negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: +Seven negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: - `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. -- `reuse-early` hands out staging buffers without their fence. All three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). +- `reuse-early` hands out staging buffers without their fence. With the internal queue held, all three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). - `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). - `ignore-feature` opens a heap although the feature query reports no support. gate sees one heap open (1 of 1), and the private buffers are shared. - `refusal-silent` keeps the default backing without reporting it. b finds no refusal in the info and no log line (2 of 2), and the kept totals stay at 0. - `hold-lock` keeps the backing's lock held while a refresh waits for a staging fence. contention's info probe then blocks for about 4.7 s, until the wait gives up after 5 s. S2 goes stale and reads B (2 of 2). +- `skip-consumer-wait` stops submissions from waiting for the internal fence. In gate2q.held, queue 2 completes before the held refresh lands and reads A (2 of 2). Case c reads zeros as well. Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index fa31de7efa..89347583d5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2922,17 +2922,22 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - Shared: a cross-adapter buffer placed on the private allocation's heap, cached by base. The GPU reads and writes title memory; nothing is copied. - An XMem view is never shared. A heap opened from a view keeps it mapped, and XMem's unmap of those pages then fails with error 87. Sharing reports `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)` (`0x80070032`) and the buffer is copied. A buffer across several allocations, or at an unaligned offset, reports `E_INVALIDARG`. Both are decided before any D3D12 call. -- Copied: a committed default buffer that the command-queue wrapper refreshes from title memory just before the title's lists run on that queue, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. A staging buffer is reused only after the queue fence of the submission that read it has completed. - - The refresh runs on the queue that executes: direct, compute or copy. The buffer rests in `COMMON` and is promoted to `COPY_DEST` implicitly on each of them. - - In render mode it runs before the wrapper takes its draw and allocator locks. +- Copied: a committed default buffer that is refreshed from title memory at each submission through a command-queue wrapper, just before the title's lists run, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. + - **Internal queue.** Every refresh runs on one internal COPY queue per device, which never waits on a title fence. It signals an internal fence value, and each buffer remembers the value of its last refresh. + - **Consumer wait.** Every submission through a queue wrapper, of any type (direct, compute or copy), first makes its queue `Wait` for the highest such value among the live copied buffers that has not completed. A consumer on any queue therefore runs after every refresh enqueued before it, wherever that refresh came from. So when one CPU write is followed by submissions on two queues, both read the new bytes, even if the first is still held behind a title fence. + - **No title-to-title waits.** No title queue ever waits on another title queue. A title's own cross-queue fences, such as queue 1 waiting on a fence that queue 2 signals after its lists, cannot form a cycle with a refresh. + - **Writes during an earlier read.** The internal queue may write a backing while an earlier submission that reads it is still waiting on its queue. Buffers allow simultaneous access from several queues, so this is valid D3D12. It also matches unified memory on the console: a read that executes later sees the CPU's latest writes. A title write to bytes that an executing submission is reading at that moment is an unsynchronized concurrent write, outside the contract, here as on the console. + - **Staging reuse.** A staging buffer is reused only after the internal fence value of the copy that read it has completed. + - **No internal queue.** If the internal queue or its fence cannot be created, copied placements keep the default backing with that HRESULT recorded. + - In render mode the refresh runs before the wrapper takes its draw and allocator locks. - The lock that guards the backing is held only to choose and publish. Waiting for a staging fence (a full pool), creating staging or a refresh list, recording it and `ExecuteCommandLists` all happen without it. A `Release`, the fixture exports and another queue's submission therefore never wait behind them. - Kept default: where neither path keeps its guarantees, slot 133 keeps the default backing above and returns what it returns without the switch. On the console `CreatePlacedResourceX` does not fail, and a title that received a failure faulted on the null object. The refusal HRESULT is recorded instead: - a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared records the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory; - - without a submit fence (`X2W_TEST_SUBMIT_FENCE_FAIL=1`), `E_NOT_VALID_STATE` (`0x8007139f`); + - without the internal refresh queue: `E_NOT_VALID_STATE` (`0x8007139f`) under `X2W_TEST_SUBMIT_FENCE_FAIL=1`, else the HRESULT of creating the queue or its fence; - when the copy's default buffer cannot be created, that HRESULT. - A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. -A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ee173d5efa..77223690b0 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1576,6 +1576,14 @@ extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBu *totals = X2wLinearBufferTotals{}; if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); } +// Fixtures: the internal queue that runs every refresh (AddRef'd), so a fixture can hold refreshes in +// flight behind a fence of its own. False before the first copied placement. +extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_internal_queue(void** queue) +{ + if (!queue) return false; + *queue = x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off ? nullptr : linear_buffers().internal_queue(); + return *queue != nullptr; +} // Fixtures: the number of desktop allocators a title allocator stands for (0 if it has none yet). extern "C" __declspec(dllexport) unsigned x2w_d3d12_allocator_pool_size(void* allocator) @@ -3511,18 +3519,12 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" -// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the queue -// just before the title's lists. A refresh that fails leaves that buffer stale (logged, counted); -// the lists run either way. -void linear_refresh(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) -{ - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().before_submit(queue, submission); -} -void linear_submitted(ID3D12CommandQueue* queue, x2w_startup::LinearBuffers::Submission& submission) +// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the internal +// refresh queue, and queue waits for those refreshes, just before the title's lists. A refresh that +// fails leaves that buffer stale (logged, counted); the lists run either way. +void linear_refresh(ID3D12CommandQueue* queue) { - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().after_submit(queue, submission); + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().before_submit(queue); } // Queue slot 10, desktop ExecuteCommandLists(count, lists). @@ -3531,7 +3533,6 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) X2W_ZONE("ExecuteCommandLists"); static LONG calls; drain_retired_resources(); - x2w_startup::LinearBuffers::Submission linear; if (render_mode()) { // A closed list stays submittable until its next Reset, as on the desktop. std::vector ready; @@ -3539,7 +3540,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) auto* queue = static_cast(self->own().real); // Before the wrapper's locks: a refresh may wait for a staging fence, and recording must not // wait with it. - if (count) linear_refresh(queue, linear); + if (count) linear_refresh(queue); // Pin the closed recording and its allocator through submission bookkeeping. AcquireSRWLockExclusive(&draw_lock); AcquireSRWLockExclusive(&allocator_lock); @@ -3587,8 +3588,6 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } else if (!ready.empty()) { submit(ready, submitted); } - // Also when no list was ready: an executed refresh still needs its fence value. - linear_submitted(queue, linear); ReleaseSRWLockExclusive(&allocator_lock); ReleaseSRWLockExclusive(&draw_lock); check_device("CommandQueue execute", 35); @@ -3602,9 +3601,8 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) std::vector real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); auto* queue = static_cast(self->own().real); - linear_refresh(queue, linear); + linear_refresh(queue); queue->ExecuteCommandLists(count, real.data()); - linear_submitted(queue, linear); if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); } diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index e7af2b111c..2a40fd3783 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -31,12 +31,30 @@ // decided without a D3D12 call. // // Copy. A committed default-heap buffer whose bytes are refreshed from the title memory at each -// submission through the command-queue wrapper, before the title's lists execute on that queue, -// never at bind or record. Only the bytes that differ from the last upload are copied, through an -// upload staging buffer. A staging buffer is reused only after the queue fence of the submission -// that read it has completed. The default buffer itself is rewritten in queue order, after every -// earlier submission on that queue; a title write to bytes that an incomplete submission still reads -// is an unsynchronized concurrent write, outside the contract. +// submission through a command-queue wrapper, before the title's lists execute, never at bind or +// record. Only the bytes that differ from the last upload are copied, through an upload staging +// buffer. +// +// Every refresh runs on one internal COPY queue per device, which never waits on a title fence. A +// refresh's copy (staging -> backing) is executed there and signals an internal fence value; the +// buffer remembers the value of its last refresh. Every submission through a queue wrapper, on any +// queue type, first makes that queue Wait for the highest such value among the live copied buffers +// (when it has not completed yet). A consumer on any queue therefore runs after every refresh that +// was enqueued before it, wherever that refresh came from, so the bytes recorded as uploaded at +// enqueue are the bytes the consumer reads. No title queue ever waits on another title queue: a +// refresh never sits behind the title's own waits, so title-owned cross-queue fences (queue 1 waits +// on a fence queue 2 signals after its lists) cannot form a cycle with it. +// +// The internal queue may write a backing while an earlier submission that reads it is still waiting +// on its queue. Buffers allow simultaneous access from several queues, so this is valid D3D12, and +// it matches unified memory on the console: a read that executes later sees the CPU's latest writes. +// A title write to bytes that an executing submission is reading at that moment is an +// unsynchronized concurrent write, outside the contract, here as on the console. +// +// A staging buffer is reused only after the internal fence value of the copy that read it has +// completed (title fences do not matter: only that copy reads it). If the internal queue or its fence +// cannot be created, the copy cannot order its consumers: placements keep the default backing and +// record the refusal (below). // // Where neither path can keep its guarantees, slot 133 keeps the default backing and returns what it // returns without this switch. A title on the console does not see CreatePlacedResourceX fail, so a @@ -47,8 +65,8 @@ // - a GPU-written use (ALLOW_UNORDERED_ACCESS) that cannot be shared: the copy has no point at which // GPU writes reach the title memory. refusal_hr is the sharing HRESULT, or DXGI_ERROR_UNSUPPORTED // when sharing was not attempted (X2W_D3D12_LINEAR_BUFFERS=copy). -// - no submit fence (X2W_TEST_SUBMIT_FENCE_FAIL=1, or the fence cannot be created): staging reuse -// cannot wait for completion. E_NOT_VALID_STATE. +// - no internal refresh queue or fence (X2W_TEST_SUBMIT_FENCE_FAIL=1 gives E_NOT_VALID_STATE, else +// the HRESULT of creating them): consumers could not be ordered behind refreshes. // - the copy's default buffer cannot be created: that HRESULT. // // At submit nothing is refused: holding back a submission can leave a title waiting on its fences. @@ -68,6 +86,8 @@ // ignore-feature sharing is attempted although the feature query reports no support // refusal-silent a kept default backing is not reported (no log text, info or totals) // hold-lock the wait for a full staging pool keeps mutex_ held (other callers block) +// skip-consumer-wait submissions do not Wait for the internal fence (consumers race refreshes) +// x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -214,8 +234,9 @@ class LinearBuffers { ++totals_.shared; } else if (uav && !linear_detail::mutant("copy-gpu-writes")) { hr = record.info.share_hr == S_FALSE ? DXGI_ERROR_UNSUPPORTED : record.info.share_hr; - } else if (linear_detail::submit_fence_forced_off() || FAILED(fence_check(device))) { - hr = E_NOT_VALID_STATE; + } else if (const HRESULT internal = linear_detail::submit_fence_forced_off() ? E_NOT_VALID_STATE : internal_ready(device); + FAILED(internal)) { + hr = internal; } else { const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; const auto desc = linear_detail::buffer(width, uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS @@ -305,21 +326,17 @@ class LinearBuffers { std::vector().swap(found->second.copy->uploaded); } - // What one submission used: released by the queue fence value that after_submit signals. - struct Submission { - std::vector staging; - RefreshList* list = nullptr; - }; - - // Before the title's lists are executed on queue (the contract's copy point): records and - // executes the refresh of every live copied buffer whose title bytes changed. Nothing here holds - // the submission back: a buffer whose refresh fails keeps its last upload and is marked stale. + // Before the title's lists are executed on queue (the contract's copy point): refreshes every live + // copied buffer whose title bytes changed, on the internal queue, then makes queue wait for every + // refresh of a live copied buffer that has not landed yet. Nothing here holds the submission back: + // a buffer whose refresh fails keeps its last upload and is marked stale. // // mutex_ is held only to read and publish state: the work is snapshotted under it, then staging // is taken (and, with the pool full, its fence waited for), filled, recorded and executed without // it, and the results are published under it again. A release() or another queue's submission - // therefore never waits behind a fence wait or ExecuteCommandLists here. - void before_submit(ID3D12CommandQueue* queue, Submission& submission) + // therefore never waits behind a fence wait or ExecuteCommandLists here. internal_mutex_ only + // keeps the internal queue's ExecuteCommandLists and Signal in fence-value order. + void before_submit(ID3D12CommandQueue* queue) { struct Work { ID3D12Resource* dest; @@ -330,15 +347,12 @@ class LinearBuffers { HRESULT hr = S_OK; }; std::vector work; - QueueState* state = nullptr; - HRESULT state_hr = S_OK; { std::lock_guard lock(mutex_); ++totals_.submissions; bool any = false; for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; - if (!any) return; - state_hr = queue_state(queue, &state); + if (!any || !internal_queue_) return; for (auto& [resource, record] : records_) { const std::shared_ptr& copy = record.copy; if (!copy || !copy->live) continue; @@ -369,96 +383,34 @@ class LinearBuffers { } } } - if (work.empty()) return; + if (!work.empty()) refresh(work); - // Without the lock: staging (each one ours alone once taken), the copy into it, the list, the queue. - std::vector taken; - bool any_staged = false; - for (Work& w : work) { - w.hr = state_hr; - if (SUCCEEDED(w.hr)) w.hr = acquire_staging(queue, w.bytes, taken, &w.staging); - if (FAILED(w.hr)) continue; - taken.push_back(w.staging); - std::memcpy(w.staging->mapped, w.source + w.offset, static_cast(w.bytes)); - any_staged = true; - } - RefreshList* list = nullptr; - HRESULT list_hr = S_OK; - if (any_staged) { - list_hr = acquire_list(queue, *state, &list); - if (SUCCEEDED(list_hr)) { - // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST (on a direct, - // compute or copy queue alike), and it decays to COMMON again when this - // ExecuteCommandLists completes, before the title's lists use it. - for (const Work& w : work) - if (SUCCEEDED(w.hr)) list->list->CopyBufferRegion(w.dest, w.offset, w.staging->buffer, 0, w.bytes); - list_hr = list->list->Close(); - } - if (SUCCEEDED(list_hr)) { - ID3D12CommandList* lists[] = {list->list}; - queue->ExecuteCommandLists(1, lists); - } + // Order this submission behind every refresh of a live copied buffer that may not have landed. + UINT64 wait_for = 0; + { + std::lock_guard lock(mutex_); + for (auto& [resource, record] : records_) + if (record.copy && record.copy->live && record.copy->refresh_value > wait_for) wait_for = record.copy->refresh_value; + if (wait_for && internal_fence_->GetCompletedValue() < wait_for && !linear_detail::mutant("skip-consumer-wait")) + ++totals_.consumer_waits; + else + wait_for = 0; } - - // Publish under the lock. Two submissions that snapshot the same buffer concurrently can both - // copy the same changed span and publish `uploaded` in either order, so `uploaded` may briefly - // lag what the GPU already holds. The next submission then compares the title against an older - // upload and copies a span that is redundant or larger than needed, never one that misses a - // change, so the cost is an extra refresh, not stale data. - std::lock_guard lock(mutex_); - if (list && FAILED(list_hr)) list->value = 0; - for (Work& w : work) { - const HRESULT hr = FAILED(w.hr) ? w.hr : list_hr; - if (FAILED(hr)) { - if (w.staging) w.staging->value = 0; // never reached the GPU - refresh_failed(w.dest, *w.copy, hr); - continue; - } - submission.staging.push_back(w.staging); - Copied& copy = *w.copy; - if (copy.live) { - // The backing now holds these bytes (the staging buffer keeps them until its fence). - try { - if (copy.uploaded.size() != copy.bytes) copy.uploaded.assign(static_cast(copy.bytes), 0); - std::memcpy(copy.uploaded.data() + w.offset, w.staging->mapped, static_cast(w.bytes)); - } catch (const std::bad_alloc&) { - copy.uploaded.clear(); // the next submission copies the whole buffer again - } - } - copy.stale = false; - ++copy.refreshes; - copy.bytes_copied += w.bytes; - copy.last_staging = w.staging->id; - ++totals_.refreshes; - totals_.bytes_copied += w.bytes; + if (wait_for) { + const HRESULT hr = queue->Wait(internal_fence_, wait_for); + if (FAILED(hr) && x2w_local::first_calls(wait_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffers: queue %p could not wait for refresh 0x%llx (0x%08lx)", + static_cast(queue), static_cast(wait_for), static_cast(hr)); } - if (SUCCEEDED(list_hr) && list) submission.list = list; } - // After the title's lists were executed on queue: the fence value that completes them also releases - // the staging buffers and refresh list used for this submission. - void after_submit(ID3D12CommandQueue* queue, Submission& submission) + // The internal queue, AddRef'd, for fixtures that hold refreshes in flight; null before the first + // copied placement. + ID3D12CommandQueue* internal_queue() { std::lock_guard lock(mutex_); - const auto found = queues_.find(queue); - if (found == queues_.end()) return; - QueueState& state = found->second; - UINT64 value = 0; - if (SUCCEEDED(queue->Signal(state.fence, state.value + 1))) value = ++state.value; - // Without a signalled value nothing used here can be proven complete: it stays in use. - for (Staging* staging : submission.staging) { - staging->fence = state.fence; - staging->value = value ? value : ~UINT64{0}; - } - if (submission.list) submission.list->value = value ? value : ~UINT64{0}; - submission = {}; - if (!value) { - if (x2w_local::first_calls(signal_logged_, 2)) - x2w_local::logf("x2w-d3d12 linear buffers: the submit fence could not be signalled; its staging stays in use"); - return; - } - for (auto& [resource, record] : records_) - if (record.copy && record.copy->live) record.copy->last_fence = value; + if (internal_queue_) internal_queue_->AddRef(); + return internal_queue_; } bool info(ID3D12Resource* resource, X2wLinearBufferInfo* out) @@ -471,7 +423,7 @@ class LinearBuffers { out->refreshes = copy->refreshes; out->bytes_copied = copy->bytes_copied; out->last_staging = copy->last_staging; - out->last_fence = copy->last_fence; + out->last_fence = copy->refresh_value; out->stale = copy->stale ? 1 : 0; out->refresh_failures = copy->refresh_failures; out->last_refresh_hr = copy->last_refresh_hr; @@ -492,7 +444,8 @@ class LinearBuffers { bool live = true; std::vector uploaded; // what the backing holds (empty before the first refresh) std::vector bound; // skip-refresh mutant: the bytes at placement - UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, last_fence = 0, refresh_failures = 0; + UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, refresh_failures = 0; + UINT64 refresh_value = 0; // internal fence value of the last enqueued refresh bool stale = false; HRESULT last_refresh_hr = S_OK; }; @@ -504,7 +457,7 @@ class LinearBuffers { ID3D12Resource* buffer = nullptr; unsigned char* mapped = nullptr; UINT64 bytes = 0, id = 0; - ID3D12Fence* fence = nullptr; // the queue fence whose value completes its last use + ID3D12Fence* fence = nullptr; // the internal fence, whose value completes the copy that read it UINT64 value = 0; // 0: free; ~0: in use with no signalled value }; struct RefreshList { @@ -512,11 +465,6 @@ class LinearBuffers { ID3D12GraphicsCommandList* list = nullptr; UINT64 value = 0; }; - struct QueueState { - ID3D12Fence* fence = nullptr; - UINT64 value = 0; - std::vector> lists; - }; struct Heap { void* base; ID3D12Heap* heap; @@ -592,39 +540,103 @@ class LinearBuffers { return hr; } - // Whether a fence can be created for this device at all (the copy path's lifetime guarantee needs one). - HRESULT fence_check(ID3D12Device* device) + // The internal refresh queue and its fence, created once (under mutex_, from place()). + HRESULT internal_ready(ID3D12Device* device) { - if (fence_check_device_ != device) { - fence_check_device_ = device; - ID3D12Fence* fence = nullptr; - fence_check_hr_ = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); - if (fence) fence->Release(); + if (internal_queue_) return S_OK; + if (internal_tried_) return internal_hr_; + internal_tried_ = true; + const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY}; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + internal_hr_ = device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)); + if (SUCCEEDED(internal_hr_)) internal_hr_ = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + if (FAILED(internal_hr_)) { + if (queue) queue->Release(); + x2w_local::logf("x2w-d3d12 linear buffers: the internal refresh queue could not be created (0x%08lx); copied " + "buffers keep the default backing", static_cast(internal_hr_)); + return internal_hr_; } - return fence_check_hr_; + queue->SetName(L"x2w linear-buffer refresh"); + internal_device_ = device; + internal_queue_ = queue; + internal_fence_ = fence; + return S_OK; } - HRESULT queue_state(ID3D12CommandQueue* queue, QueueState** out) + // Staging, the refresh list and the internal queue, without mutex_; then publish under it. + template + void refresh(std::vector& work) { - auto found = queues_.find(queue); - if (found == queues_.end()) { - if (linear_detail::submit_fence_forced_off()) return E_NOT_VALID_STATE; - ID3D12Device* device = nullptr; - HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); - ID3D12Fence* fence = nullptr; - if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); - if (device) device->Release(); - if (FAILED(hr)) return hr; - try { - found = queues_.emplace(queue, QueueState{}).first; - } catch (const std::bad_alloc&) { - fence->Release(); - return E_OUTOFMEMORY; + std::vector taken; + bool any_staged = false; + for (Work& w : work) { + w.hr = acquire_staging(w.bytes, taken, &w.staging); + if (FAILED(w.hr)) continue; + taken.push_back(w.staging); + std::memcpy(w.staging->mapped, w.source + w.offset, static_cast(w.bytes)); + any_staged = true; + } + RefreshList* list = nullptr; + HRESULT list_hr = S_OK; + bool executed = false; + UINT64 value = 0; + if (any_staged) { + list_hr = acquire_list(&list); + if (SUCCEEDED(list_hr)) { + // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST on the internal + // queue, and it decays to COMMON again when this ExecuteCommandLists completes. + for (const Work& w : work) + if (SUCCEEDED(w.hr)) list->list->CopyBufferRegion(w.dest, w.offset, w.staging->buffer, 0, w.bytes); + list_hr = list->list->Close(); + } + if (SUCCEEDED(list_hr)) { + std::lock_guard submit(internal_mutex_); + ID3D12CommandList* lists[] = {list->list}; + internal_queue_->ExecuteCommandLists(1, lists); + executed = true; + list_hr = internal_queue_->Signal(internal_fence_, internal_value_ + 1); + if (SUCCEEDED(list_hr)) value = ++internal_value_; } - found->second.fence = fence; } - *out = &found->second; - return S_OK; + + // Publish under the lock. Two submissions that snapshot the same buffer concurrently can both + // copy the same changed span and publish `uploaded` in either order, so `uploaded` may briefly + // lag what the GPU already holds. The next submission then compares the title against an older + // upload and copies a span that is redundant or larger than needed, never one that misses a + // change, so the cost is an extra refresh, not stale data. Every consumer waits for the higher + // of the two fence values. + std::lock_guard lock(mutex_); + // Executed without a fence value: what it read can never be proven free, so it stays in use. + const UINT64 held = executed ? ~UINT64{0} : 0; + if (list) list->value = value ? value : (FAILED(list_hr) ? held : value); + for (Work& w : work) { + const HRESULT hr = FAILED(w.hr) ? w.hr : list_hr; + if (FAILED(hr)) { + if (w.staging) w.staging->value = held; + refresh_failed(w.dest, *w.copy, hr); + continue; + } + w.staging->fence = internal_fence_; + w.staging->value = value; + Copied& copy = *w.copy; + if (value > copy.refresh_value) copy.refresh_value = value; + if (copy.live) { + // The backing holds these bytes once `value` completes; every consumer waits for it. + try { + if (copy.uploaded.size() != copy.bytes) copy.uploaded.assign(static_cast(copy.bytes), 0); + std::memcpy(copy.uploaded.data() + w.offset, w.staging->mapped, static_cast(w.bytes)); + } catch (const std::bad_alloc&) { + copy.uploaded.clear(); // the next submission copies the whole buffer again + } + } + copy.stale = false; + ++copy.refreshes; + copy.bytes_copied += w.bytes; + copy.last_staging = w.staging->id; + ++totals_.refreshes; + totals_.bytes_copied += w.bytes; + } } static bool complete(const Staging& staging) @@ -636,7 +648,7 @@ class LinearBuffers { // Takes a staging buffer of at least `bytes` that no submission still reads, for this submission // alone (`taken` are the ones it already holds). Called without mutex_: the lock is taken only to // choose or publish a buffer; creating one and waiting for a fence happen outside it. - HRESULT acquire_staging(ID3D12CommandQueue* queue, UINT64 bytes, const std::vector& taken, Staging** out) + HRESULT acquire_staging(UINT64 bytes, const std::vector& taken, Staging** out) { const bool early = linear_detail::mutant("reuse-early"); { @@ -679,7 +691,7 @@ class LinearBuffers { } } } - if (create) return create_staging(queue, bytes, out); + if (create) return create_staging(bytes, out); if (!fence || attempt) break; // The hold-lock mutant waits with mutex_ held, as before the review: other callers block. std::unique_lock held; @@ -694,21 +706,16 @@ class LinearBuffers { } // Called without mutex_ after acquire_staging reserved a place in the pool (creating_). - HRESULT create_staging(ID3D12CommandQueue* queue, UINT64 bytes, Staging** out) + HRESULT create_staging(UINT64 bytes, Staging** out) { auto staging = std::make_unique(); - ID3D12Device* device = nullptr; - HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); - if (SUCCEEDED(hr)) { - const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; - const UINT64 rounded = (bytes + 0xFFFF) & ~UINT64{0xFFFF}; - const UINT64 size = rounded ? rounded : 0x10000; - const auto desc = linear_detail::buffer(size, D3D12_RESOURCE_FLAG_NONE); - hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&staging->buffer)); - device->Release(); - staging->bytes = size; - } + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; + const UINT64 rounded = (bytes + 0xFFFF) & ~UINT64{0xFFFF}; + const UINT64 size = rounded ? rounded : 0x10000; + const auto desc = linear_detail::buffer(size, D3D12_RESOURCE_FLAG_NONE); + HRESULT hr = internal_device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&staging->buffer)); + staging->bytes = size; void* mapped = nullptr; const D3D12_RANGE none{0, 0}; if (SUCCEEDED(hr)) hr = staging->buffer->Map(0, &none, &mapped); @@ -731,15 +738,15 @@ class LinearBuffers { return S_OK; } - // A refresh list for queue whose last use has completed, or a new one, reset and ours alone. - // Called without mutex_; the lock covers only the choice and the pool. - HRESULT acquire_list(ID3D12CommandQueue* queue, QueueState& state, RefreshList** out) + // A refresh list for the internal queue whose last use has completed, or a new one, reset and ours + // alone. Called without mutex_; the lock covers only the choice and the pool. + HRESULT acquire_list(RefreshList** out) { RefreshList* found = nullptr; { std::lock_guard lock(mutex_); - const UINT64 completed = state.fence->GetCompletedValue(); - for (const auto& list : state.lists) { + const UINT64 completed = internal_fence_->GetCompletedValue(); + for (const auto& list : internal_lists_) { if (list->value == ~UINT64{0} || list->value > completed) continue; list->value = ~UINT64{0}; found = list.get(); @@ -752,15 +759,11 @@ class LinearBuffers { *out = found; // on failure the caller frees it again under the lock return hr; } - ID3D12Device* device = nullptr; - HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); - if (FAILED(hr)) return hr; - const D3D12_COMMAND_LIST_TYPE type = queue->GetDesc().Type; auto list = std::make_unique(); - hr = device->CreateCommandAllocator(type, IID_PPV_ARGS(&list->allocator)); + HRESULT hr = internal_device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&list->allocator)); if (SUCCEEDED(hr)) - hr = device->CreateCommandList(0, type, list->allocator, nullptr, IID_PPV_ARGS(&list->list)); - device->Release(); + hr = internal_device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, list->allocator, nullptr, + IID_PPV_ARGS(&list->list)); if (FAILED(hr)) { if (list->list) list->list->Release(); if (list->allocator) list->allocator->Release(); @@ -769,11 +772,11 @@ class LinearBuffers { list->value = ~UINT64{0}; std::lock_guard lock(mutex_); try { - state.lists.push_back(std::move(list)); + internal_lists_.push_back(std::move(list)); } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } - *out = state.lists.back().get(); + *out = internal_lists_.back().get(); return S_OK; } @@ -792,17 +795,22 @@ class LinearBuffers { std::mutex mutex_; std::unordered_map records_; - std::unordered_map queues_; + std::mutex internal_mutex_; // the internal queue's ExecuteCommandLists and Signal, in value order + ID3D12Device* internal_device_ = nullptr; + ID3D12CommandQueue* internal_queue_ = nullptr; + ID3D12Fence* internal_fence_ = nullptr; + UINT64 internal_value_ = 0; // under internal_mutex_ + bool internal_tried_ = false; + HRESULT internal_hr_ = S_OK; + std::vector> internal_lists_; std::vector> staging_; std::vector heaps_; ID3D12Device* feature_device_ = nullptr; HRESULT feature_hr_ = S_FALSE; - ID3D12Device* fence_check_device_ = nullptr; - HRESULT fence_check_hr_ = S_OK; UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; - volatile LONG unreadable_logged_ = 0, signal_logged_ = 0, refresh_logged_ = 0; + volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index fae1176e76..687f8fc576 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -18,7 +18,7 @@ struct X2wLinearBufferInfo { std::uint64_t refreshes; // copied: submissions that copied bytes into the backing std::uint64_t bytes_copied; // copied: bytes copied from title memory into the backing std::uint64_t last_staging; // copied: id of the staging buffer of the last refresh (0: none) - std::uint64_t last_fence; // copied: queue fence value after the last submission (0: none) + std::uint64_t last_fence; // copied: internal fence value of the last refresh (0: none) std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none std::int32_t reserved; @@ -29,5 +29,6 @@ struct X2wLinearBufferTotals { std::uint64_t feature_queries, heap_opens, heap_open_failures, heap_cache_hits, place_failures; std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; std::uint64_t refresh_failures; + std::uint64_t consumer_waits; // submissions made to Wait for a refresh on the internal queue std::int32_t last_refusal_hr, last_refresh_hr; }; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 41106117e0..1f4037aaec 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -32,7 +32,7 @@ // pagefile sections) mapped with X2W_XMEM_SHARED_VIEWS=1, five pages per mapping call (one view): // three neighbour pages, then the two-page buffer at view offset 0x30000. A previous user's pages are // freed first, so the first buffer lands on reused slots that must read zero. "private": one -// committed 4 MiB VirtualAlloc range, five pages per allocation in the same layout. +// committed 8 MiB VirtualAlloc range, five pages per allocation in the same layout. // // Cases (sentinels A, B, C, D, E, G, P, filler and neighbour differ in every word): // a bind A: slot 133 and a list that reads the buffer are recorded over A. The CPU writes B @@ -61,10 +61,17 @@ // q.comp, q.copy (copy only) the buffer is read by a list on a COMPUTE queue (a dispatch) and on a // COPY queue (CopyBufferRegion) submitted through those queues' wrappers: the refresh runs on // that queue, the first submission reads B, and a 16-word change then copies 64 bytes. +// gate2q, gate2q.held (copy only) one buffer holding A, read by a list on queue 1 behind a title gate +// and by a list on queue 2; the CPU writes B once before both submissions. Queue 2 must complete +// while the gate is closed and read B, and queue 1 must read B after it. In .held the fixture also +// holds the internal refresh queue: queue 2 must not complete before the refresh lands. +// xq (copy only) queue 1 waits on a title fence that queue 2 signals after its list (a cross-queue +// dependency the title owns); both read the buffer the CPU changed to B. Both must complete (no +// deadlock) and read B. // contention (contention only) a second queue, a release() and the info export while a submission -// waits for the only staging buffer, which a gate-held submission still reads: all three must -// finish while the wait is still under way. After the gate opens the waiting refresh takes that -// buffer again (none is created), and each submission reads its own bytes. +// waits for the only staging buffer, whose copy the fixture holds on the internal refresh +// queue: all three must finish while the wait is still under way. After the refreshes land the +// waiting refresh has taken that buffer again (none is created), and both gated reads see C. // pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on // it, then XMem's unmap of those pages, while they live and after their release. // @@ -75,7 +82,12 @@ // --mutate sets X2W_TEST_LINEAR_BUFFER_MUTANT, which removes one guarantee inside d3d12_xs.dll: // skip-refresh (copy) case a, reuse-early (copy) case c, copy-gpu-writes (copy) case b, // ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported), -// hold-lock (contention) case contention (the wait keeps the backing's lock held). +// hold-lock (contention) case contention (the wait keeps the backing's lock held), +// skip-consumer-wait (copy) case gate2q.held (no submission waits for the internal fence). +// +// Refreshes run on an internal COPY queue that the DLL exports to fixtures +// (x2w_d3d12_linear_buffer_internal_queue); cases c, contention and gate2q.held hold it behind a fence +// of their own to keep a refresh in flight. // The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). // X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. // Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter @@ -102,6 +114,7 @@ extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_internal_queue(void**); extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void*, SIZE_T, DWORD, ULONGLONG, DWORD); extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR, PULONG_PTR, PULONG_PTR); extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR); @@ -276,7 +289,7 @@ struct Pool { bool init() { - bytes = xmem ? UINT64{16} << 30 : UINT64{4} << 20; // XMem takes the 16 GiB startup reservation shape + bytes = xmem ? UINT64{16} << 30 : UINT64{8} << 20; // XMem takes the 16 GiB startup reservation shape base = static_cast(xmem ? XMemVirtualAlloc(nullptr, static_cast(bytes), 0x20402000, 0x21, PAGE_READWRITE) : VirtualAlloc(nullptr, static_cast(bytes), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!base) return false; @@ -408,6 +421,33 @@ struct Gpu { return true; } + // The DLL's internal refresh queue, held behind a fence of the fixture's own. + ComPtr internal; + ComPtr internal_gate, internal_done; + UINT64 internal_gate_value = 0, internal_done_value = 0; + bool hold_internal() + { + if (!internal) { + void* queue = nullptr; + if (!x2w_d3d12_linear_buffer_internal_queue(&queue)) return false; + internal.Attach(static_cast(queue)); + } + if (!internal_gate && (FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&internal_gate))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&internal_done))))) + return false; + return SUCCEEDED(internal->Wait(internal_gate.Get(), ++internal_gate_value)); + } + void open_internal() + { + if (internal_gate) internal_gate->Signal(internal_gate_value); + } + // Every refresh enqueued so far has landed. + bool drain_internal() + { + return internal && SUCCEEDED(internal->Signal(internal_done.Get(), ++internal_done_value)) && + wait_fence(internal_done.Get(), internal_done_value); + } + // Later submissions wait on the gate until open_gate(). void hold() { @@ -777,6 +817,8 @@ struct Run { Held held[3]; const X2wLinearBufferTotals start = totals(); gpu.hold(); + // Copying: the refreshes are held too, on the internal queue, so their staging stays in flight. + if (copying && !gpu.hold_internal()) return row(pool, "c", false, "internal refresh queue not available"); for (int i = 0; i < 3; ++i) { Held& h = held[i]; h.tag = tags[i]; @@ -793,6 +835,7 @@ struct Run { const X2wLinearBufferTotals during = totals(); const bool pending = gpu.done->GetCompletedValue() < held[0].value; // Each held submission reads its own buffer into its own result slot. + if (copying) gpu.open_internal(); gpu.open_gate(); if (!gpu.wait(held[2].value)) return row(pool, "c", false, "fence timeout"); std::string reads = "held reads"; @@ -960,6 +1003,87 @@ struct Run { } } + // gate2q: one buffer, two queues, one CPU write before both submissions (the review repro). + void case_gate2q(Pool& pool, bool held) + { + const char* name = held ? "gate2q.held" : "gate2q"; + Lane q2; + Memory memory; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A)) return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + write(memory.buffer(), r0, B, words); + const X2wLinearBufferTotals before = totals(); + gpu.hold(); + if (held && !gpu.hold_internal()) return row(pool, name, false, "internal refresh queue not available"); + const UINT64 v1 = l1.submit(); // queue 1, behind the title gate: its refresh goes to the internal queue + const UINT64 v2 = l2.submit_on(q2); + bool q2_waited = true; + if (held) { + // Queue 2 has nothing to refresh itself (B is already enqueued) but must wait for that refresh. + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + q2_waited = q2.fence->GetCompletedValue() < v2; + gpu.open_internal(); + } + const bool q2_done = wait_fence(q2.fence.Get(), v2); + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + const Tally t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + gpu.open_gate(); + if (!gpu.wait(v1)) return row(pool, name, false, "fence timeout (queue 1)"); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = q2_done && q1_pending && q2_waited && t2.count[B] == words && t1.count[B] == words && !x.info.stale && + x.info.refresh_failures == 0 && after.consumer_waits > before.consumer_waits; + row(pool, name, pass, + std::string("queue 2 ") + (q2_done ? "completed" : "DID NOT COMPLETE") + " with queue 1 " + + (q1_pending ? "still gated" : "NOT GATED") + (held ? (q2_waited ? ", after waiting for the held refresh" : ", WITHOUT WAITING for the held refresh") : "") + + ": read " + t2.text() + "; queue 1 then read " + t1.text() + "; consumer waits +" + + std::to_string(after.consumer_waits - before.consumer_waits) + (x.info.stale ? ", STALE" : "")); + } + + // xq: queue 1 waits on a title fence that queue 2 signals after its list. + void case_xq(Pool& pool) + { + Lane q2; + Memory memory; + ComPtr title_fence; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A) || + FAILED(gpu.desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&title_fence)))) + return row(pool, "xq", false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, "xq", false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, "xq", false, "fence timeout"); + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + write(memory.buffer(), r0, B, words); + gpu.queue->Wait(title_fence.Get(), 1); // the title's own cross-queue dependency + const UINT64 v1 = l1.submit(); + const UINT64 v2 = l2.submit_on(q2); + q2.native->Signal(title_fence.Get(), 1); + const bool q2_done = wait_fence(q2.fence.Get(), v2), q1_done = gpu.wait(v1); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + const bool pass = q1_done && q2_done && t1.count[B] == words && t2.count[B] == words; + row(pool, "xq", pass, + std::string("queue 1 waits on a fence queue 2 signals after its list: queue 2 ") + (q2_done ? "completed" : "DID NOT COMPLETE") + + " and read " + t2.text() + ", queue 1 " + (q1_done ? "completed" : "DID NOT COMPLETE (deadlock?)") + " and read " + t1.text()); + } + // contention: nothing waits behind a submission that waits for the only staging buffer. void case_contention(Pool& pool) { @@ -984,15 +1108,17 @@ struct Run { if (!wait_fence(second.fence.Get(), lw.submit_on(second))) return row(pool, "contention", false, "fence timeout"); const X2wLinearBufferTotals before = totals(); - // S1 reads B and is held on the gate; its refresh holds the only staging buffer. + // S1 reads X behind the title gate; its refresh (B) is held on the internal queue and holds the + // only staging buffer. gpu.hold(); + if (!gpu.hold_internal()) return row(pool, "contention", false, "internal refresh queue not available"); write(mx.buffer(), r0, B, words); TitleList s1, s2, probe; if (!s1.begin(gpu) || !s2.begin(gpu) || !probe.begin(gpu)) return row(pool, "contention", false, "list"); s1.read(x.backing.Get(), 1); s1.close(); s1.submit(); - // S2's refresh (C) must wait for S1's fence: on another thread. + // S2's refresh (C) must wait for that staging buffer's copy: on another thread. write(mx.buffer(), r0, C, words); s2.read(x.backing.Get(), 2); s2.close(); @@ -1023,15 +1149,18 @@ struct Run { const auto submit_time = clock::now() - t; const bool waiting_after = !done; const Tally w_read = tally(gpu.read_output(3).data(), r0 / 4, key); - gpu.open_gate(); + // Let the refreshes land (B, then C), then the gated reads run: both see C, the CPU's last write. + gpu.open_internal(); waiter.join(); - if (!gpu.wait(s2_value)) return row(pool, "contention", false, "fence timeout after the gate"); + const bool drained = gpu.drain_internal(); + gpu.open_gate(); + if (!drained || !gpu.wait(s2_value)) return row(pool, "contention", false, "fence timeout after the gates"); const Tally r1 = tally(gpu.read_output(1).data(), r0 / 4, key), r2 = tally(gpu.read_output(2).data(), r0 / 4, key); X2wLinearBufferInfo xi{}; x2w_d3d12_linear_buffer_info(x_wrapper, &xi); const X2wLinearBufferTotals after = totals(); const bool reused = after.staging_created == before.staging_created && after.staging_reused >= before.staging_reused + 2; - const bool pass = waiting_before && waiting_after && probe_done && w_read.count[D] == words && r1.count[B] == words && + const bool pass = waiting_before && waiting_after && probe_done && w_read.count[D] == words && r1.count[C] == words && r2.count[C] == words && !xi.stale && xi.refresh_failures == 0 && reused && ms(t1_time) >= ms(info_time + release_time + submit_time); char text[400]; @@ -1196,7 +1325,12 @@ int main(int argc, char** argv) run.case_c(pool); run.case_d1(pool); if (path != Path::default_backing) run.case_b(pool, true); - if (path == Path::copy) run.case_queues(pool); + if (path == Path::copy) { + run.case_queues(pool); + run.case_gate2q(pool, false); + run.case_gate2q(pool, true); + run.case_xq(pool); + } run.probe_view_pin(pool); } const X2wLinearBufferTotals t = totals(); @@ -1247,7 +1381,7 @@ int main(int argc, char** argv) if (!mutant.empty()) { const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" - : mutant == "hold-lock" ? "contention" : nullptr; + : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results) From e896410b07412bd0dde2569ed1a0e3c5ba0e2500 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 15:35:33 +0100 Subject: [PATCH 06/18] gpu: count linear-buffer backings in the D3D12 budget With X2W_D3D12_BUDGET=1, slot 133's linear buffers are counted as the default backing counts its own: a shared buffer as a placed resource whose heap (opened once per private range) has a backing-heap ticket in use while a buffer on it is held, a copied buffer as a committed default buffer. The pool's staging buffers are counted as upload memory when they are created; they live for the process. The fixture enables the budget and checks, on the share and copy paths, that one placement goes live in its category, the heap is live for a shared one, and the title's release moves it to retained, with nothing unmeasured. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/d3d12_xs_device.cpp | 8 +++-- src/startup_stubs/linear_buffer_backing.h | 21 +++++++++---- tests/linear_buffer_backing_check.cpp | 38 +++++++++++++++++++++++ 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 77223690b0..9e1a74267b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4354,14 +4354,18 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 const bool uav = (sanitized(*desc).Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; ID3D12Resource* resource = nullptr; bool shared = false; - const HRESULT placed = linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, &shared, &linear); + x2w_budget::Ticket* linear_heap_budget = nullptr; + const HRESULT placed = linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, &shared, + &linear_heap_budget, &linear); if (SUCCEEDED(placed)) { log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer address=%p base=%p type=0x%lx offset=0x%llx " "width=0x%llx flags=0x%x use=%s existing-heaps=0x%08lx share=0x%08lx -> 0x%08lx %s gpuva=0x%llx", address, base, static_cast(range.type), offset, desc->Width, desc->Flags, uav ? "gpu-written" : "gpu-read", static_cast(linear.feature_hr), static_cast(linear.share_hr), static_cast(placed), shared ? "shared" : "copied at submit", resource->GetGPUVirtualAddress()); - return publish_placed_buffer(self, address, desc, initial_state, resource, shared, nullptr, out); + // Budgets as for the default backing: a shared buffer is a placed resource on its heap, a copied + // one a committed default buffer (its staging is counted as upload memory when it is created). + return publish_placed_buffer(self, address, desc, initial_state, resource, shared, linear_heap_budget, out); } if (x2w_startup::LinearBuffers::report_refusals()) std::snprintf(linear_note, sizeof(linear_note), diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 2a40fd3783..a0aed6b6b3 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -107,6 +107,7 @@ #include "startup_stubs/linear_buffer_report.h" #include "startup_stubs/local_log.h" #include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/resource_budget.h" namespace x2w_startup { @@ -199,13 +200,15 @@ class LinearBuffers { // Slot 133 for an eligible buffer. range is measure_placed_buffer's answer for (address, width) and // uav says whether the desktop flags keep ALLOW_UNORDERED_ACCESS. On success *out holds the - // desktop resource and *shared whether it aliases the title memory. A failure is a refusal: the - // caller keeps the default backing and passes *report (path kept_default_path) to kept_default(). + // desktop resource and *shared whether it aliases the title memory; a shared one's heap budget + // (X2W_D3D12_BUDGET, or null) is in *backing_budget. A failure is a refusal: the caller keeps the + // default backing and passes *report (path kept_default_path) to kept_default(). HRESULT place(ID3D12Device* device, void* address, UINT64 width, bool uav, const PlacedBufferRange& range, - ID3D12Resource** out, bool* shared, X2wLinearBufferInfo* report) + ID3D12Resource** out, bool* shared, x2w_budget::Ticket** backing_budget, X2wLinearBufferInfo* report) { *out = nullptr; *shared = false; + *backing_budget = nullptr; std::lock_guard lock(mutex_); ++totals_.placements; Record record{}; @@ -226,7 +229,8 @@ class LinearBuffers { else if (range.type != MEM_PRIVATE) record.info.share_hr = E_INVALIDARG; else - record.info.share_hr = share(device, range, offset, width, uav, &resource, &record.info.heap_generation); + record.info.share_hr = share(device, range, offset, width, uav, &resource, &record.info.heap_generation, + backing_budget); } HRESULT hr = S_OK; if (SUCCEEDED(record.info.share_hr) && record.info.share_hr != S_FALSE) { @@ -277,6 +281,7 @@ class LinearBuffers { } if (FAILED(hr)) { if (resource) resource->Release(); + *backing_budget = nullptr; record.info.path = kept_default_path; record.info.refusal_hr = hr; record.info.backing = nullptr; @@ -469,6 +474,7 @@ class LinearBuffers { void* base; ID3D12Heap* heap; UINT64 generation, bytes; + x2w_budget::Ticket* budget; // the heap's budget ticket (X2W_D3D12_BUDGET), counted while a buffer uses it }; // 256 staging buffers; X2W_TEST_LINEAR_STAGING_LIMIT= (fixtures) lowers it, to make the pool fill. static std::size_t staging_limit() @@ -504,7 +510,7 @@ class LinearBuffers { // A private range only (place() decides the rest). Its heap is opened once per allocation base and // cached: the open heap keeps the range from being released, so the base cannot name other memory. HRESULT share(ID3D12Device* device, const PlacedBufferRange& range, UINT64 offset, UINT64 width, bool uav, - ID3D12Resource** out, UINT64* generation) + ID3D12Resource** out, UINT64* generation, x2w_budget::Ticket** budget) { const Heap* entry = nullptr; for (const Heap& known : heaps_) @@ -523,7 +529,7 @@ class LinearBuffers { } if (FAILED(hr)) return hr; try { - heaps_.push_back({range.base, heap, ++generation_, heap->GetDesc().SizeInBytes}); + heaps_.push_back({range.base, heap, ++generation_, heap->GetDesc().SizeInBytes, x2w_budget::backing_heap(heap, 0)}); } catch (const std::bad_alloc&) { heap->Release(); return E_OUTOFMEMORY; @@ -531,6 +537,7 @@ class LinearBuffers { entry = &heaps_.back(); } *generation = entry->generation; + *budget = entry->budget; if (entry->bytes < offset || width > entry->bytes - offset) return E_INVALIDARG; const auto desc = linear_detail::buffer(width, static_cast( (uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER)); @@ -716,6 +723,8 @@ class LinearBuffers { HRESULT hr = internal_device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&staging->buffer)); staging->bytes = size; + // The pool's staging buffers live for the process: counted as upload memory (X2W_D3D12_BUDGET). + if (SUCCEEDED(hr)) x2w_budget::committed(internal_device_, staging->buffer, D3D12_HEAP_TYPE_UPLOAD); void* mapped = nullptr; const D3D12_RANGE none{0, 0}; if (SUCCEEDED(hr)) hr = staging->buffer->Map(0, &none, &mapped); diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 1f4037aaec..b5ead96918 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -72,6 +72,8 @@ // waits for the only staging buffer, whose copy the fixture holds on the internal refresh // queue: all three must finish while the wait is still under way. After the refreshes land the // waiting refresh has taken that buffer again (none is created), and both gated reads see C. +// budget (share, copy) with X2W_D3D12_BUDGET=1: a shared buffer counts as placed memory (its heap +// live), a copied one as a committed buffer; live while held, retained after the title's release. // pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on // it, then XMem's unmap of those pages, while they live and after their release. // @@ -110,11 +112,13 @@ #include "xmem_test_device.h" #include "../src/startup_stubs/linear_buffer_report.h" +#include "../src/startup_stubs/resource_budget.h" extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_internal_queue(void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void*, SIZE_T, DWORD, ULONGLONG, DWORD); extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR, PULONG_PTR, PULONG_PTR); extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR); @@ -1052,6 +1056,37 @@ struct Run { } // xq: queue 1 waits on a title fence that queue 2 signals after its list. + // budget (share, copy): X2W_D3D12_BUDGET counts a shared buffer as placed memory on its heap and a + // copied one as a committed buffer, live while the title holds it and retained after its release. + void case_budget(Pool& pool) + { + Memory memory; + x2w_budget::Snapshot before{}, held{}, released{}; + if (!pool.allocate(memory, A) || !x2w_d3d12_budget_snapshot(&before, sizeof(before))) + return row(pool, "budget", false, "setup failed or X2W_D3D12_BUDGET not on"); + Placed p = place(gpu, memory.buffer(), false); + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, "budget", false, "slot 133 -> " + hex(p.hr)); + list.read(p.backing.Get()); + list.close(); + if (!gpu.wait(list.submit())) return row(pool, "budget", false, "fence timeout"); + x2w_d3d12_budget_snapshot(&held, sizeof(held)); + const bool shared = p.linear && p.info.path == 1; + const int category = shared ? x2w_budget::placed : x2w_budget::buffer; + p.wrapper.Reset(); // the title's release + x2w_d3d12_budget_snapshot(&released, sizeof(released)); + const auto live = [&](const x2w_budget::Snapshot& snap) { return snap.live[category].objects; }; + const auto kept = [&](const x2w_budget::Snapshot& snap) { return snap.retained[category].objects; }; + const bool heap_live = !shared || held.live[x2w_budget::heap].objects >= 1; + const bool pass = p.linear && live(held) == live(before) + 1 && live(released) == live(before) && + kept(released) == kept(before) + 1 && heap_live && released.unmeasured == before.unmeasured; + row(pool, "budget", pass, + std::string(shared ? "shared: placed" : "copied: buffer") + " objects live " + std::to_string(live(before)) + " -> " + + std::to_string(live(held)) + " -> " + std::to_string(live(released)) + " after release, retained +" + + std::to_string(kept(released) - kept(before)) + (shared ? ", heap live " + std::to_string(held.live[x2w_budget::heap].objects) : "") + + ", unmeasured +" + std::to_string(released.unmeasured - before.unmeasured)); + } + void case_xq(Pool& pool) { Lane q2; @@ -1231,6 +1266,7 @@ int main(int argc, char** argv) // The switches are read once, by the first call that needs them: set them before any. SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_BUDGET", L"1"); // budget accounting (case budget); changes no backing SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); @@ -1330,8 +1366,10 @@ int main(int argc, char** argv) run.case_gate2q(pool, false); run.case_gate2q(pool, true); run.case_xq(pool); + run.case_budget(pool); } run.probe_view_pin(pool); + if (path == Path::share) run.case_budget(pool); } const X2wLinearBufferTotals t = totals(); std::printf("totals: placements %llu (shared %llu, copied %llu, kept default %llu), feature queries %llu, heap opens %llu " From 829d39479ce7b110bd502aedeec9491dafe6a272 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 15:36:49 +0100 Subject: [PATCH 07/18] gpu: defer slot 133 linear buffers to the XMem lease path The mesh XMem lease path (#2280; X2W_MESH86_XMEM_SRV or X2W_MESH_INDIRECT_XMEM) takes the default copied placements of XMem pages whose console flags are 0: it mirrors their GPU writes into a leased view of the section and publishes that to mesh readers. Those are exactly the GPU-read XMem buffers the linear copy path would back. While the lease path is on, slot 133 now keeps the default backing for such a placement and records the deferral as a refusal, HRESULT_FROM_WIN32(ERROR_BUSY), in the log line, the info and the totals, so one placement never has two owners. Other placements are unaffected, and nothing changes while the lease path is off. The fixture adds a lease path (=copy with X2W_MESH86_XMEM_SRV=1): an XMem buffer keeps the default backing with the deferral reported, and a private one is still copied. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 8 +++-- src/startup_stubs/linear_buffer_backing.h | 18 ++++++++++ tests/linear_buffer_backing_check.cpp | 44 +++++++++++++++++++++-- 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 97c61ba7db..1f31f11926 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2599,7 +2599,7 @@ target_include_directories(linear_buffer_backing_check PRIVATE tests) target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) target_link_libraries(linear_buffer_backing_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi d3dcompiler) foreach(adapter IN ITEMS warp hardware) - foreach(path IN ITEMS default share copy refusal untracked stale contention) + foreach(path IN ITEMS default share copy refusal untracked stale contention lease) add_test(NAME linear_buffer_backing_${path}_${adapter} COMMAND linear_buffer_backing_check ${adapter} ${path}) set_tests_properties(linear_buffer_backing_${path}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 9e1a74267b..4cd40a872d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4355,8 +4355,12 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 ID3D12Resource* resource = nullptr; bool shared = false; x2w_budget::Ticket* linear_heap_budget = nullptr; - const HRESULT placed = linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, &shared, - &linear_heap_budget, &linear); + // The mesh XMem lease path takes the default (copied) placements of XMem pages whose console flags + // are 0 (note_mesh_xmem_write); while it is on, the linear backing defers to it there. + const bool lease_owns = mesh_xmem_tracking() && range.type == MEM_MAPPED && desc->Flags == D3D12_RESOURCE_FLAG_NONE; + const HRESULT placed = lease_owns ? x2w_startup::LinearBuffers::defer(uav, &linear) + : linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, + &shared, &linear_heap_budget, &linear); if (SUCCEEDED(placed)) { log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer address=%p base=%p type=0x%lx offset=0x%llx " "width=0x%llx flags=0x%x use=%s existing-heaps=0x%08lx share=0x%08lx -> 0x%08lx %s gpuva=0x%llx", address, base, diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index a0aed6b6b3..d5f14fff3c 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -68,6 +68,10 @@ // - no internal refresh queue or fence (X2W_TEST_SUBMIT_FENCE_FAIL=1 gives E_NOT_VALID_STATE, else // the HRESULT of creating them): consumers could not be ordered behind refreshes. // - the copy's default buffer cannot be created: that HRESULT. +// - the XMem lease path is on (X2W_MESH86_XMEM_SRV or X2W_MESH_INDIRECT_XMEM) and the placement is one +// it takes: XMem pages (MEM_MAPPED) with console flags 0, kept as the default copied placement that +// the lease path mirrors and publishes. HRESULT_FROM_WIN32(ERROR_BUSY): deferred to that owner, so +// the two never back one placement. // // At submit nothing is refused: holding back a submission can leave a title waiting on its fences. // When a copied buffer's refresh cannot be staged (a staging buffer or refresh list cannot be @@ -195,6 +199,20 @@ class LinearBuffers { desc.Width && initial_state == D3D12_RESOURCE_STATE_COMMON; } + // The refusal recorded for a placement that another owner takes: the XMem lease path, which takes + // the default (copied) placements of XMem pages whose console flags are 0 while it is on. + static constexpr HRESULT lease_deferral = HRESULT_FROM_WIN32(ERROR_BUSY); + static HRESULT defer(bool uav, X2wLinearBufferInfo* report) + { + *report = X2wLinearBufferInfo{}; + report->use = uav ? gpu_written : gpu_read; + report->feature_hr = S_FALSE; + report->share_hr = S_FALSE; + report->path = kept_default_path; + report->refusal_hr = lease_deferral; + return lease_deferral; + } + // False under the refusal-silent mutant: a kept default backing is then not reported anywhere. static bool report_refusals() { return !linear_detail::mutant("refusal-silent"); } diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index b5ead96918..9ffa34d14f 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -19,6 +19,8 @@ // 5, 8 ... fail, so one refresh per pool cannot be staged // contention X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_LINEAR_STAGING_LIMIT=1: one staging buffer, // so a refresh waits for the fence of the submission that holds it +// lease X2W_D3D12_LINEAR_BUFFERS=copy with X2W_MESH86_XMEM_SRV=1: the mesh XMem lease path is on and +// owns XMem placements with console flags 0; the linear backing must defer to it there // // Where the new path cannot keep its guarantees (a GPU-written use that is not shared, no submit // fence), slot 133 must keep the default backing and return what it returns with the switch off: @@ -74,6 +76,8 @@ // waiting refresh has taken that buffer again (none is created), and both gated reads see C. // budget (share, copy) with X2W_D3D12_BUDGET=1: a shared buffer counts as placed memory (its heap // live), a copied one as a committed buffer; live while held, retained after the title's release. +// lease (lease only) an XMem buffer keeps the default backing with HRESULT_FROM_WIN32(ERROR_BUSY) +// reported (old behaviour: reads zero); a private one is copied and reads B. // pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on // it, then XMem's unmap of those pages, while they live and after their release. // @@ -262,7 +266,7 @@ std::string pointer_text(const void* p) return text; } -enum class Path { default_backing, share, copy, refusal, untracked, stale, contention }; +enum class Path { default_backing, share, copy, refusal, untracked, stale, contention, lease }; const char* path_name(Path p) { switch (p) { @@ -272,7 +276,8 @@ const char* path_name(Path p) case Path::refusal: return "refusal"; case Path::untracked: return "untracked"; case Path::stale: return "stale"; - default: return "contention"; + case Path::contention: return "contention"; + default: return "lease"; } } @@ -1056,6 +1061,32 @@ struct Run { } // xq: queue 1 waits on a title fence that queue 2 signals after its list. + // lease: with the mesh XMem lease path on, an XMem placement with console flags 0 is the lease path's: + // slot 133 keeps the default backing (not aliased) and records the deferral; a private one is copied. + void case_lease(Pool& pool) + { + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "lease", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, "lease", false, "slot 133 -> " + hex(p.hr)); + list.read(p.backing.Get()); + list.close(); + write(memory.buffer(), r0, B, words); + if (!gpu.wait(list.submit())) return row(pool, "lease", false, "fence timeout"); + const Tally t = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; GPU read " + t.text(); + bool pass; + if (pool.xmem) { + pass = kept_ok(p, HRESULT_FROM_WIN32(ERROR_BUSY), text) && t.zero == words; + text += " (deferred to the XMem lease path; old behaviour: not aliased)"; + } else { + pass = p.linear && p.info.path == 2 && t.count[B] == words; + } + row(pool, "lease", pass, text); + } + // budget (share, copy): X2W_D3D12_BUDGET counts a shared buffer as placed memory on its heap and a // copied one as a committed buffer, live while the title holds it and retained after its release. void case_budget(Pool& pool) @@ -1259,6 +1290,7 @@ int main(int argc, char** argv) else if (p == "untracked") path = Path::untracked; else if (p == "stale") path = Path::stale; else if (p == "contention") path = Path::contention; + else if (p == "lease") path = Path::lease; else return 2; std::string mutant; if (argc == 5 && std::strcmp(argv[3], "--mutate") == 0) mutant = argv[4]; @@ -1271,11 +1303,13 @@ int main(int argc, char** argv) SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr - : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention ? L"copy" : L"1"); + : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention || + path == Path::lease ? L"copy" : L"1"); SetEnvironmentVariableW(L"X2W_TEST_EXISTING_HEAPS_UNSUPPORTED", path == Path::refusal ? L"1" : nullptr); SetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", path == Path::untracked ? L"1" : nullptr); SetEnvironmentVariableW(L"X2W_TEST_LINEAR_REFRESH_FAIL", path == Path::stale ? L"3" : nullptr); SetEnvironmentVariableW(L"X2W_TEST_LINEAR_STAGING_LIMIT", path == Path::contention ? L"1" : nullptr); + SetEnvironmentVariableW(L"X2W_MESH86_XMEM_SRV", path == Path::lease ? L"1" : nullptr); SetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", mutant.empty() ? nullptr : mutant.c_str()); { // The DLL's log lines go to linear_buffer_backing__[_].log next to this executable. @@ -1355,6 +1389,10 @@ int main(int argc, char** argv) run.case_contention(pool); continue; } + if (path == Path::lease) { + run.case_lease(pool); + continue; + } run.case_a(pool); if (path == Path::share && xmem) run.case_a(pool, true); run.case_b(pool, false); From 7c75f6e99eff38ae0fa74b4d7caa33b9b24deef4 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 15:38:22 +0100 Subject: [PATCH 08/18] gpu: stop refreshing a copied linear buffer that a list copy writes Main now forwards CopyBufferRegion and CopyResource into slot 133 placed buffers (list_copy.inl), so a copied linear buffer can be written by the GPU. Those bytes never reach the title memory, and a later refresh whose changed span covers them copied the title's older bytes over them. A copied buffer that a recorded copy writes now keeps the GPU's bytes from that recording on and is no longer refreshed, as the default backing behaves for it. The info (gpu_written) and the totals report it, and the first few are logged. The fixture adds gpuw on the copy path: a list CopyBufferRegion (list slot 15) writes G into the buffer, the title changes the words on both sides, and the next read must still see G. The refresh-gpu-written mutant keeps refreshing and must fail it. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 2 +- src/startup_stubs/linear_buffer_backing.h | 28 +++++++++++++-- src/startup_stubs/linear_buffer_report.h | 3 +- src/startup_stubs/list_copy.inl | 11 ++++++ tests/linear_buffer_backing_check.cpp | 42 +++++++++++++++++++++-- 5 files changed, 80 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f31f11926..adcad71760 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2605,7 +2605,7 @@ foreach(adapter IN ITEMS warp hardware) endforeach() endforeach() foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature - copy:refusal_silent contention:hold_lock copy:skip_consumer_wait) + copy:refusal_silent contention:hold_lock copy:skip_consumer_wait copy:refresh_gpu_written) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index d5f14fff3c..6190afed53 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -80,6 +80,12 @@ // refresh succeeds; the HRESULT is logged (the first few times) and kept in the buffer's info and the // totals (refresh_failures, last_refresh_hr). // +// A copied buffer that a recorded copy writes (list CopyBufferRegion or CopyResource, list_copy.inl) +// keeps the GPU's bytes from that recording on: it is no longer refreshed. The title memory never +// receives those bytes, and a later refresh that spans them would copy the title's older bytes over +// them. This is what the default backing does for such a buffer; info and totals report it +// (gpu_written). +// // Fixtures only: // X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1 the feature query reports no support (an adapter such as // Intel Gen9 reports EXISTING_HEAPS = 0). @@ -91,6 +97,7 @@ // refusal-silent a kept default backing is not reported (no log text, info or totals) // hold-lock the wait for a full staging pool keeps mutex_ held (other callers block) // skip-consumer-wait submissions do not Wait for the internal fence (consumers race refreshes) +// refresh-gpu-written a copied buffer that a recorded copy wrote is still refreshed // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -331,6 +338,21 @@ class LinearBuffers { } } + // A recorded copy writes the backing of `resource` (list_copy.inl): if it is a copied buffer, it keeps + // the GPU's bytes from now on and is no longer refreshed from the title memory. + void note_gpu_write(ID3D12Resource* resource) + { + if (linear_detail::mutant("refresh-gpu-written")) return; + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + if (found == records_.end() || !found->second.copy || found->second.copy->gpu_written) return; + found->second.copy->gpu_written = true; + ++totals_.gpu_written; + if (x2w_local::first_calls(gpu_write_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffer %p: a recorded copy writes it; it keeps the GPU's bytes and is no " + "longer refreshed from title memory", static_cast(resource)); + } + // The resource never reached the title and is about to be released. void discard(ID3D12Resource* resource) { @@ -378,7 +400,7 @@ class LinearBuffers { if (!any || !internal_queue_) return; for (auto& [resource, record] : records_) { const std::shared_ptr& copy = record.copy; - if (!copy || !copy->live) continue; + if (!copy || !copy->live || copy->gpu_written) continue; const std::size_t bytes = static_cast(copy->bytes); const unsigned char* source = copy->bound.empty() ? copy->title : copy->bound.data(); if (copy->bound.empty() && x2w_local::probe_readable(reinterpret_cast(source), bytes) < bytes) { @@ -448,6 +470,7 @@ class LinearBuffers { out->last_staging = copy->last_staging; out->last_fence = copy->refresh_value; out->stale = copy->stale ? 1 : 0; + out->gpu_written = copy->gpu_written ? 1 : 0; out->refresh_failures = copy->refresh_failures; out->last_refresh_hr = copy->last_refresh_hr; } @@ -470,6 +493,7 @@ class LinearBuffers { UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, refresh_failures = 0; UINT64 refresh_value = 0; // internal fence value of the last enqueued refresh bool stale = false; + bool gpu_written = false; // a recorded copy wrote it: not refreshed any more HRESULT last_refresh_hr = S_OK; }; struct Record { @@ -837,7 +861,7 @@ class LinearBuffers { UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; - volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0; + volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index 687f8fc576..bb15bcea51 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -21,7 +21,7 @@ struct X2wLinearBufferInfo { std::uint64_t last_fence; // copied: internal fence value of the last refresh (0: none) std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none - std::int32_t reserved; + std::uint32_t gpu_written; // copied: 1 once a recorded copy wrote it; it is no longer refreshed }; struct X2wLinearBufferTotals { @@ -30,5 +30,6 @@ struct X2wLinearBufferTotals { std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; std::uint64_t refresh_failures; std::uint64_t consumer_waits; // submissions made to Wait for a refresh on the internal queue + std::uint64_t gpu_written; // copied buffers that a recorded copy wrote (held from then on) std::int32_t last_refusal_hr, last_refresh_hr; }; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 5ed62c7248..d55b96cd40 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -152,6 +152,15 @@ void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) ReleaseSRWLockExclusive(&pending_writes_lock); } +// X2W_D3D12_LINEAR_BUFFERS: a copied linear buffer that a recorded copy writes keeps the GPU's bytes +// from now on and is no longer refreshed from its title memory (linear_buffer_backing.h). +void note_linear_gpu_write(const CopyEndpoint& destination) +{ + if (destination.wrapper && destination.wrapper->own().title_memory && + x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().note_gpu_write(destination.resource); +} + // Refusal shared by the three handlers once the descriptions passed, or none. x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& to, const CopyEndpoint& from, bool sync) { @@ -218,6 +227,7 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti note_mesh_xmem_write(self, to.wrapper, destination_offset, bytes, 15, source_kind, srv_word || mesh_record ? from.resource : nullptr, source_offset); } + note_linear_gpu_write(to); if (indirect_copy_ranges()) { const auto* info = to.wrapper ? resource_info(to.wrapper) : nullptr; note_copy_gpu_range(self, to.resource, destination_offset, bytes, authoritative && info && @@ -247,6 +257,7 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width, 17, "buffer"); note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); + note_linear_gpu_write(to); } else mark_gpu_written(self, to); InterlockedIncrement(&list_resource_copies); } diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 9ffa34d14f..d8944030f2 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -76,6 +76,8 @@ // waiting refresh has taken that buffer again (none is created), and both gated reads see C. // budget (share, copy) with X2W_D3D12_BUDGET=1: a shared buffer counts as placed memory (its heap // live), a copied one as a committed buffer; live while held, retained after the title's release. +// gpuw (copy only) a recorded copy (list slot 15) writes G into a copied buffer, then the title changes +// its first and last words: the buffer keeps G (it is no longer refreshed), reported as gpu_written. // lease (lease only) an XMem buffer keeps the default backing with HRESULT_FROM_WIN32(ERROR_BUSY) // reported (old behaviour: reads zero); a private one is copied and reads B. // pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on @@ -89,7 +91,8 @@ // skip-refresh (copy) case a, reuse-early (copy) case c, copy-gpu-writes (copy) case b, // ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported), // hold-lock (contention) case contention (the wait keeps the backing's lock held), -// skip-consumer-wait (copy) case gate2q.held (no submission waits for the internal fence). +// skip-consumer-wait (copy) case gate2q.held (no submission waits for the internal fence), +// refresh-gpu-written (copy) case gpuw (a refresh spanning the written words copies the title's A over G). // // Refreshes run on an internal COPY queue that the DLL exports to fixtures // (x2w_d3d12_linear_buffer_internal_queue); cases c, contention and gate2q.held hold it behind a fence @@ -1061,6 +1064,39 @@ struct Run { } // xq: queue 1 waits on a title fence that queue 2 signals after its list. + // gpuw: a recorded copy (list slot 15, CopyBufferRegion) writes G into a copied buffer; the title then + // changes bytes on both sides of it. The buffer keeps the GPU's bytes (no refresh spans them), and + // info and totals report it. + void case_gpuw(Pool& pool) + { + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "gpuw", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(p.hr) || !p.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, "gpuw", false, "slot 133 -> " + hex(p.hr)); + l0.read(p.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, "gpuw", false, "fence timeout"); // A uploaded + const X2wLinearBufferTotals before = totals(); + // The title's copy, through the list wrapper: G (indexed as at r1) into the buffer at r0. + invoke(l1.list.Get(), 15, arg(p.wrapper.Get()), r0, arg(gpu.source.Get()), 0, region_bytes); + if (!l1.close() || !gpu.wait(l1.submit())) return row(pool, "gpuw", false, "copy submission failed"); + write(memory.buffer(), 0, D, 1); // the first and last words, around the written region + write(memory.buffer(), buffer_bytes - 4, D, 1); + l2.read(p.backing.Get(), 1); + l2.close(); + if (!gpu.wait(l2.submit())) return row(pool, "gpuw", false, "fence timeout"); + const Tally t = tally(gpu.read_output(1).data(), r1 / 4, key); // G words carry their r1 indices + refresh_info(p); + const X2wLinearBufferTotals after = totals(); + const bool pass = p.linear && p.info.path == 2 && p.info.gpu_written == 1 && t.count[G] == words && + after.gpu_written == before.gpu_written + 1; + row(pool, "gpuw", pass, + "after a recorded copy of G and title writes around it the GPU read " + t.text() + " (expected G: not refreshed); " + + "gpu_written " + std::to_string(p.info.gpu_written) + ", totals +" + std::to_string(after.gpu_written - before.gpu_written)); + } + // lease: with the mesh XMem lease path on, an XMem placement with console flags 0 is the lease path's: // slot 133 keeps the default backing (not aliased) and records the deferral; a private one is copied. void case_lease(Pool& pool) @@ -1405,6 +1441,7 @@ int main(int argc, char** argv) run.case_gate2q(pool, true); run.case_xq(pool); run.case_budget(pool); + run.case_gpuw(pool); } run.probe_view_pin(pool); if (path == Path::share) run.case_budget(pool); @@ -1457,7 +1494,8 @@ int main(int argc, char** argv) if (!mutant.empty()) { const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" - : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" : nullptr; + : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" + : mutant == "refresh-gpu-written" ? "gpuw" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results) From bfdd583fbe9b4d4bc0102bf5866fa3a3300d6ec6 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 15:42:40 +0100 Subject: [PATCH 09/18] docs: record linear-buffer budgets, list-copy holds and the lease deferral Describe, for slot 133's opt-in linear buffers on current main: the refresh and consumer Wait ahead of red_producers and split mesh submissions, the D3D12 budget categories, a copied buffer that a list copy wrote, and the deferral to the mesh XMem lease path. Record the budget, gpuw and lease cases, the refresh-gpu-written control and the results at ff06794b on WARP and an RX 9070 XT (driver 32.0.32029.2010), and note sharing XMem views through the section lease (#2280) as a follow-up. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 4 +++- docs/experiments.md | 16 ++++++++++++---- docs/startup-runtime.md | 7 +++++-- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index adcad71760..e160009627 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2593,7 +2593,9 @@ endforeach() # (a waiting refresh must not block release(), the info export or another queue). Refreshes run on an # internal copy queue; the copy path also reads on COMPUTE and COPY queues, reads one buffer on two # queues after one CPU write (both must see it), and follows a title-owned cross-queue fence without -# deadlock. Each mutant removes one guarantee in the DLL and must fail its case. +# deadlock. It also counts the backings in the D3D12 budget, keeps a buffer a list copy wrote, and defers +# XMem placements to the mesh XMem lease path when that is on. Each mutant removes one guarantee in the +# DLL and must fail its case. add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) target_include_directories(linear_buffer_backing_check PRIVATE tests) target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) diff --git a/docs/experiments.md b/docs/experiments.md index 038774b684..ab20a76243 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9666,7 +9666,7 @@ A title run motivated the fallback. An earlier revision returned the refusal fro - 506 GPU-written buffers (856 MiB), not aliased; - 61 GPU-written buffers (167 MiB), aliased (private). -`tests/linear_buffer_backing_check.cpp` drives the production entry points: slot 133 on the device wrapper, list Reset (139) and Close (9) on wrapper lists recorded on their desktop lists, and `ExecuteCommandLists` (queue slot 10) on the queue wrapper, in render mode. It reuses #1942's sentinels and cases. The GPU reads the buffer through a root SRV and writes it through a root UAV. Title memory is either `xmem.dll` physical pages (64 KiB slots of 256 MiB sections, `X2W_XMEM_SHARED_VIEWS=1`) or one committed private range. The buffer sits at offset `0x30000` behind three neighbour pages, and the first XMem buffer lands on slots that a previous user freed, which must read zero. Each run sets its own environment. The path is one of `default` (unset), `share` (`=1`), `copy` (`=copy`), `refusal` (`=1` with `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1`, as on an adapter with `EXISTING_HEAPS = 0`), `untracked` (`=copy` with `X2W_TEST_SUBMIT_FENCE_FAIL=1`) and `stale` (`=copy` with `X2W_TEST_LINEAR_REFRESH_FAIL=3`, so staging requests 2, 5, 8 and so on fail with `E_OUTOFMEMORY`). A kept default must return `S_OK` with an object, behave as before (an XMem view not aliased, a private range aliased on an adapter with existing heaps), and carry the refusal HRESULT in `x2w_d3d12_linear_buffer_info`, in the totals and in its slot 133 log line. The fixture reads that line back from `X2W_TRAP_LOG`. +`tests/linear_buffer_backing_check.cpp` drives the production entry points: slot 133 on the device wrapper, list Reset (139) and Close (9) on wrapper lists recorded on their desktop lists, and `ExecuteCommandLists` (queue slot 10) on the queue wrapper, in render mode. It reuses #1942's sentinels and cases. The GPU reads the buffer through a root SRV and writes it through a root UAV. Title memory is either `xmem.dll` physical pages (64 KiB slots of 256 MiB sections, `X2W_XMEM_SHARED_VIEWS=1`) or one committed private range. The buffer sits at offset `0x30000` behind three neighbour pages, and the first XMem buffer lands on slots that a previous user freed, which must read zero. Each run sets its own environment. The path is one of `default` (unset), `share` (`=1`), `copy` (`=copy`), `refusal` (`=1` with `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1`, as on an adapter with `EXISTING_HEAPS = 0`), `untracked` (`=copy` with `X2W_TEST_SUBMIT_FENCE_FAIL=1`), `stale` (`=copy` with `X2W_TEST_LINEAR_REFRESH_FAIL=3`, so staging requests 2, 5, 8 and so on fail with `E_OUTOFMEMORY`), `contention` (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`) and `lease` (`=copy` with `X2W_MESH86_XMEM_SRV=1`, the mesh XMem lease path on). Every run sets `X2W_D3D12_BUDGET=1`. A kept default must return `S_OK` with an object, behave as before (an XMem view not aliased, a private range aliased on an adapter with existing heaps), and carry the refusal HRESULT in `x2w_d3d12_linear_buffer_info`, in the totals and in its slot 133 log line. The fixture reads that line back from `X2W_TRAP_LOG`. | Case | Sequence and oracle | |---|---| @@ -9684,9 +9684,12 @@ A title run motivated the fallback. An earlier revision returned the refusal fro | q.comp, q.copy | `copy` only: the buffer is read on a COMPUTE queue (a dispatch) and on a COPY queue (`CopyBufferRegion`), each through its queue wrapper, so the refresh runs on that queue. The first submission must read B with the whole buffer copied, and a 16-word change must then copy 64 bytes. | | gate2q, gate2q.held | `copy` only (review repro): one buffer holding A, read by a list on queue 1 behind a title gate and by a list on queue 2, with one CPU write of B before both submissions. Queue 2 must complete while the gate is still closed and read B, and queue 1 must read B after it. In `.held` the fixture also holds the internal refresh queue, and queue 2 must not complete before the refresh lands. | | xq | `copy` only: queue 1 waits on a title fence that queue 2 signals after its list. Both read the buffer the CPU changed to B. Both must complete, with no deadlock, and read B. | +| budget | `share` and `copy`: one placement must go live in its budget category, placed for a shared buffer (with its heap live) and buffer for a copied one. The title's release must move it to retained, with nothing unmeasured. | +| gpuw | `copy` only: a list `CopyBufferRegion` (list slot 15) writes G into the buffer, and the title then changes its first and last words. The next read must still see G (no refresh spans the written words), and info and totals must report it as GPU-written. | +| lease | `lease` only: an XMem buffer must keep the default backing (not aliased: it reads zero) with the deferral `0x800700aa` reported. A private buffer must still be copied and read B. | | contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a title gate, and its refresh, held on the internal queue, holds the only staging buffer. S2's refresh of X, on another thread, must wait for that copy. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the refreshes land and the gate opens, S2 must have reused the same staging buffer (none created). S1 and S2 must both read C, the CPU's last write before they ran, with no refresh failure. | -On Windows 11 build 26300 at `793b52b5` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.31044.16), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All seven paths pass with no skips. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. +On Windows 11 build 26300.9974 at `ff06794b` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All eight paths pass with no skips, and every totals line matches across the four runs. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. | Path | Pool | Backing | Slot 133 / sharing HRESULT | Bytes copied | Results | |---|---|---|---|---|---| @@ -9700,11 +9703,15 @@ On Windows 11 build 26300 at `793b52b5` plus this change, the results were ident | `stale` | XMem, private | copied | `S_OK` / not attempted | 131,072 + 4,096 per pool; the failed refresh copies 0 | the failed submission completes and reads A, stale reported with `0x8007000E`, then B and stale cleared; 2 refresh failures | | `copy` (q.comp, q.copy) | XMem, private | copied, refreshed on the COMPUTE or COPY queue | `S_OK` / not attempted | 131,072, then 64 | B in all words, then 16 E; no refresh failure | | `copy` (gate2q, gate2q.held, xq) | XMem, private | copied | `S_OK` / not attempted | 131,072 for A, then 4,096 for B | queue 2 completes with queue 1 still gated and reads B; queue 1 then reads B; `.held`: queue 2 waits for the held refresh; xq: both complete and read B | +| `copy` (budget, gpuw) | XMem, private | copied | `S_OK` / not attempted | 131,072; gpuw then 0 (not refreshed) | budget: buffer objects live 0 -> 1 -> 0 after release, retained +1; gpuw: G after the title's writes around it, `gpu_written` 1 | +| `share` (budget) | private | shared | `S_OK` / `S_OK` | 0 | placed objects live 0 -> 1 -> 0, retained +1, heap live 1 | +| `lease` | XMem | kept default, deferred to the lease path | `S_OK` / not attempted / refusal `0x800700AA` | 0 | reads zero, as before; deferral in info, totals and the log | +| `lease` | private | copied | `S_OK` / not attempted | 131,072 | B | | `contention` | XMem, private | copied, one staging buffer | `S_OK` / not attempted | 540,672 for the run | the probes took 0 ms each while S2 waited about 310 ms for the held copy; S1 C, S2 C; staging created 1, no refresh failure | The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. -Seven negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: +Eight negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: - `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. - `reuse-early` hands out staging buffers without their fence. With the internal queue held, all three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). - `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). @@ -9712,8 +9719,9 @@ Seven negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes - `refusal-silent` keeps the default backing without reporting it. b finds no refusal in the info and no log line (2 of 2), and the kept totals stay at 0. - `hold-lock` keeps the backing's lock held while a refresh waits for a staging fence. contention's info probe then blocks for about 4.7 s, until the wait gives up after 5 s. S2 goes stale and reads B (2 of 2). - `skip-consumer-wait` stops submissions from waiting for the internal fence. In gate2q.held, queue 2 completes before the held refresh lands and reads A (2 of 2). Case c reads zeros as well. +- `refresh-gpu-written` keeps refreshing a copied buffer that a list copy wrote. In gpuw, the refresh of the title's two changed words spans the written region and copies A over G (2 of 2). -Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. +Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. A copied buffer that a list copy wrote keeps the GPU's bytes and stops following the title memory, as the default backing does. Sharing XMem views through the section lease (#2280) instead of copying them is a follow-up. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. #### Xbox frame events and token wait semantics (#874) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 89347583d5..9890bb6025 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2929,12 +2929,15 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - **Writes during an earlier read.** The internal queue may write a backing while an earlier submission that reads it is still waiting on its queue. Buffers allow simultaneous access from several queues, so this is valid D3D12. It also matches unified memory on the console: a read that executes later sees the CPU's latest writes. A title write to bytes that an executing submission is reading at that moment is an unsynchronized concurrent write, outside the contract, here as on the console. - **Staging reuse.** A staging buffer is reused only after the internal fence value of the copy that read it has completed. - **No internal queue.** If the internal queue or its fence cannot be created, copied placements keep the default backing with that HRESULT recorded. - - In render mode the refresh runs before the wrapper takes its draw and allocator locks. + - In render mode the refresh and the consumer `Wait` run before the wrapper takes its draw and allocator locks, so they precede every list of the submission, including the producer fences `red_producers` adds and each split submission of mesh XMem recordings. + - Budgets (`X2W_D3D12_BUDGET=1`) count the linear backings as the default backing counts its own. A shared buffer counts as placed memory on its heap, whose backing-heap ticket is in use while a buffer on it is held. A copied buffer counts as a committed buffer. Staging buffers count as upload memory and live for the process. + - A copied buffer that a recorded copy writes (list `CopyBufferRegion` or `CopyResource`, `list_copy.inl`) keeps the GPU's bytes from that recording on and is no longer refreshed, as the default backing behaves for it. The title memory never receives those bytes, and a refresh spanning them would copy older title bytes over them. Info and totals report it (`gpu_written`). - The lock that guards the backing is held only to choose and publish. Waiting for a staging fence (a full pool), creating staging or a refresh list, recording it and `ExecuteCommandLists` all happen without it. A `Release`, the fixture exports and another queue's submission therefore never wait behind them. - Kept default: where neither path keeps its guarantees, slot 133 keeps the default backing above and returns what it returns without the switch. On the console `CreatePlacedResourceX` does not fail, and a title that received a failure faulted on the null object. The refusal HRESULT is recorded instead: - a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared records the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory; - without the internal refresh queue: `E_NOT_VALID_STATE` (`0x8007139f`) under `X2W_TEST_SUBMIT_FENCE_FAIL=1`, else the HRESULT of creating the queue or its fence; - - when the copy's default buffer cannot be created, that HRESULT. + - when the copy's default buffer cannot be created, that HRESULT; + - when the mesh XMem lease path is on (`X2W_MESH86_XMEM_SRV` or `X2W_MESH_INDIRECT_XMEM`) and the placement is one it takes: XMem pages (`MEM_MAPPED`) with console flags 0. `HRESULT_FROM_WIN32(ERROR_BUSY)` (`0x800700aa`) means the placement was deferred to the lease path, which mirrors and publishes that default copied placement. The two never back one placement. - A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). From e880a3cbe2d228a5e67176a4f66c5fbd14e20055 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 21:50:26 +0100 Subject: [PATCH 10/18] gpu: mark a copied linear buffer GPU-written when its copy is submitted A list copy into a copied linear buffer changed the backing when the copy was recorded. A recording that was closed and then reset without being submitted therefore stopped the buffer's refreshes for good: the next read saw the old upload instead of the CPU's later bytes, on XMem and private memory alike (review repro on WARP and an RTX 4060). The write is now pending on the recording, next to the texture writes that list_copy.inl already tracks: commit_list_gpu_writes marks the buffer GPU-written after the recording's ExecuteCommandLists, and a Reset or a failed Close (discard_list_gpu_writes) drops it. The recording's own submission still refreshes the buffer first, and its queue waits for that refresh before the copy runs. The gpuw-at-record mutant restores the recording-time mark. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/linear_buffer_backing.h | 16 ++++++---- src/startup_stubs/list_copy.inl | 37 ++++++++++++++++++----- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 6190afed53..6720ecba58 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -81,10 +81,12 @@ // totals (refresh_failures, last_refresh_hr). // // A copied buffer that a recorded copy writes (list CopyBufferRegion or CopyResource, list_copy.inl) -// keeps the GPU's bytes from that recording on: it is no longer refreshed. The title memory never -// receives those bytes, and a later refresh that spans them would copy the title's older bytes over -// them. This is what the default backing does for such a buffer; info and totals report it -// (gpu_written). +// keeps the GPU's bytes once that recording is submitted: it is no longer refreshed. The title memory +// never receives those bytes, and a later refresh that spans them would copy the title's older bytes +// over them. This is what the default backing does for such a buffer; info and totals report it +// (gpu_written). Until the submission the write is pending on the recording, with the texture writes +// of list_copy.inl: a Reset or a failed Close drops it, and the buffer stays refreshed. The recording's +// own submission still refreshes it first (its queue waits for that refresh, then the copy runs). // // Fixtures only: // X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1 the feature query reports no support (an adapter such as @@ -98,6 +100,7 @@ // hold-lock the wait for a full staging pool keeps mutex_ held (other callers block) // skip-consumer-wait submissions do not Wait for the internal fence (consumers race refreshes) // refresh-gpu-written a copied buffer that a recorded copy wrote is still refreshed +// gpuw-at-record the buffer stops being refreshed when the copy is recorded, not when it is submitted // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -338,8 +341,9 @@ class LinearBuffers { } } - // A recorded copy writes the backing of `resource` (list_copy.inl): if it is a copied buffer, it keeps - // the GPU's bytes from now on and is no longer refreshed from the title memory. + // A submitted recording writes the backing of `resource` (list_copy.inl, after its ExecuteCommandLists): + // if it is a copied buffer, it keeps the GPU's bytes from now on and is no longer refreshed from the + // title memory. void note_gpu_write(ID3D12Resource* resource) { if (linear_detail::mutant("refresh-gpu-written")) return; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index d55b96cd40..6538a5cd02 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -110,6 +110,14 @@ std::unordered_map>& pending_gpu_writes() static std::unordered_map> m; return m; } +// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers a recording wrote (list slots 15 and 17), under the same +// rule. A copied buffer stops being refreshed from its title memory only once a recording that writes it is +// submitted; a recording that is discarded leaves it refreshed (linear_buffer_backing.h). +std::unordered_map>& pending_linear_writes() +{ + static std::unordered_map> m; + return m; +} bool list_wrote(Wrapper* list, ID3D12Resource* resource) { @@ -125,11 +133,13 @@ void discard_list_gpu_writes(Wrapper* self) { AcquireSRWLockExclusive(&pending_writes_lock); pending_gpu_writes().erase(self); + pending_linear_writes().erase(self); ReleaseSRWLockExclusive(&pending_writes_lock); } void commit_list_gpu_writes(Wrapper* self) { + std::vector linear; AcquireSRWLockShared(&pending_writes_lock); if (const auto it = pending_gpu_writes().find(self); it != pending_gpu_writes().end()) { for (ID3D12Resource* resource : it->second) { @@ -138,7 +148,10 @@ void commit_list_gpu_writes(Wrapper* self) state.done = true; } } + if (const auto it = pending_linear_writes().find(self); it != pending_linear_writes().end()) linear = it->second; ReleaseSRWLockShared(&pending_writes_lock); + // After the recording's ExecuteCommandLists, outside the lock (the backing takes its own). + for (ID3D12Resource* resource : linear) linear_buffers().note_gpu_write(resource); } // A copy or resolve destination will hold what the GPU wrote once `self` is submitted. A title-backed texture @@ -152,13 +165,23 @@ void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) ReleaseSRWLockExclusive(&pending_writes_lock); } -// X2W_D3D12_LINEAR_BUFFERS: a copied linear buffer that a recorded copy writes keeps the GPU's bytes -// from now on and is no longer refreshed from its title memory (linear_buffer_backing.h). -void note_linear_gpu_write(const CopyEndpoint& destination) +// X2W_D3D12_LINEAR_BUFFERS: a copied linear buffer that a recorded copy writes keeps the GPU's bytes once +// `self` is submitted, and is no longer refreshed from its title memory from then on (linear_buffer_backing.h). +// Until then the write is pending on the recording: Reset or a failed Close drops it with the texture writes. +void note_linear_gpu_write(Wrapper* self, const CopyEndpoint& destination) { - if (destination.wrapper && destination.wrapper->own().title_memory && - x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + if (!destination.wrapper || !destination.wrapper->own().title_memory || + x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + return; + if (x2w_startup::linear_detail::mutant("gpuw-at-record")) { + // Mutant: the backing changes at recording, so a discarded recording still stops its refreshes. linear_buffers().note_gpu_write(destination.resource); + return; + } + AcquireSRWLockExclusive(&pending_writes_lock); + auto& writes = pending_linear_writes()[self]; + if (std::find(writes.begin(), writes.end(), destination.resource) == writes.end()) writes.push_back(destination.resource); + ReleaseSRWLockExclusive(&pending_writes_lock); } // Refusal shared by the three handlers once the descriptions passed, or none. @@ -227,7 +250,7 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti note_mesh_xmem_write(self, to.wrapper, destination_offset, bytes, 15, source_kind, srv_word || mesh_record ? from.resource : nullptr, source_offset); } - note_linear_gpu_write(to); + note_linear_gpu_write(self, to); if (indirect_copy_ranges()) { const auto* info = to.wrapper ? resource_info(to.wrapper) : nullptr; note_copy_gpu_range(self, to.resource, destination_offset, bytes, authoritative && info && @@ -257,7 +280,7 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width, 17, "buffer"); note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); - note_linear_gpu_write(to); + note_linear_gpu_write(self, to); } else mark_gpu_written(self, to); InterlockedIncrement(&list_resource_copies); } From 07c7a19e6ba381902b33f5f8e381ec96653e9613 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 21:54:25 +0100 Subject: [PATCH 11/18] gpu: order linear-buffer refreshes behind earlier submissions A refresh's copy into a copied linear buffer was ordered only before later consumers (their queues Wait for the internal fence). An earlier submission that still reads or writes the backing, on any queue, could run at the same time as the internal COPY queue overwrote it. Simultaneous access allows concurrent operations on one buffer only on disjoint ranges. Each queue wrapper now signals a user fence of its own after the title's lists (render and plain submissions). Before a refresh's copy executes, the internal queue Waits for every queue's latest user fence value that has not completed (totals: producer_waits). The wrappers cannot tell which buffers a submission reads, since titles bind them by GPU virtual address, so every earlier submission counts as a user of every copied backing. A queue whose latest submission sits behind a title Wait (queue slot 17) on a fence that has not been reached is not waited for (totals: producer_wait_skips, logged): a later submission that waits for this refresh may be the one that signals that fence, and waiting would deadlock both queues. That submission has not started and reads the CPU's newer bytes once it runs. A fence reached while the copy still executes can still overlap the read; the header says so. A submission now also waits for the refresh it enqueued itself, even if the title released the buffer meanwhile; before, such a refresh was left out of the consumer Wait. The contention case asserts the new order: S1, gated, reads B because C's copy waits for it; S2 reads C. The gate opens before the internal queue is drained. The skip-producer-wait mutant removes the wait. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/d3d12_xs_device.cpp | 10 ++ src/startup_stubs/linear_buffer_backing.h | 174 ++++++++++++++++++++-- src/startup_stubs/linear_buffer_report.h | 6 +- tests/linear_buffer_backing_check.cpp | 10 +- 4 files changed, 182 insertions(+), 18 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 4cd40a872d..53987032e4 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3526,6 +3526,11 @@ void linear_refresh(ID3D12CommandQueue* queue) { if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().before_submit(queue); } +// After the title's lists on queue: a later refresh's copy waits for this submission (the producer wait). +void linear_submitted(ID3D12CommandQueue* queue) +{ + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().after_submit(queue); +} // Queue slot 10, desktop ExecuteCommandLists(count, lists). void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) @@ -3588,6 +3593,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } else if (!ready.empty()) { submit(ready, submitted); } + if (!ready.empty()) linear_submitted(queue); ReleaseSRWLockExclusive(&allocator_lock); ReleaseSRWLockExclusive(&draw_lock); check_device("CommandQueue execute", 35); @@ -3603,6 +3609,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) auto* queue = static_cast(self->own().real); linear_refresh(queue); queue->ExecuteCommandLists(count, real.data()); + if (count) linear_submitted(queue); if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); } @@ -3719,6 +3726,9 @@ u64 __stdcall queue_wait(Wrapper* self, u64 rdx, u64 r8, u64 r9) if (!fence || fence->own().kind != fence_kind) return queue_dynamic<17>(self, rdx, r8, r9); InterlockedExchange(&self->own().queue_wait_seen, 1); const HRESULT hr = static_cast(self->own().real)->Wait(static_cast(fence->own().real), r8); + // X2W_D3D12_LINEAR_BUFFERS: a refresh does not wait for a submission behind this wait until it is reached. + if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().note_title_wait(static_cast(self->own().real), static_cast(fence->own().real), r8); static LONG calls; if (first_calls(calls, 2)) log("x2w-d3d12 CommandQueue::slot17(fence=%p, value=0x%llx) -> Wait 0x%08lx", static_cast(fence), r8, diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 6720ecba58..bf17d57c08 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -41,15 +41,28 @@ // queue type, first makes that queue Wait for the highest such value among the live copied buffers // (when it has not completed yet). A consumer on any queue therefore runs after every refresh that // was enqueued before it, wherever that refresh came from, so the bytes recorded as uploaded at -// enqueue are the bytes the consumer reads. No title queue ever waits on another title queue: a -// refresh never sits behind the title's own waits, so title-owned cross-queue fences (queue 1 waits -// on a fence queue 2 signals after its lists) cannot form a cycle with it. +// enqueue are the bytes the consumer reads. A submission whose recording writes a copied buffer +// (gpu_written, below) is ordered behind that buffer's earlier refreshes by the same Wait. // -// The internal queue may write a backing while an earlier submission that reads it is still waiting -// on its queue. Buffers allow simultaneous access from several queues, so this is valid D3D12, and -// it matches unified memory on the console: a read that executes later sees the CPU's latest writes. -// A title write to bytes that an executing submission is reading at that moment is an -// unsynchronized concurrent write, outside the contract, here as on the console. +// The refresh is ordered behind earlier GPU access too (the producer wait). Simultaneous access +// allows concurrent operations on one buffer from several queues only on disjoint ranges, so a copy +// into a backing must not overlap an earlier submission that still reads or writes it. After the +// title's lists, each queue wrapper signals a fence of its own (one per desktop queue); before a +// refresh's copy executes, the internal queue Waits for every such queue's latest value that has not +// completed (producer_waits in the totals). The wrappers cannot tell which buffers a submission +// reads (the title binds them by GPU virtual address in root arguments, views and descriptors), so +// every earlier submission counts as a user of every copied backing: the conservative choice. +// +// One exception keeps title fences from closing a cycle through the internal queue. A queue whose +// latest submission sits behind a title Wait (queue slot 17) on a fence that has not reached its +// value is not waited for (producer_wait_skips, logged): that fence may be signalled only by a later +// submission, which itself waits for this refresh (queue 1 waits on a fence that queue 2 signals after +// its lists, case xq.write), and waiting would deadlock both queues. The skipped submission has not +// started; it executes after the title's fence and reads the CPU's newer bytes, as unified memory +// does on the console. Not closed: if that fence is reached while the copy still executes (a CPU +// Signal, or a Signal that another queue enqueued right behind a submission the refresh waits for), +// the read may overlap the copy. A title Wait issued on the desktop queue past the wrapper is not +// seen, and that queue is waited for. // // A staging buffer is reused only after the internal fence value of the copy that read it has // completed (title fences do not matter: only that copy reads it). If the internal queue or its fence @@ -101,6 +114,7 @@ // skip-consumer-wait submissions do not Wait for the internal fence (consumers race refreshes) // refresh-gpu-written a copied buffer that a recorded copy wrote is still refreshed // gpuw-at-record the buffer stops being refreshed when the copy is recorded, not when it is submitted +// skip-producer-wait a refresh does not Wait for earlier submissions (it may overwrite a backing in use) // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -432,10 +446,11 @@ class LinearBuffers { } } } - if (!work.empty()) refresh(work); + // This submission's own refreshes, including those of a buffer the title released meanwhile. + const UINT64 own = work.empty() ? 0 : refresh(work); // Order this submission behind every refresh of a live copied buffer that may not have landed. - UINT64 wait_for = 0; + UINT64 wait_for = own; { std::lock_guard lock(mutex_); for (auto& [resource, record] : records_) @@ -453,6 +468,53 @@ class LinearBuffers { } } + // After the title's lists were executed on `queue` (a queue wrapper): signals that queue's user fence, + // so a later refresh can be ordered behind this submission (the producer wait). Nothing before the + // first copied placement: earlier submissions cannot name a copied backing that did not exist yet. + void after_submit(ID3D12CommandQueue* queue) + { + std::lock_guard lock(mutex_); + if (!internal_queue_) return; + UserQueue* user = user_queue(queue); + if (!user) return; + if (!user->fence && !user->untracked) { + ID3D12Device* device = nullptr; + HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); + if (SUCCEEDED(hr)) { + hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&user->fence)); + device->Release(); + } + if (FAILED(hr)) { + user->fence = nullptr; + x2w_local::logf("x2w-d3d12 linear buffers: queue %p has no user fence (0x%08lx); refreshes cannot wait for " + "its submissions", static_cast(queue), static_cast(hr)); + } + } + if (!user->fence || FAILED(queue->Signal(user->fence, user->value + 1))) { + user->untracked = true; // this submission cannot be waited for: refreshes report the queue as skipped + return; + } + user->untracked = false; + ++user->value; + } + + // The title enqueued Wait(fence, value) on `queue` (queue slot 17, already forwarded). Recorded until the + // fence reaches the value: a submission behind it may depend on later work (see the producer wait). + void note_title_wait(ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64 value) + { + if (!fence || fence->GetCompletedValue() >= value) return; + std::lock_guard lock(mutex_); + UserQueue* user = user_queue(queue); + if (!user) return; + prune_waits(*user); + try { + user->waits.push_back({fence, value, user->value + 1}); + fence->AddRef(); + } catch (const std::bad_alloc&) { + user->untracked = true; // not remembered: the queue is not waited for until it submits again + } + } + // The internal queue, AddRef'd, for fixtures that hold refreshes in flight; null before the first // copied placement. ID3D12CommandQueue* internal_queue() @@ -516,6 +578,21 @@ class LinearBuffers { ID3D12GraphicsCommandList* list = nullptr; UINT64 value = 0; }; + // A title Wait (queue slot 17) that had not completed when it was enqueued; `before` is the first user + // value it precedes. + struct TitleWait { + ID3D12Fence* fence; + UINT64 value, before; + }; + // A queue wrapper's desktop queue, its user fence (signalled after each submission of the title's + // lists) and the title waits it may still sit behind. Kept for the process, as the queues are. + struct UserQueue { + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; // the latest submission's user fence value (0: none yet) + bool untracked = false; // the latest submission has no fence value: it cannot be waited for + std::vector waits; + }; struct Heap { void* base; ID3D12Heap* heap; @@ -536,6 +613,64 @@ class LinearBuffers { return limit; } + // Under mutex_. The record of `queue`, created on first use; null if it cannot be stored. + UserQueue* user_queue(ID3D12CommandQueue* queue) + { + for (UserQueue& user : users_) + if (user.queue == queue) return &user; + try { + users_.emplace_back(); + } catch (const std::bad_alloc&) { + return nullptr; + } + users_.back().queue = queue; + return &users_.back(); + } + // Under mutex_: forgets the title waits whose fences reached their values. + static void prune_waits(UserQueue& user) + { + auto& waits = user.waits; + for (std::size_t i = 0; i < waits.size();) { + if (waits[i].fence->GetCompletedValue() >= waits[i].value) { + waits[i].fence->Release(); + waits[i] = waits.back(); + waits.pop_back(); + } else { + ++i; + } + } + } + // Under mutex_: the (user fence, value) of each queue's latest submission that has not completed, which + // a refresh's copy waits for. A queue behind an unreached title wait, or one whose latest submission + // has no fence value, is skipped and counted (see the producer wait above). + std::vector> earlier_users() + { + std::vector> out; + for (UserQueue& user : users_) { + prune_waits(user); + const bool pending = user.fence && user.value && user.fence->GetCompletedValue() < user.value; + if (!pending && !user.untracked) continue; + bool blocked = user.untracked; + for (const TitleWait& wait : user.waits) blocked |= wait.before <= user.value; + if (blocked) { + ++totals_.producer_wait_skips; + if (x2w_local::first_calls(producer_skip_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffers: a refresh does not wait for queue %p (%s): its copy may run before " + "that queue's earlier submission", static_cast(user.queue), + user.untracked ? "no user fence value" : "behind a title Wait that has not completed"); + continue; + } + if (linear_detail::mutant("skip-producer-wait")) continue; + try { + out.emplace_back(user.fence, user.value); + } catch (const std::bad_alloc&) { + continue; + } + ++totals_.producer_waits; + } + return out; + } + HRESULT feature(ID3D12Device* device) { if (feature_device_ != device) { @@ -618,8 +753,9 @@ class LinearBuffers { } // Staging, the refresh list and the internal queue, without mutex_; then publish under it. + // Returns the internal fence value of the refresh it enqueued (0: none). template - void refresh(std::vector& work) + UINT64 refresh(std::vector& work) { std::vector taken; bool any_staged = false; @@ -645,6 +781,18 @@ class LinearBuffers { } if (SUCCEEDED(list_hr)) { std::lock_guard submit(internal_mutex_); + // The producer wait: the copy runs after every earlier submission that may use a backing. + std::vector> users; + { + std::lock_guard lock(mutex_); + users = earlier_users(); + } + for (const auto& [fence, user_value] : users) { + const HRESULT hr = internal_queue_->Wait(fence, user_value); + if (FAILED(hr) && x2w_local::first_calls(wait_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffers: the refresh queue could not wait for submission 0x%llx (0x%08lx)", + static_cast(user_value), static_cast(hr)); + } ID3D12CommandList* lists[] = {list->list}; internal_queue_->ExecuteCommandLists(1, lists); executed = true; @@ -690,6 +838,7 @@ class LinearBuffers { ++totals_.refreshes; totals_.bytes_copied += w.bytes; } + return value; } static bool complete(const Staging& staging) @@ -860,12 +1009,13 @@ class LinearBuffers { std::vector> internal_lists_; std::vector> staging_; std::vector heaps_; + std::vector users_; // under mutex_ ID3D12Device* feature_device_ = nullptr; HRESULT feature_hr_ = S_FALSE; UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; - volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0; + volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0, producer_skip_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index bb15bcea51..c3618d8317 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -21,7 +21,7 @@ struct X2wLinearBufferInfo { std::uint64_t last_fence; // copied: internal fence value of the last refresh (0: none) std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none - std::uint32_t gpu_written; // copied: 1 once a recorded copy wrote it; it is no longer refreshed + std::uint32_t gpu_written; // copied: 1 once a submitted copy wrote it; it is no longer refreshed }; struct X2wLinearBufferTotals { @@ -30,6 +30,8 @@ struct X2wLinearBufferTotals { std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; std::uint64_t refresh_failures; std::uint64_t consumer_waits; // submissions made to Wait for a refresh on the internal queue - std::uint64_t gpu_written; // copied buffers that a recorded copy wrote (held from then on) + std::uint64_t gpu_written; // copied buffers that a submitted copy wrote (held from then on) + std::uint64_t producer_waits; // refresh copies made to Wait for a queue's earlier, uncompleted submission + std::uint64_t producer_wait_skips; // queues a refresh did not wait for (behind an unreached title Wait) std::int32_t last_refusal_hr, last_refresh_hr; }; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index d8944030f2..368afcd337 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -73,7 +73,8 @@ // contention (contention only) a second queue, a release() and the info export while a submission // waits for the only staging buffer, whose copy the fixture holds on the internal refresh // queue: all three must finish while the wait is still under way. After the refreshes land the -// waiting refresh has taken that buffer again (none is created), and both gated reads see C. +// waiting refresh has taken that buffer again (none is created). The gated S1 reads B: C's copy +// waits for it (the producer wait). S2 reads C. // budget (share, copy) with X2W_D3D12_BUDGET=1: a shared buffer counts as placed memory (its heap // live), a copied one as a committed buffer; live while held, retained after the title's release. // gpuw (copy only) a recorded copy (list slot 15) writes G into a copied buffer, then the title changes @@ -1251,18 +1252,19 @@ struct Run { const auto submit_time = clock::now() - t; const bool waiting_after = !done; const Tally w_read = tally(gpu.read_output(3).data(), r0 / 4, key); - // Let the refreshes land (B, then C), then the gated reads run: both see C, the CPU's last write. + // Let B land and the gated reads run. C's copy waits for S1, the earlier submission (the producer + // wait): S1 reads B, S2 then reads C, the CPU's last write. gpu.open_internal(); waiter.join(); - const bool drained = gpu.drain_internal(); gpu.open_gate(); + const bool drained = gpu.drain_internal(); if (!drained || !gpu.wait(s2_value)) return row(pool, "contention", false, "fence timeout after the gates"); const Tally r1 = tally(gpu.read_output(1).data(), r0 / 4, key), r2 = tally(gpu.read_output(2).data(), r0 / 4, key); X2wLinearBufferInfo xi{}; x2w_d3d12_linear_buffer_info(x_wrapper, &xi); const X2wLinearBufferTotals after = totals(); const bool reused = after.staging_created == before.staging_created && after.staging_reused >= before.staging_reused + 2; - const bool pass = waiting_before && waiting_after && probe_done && w_read.count[D] == words && r1.count[C] == words && + const bool pass = waiting_before && waiting_after && probe_done && w_read.count[D] == words && r1.count[B] == words && r2.count[C] == words && !xi.stale && xi.refresh_failures == 0 && reused && ms(t1_time) >= ms(info_time + release_time + submit_time); char text[400]; From 8c52d38d5179997795fc17879d2736bb1c079a3a Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 21:55:10 +0100 Subject: [PATCH 12/18] gpu: publish linear-buffer uploads in the order their copies execute Two submissions on different threads could snapshot one copied buffer against the same upload record, stage the title's bytes at different times, execute their copies in one order and publish the upload record in the other. With X staged first, the CPU then writing Y and Y staged second, Y's copy could take the lower internal fence value and X's the higher, so the backing held X while the record said Y. No later submission refreshed the buffer until the title changed those bytes again. The comment that called this a redundant copy at worst was wrong. A copied buffer now remembers the internal fence value of its newest applied publish. A newer refresh applies its span; an older one that arrives after it drops the record (totals: reordered_publishes), and the next submission copies the whole buffer. An unknown record is set again only by a copy of the whole buffer. The publish-out-of-order mutant applies every publish in lock order, as before. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/linear_buffer_backing.h | 33 ++++++++++++++++------- src/startup_stubs/linear_buffer_report.h | 1 + 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index bf17d57c08..40e22634fa 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -115,6 +115,7 @@ // refresh-gpu-written a copied buffer that a recorded copy wrote is still refreshed // gpuw-at-record the buffer stops being refreshed when the copy is recorded, not when it is submitted // skip-producer-wait a refresh does not Wait for earlier submissions (it may overwrite a backing in use) +// publish-out-of-order an older refresh's span is applied to `uploaded` after a newer one's // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -558,6 +559,7 @@ class LinearBuffers { std::vector bound; // skip-refresh mutant: the bytes at placement UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, refresh_failures = 0; UINT64 refresh_value = 0; // internal fence value of the last enqueued refresh + UINT64 published_value = 0; // internal fence value of the newest refresh published into `uploaded` bool stale = false; bool gpu_written = false; // a recorded copy wrote it: not refreshed any more HRESULT last_refresh_hr = S_OK; @@ -801,12 +803,15 @@ class LinearBuffers { } } - // Publish under the lock. Two submissions that snapshot the same buffer concurrently can both - // copy the same changed span and publish `uploaded` in either order, so `uploaded` may briefly - // lag what the GPU already holds. The next submission then compares the title against an older - // upload and copies a span that is redundant or larger than needed, never one that misses a - // change, so the cost is an extra refresh, not stale data. Every consumer waits for the higher - // of the two fence values. + // Publish under the lock. Two submissions on different threads can snapshot one buffer against the + // same `uploaded`, stage the title's bytes at different times (X, then the CPU writes Y, then Y), + // execute in one order (internal_mutex_: Y gets the lower value, X the higher, so the backing ends + // with X) and publish in the other. Applying both publishes in lock order would leave `uploaded` + // saying Y while the backing holds X, and no later submission would refresh it. So a buffer + // remembers the internal value of its last applied publish: a newer one applies its span; an older + // one arriving after it drops `uploaded` (the backing holds the newer copy's bytes where the spans + // overlap and the older one's elsewhere), and the next submission copies the whole buffer. Every + // consumer waits for the higher of the two fence values. std::lock_guard lock(mutex_); // Executed without a fence value: what it read can never be proven free, so it stays in use. const UINT64 held = executed ? ~UINT64{0} : 0; @@ -822,15 +827,23 @@ class LinearBuffers { w.staging->value = value; Copied& copy = *w.copy; if (value > copy.refresh_value) copy.refresh_value = value; - if (copy.live) { - // The backing holds these bytes once `value` completes; every consumer waits for it. + if (copy.live && value < copy.published_value && !linear_detail::mutant("publish-out-of-order")) { + copy.uploaded.clear(); // an older copy after a newer one: unknown, the next submission copies it all + ++totals_.reordered_publishes; + } else if (copy.live) { + // The backing holds these bytes once `value` completes; every consumer waits for it. An unknown + // `uploaded` (empty) is set only by a copy of the whole buffer. + const bool whole = w.offset == 0 && w.bytes == copy.bytes; try { - if (copy.uploaded.size() != copy.bytes) copy.uploaded.assign(static_cast(copy.bytes), 0); - std::memcpy(copy.uploaded.data() + w.offset, w.staging->mapped, static_cast(w.bytes)); + if (copy.uploaded.size() != copy.bytes && (whole || linear_detail::mutant("publish-out-of-order"))) + copy.uploaded.assign(static_cast(copy.bytes), 0); + if (copy.uploaded.size() == copy.bytes) + std::memcpy(copy.uploaded.data() + w.offset, w.staging->mapped, static_cast(w.bytes)); } catch (const std::bad_alloc&) { copy.uploaded.clear(); // the next submission copies the whole buffer again } } + if (value > copy.published_value) copy.published_value = value; copy.stale = false; ++copy.refreshes; copy.bytes_copied += w.bytes; diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index c3618d8317..092fa2d9db 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -33,5 +33,6 @@ struct X2wLinearBufferTotals { std::uint64_t gpu_written; // copied buffers that a submitted copy wrote (held from then on) std::uint64_t producer_waits; // refresh copies made to Wait for a queue's earlier, uncompleted submission std::uint64_t producer_wait_skips; // queues a refresh did not wait for (behind an unreached title Wait) + std::uint64_t reordered_publishes; // an older refresh published after a newer one: `uploaded` dropped std::int32_t last_refusal_hr, last_refresh_hr; }; From b605d7c9e9988a0386679cff92e9c7f4bc63fa9a Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 21:56:12 +0100 Subject: [PATCH 13/18] gpu: probe and guard title memory right before staging a linear buffer before_submit snapshots every live copied buffer, not only those the submitted lists read, and probes its title memory under the lock. refresh() then copied that memory into staging without the lock. If the title released one of those buffers on another thread and freed or unmapped its pages in between, the copy faulted inside d3d12_xs.dll. The title memory is now probed again right before it is staged, and the copy runs under a fault guard (access violation or in-page error). A buffer whose memory is gone is skipped and counted (unreadable), as the snapshot already does; a read that faults anyway is counted (copy_faults) and fails that buffer's refresh. A buffer released after the snapshot whose pages are still mapped is staged for that submission, which may read it (the contention case does). The wrappers cannot tell which buffers a submission's lists read, so the snapshot still covers every live copied buffer. The copy-after-retire mutant skips the second probe; the guard then catches the faulting read. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/linear_buffer_backing.h | 54 ++++++++++++++++++++++- src/startup_stubs/linear_buffer_report.h | 1 + 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 40e22634fa..094bfbc922 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -86,6 +86,14 @@ // the lease path mirrors and publishes. HRESULT_FROM_WIN32(ERROR_BUSY): deferred to that owner, so // the two never back one placement. // +// Title memory is read twice per refresh: compared with the last upload under mutex_ (after a probe), +// then staged without it. Every live copied buffer is snapshotted, not only those the submitted lists +// read (the wrappers cannot tell), so the title may release one on another thread in between and free +// or unmap its pages. Its memory is probed again right before it is staged, and staged under a fault +// guard: a buffer that is gone is skipped and counted (unreadable), a read that faults anyway is +// counted (copy_faults) and fails that buffer's refresh. A buffer released after the snapshot whose +// pages are still there is staged for that submission, which may read it. +// // At submit nothing is refused: holding back a submission can leave a title waiting on its fences. // When a copied buffer's refresh cannot be staged (a staging buffer or refresh list cannot be // created, or the pool stays full of buffers in flight past a 5 s wait: DXGI_ERROR_WAS_STILL_DRAWING), @@ -116,6 +124,8 @@ // gpuw-at-record the buffer stops being refreshed when the copy is recorded, not when it is submitted // skip-producer-wait a refresh does not Wait for earlier submissions (it may overwrite a backing in use) // publish-out-of-order an older refresh's span is applied to `uploaded` after a newer one's +// copy-after-retire the title memory is not probed again right before it is staged (the fault guard +// then catches the read of a released buffer's freed pages) // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -192,6 +202,18 @@ inline bool submit_fence_forced_off() static const bool on = GetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", nullptr, 0) != 0; return on; } +// Copies title memory that may have been freed or unmapped since it was probed: false on an access +// violation or an in-page error instead of a fault in the DLL. +inline bool guarded_copy(void* to, const void* from, std::size_t bytes) noexcept +{ + __try { + std::memcpy(to, from, bytes); + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } + return true; +} inline D3D12_RESOURCE_DESC buffer(UINT64 width, D3D12_RESOURCE_FLAGS flags) { D3D12_RESOURCE_DESC desc{}; @@ -409,6 +431,8 @@ class LinearBuffers { UINT64 offset, bytes; Staging* staging = nullptr; HRESULT hr = S_OK; + bool unreadable = false; // the title memory was gone when it was to be staged + bool faulted = false; // reading it faulted (caught) }; std::vector work; { @@ -765,7 +789,22 @@ class LinearBuffers { w.hr = acquire_staging(w.bytes, taken, &w.staging); if (FAILED(w.hr)) continue; taken.push_back(w.staging); - std::memcpy(w.staging->mapped, w.source + w.offset, static_cast(w.bytes)); + // The snapshot probed the title memory under mutex_, but the title may have released this buffer + // since (any live buffer is snapshotted, not only those the lists read) and freed or unmapped its + // pages: probe again right before reading, and read under a fault guard. + const unsigned char* from = w.source + w.offset; + const auto bytes = static_cast(w.bytes); + if (!linear_detail::mutant("copy-after-retire") && + x2w_local::probe_readable(reinterpret_cast(from), bytes) < bytes) { + w.unreadable = true; + w.hr = HRESULT_FROM_WIN32(ERROR_NOACCESS); + continue; + } + if (!linear_detail::guarded_copy(w.staging->mapped, from, bytes)) { + w.faulted = true; + w.hr = HRESULT_FROM_WIN32(ERROR_NOACCESS); + continue; + } any_staged = true; } RefreshList* list = nullptr; @@ -817,6 +856,19 @@ class LinearBuffers { const UINT64 held = executed ? ~UINT64{0} : 0; if (list) list->value = value ? value : (FAILED(list_hr) ? held : value); for (Work& w : work) { + if (w.unreadable || w.faulted) { + w.staging->value = 0; // never read by a copy: free again + if (w.faulted) { + ++totals_.copy_faults; + refresh_failed(w.dest, *w.copy, w.hr); + } else { + ++totals_.unreadable; + if (x2w_local::first_calls(unreadable_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffer %p: title memory %p is no longer readable; its backing " + "keeps the last upload", static_cast(w.dest), static_cast(w.source)); + } + continue; + } const HRESULT hr = FAILED(w.hr) ? w.hr : list_hr; if (FAILED(hr)) { if (w.staging) w.staging->value = held; diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index 092fa2d9db..8f810b0d02 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -34,5 +34,6 @@ struct X2wLinearBufferTotals { std::uint64_t producer_waits; // refresh copies made to Wait for a queue's earlier, uncompleted submission std::uint64_t producer_wait_skips; // queues a refresh did not wait for (behind an unreached title Wait) std::uint64_t reordered_publishes; // an older refresh published after a newer one: `uploaded` dropped + std::uint64_t copy_faults; // staging reads of title memory that faulted (caught; that refresh failed) std::int32_t last_refusal_hr, last_refresh_hr; }; From 981b519caa9a9edc3f4c2fec02009604526879c2 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 22:01:18 +0100 Subject: [PATCH 14/18] tests: drive discarded copies, earlier reads and refresh races in linear_buffer_backing New cases on the copy path, on XMem and private memory: - gpuw.discard (the review repro): a list copy into a copied buffer is recorded, closed and reset without a submission; after the CPU writes B the next read must see B, with gpu_written 0. - war: a read of A on queue 1 behind a title gate; the CPU writes B and queue 2 submits a read. Queue 2 must not complete while the gate is closed, queue 1 must read A, queue 2 B, and producer_waits must grow. - xq.write: queue 1 waits through its wrapper (slot 17) on a title fence and submits a read; after the CPU writes B, queue 2's read must complete while queue 1 still waits (no deadlock), both read B, and the skip is counted. - order: two threads refresh one buffer, parked through a new fixture hook (x2w_d3d12_linear_buffer_test_pause) so that the older copy publishes last; the next submission must refresh and read D. - retire: a submission parks after its snapshot while the title releases X and frees its pages; X must be skipped as unreadable, with no copy fault and no failed refresh, and Y must read C. Four controls run on WARP with WILL_FAIL, each failing its own case: gpuw-at-record, skip-producer-wait, publish-out-of-order and copy-after-retire. The totals line prints the new counters. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 11 +- src/startup_stubs/d3d12_xs_device.cpp | 8 + src/startup_stubs/linear_buffer_backing.h | 43 ++++ tests/linear_buffer_backing_check.cpp | 292 +++++++++++++++++++++- 4 files changed, 346 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e160009627..f576ca3004 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2593,9 +2593,11 @@ endforeach() # (a waiting refresh must not block release(), the info export or another queue). Refreshes run on an # internal copy queue; the copy path also reads on COMPUTE and COPY queues, reads one buffer on two # queues after one CPU write (both must see it), and follows a title-owned cross-queue fence without -# deadlock. It also counts the backings in the D3D12 budget, keeps a buffer a list copy wrote, and defers -# XMem placements to the mesh XMem lease path when that is on. Each mutant removes one guarantee in the -# DLL and must fail its case. +# deadlock. It also counts the backings in the D3D12 budget, keeps a buffer a submitted list copy wrote +# (and refreshes one whose copy was discarded), orders a refresh behind an earlier read on another queue, +# publishes two threads' refreshes in execution order, skips a buffer released and freed mid-refresh, and +# defers XMem placements to the mesh XMem lease path when that is on. Each mutant removes one guarantee in +# the DLL and must fail its case. add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) target_include_directories(linear_buffer_backing_check PRIVATE tests) target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) @@ -2607,7 +2609,8 @@ foreach(adapter IN ITEMS warp hardware) endforeach() endforeach() foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature - copy:refusal_silent contention:hold_lock copy:skip_consumer_wait copy:refresh_gpu_written) + copy:refusal_silent contention:hold_lock copy:skip_consumer_wait copy:refresh_gpu_written copy:gpuw_at_record + copy:skip_producer_wait copy:publish_out_of_order copy:copy_after_retire) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 53987032e4..3316438b9f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1576,6 +1576,14 @@ extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBu *totals = X2wLinearBufferTotals{}; if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); } +// Fixtures: the next refresh that reaches `point` (0 before staging, 1 after the title bytes are staged, +// 2 after its copy was executed, before it is published) sets the `reached` event, then waits up to 20 s +// for `resume`. Null events disarm the point. False with the switch off or for an unknown point. +extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_test_pause(unsigned point, void* reached, void* resume) +{ + return x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off && + linear_buffers().arm_pause(point, static_cast(reached), static_cast(resume)); +} // Fixtures: the internal queue that runs every refresh (AddRef'd), so a fixture can hold refreshes in // flight behind a fence of its own. False before the first copied placement. extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_internal_queue(void** queue) diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 094bfbc922..3232f5e9e6 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -126,6 +126,9 @@ // publish-out-of-order an older refresh's span is applied to `uploaded` after a newer one's // copy-after-retire the title memory is not probed again right before it is staged (the fault guard // then catches the read of a released buffer's freed pages) +// x2w_d3d12_linear_buffer_test_pause parks the next refresh at one point (before staging, after +// staging, after its copy executed), so a fixture can order two +// threads' refreshes or release a buffer while one is parked // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -134,6 +137,7 @@ #include #include +#include #include #include #include @@ -540,6 +544,21 @@ class LinearBuffers { } } + // Fixtures only (x2w_d3d12_linear_buffer_test_pause): the next refresh that reaches `point` sets + // `reached`, then waits up to 20 s for `resume`, holding no lock. One shot per arming. The points: + // before its staging (after the snapshot), after the title bytes are staged (before its copy is + // executed), and after the copy is executed and signalled (before it is published). Null events + // disarm the point, so a fixture can close its events when no refresh came. + enum PausePoint : unsigned { pause_before_stage, pause_after_stage, pause_after_execute, pause_points }; + bool arm_pause(unsigned point, HANDLE reached, HANDLE resume) + { + if (point >= pause_points) return false; + std::lock_guard lock(pause_mutex_); + pauses_[point] = reached && resume ? Pause{reached, resume} : Pause{}; + if (pauses_[point].reached) pauses_armed_.store(true); + return true; + } + // The internal queue, AddRef'd, for fixtures that hold refreshes in flight; null before the first // copied placement. ID3D12CommandQueue* internal_queue() @@ -639,6 +658,21 @@ class LinearBuffers { return limit; } + // A fixture's pause (arm_pause); nothing unless one was armed. + void pause_at(unsigned point) + { + if (!pauses_armed_.load()) return; + Pause pause{}; + { + std::lock_guard lock(pause_mutex_); + pause = pauses_[point]; + pauses_[point] = {}; + } + if (!pause.reached) return; + SetEvent(pause.reached); + WaitForSingleObject(pause.resume, 20000); + } + // Under mutex_. The record of `queue`, created on first use; null if it cannot be stored. UserQueue* user_queue(ID3D12CommandQueue* queue) { @@ -783,6 +817,7 @@ class LinearBuffers { template UINT64 refresh(std::vector& work) { + pause_at(pause_before_stage); std::vector taken; bool any_staged = false; for (Work& w : work) { @@ -807,6 +842,7 @@ class LinearBuffers { } any_staged = true; } + if (any_staged) pause_at(pause_after_stage); RefreshList* list = nullptr; HRESULT list_hr = S_OK; bool executed = false; @@ -841,6 +877,7 @@ class LinearBuffers { if (SUCCEEDED(list_hr)) value = ++internal_value_; } } + if (executed) pause_at(pause_after_execute); // Publish under the lock. Two submissions on different threads can snapshot one buffer against the // same `uploaded`, stage the title's bytes at different times (X, then the CPU writes Y, then Y), @@ -1075,6 +1112,12 @@ class LinearBuffers { std::vector> staging_; std::vector heaps_; std::vector users_; // under mutex_ + struct Pause { + HANDLE reached = nullptr, resume = nullptr; + }; + std::mutex pause_mutex_; // fixtures' pauses (a leaf: nothing else is taken under it) + Pause pauses_[pause_points]; + std::atomic pauses_armed_{false}; ID3D12Device* feature_device_ = nullptr; HRESULT feature_hr_ = S_FALSE; UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 368afcd337..cb2cf4a599 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -79,6 +79,22 @@ // live), a copied one as a committed buffer; live while held, retained after the title's release. // gpuw (copy only) a recorded copy (list slot 15) writes G into a copied buffer, then the title changes // its first and last words: the buffer keeps G (it is no longer refreshed), reported as gpu_written. +// gpuw.discard (copy only) the same copy is recorded and closed, then the list is reset without a +// submission; the CPU writes B: the next read sees B and the buffer is not gpu_written. +// war (copy only) a read of A on queue 1 behind a title gate (on the desktop queue); the CPU writes B and +// queue 2 submits a read. Its refresh's copy waits for queue 1 (producer_waits): queue 2 cannot +// complete while the gate is closed, queue 1 reads A and queue 2 reads B. +// xq.write (copy only) queue 1 waits through its wrapper (slot 17) on a title fence, then submits a read; +// the CPU writes B and queue 2 submits a read. The refresh must not wait for queue 1 (counted as a +// producer wait skip): queue 2 completes while queue 1 still waits, then the CPU reaches the fence +// and queue 1 reads B too. +// order (copy only) two threads refresh one buffer, parked through x2w_d3d12_linear_buffer_test_pause: +// thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes +// first and parks before publishing; A executes (the backing ends with C) and publishes, B publishes +// last. The next submission must refresh D (reordered_publishes +1) and read it. +// retire (copy only) a submission that reads Y snapshots the changed X and Y and parks before staging; +// the title releases X and frees its pages. X is skipped as unreadable (no copy fault, no failed +// refresh); Y reads C. // lease (lease only) an XMem buffer keeps the default backing with HRESULT_FROM_WIN32(ERROR_BUSY) // reported (old behaviour: reads zero); a private one is copied and reads B. // pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on @@ -93,11 +109,16 @@ // ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported), // hold-lock (contention) case contention (the wait keeps the backing's lock held), // skip-consumer-wait (copy) case gate2q.held (no submission waits for the internal fence), -// refresh-gpu-written (copy) case gpuw (a refresh spanning the written words copies the title's A over G). +// refresh-gpu-written (copy) case gpuw (a refresh spanning the written words copies the title's A over G), +// gpuw-at-record (copy) case gpuw.discard (the buffer stops being refreshed when the copy is recorded), +// skip-producer-wait (copy) case war (the refresh's copy lands before queue 1's earlier read), +// publish-out-of-order (copy) case order (B's older publish is applied after A's: no further refresh), +// copy-after-retire (copy) case retire (no probe before staging: the fault guard catches the read). // // Refreshes run on an internal COPY queue that the DLL exports to fixtures // (x2w_d3d12_linear_buffer_internal_queue); cases c, contention and gate2q.held hold it behind a fence -// of their own to keep a refresh in flight. +// of their own to keep a refresh in flight. Cases order and retire park a refresh on its thread through +// x2w_d3d12_linear_buffer_test_pause. // The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). // X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. // Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter @@ -126,6 +147,7 @@ extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_internal_queue(void**); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_test_pause(unsigned, void*, void*); extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void*, SIZE_T, DWORD, ULONGLONG, DWORD); extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR, PULONG_PTR, PULONG_PTR); @@ -1098,6 +1120,257 @@ struct Run { "gpu_written " + std::to_string(p.info.gpu_written) + ", totals +" + std::to_string(after.gpu_written - before.gpu_written)); } + // gpuw.discard (the review repro): a recorded copy into a copied buffer that is closed and then reset + // without being submitted. The buffer must stay refreshed: the next read sees the CPU's B, and it is + // not reported GPU-written. + void case_gpuw_discard(Pool& pool) + { + const char* name = "gpuw.discard"; + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, name, false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(p.hr) || !p.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(p.hr)); + l0.read(p.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + const X2wLinearBufferTotals before = totals(); + // The title's copy of G into the buffer, recorded and closed on another list, then discarded. + invoke(l1.list.Get(), 15, arg(p.wrapper.Get()), r0, arg(gpu.source.Get()), 0, region_bytes); + const bool closed = l1.close(); + const bool reset = SUCCEEDED(static_cast(invoke(l1.list.Get(), 139, arg(l1.allocator.Get())))); + write(memory.buffer(), r0, B, words); + l2.read(p.backing.Get(), 1); + l2.close(); + if (!gpu.wait(l2.submit())) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output(1).data(), r0 / 4, key); + refresh_info(p); + const X2wLinearBufferTotals after = totals(); + const bool pass = closed && reset && p.linear && p.info.path == 2 && p.info.gpu_written == 0 && t.count[B] == words && + after.gpu_written == before.gpu_written && !p.info.stale; + row(pool, name, pass, + std::string("a copy of G recorded, closed ") + (closed ? "" : "(CLOSE FAILED) ") + "and reset " + + (reset ? "" : "(RESET FAILED) ") + "without a submission, then the CPU wrote B: the GPU read " + t.text() + + " (expected B: still refreshed); gpu_written " + std::to_string(p.info.gpu_written) + ", totals +" + + std::to_string(after.gpu_written - before.gpu_written)); + } + + // war: a read of A on queue 1 is held behind a title gate (on the desktop queue, past the wrapper); the + // CPU then writes B and queue 2 submits a read, whose refresh must not land before queue 1's read: queue + // 1 reads A, queue 2 reads B, and the refresh's copy waited for queue 1 (producer_waits). + void case_war(Pool& pool) + { + const char* name = "war"; + Lane q2; + Memory memory; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A)) return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + const X2wLinearBufferTotals before = totals(); + gpu.hold(); + const UINT64 v1 = l1.submit(); // queue 1, gated: nothing to refresh (the title still holds A) + write(memory.buffer(), r0, B, words); + const UINT64 v2 = l2.submit_on(q2); // its refresh (B) is ordered behind queue 1's read + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + const bool q2_held = q2.fence->GetCompletedValue() < v2; + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + gpu.open_gate(); + const bool q1_done = gpu.wait(v1), q2_done = wait_fence(q2.fence.Get(), v2); + if (!q1_done || !q2_done) return row(pool, name, false, "fence timeout after the gate"); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = q1_pending && q2_held && t1.count[A] == words && t2.count[B] == words && !x.info.stale && + x.info.refresh_failures == 0 && after.producer_waits > before.producer_waits; + row(pool, name, pass, + std::string("queue 1 ") + (q1_pending ? "gated" : "NOT GATED") + " with a read of A; after the CPU wrote B, queue 2 " + + (q2_held ? "waited for it" : "COMPLETED FIRST (the refresh did not wait)") + "; queue 1 read " + t1.text() + + " (expected A), queue 2 read " + t2.text() + " (expected B); producer waits +" + + std::to_string(after.producer_waits - before.producer_waits)); + } + + // xq.write: queue 1 waits through its wrapper (queue slot 17) on a title fence, then submits a read; the CPU + // writes B and queue 2 submits a read. The refresh must not wait for queue 1 (the fence is reached only + // later, here by the CPU once queue 2 is done; a title can equally signal it from queue 2): queue 2 completes + // while queue 1 still waits, both read B, and the skip is counted. + void case_xq_write(Pool& pool) + { + const char* name = "xq.write"; + Lane q2; + Memory memory; + ComPtr fence; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A) || + FAILED(static_cast(invoke(gpu.guest.Get(), 36, 0, D3D12_FENCE_FLAG_NONE, arg(&__uuidof(ID3D12Fence)), + arg(fence.GetAddressOf())))) || !fence) + return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + const X2wLinearBufferTotals before = totals(); + if (FAILED(static_cast(invoke(gpu.guest_queue.Get(), 17, arg(fence.Get()), 1)))) + return row(pool, name, false, "queue wait (slot 17) failed"); + const UINT64 v1 = l1.submit(); + write(memory.buffer(), r0, B, words); + const UINT64 v2 = l2.submit_on(q2); + const bool q2_done = wait_fence(q2.fence.Get(), v2); + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + invoke(fence.Get(), 10, 1); // the title's fence, from the CPU (fence slot 10) + const bool q1_done = gpu.wait(v1); + if (!q2_done && !wait_fence(q2.fence.Get(), v2)) return row(pool, name, false, "fence timeout (queue 2)"); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + const X2wLinearBufferTotals after = totals(); + const bool pass = q2_done && q1_pending && q1_done && t1.count[B] == words && t2.count[B] == words && + after.producer_wait_skips > before.producer_wait_skips; + row(pool, name, pass, + std::string("queue 1 behind a title Wait (slot 17); queue 2 ") + + (q2_done ? "completed" : "DID NOT COMPLETE (the refresh waited for queue 1: deadlock)") + " while queue 1 " + + (q1_pending ? "still waited" : "HAD RUN") + " and read " + t2.text() + "; queue 1 " + (q1_done ? "then read " : "DID NOT COMPLETE, read ") + + t1.text() + "; producer wait skips +" + std::to_string(after.producer_wait_skips - before.producer_wait_skips)); + } + + // order: two threads' refreshes of one buffer, driven through the pause hook. Thread A stages C and parks + // before its copy is executed; the CPU writes D; thread B stages D, executes its copy first (the lower + // internal value) and parks before publishing; A then executes (the higher value: the backing ends with C) + // and publishes; B publishes last. The next submission must refresh D, which the GPU then reads. + void case_order(Pool& pool) + { + const char* name = "order"; + Lane q2; + Memory memory; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A)) return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, la, lb, lc; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !la.begin(gpu) || !lb.begin(gpu) || !lc.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded + la.read(x.backing.Get(), 1); + la.close(); + lb.read(x.backing.Get(), 2); + lb.close(); + lc.read(x.backing.Get(), 3); + lc.close(); + HANDLE staged = CreateEventW(nullptr, TRUE, FALSE, nullptr), staged_go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE executed = CreateEventW(nullptr, TRUE, FALSE, nullptr), executed_go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + const auto close_events = [&] { + x2w_d3d12_linear_buffer_test_pause(1, nullptr, nullptr); // disarm what no refresh reached + x2w_d3d12_linear_buffer_test_pause(2, nullptr, nullptr); + for (HANDLE h : {staged, staged_go, executed, executed_go}) + if (h) CloseHandle(h); + }; + if (!staged || !staged_go || !executed || !executed_go || !x2w_d3d12_linear_buffer_test_pause(1, staged, staged_go)) { + close_events(); + return row(pool, name, false, "pause hook not available"); + } + const X2wLinearBufferTotals before = totals(); + write(memory.buffer(), r0, C, words); + UINT64 va = 0, vb = 0; + std::thread ta([&] { va = la.submit(); }); + const bool a_parked = WaitForSingleObject(staged, 5000) == WAIT_OBJECT_0; + write(memory.buffer(), r0, D, words); + const bool armed = x2w_d3d12_linear_buffer_test_pause(2, executed, executed_go); + std::thread tb([&] { vb = lb.submit_on(q2); }); + const bool b_parked = armed && WaitForSingleObject(executed, 5000) == WAIT_OBJECT_0; + SetEvent(staged_go); // A executes after B and publishes first + ta.join(); + SetEvent(executed_go); // then B publishes + tb.join(); + close_events(); + if (!gpu.wait(va) || !wait_fence(q2.fence.Get(), vb)) return row(pool, name, false, "fence timeout"); + const UINT64 vc = lc.submit(); + if (!gpu.wait(vc)) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output(3).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = a_parked && b_parked && t.count[D] == words && after.reordered_publishes == before.reordered_publishes + 1 && + !x.info.stale && x.info.refresh_failures == 0; + row(pool, name, pass, + std::string("thread A staged C ") + (a_parked ? "and parked" : "BUT DID NOT PARK") + ", thread B staged D and executed first " + + (b_parked ? "and parked" : "BUT DID NOT PARK") + "; A executed and published, then B: the next submission read " + t.text() + + " (expected D: the older publish dropped the upload record); reordered publishes +" + + std::to_string(after.reordered_publishes - before.reordered_publishes)); + } + + // retire: a submission that reads Y snapshots both changed buffers X and Y and parks before staging; the + // title releases X and frees its pages; the submission resumes. X must be skipped as unreadable (no + // fault, no failed refresh); Y is refreshed and read. + void case_retire(Pool& pool) + { + const char* name = "retire"; + Memory mx, my; + // A private X gets an allocation of its own: the pool's range is pinned by the heap that the default + // backing opened on it (case b), so its pages cannot be decommitted. + if (!pool.xmem) { + mx.cpu = static_cast(VirtualAlloc(nullptr, alloc_pages * page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (mx.cpu) { + write(mx.cpu, 0, neighbour, buffer_offset / 4); + write(mx.buffer(), 0, A, buffer_bytes / 4); + } + } + if ((pool.xmem ? !pool.allocate(mx, A) : !mx.cpu) || !pool.allocate(my, A)) return row(pool, name, false, "allocation failed"); + Placed x = place(gpu, mx.buffer(), false), y = place(gpu, my.buffer(), false); + TitleList l0, la; + if (FAILED(x.hr) || FAILED(y.hr) || !x.backing || !y.backing || !l0.begin(gpu) || !la.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr) + "/" + hex(y.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // both uploaded + la.read(y.backing.Get(), 1); + la.close(); + HANDLE parked = CreateEventW(nullptr, TRUE, FALSE, nullptr), go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!parked || !go || !x2w_d3d12_linear_buffer_test_pause(0, parked, go)) { + if (parked) CloseHandle(parked); + if (go) CloseHandle(go); + return row(pool, name, false, "pause hook not available"); + } + write(mx.buffer(), r0, B, words); + write(my.buffer(), r0, C, words); + const X2wLinearBufferTotals before = totals(); + UINT64 va = 0; + std::thread ta([&] { va = la.submit(); }); + const bool was_parked = WaitForSingleObject(parked, 5000) == WAIT_OBJECT_0; + auto* x_wrapper = x.wrapper.Get(); + x.wrapper.Reset(); // release(): retire X + const bool freed = pool.xmem ? pool.release(mx) : VirtualFree(mx.cpu, 0, MEM_RELEASE) != FALSE; + SetEvent(go); + ta.join(); + x2w_d3d12_linear_buffer_test_pause(0, nullptr, nullptr); // disarm, if no refresh reached it + CloseHandle(parked); + CloseHandle(go); + if (!gpu.wait(va)) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output(1).data(), r0 / 4, key); + X2wLinearBufferInfo xi{}; + x2w_d3d12_linear_buffer_info(x_wrapper, &xi); + refresh_info(y); + const X2wLinearBufferTotals after = totals(); + const bool pass = was_parked && freed && t.count[C] == words && after.unreadable == before.unreadable + 1 && + after.copy_faults == before.copy_faults && xi.refresh_failures == 0 && !y.info.stale; + row(pool, name, pass, + std::string("parked after the snapshot ") + (was_parked ? "" : "(DID NOT PARK) ") + "while the title released X and " + + (freed ? "freed" : "COULD NOT FREE") + " its pages: unreadable +" + std::to_string(after.unreadable - before.unreadable) + + " (expected 1), copy faults +" + std::to_string(after.copy_faults - before.copy_faults) + " (expected 0), X refresh failures " + + std::to_string(xi.refresh_failures) + "; Y read " + t.text()); + } + // lease: with the mesh XMem lease path on, an XMem placement with console flags 0 is the lease path's: // slot 133 keeps the default backing (not aliased) and records the deferral; a private one is copied. void case_lease(Pool& pool) @@ -1444,6 +1717,11 @@ int main(int argc, char** argv) run.case_xq(pool); run.case_budget(pool); run.case_gpuw(pool); + run.case_gpuw_discard(pool); + run.case_war(pool); + run.case_xq_write(pool); + run.case_order(pool); + run.case_retire(pool); // last: it frees the pages of one buffer } run.probe_view_pin(pool); if (path == Path::share) run.case_budget(pool); @@ -1451,7 +1729,8 @@ int main(int argc, char** argv) const X2wLinearBufferTotals t = totals(); std::printf("totals: placements %llu (shared %llu, copied %llu, kept default %llu), feature queries %llu, heap opens %llu " "(failed %llu, cache hits %llu), placements failed %llu, submissions %llu, refreshes %llu, bytes copied %llu, " - "staging created %llu reused %llu, unreadable %llu, refresh failures %llu, last refusal %s, last refresh failure %s\n", + "staging created %llu reused %llu, unreadable %llu, refresh failures %llu, consumer waits %llu, producer waits %llu " + "(skipped %llu), gpu written %llu, reordered publishes %llu, copy faults %llu, last refusal %s, last refresh failure %s\n", static_cast(t.placements), static_cast(t.shared), static_cast(t.copied), static_cast(t.kept_default), static_cast(t.feature_queries), static_cast(t.heap_opens), @@ -1460,6 +1739,9 @@ int main(int argc, char** argv) static_cast(t.refreshes), static_cast(t.bytes_copied), static_cast(t.staging_created), static_cast(t.staging_reused), static_cast(t.unreadable), static_cast(t.refresh_failures), + static_cast(t.consumer_waits), static_cast(t.producer_waits), + static_cast(t.producer_wait_skips), static_cast(t.gpu_written), + static_cast(t.reordered_publishes), static_cast(t.copy_faults), hex(t.last_refusal_hr).c_str(), hex(t.last_refresh_hr).c_str()); { Pool none(false); @@ -1497,7 +1779,9 @@ int main(int argc, char** argv) const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" - : mutant == "refresh-gpu-written" ? "gpuw" : nullptr; + : mutant == "refresh-gpu-written" ? "gpuw" : mutant == "gpuw-at-record" ? "gpuw.discard" + : mutant == "skip-producer-wait" ? "war" : mutant == "publish-out-of-order" ? "order" + : mutant == "copy-after-retire" ? "retire" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results) From 58971a4a505df7b5d3bc36311af3957a4cf3c635 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 22:17:52 +0100 Subject: [PATCH 15/18] docs: record the linear-buffer submit-time GPU write, producer wait and refresh races Describe the review fixes for slot 133's copied linear buffers. A list copy marks a buffer GPU-written only when its recording is submitted. A refresh's copy waits for every queue's earlier submission, except one that sits behind an unreached title Wait, which is skipped so that title fences cannot close a cycle. Uploads are published in the order their copies execute. Title memory is probed again and read under a fault guard right before it is staged. Add the gpuw.discard, war, xq.write, order and retire cases, the changed contention expectation (S1 reads B), the four new controls, and the results at 981b519c on WARP and an RX 9070 XT (driver 32.0.32029.2010) in the dev and release presets. Note the remaining overlap window and the cost of treating every submission as a user of every backing. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 19 ++++++++++++++++--- docs/startup-runtime.md | 11 +++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index ab20a76243..83059a911c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9686,8 +9686,13 @@ A title run motivated the fallback. An earlier revision returned the refusal fro | xq | `copy` only: queue 1 waits on a title fence that queue 2 signals after its list. Both read the buffer the CPU changed to B. Both must complete, with no deadlock, and read B. | | budget | `share` and `copy`: one placement must go live in its budget category, placed for a shared buffer (with its heap live) and buffer for a copied one. The title's release must move it to retained, with nothing unmeasured. | | gpuw | `copy` only: a list `CopyBufferRegion` (list slot 15) writes G into the buffer, and the title then changes its first and last words. The next read must still see G (no refresh spans the written words), and info and totals must report it as GPU-written. | +| gpuw.discard | `copy` only (review repro): the same copy is recorded and closed, then the list is reset without a submission, and the CPU writes B. The next read must see B, and the buffer must not be reported GPU-written. | +| war | `copy` only: a read of A on queue 1 behind a title gate (on the desktop queue), then the CPU writes B and queue 2 submits a read. Queue 2 must not complete while the gate is closed, queue 1 must read A, queue 2 must read B, and `producer_waits` must grow. | +| xq.write | `copy` only: queue 1 waits through its wrapper (queue slot 17) on a title fence and submits a read; the CPU writes B and queue 2 submits a read. Queue 2 must complete while queue 1 still waits (no deadlock), both must read B once the CPU reaches the fence, and `producer_wait_skips` must grow. | +| order | `copy` only: two threads refresh one buffer, parked through `x2w_d3d12_linear_buffer_test_pause`. Thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes its copy first and parks before publishing; A executes (the backing ends with C) and publishes, and B publishes last. The next submission must refresh D and read it, with `reordered_publishes` +1. | +| retire | `copy` only: a submission that reads Y snapshots the changed X and Y and parks before staging. The title releases X and frees its pages. X must be skipped as unreadable, with no copy fault and no failed refresh, and Y must read C. | | lease | `lease` only: an XMem buffer must keep the default backing (not aliased: it reads zero) with the deferral `0x800700aa` reported. A private buffer must still be copied and read B. | -| contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a title gate, and its refresh, held on the internal queue, holds the only staging buffer. S2's refresh of X, on another thread, must wait for that copy. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the refreshes land and the gate opens, S2 must have reused the same staging buffer (none created). S1 and S2 must both read C, the CPU's last write before they ran, with no refresh failure. | +| contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a title gate, and its refresh, held on the internal queue, holds the only staging buffer. S2's refresh of X, on another thread, must wait for that copy. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the refreshes land and the gate opens, S2 must have reused the same staging buffer (none created), with no refresh failure. S1 must read B, because C's copy waits for S1 (the producer wait), and S2 must read C. Before the producer wait both read C. | On Windows 11 build 26300.9974 at `ff06794b` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All eight paths pass with no skips, and every totals line matches across the four runs. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. @@ -9711,7 +9716,7 @@ On Windows 11 build 26300.9974 at `ff06794b` plus this change, the results were The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. -Eight negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools, and on both adapters each does: +Negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools. The first eight did so on both adapters at `ff06794b`: - `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. - `reuse-early` hands out staging buffers without their fence. With the internal queue held, all three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). - `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). @@ -9721,7 +9726,15 @@ Eight negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes - `skip-consumer-wait` stops submissions from waiting for the internal fence. In gate2q.held, queue 2 completes before the held refresh lands and reads A (2 of 2). Case c reads zeros as well. - `refresh-gpu-written` keeps refreshing a copied buffer that a list copy wrote. In gpuw, the refresh of the title's two changed words spans the written region and copies A over G (2 of 2). -Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. A copied buffer that a list copy wrote keeps the GPU's bytes and stops following the title memory, as the default backing does. Sharing XMem views through the section lease (#2280) instead of copying them is a follow-up. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. +The review of `bfdd583f` found four more problems. A list copy into a copied buffer changed its backing when recorded, so a discarded recording stopped its refreshes for good. A refresh's copy was not ordered behind earlier submissions that still read the backing. Two threads' refreshes could publish the upload record in the opposite order to their copies, leaving the buffer stale. And title memory was staged without the lock, so a buffer released and freed on another thread could fault the DLL. The rework adds gpuw.discard, war, xq.write, order and retire, changes contention as above, and adds four controls: +- `gpuw-at-record` marks the buffer GPU-written when the copy is recorded. gpuw.discard reads A, `gpu_written` 1 (2 of 2). +- `skip-producer-wait` stops the refresh's copy from waiting for earlier submissions. In war, queue 2 completes while the gate is closed and queue 1 reads B (2 of 2). +- `publish-out-of-order` applies every publish in lock order. order then reads C, `reordered_publishes` +0 (2 of 2). +- `copy-after-retire` skips the probe right before staging. In retire, the fault guard catches the read of X's freed pages: copy faults +1, one refresh failure `0x800703E6` (2 of 2). + +On Windows 11 build 26300.9974 at `981b519c`, in-box WARP (`1414:008c`, driver 10.0.26100.9818) and the AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), debug layer off: all 16 path entries pass, with no skips, in the dev and release presets. Every new row passes in both pools on both adapters: gpuw.discard B, `gpu_written` 0; war queue 1 A and queue 2 B, producer waits +1; xq.write queue 2 completes while queue 1 waits, both B, skips +1; order D, reordered publishes +1; retire unreadable +1, copy faults 0, Y C; contention S1 B and S2 C. All twelve controls fail their targeted rows (2 of 2, gate 1 of 1). The producer wait can idle the GPU between submissions, because every earlier submission counts as a user of every copied backing. A title fence reached while a refresh's copy executes, after the refresh skipped the queue behind it, can still overlap that queue's read. + +Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. A copied buffer that a submitted list copy wrote keeps the GPU's bytes and stops following the title memory, as the default backing does. Sharing XMem views through the section lease (#2280) instead of copying them is a follow-up. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. #### Xbox frame events and token wait semantics (#874) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9890bb6025..77811d6648 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2925,13 +2925,16 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - Copied: a committed default buffer that is refreshed from title memory at each submission through a command-queue wrapper, just before the title's lists run, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. - **Internal queue.** Every refresh runs on one internal COPY queue per device, which never waits on a title fence. It signals an internal fence value, and each buffer remembers the value of its last refresh. - **Consumer wait.** Every submission through a queue wrapper, of any type (direct, compute or copy), first makes its queue `Wait` for the highest such value among the live copied buffers that has not completed. A consumer on any queue therefore runs after every refresh enqueued before it, wherever that refresh came from. So when one CPU write is followed by submissions on two queues, both read the new bytes, even if the first is still held behind a title fence. - - **No title-to-title waits.** No title queue ever waits on another title queue. A title's own cross-queue fences, such as queue 1 waiting on a fence that queue 2 signals after its lists, cannot form a cycle with a refresh. - - **Writes during an earlier read.** The internal queue may write a backing while an earlier submission that reads it is still waiting on its queue. Buffers allow simultaneous access from several queues, so this is valid D3D12. It also matches unified memory on the console: a read that executes later sees the CPU's latest writes. A title write to bytes that an executing submission is reading at that moment is an unsynchronized concurrent write, outside the contract, here as on the console. + - **Producer wait.** A refresh's copy is also ordered behind earlier GPU access to the backing. Simultaneous access allows concurrent operations on one buffer only on disjoint ranges, so the copy must not overlap an earlier submission that still reads or writes it. Each queue wrapper signals a user fence of its own after the title's lists. Before a refresh's copy executes, the internal queue `Wait`s for every queue's latest user fence value that has not completed (`producer_waits`). The wrappers cannot tell which buffers a submission reads, because titles bind them by GPU virtual address, so every earlier submission counts as a user of every copied backing. This conservative choice can idle the GPU between a frame's submissions and the next refresh. + - **No cycle through title fences.** A queue whose latest submission sits behind a title `Wait` (queue slot 17) on a fence that has not been reached is not waited for (`producer_wait_skips`, logged). A later submission that waits for this refresh may be the one that signals that fence, such as queue 2 signalling a fence that queue 1 waits on, and waiting would deadlock both queues. That submission has not started; it runs after the title's fence and reads the CPU's newer bytes, as unified memory does on the console. Not closed: if that fence is reached while the copy still executes, the read can overlap the copy. A title `Wait` issued on the desktop queue past the wrapper is not seen, and that queue is waited for. + - **Own refresh.** A submission also waits for the refresh it enqueued itself, even if the title released that buffer meanwhile. - **Staging reuse.** A staging buffer is reused only after the internal fence value of the copy that read it has completed. - **No internal queue.** If the internal queue or its fence cannot be created, copied placements keep the default backing with that HRESULT recorded. - In render mode the refresh and the consumer `Wait` run before the wrapper takes its draw and allocator locks, so they precede every list of the submission, including the producer fences `red_producers` adds and each split submission of mesh XMem recordings. - Budgets (`X2W_D3D12_BUDGET=1`) count the linear backings as the default backing counts its own. A shared buffer counts as placed memory on its heap, whose backing-heap ticket is in use while a buffer on it is held. A copied buffer counts as a committed buffer. Staging buffers count as upload memory and live for the process. - - A copied buffer that a recorded copy writes (list `CopyBufferRegion` or `CopyResource`, `list_copy.inl`) keeps the GPU's bytes from that recording on and is no longer refreshed, as the default backing behaves for it. The title memory never receives those bytes, and a refresh spanning them would copy older title bytes over them. Info and totals report it (`gpu_written`). + - A copied buffer that a recorded copy writes (list `CopyBufferRegion` or `CopyResource`, `list_copy.inl`) keeps the GPU's bytes once that recording is submitted and is no longer refreshed, as the default backing behaves for it. The title memory never receives those bytes, and a refresh spanning them would copy older title bytes over them. Info and totals report it (`gpu_written`). Until the submission the write is pending on the recording, with the texture writes of `list_copy.inl`: a `Reset` or a failed `Close` drops it, and the buffer stays refreshed. The recording's own submission still refreshes the buffer first, and its queue waits for that refresh before the copy runs. + - **Publish order.** Two submissions on different threads can stage one buffer's bytes at different times and execute their copies in one order but publish the upload record in the other. A buffer remembers the internal fence value of its newest applied publish. An older publish that arrives after a newer one drops the record (`reordered_publishes`), and the next submission copies the whole buffer. + - **Title memory reads.** Every live copied buffer is snapshotted, not only those the submitted lists read. Its title memory is probed again right before it is staged, and staged under a fault guard. A buffer whose memory the title freed after the snapshot is skipped and counted (`unreadable`); a read that faults anyway is counted (`copy_faults`) and fails that buffer's refresh. A buffer released after the snapshot whose pages are still mapped is staged for that submission, which may read it. - The lock that guards the backing is held only to choose and publish. Waiting for a staging fence (a full pool), creating staging or a refresh list, recording it and `ExecuteCommandLists` all happen without it. A `Release`, the fixture exports and another queue's submission therefore never wait behind them. - Kept default: where neither path keeps its guarantees, slot 133 keeps the default backing above and returns what it returns without the switch. On the console `CreatePlacedResourceX` does not fail, and a title that received a failure faulted on the null object. The refusal HRESULT is recorded instead: - a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared records the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory; @@ -2940,7 +2943,7 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - when the mesh XMem lease path is on (`X2W_MESH86_XMEM_SRV` or `X2W_MESH_INDIRECT_XMEM`) and the placement is one it takes: XMem pages (`MEM_MAPPED`) with console flags 0. `HRESULT_FROM_WIN32(ERROR_BUSY)` (`0x800700aa`) means the placement was deferred to the lease path, which mirrors and publishes that default copied placement. The two never back one placement. - A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. -A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. From c6a0c8a9292c4fee67761911c63baca92b879bf7 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 22:51:40 +0100 Subject: [PATCH 16/18] gpu: refuse a linear-buffer submission whose refresh has no safe completion order A refresh no longer skips a queue whose latest submission sits behind an unreached title Wait (slot 17). Skipping did not prove that the fence stays blocked until the copy finishes: another producer can reach it meanwhile and the copy then overlaps that read. Instead, right before the refresh would be enqueued (under internal_mutex_), a refresh that would have to wait for such a submission, or for one without a user fence value, refuses the whole submission: no refresh, consumer Wait, title lists or user fence Signal is enqueued. Staging buffers and the refresh list are freed, no upload record or refresh state changes, and recorded GPU writes stay pending on their recordings. The title's own Signal/Wait paths are untouched, so a later Signal still releases the earlier queue. Counted as unsafe_refresh_refusals (replacing producer_wait_skips) and logged. A title wait that cannot be stored now blocks the queue until the next submission behind it completes, instead of being forgotten at that submission. xq.write now gates queue 1 on a title fence with a read of A, writes B and expects queue 2's read to be refused (slot keeps P), queue 1 to read A after the title's Signal through queue 2's wrapper, and the refused recording to read B when resubmitted. New control accept-unsafe-refresh restores the skip. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 3 +- src/startup_stubs/d3d12_xs_device.cpp | 20 ++- src/startup_stubs/linear_buffer_backing.h | 178 ++++++++++++++-------- src/startup_stubs/linear_buffer_report.h | 2 +- tests/linear_buffer_backing_check.cpp | 84 +++++++--- 5 files changed, 193 insertions(+), 94 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f576ca3004..69f587f005 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2595,6 +2595,7 @@ endforeach() # queues after one CPU write (both must see it), and follows a title-owned cross-queue fence without # deadlock. It also counts the backings in the D3D12 budget, keeps a buffer a submitted list copy wrote # (and refreshes one whose copy was discarded), orders a refresh behind an earlier read on another queue, +# refuses a submission whose refresh would have to wait for a queue behind an unreached title Wait, # publishes two threads' refreshes in execution order, skips a buffer released and freed mid-refresh, and # defers XMem placements to the mesh XMem lease path when that is on. Each mutant removes one guarantee in # the DLL and must fail its case. @@ -2610,7 +2611,7 @@ foreach(adapter IN ITEMS warp hardware) endforeach() foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature copy:refusal_silent contention:hold_lock copy:skip_consumer_wait copy:refresh_gpu_written copy:gpuw_at_record - copy:skip_producer_wait copy:publish_out_of_order copy:copy_after_retire) + copy:skip_producer_wait copy:publish_out_of_order copy:copy_after_retire copy:accept_unsafe_refresh) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 3316438b9f..d455b8d633 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3529,10 +3529,14 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); // X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the internal // refresh queue, and queue waits for those refreshes, just before the title's lists. A refresh that -// fails leaves that buffer stale (logged, counted); the lists run either way. -void linear_refresh(ID3D12CommandQueue* queue) +// fails leaves that buffer stale (logged, counted); the lists run either way. False: a refresh had no +// safe completion order and the submission is refused (logged, counted): nothing was enqueued, and the +// caller drops the title's lists without executing them or committing their bookkeeping. The title's +// fence Signal and Wait on its queues stay as they are, so a later Signal still releases a queue that +// waits on it. +bool linear_refresh(ID3D12CommandQueue* queue) { - if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().before_submit(queue); + return x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off || linear_buffers().before_submit(queue); } // After the title's lists on queue: a later refresh's copy waits for this submission (the producer wait). void linear_submitted(ID3D12CommandQueue* queue) @@ -3552,8 +3556,9 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) std::vector submitted; auto* queue = static_cast(self->own().real); // Before the wrapper's locks: a refresh may wait for a staging fence, and recording must not - // wait with it. - if (count) linear_refresh(queue); + // wait with it. A refused submission runs nothing: its recordings stay closed and submittable, + // with their pending GPU writes (committed only after an executed submission). + if (count && !linear_refresh(queue)) return; // Pin the closed recording and its allocator through submission bookkeeping. AcquireSRWLockExclusive(&draw_lock); AcquireSRWLockExclusive(&allocator_lock); @@ -3615,7 +3620,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) std::vector real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); auto* queue = static_cast(self->own().real); - linear_refresh(queue); + if (!linear_refresh(queue)) return; queue->ExecuteCommandLists(count, real.data()); if (count) linear_submitted(queue); if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); @@ -3734,7 +3739,8 @@ u64 __stdcall queue_wait(Wrapper* self, u64 rdx, u64 r8, u64 r9) if (!fence || fence->own().kind != fence_kind) return queue_dynamic<17>(self, rdx, r8, r9); InterlockedExchange(&self->own().queue_wait_seen, 1); const HRESULT hr = static_cast(self->own().real)->Wait(static_cast(fence->own().real), r8); - // X2W_D3D12_LINEAR_BUFFERS: a refresh does not wait for a submission behind this wait until it is reached. + // X2W_D3D12_LINEAR_BUFFERS: until this wait is reached, a submission whose refresh would have to wait for a + // submission behind it is refused. if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().note_title_wait(static_cast(self->own().real), static_cast(fence->own().real), r8); static LONG calls; diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 3232f5e9e6..04cee16f58 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -53,16 +53,26 @@ // reads (the title binds them by GPU virtual address in root arguments, views and descriptors), so // every earlier submission counts as a user of every copied backing: the conservative choice. // -// One exception keeps title fences from closing a cycle through the internal queue. A queue whose -// latest submission sits behind a title Wait (queue slot 17) on a fence that has not reached its -// value is not waited for (producer_wait_skips, logged): that fence may be signalled only by a later -// submission, which itself waits for this refresh (queue 1 waits on a fence that queue 2 signals after -// its lists, case xq.write), and waiting would deadlock both queues. The skipped submission has not -// started; it executes after the title's fence and reads the CPU's newer bytes, as unified memory -// does on the console. Not closed: if that fence is reached while the copy still executes (a CPU -// Signal, or a Signal that another queue enqueued right behind a submission the refresh waits for), -// the read may overlap the copy. A title Wait issued on the desktop queue past the wrapper is not -// seen, and that queue is waited for. +// A submission whose refresh has no safe completion order is refused (unsafe_refresh_refusals, +// logged). That is the case when the refresh would have to wait for an earlier submission, on any +// queue including its own, that sits behind a title Wait (queue slot 17) on a fence that has not +// reached its value, or for a submission without a user fence value (its Signal failed). Waiting could +// deadlock: the fence may be signalled only by work that itself waits for this refresh (queue 1 waits on +// a fence that queue 2 signals after its lists, case xq.write; every later consumer waits for the +// refresh). Not waiting would let the copy overlap that read: a blocked queue is not known to stay +// blocked until the copy finishes, since another producer (the CPU, or another queue) may reach the +// fence while it runs. The decision is made under internal_mutex_, right before the refresh would be +// enqueued: nothing of the submission reaches the GPU, neither the refresh, nor the consumer Wait, nor +// the title's lists, nor the queue's user fence Signal after them (no value stands for lists that did +// not run). Bookkeeping stays as it was: the staging buffers and refresh list are free again, no +// buffer's upload record, refresh value, staleness or failure count changes, and a recorded copy's GPU +// write stays pending on its recording (list_copy.inl commits it only after an executed submission). The +// next submission compares the title memory with the same upload record and copies what still differs. +// The title's own Signal and Wait on its queues (slot 16 and any shape-dispatched Signal, slot 17) do not +// go through this file, so a later Signal still releases the earlier queue. A title Wait issued on the +// desktop queue past the wrapper is not seen, and that queue is waited for. A submission that has no +// changed bytes to refresh is never refused; it waits only for refreshes already enqueued, none of which +// waits for a blocked queue. // // A staging buffer is reused only after the internal fence value of the copy that read it has // completed (title fences do not matter: only that copy reads it). If the internal queue or its fence @@ -94,12 +104,12 @@ // counted (copy_faults) and fails that buffer's refresh. A buffer released after the snapshot whose // pages are still there is staged for that submission, which may read it. // -// At submit nothing is refused: holding back a submission can leave a title waiting on its fences. -// When a copied buffer's refresh cannot be staged (a staging buffer or refresh list cannot be -// created, or the pool stays full of buffers in flight past a 5 s wait: DXGI_ERROR_WAS_STILL_DRAWING), -// the title's lists run with the backing's last upload. The buffer is marked stale until a later -// refresh succeeds; the HRESULT is logged (the first few times) and kept in the buffer's info and the -// totals (refresh_failures, last_refresh_hr). +// Apart from the unsafe refresh above, nothing is refused at submit: holding back a submission can +// leave a title waiting on its fences. When a copied buffer's refresh cannot be staged (a staging +// buffer or refresh list cannot be created, or the pool stays full of buffers in flight past a 5 s +// wait: DXGI_ERROR_WAS_STILL_DRAWING), the title's lists run with the backing's last upload. The +// buffer is marked stale until a later refresh succeeds; the HRESULT is logged (the first few times) +// and kept in the buffer's info and the totals (refresh_failures, last_refresh_hr). // // A copied buffer that a recorded copy writes (list CopyBufferRegion or CopyResource, list_copy.inl) // keeps the GPU's bytes once that recording is submitted: it is no longer refreshed. The title memory @@ -126,6 +136,8 @@ // publish-out-of-order an older refresh's span is applied to `uploaded` after a newer one's // copy-after-retire the title memory is not probed again right before it is staged (the fault guard // then catches the read of a released buffer's freed pages) +// accept-unsafe-refresh a refresh with no safe completion order is enqueued without waiting for the +// blocked queue instead of refusing the submission (its copy may overlap that read) // x2w_d3d12_linear_buffer_test_pause parks the next refresh at one point (before staging, after // staging, after its copy executed), so a fixture can order two // threads' refreshes or release a buffer while one is parked @@ -418,15 +430,18 @@ class LinearBuffers { // Before the title's lists are executed on queue (the contract's copy point): refreshes every live // copied buffer whose title bytes changed, on the internal queue, then makes queue wait for every - // refresh of a live copied buffer that has not landed yet. Nothing here holds the submission back: - // a buffer whose refresh fails keeps its last upload and is marked stale. + // refresh of a live copied buffer that has not landed yet. A buffer whose refresh fails keeps its last + // upload and is marked stale; the submission still runs. False: the refresh has no safe completion + // order (see the producer wait above) and the submission is refused: nothing was enqueued, and the + // caller must neither execute the title's lists nor call after_submit or commit their GPU writes. // // mutex_ is held only to read and publish state: the work is snapshotted under it, then staging // is taken (and, with the pool full, its fence waited for), filled, recorded and executed without // it, and the results are published under it again. A release() or another queue's submission // therefore never waits behind a fence wait or ExecuteCommandLists here. internal_mutex_ only - // keeps the internal queue's ExecuteCommandLists and Signal in fence-value order. - void before_submit(ID3D12CommandQueue* queue) + // keeps the internal queue's ExecuteCommandLists and Signal in fence-value order (and the refusal + // decision next to them). + [[nodiscard]] bool before_submit(ID3D12CommandQueue* queue) { struct Work { ID3D12Resource* dest; @@ -444,7 +459,7 @@ class LinearBuffers { ++totals_.submissions; bool any = false; for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; - if (!any || !internal_queue_) return; + if (!any || !internal_queue_) return true; for (auto& [resource, record] : records_) { const std::shared_ptr& copy = record.copy; if (!copy || !copy->live || copy->gpu_written) continue; @@ -476,7 +491,9 @@ class LinearBuffers { } } // This submission's own refreshes, including those of a buffer the title released meanwhile. - const UINT64 own = work.empty() ? 0 : refresh(work); + bool refused = false; + const UINT64 own = work.empty() ? 0 : refresh(work, queue, &refused); + if (refused) return false; // Order this submission behind every refresh of a live copied buffer that may not have landed. UINT64 wait_for = own; @@ -495,11 +512,13 @@ class LinearBuffers { x2w_local::logf("x2w-d3d12 linear buffers: queue %p could not wait for refresh 0x%llx (0x%08lx)", static_cast(queue), static_cast(wait_for), static_cast(hr)); } + return true; } // After the title's lists were executed on `queue` (a queue wrapper): signals that queue's user fence, // so a later refresh can be ordered behind this submission (the producer wait). Nothing before the // first copied placement: earlier submissions cannot name a copied backing that did not exist yet. + // Not called for a refused submission: its lists did not run, so no user value stands for them. void after_submit(ID3D12CommandQueue* queue) { std::lock_guard lock(mutex_); @@ -520,7 +539,9 @@ class LinearBuffers { } } if (!user->fence || FAILED(queue->Signal(user->fence, user->value + 1))) { - user->untracked = true; // this submission cannot be waited for: refreshes report the queue as skipped + // This submission cannot be waited for: a refresh that would have to wait for it is refused until + // the queue's next submission has a value (which then covers this one). + user->untracked = true; return; } user->untracked = false; @@ -528,7 +549,8 @@ class LinearBuffers { } // The title enqueued Wait(fence, value) on `queue` (queue slot 17, already forwarded). Recorded until the - // fence reaches the value: a submission behind it may depend on later work (see the producer wait). + // fence reaches the value: a refresh that would have to wait for a submission behind it is refused (see + // the producer wait). void note_title_wait(ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64 value) { if (!fence || fence->GetCompletedValue() >= value) return; @@ -540,7 +562,9 @@ class LinearBuffers { user->waits.push_back({fence, value, user->value + 1}); fence->AddRef(); } catch (const std::bad_alloc&) { - user->untracked = true; // not remembered: the queue is not waited for until it submits again + // Not remembered with its fence: the queue's submissions from the next one on count as blocked until + // that next one completes (its user fence value passes the unknown wait). + if (!user->lost_wait_before) user->lost_wait_before = user->value + 1; } } @@ -637,6 +661,7 @@ class LinearBuffers { UINT64 value = 0; // the latest submission's user fence value (0: none yet) bool untracked = false; // the latest submission has no fence value: it cannot be waited for std::vector waits; + UINT64 lost_wait_before = 0; // a title wait that could not be stored precedes this user value (0: none) }; struct Heap { void* base; @@ -686,9 +711,13 @@ class LinearBuffers { users_.back().queue = queue; return &users_.back(); } - // Under mutex_: forgets the title waits whose fences reached their values. + // Under mutex_: forgets the title waits whose fences reached their values, and a lost one once the first + // submission behind it completed. static void prune_waits(UserQueue& user) { + if (user.lost_wait_before && user.fence && user.value >= user.lost_wait_before && + user.fence->GetCompletedValue() >= user.lost_wait_before) + user.lost_wait_before = 0; auto& waits = user.waits; for (std::size_t i = 0; i < waits.size();) { if (waits[i].fence->GetCompletedValue() >= waits[i].value) { @@ -701,34 +730,36 @@ class LinearBuffers { } } // Under mutex_: the (user fence, value) of each queue's latest submission that has not completed, which - // a refresh's copy waits for. A queue behind an unreached title wait, or one whose latest submission - // has no fence value, is skipped and counted (see the producer wait above). - std::vector> earlier_users() + // a refresh's copy waits for, in *out. False when one of them has no safe completion order (behind an + // unreached title wait, or without a fence value): the refresh must not be enqueued and the submission is + // refused (see the producer wait above); *blocker and *why name the first such queue. bad_alloc + // propagates: a refresh that cannot list what it waits for is not enqueued either. + bool earlier_users(std::vector>* out, ID3D12CommandQueue** blocker, const char** why) { - std::vector> out; + bool safe = true; for (UserQueue& user : users_) { prune_waits(user); const bool pending = user.fence && user.value && user.fence->GetCompletedValue() < user.value; if (!pending && !user.untracked) continue; - bool blocked = user.untracked; - for (const TitleWait& wait : user.waits) blocked |= wait.before <= user.value; - if (blocked) { - ++totals_.producer_wait_skips; - if (x2w_local::first_calls(producer_skip_logged_, 8)) - x2w_local::logf("x2w-d3d12 linear buffers: a refresh does not wait for queue %p (%s): its copy may run before " - "that queue's earlier submission", static_cast(user.queue), - user.untracked ? "no user fence value" : "behind a title Wait that has not completed"); + const char* reason = user.untracked ? "its latest submission has no user fence value" : nullptr; + if (!reason && user.lost_wait_before && user.lost_wait_before <= user.value) + reason = "its latest submission is behind a title Wait that could not be recorded"; + for (const TitleWait& wait : user.waits) + if (!reason && wait.before <= user.value) reason = "its latest submission is behind a title Wait that has not completed"; + if (reason) { + // Mutant: the blocked queue is not waited for and the refresh goes ahead (it may overlap that read). + if (linear_detail::mutant("accept-unsafe-refresh")) continue; + if (safe) { + *blocker = user.queue; + *why = reason; + } + safe = false; continue; } if (linear_detail::mutant("skip-producer-wait")) continue; - try { - out.emplace_back(user.fence, user.value); - } catch (const std::bad_alloc&) { - continue; - } - ++totals_.producer_waits; + out->emplace_back(user.fence, user.value); } - return out; + return safe; } HRESULT feature(ID3D12Device* device) @@ -813,9 +844,10 @@ class LinearBuffers { } // Staging, the refresh list and the internal queue, without mutex_; then publish under it. - // Returns the internal fence value of the refresh it enqueued (0: none). + // Returns the internal fence value of the refresh it enqueued (0: none). *refused: the refresh had no + // safe completion order and nothing was enqueued or published (the submission on `queue` is refused). template - UINT64 refresh(std::vector& work) + UINT64 refresh(std::vector& work, ID3D12CommandQueue* queue, bool* refused) { pause_at(pause_before_stage); std::vector taken; @@ -858,23 +890,49 @@ class LinearBuffers { } if (SUCCEEDED(list_hr)) { std::lock_guard submit(internal_mutex_); - // The producer wait: the copy runs after every earlier submission that may use a backing. + // The producer wait: the copy runs after every earlier submission that may use a backing, or + // the submission is refused when one of them has no safe completion order. Decided here, under + // internal_mutex_, so no refresh can be enqueued between the decision and this copy. std::vector> users; + ID3D12CommandQueue* blocker = nullptr; + const char* why = ""; + bool safe = true; { std::lock_guard lock(mutex_); - users = earlier_users(); + try { + safe = earlier_users(&users, &blocker, &why); + } catch (const std::bad_alloc&) { + list_hr = E_OUTOFMEMORY; // the refresh fails (stale); nothing is enqueued without its waits + } + if (SUCCEEDED(list_hr) && !safe) { + // Nothing was executed: the list and every staging buffer are free again, and no buffer's + // state changes (the next submission compares against the same upload record). + list->value = 0; + for (Work& w : work) + if (w.staging) w.staging->value = 0; + ++totals_.unsafe_refresh_refusals; + if (x2w_local::first_calls(unsafe_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffers: submission on queue %p refused: its refresh would have to " + "wait for queue %p (%s), so it has no safe completion order; none of its lists ran", + static_cast(queue), static_cast(blocker), why); + *refused = true; + return 0; + } + if (SUCCEEDED(list_hr)) totals_.producer_waits += users.size(); } - for (const auto& [fence, user_value] : users) { - const HRESULT hr = internal_queue_->Wait(fence, user_value); - if (FAILED(hr) && x2w_local::first_calls(wait_logged_, 4)) - x2w_local::logf("x2w-d3d12 linear buffers: the refresh queue could not wait for submission 0x%llx (0x%08lx)", - static_cast(user_value), static_cast(hr)); + if (SUCCEEDED(list_hr)) { + for (const auto& [fence, user_value] : users) { + const HRESULT hr = internal_queue_->Wait(fence, user_value); + if (FAILED(hr) && x2w_local::first_calls(wait_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffers: the refresh queue could not wait for submission 0x%llx (0x%08lx)", + static_cast(user_value), static_cast(hr)); + } + ID3D12CommandList* lists[] = {list->list}; + internal_queue_->ExecuteCommandLists(1, lists); + executed = true; + list_hr = internal_queue_->Signal(internal_fence_, internal_value_ + 1); + if (SUCCEEDED(list_hr)) value = ++internal_value_; } - ID3D12CommandList* lists[] = {list->list}; - internal_queue_->ExecuteCommandLists(1, lists); - executed = true; - list_hr = internal_queue_->Signal(internal_fence_, internal_value_ + 1); - if (SUCCEEDED(list_hr)) value = ++internal_value_; } } if (executed) pause_at(pause_after_execute); @@ -1123,7 +1181,7 @@ class LinearBuffers { UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; std::size_t creating_ = 0; // staging buffers being created outside the lock X2wLinearBufferTotals totals_{}; - volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0, producer_skip_logged_ = 0; + volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0, unsafe_logged_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h index 8f810b0d02..107ca76e28 100644 --- a/src/startup_stubs/linear_buffer_report.h +++ b/src/startup_stubs/linear_buffer_report.h @@ -32,7 +32,7 @@ struct X2wLinearBufferTotals { std::uint64_t consumer_waits; // submissions made to Wait for a refresh on the internal queue std::uint64_t gpu_written; // copied buffers that a submitted copy wrote (held from then on) std::uint64_t producer_waits; // refresh copies made to Wait for a queue's earlier, uncompleted submission - std::uint64_t producer_wait_skips; // queues a refresh did not wait for (behind an unreached title Wait) + std::uint64_t unsafe_refresh_refusals; // submissions refused: their refresh had no safe completion order std::uint64_t reordered_publishes; // an older refresh published after a newer one: `uploaded` dropped std::uint64_t copy_faults; // staging reads of title memory that faulted (caught; that refresh failed) std::int32_t last_refusal_hr, last_refresh_hr; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index cb2cf4a599..1cd4571fd0 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -84,10 +84,11 @@ // war (copy only) a read of A on queue 1 behind a title gate (on the desktop queue); the CPU writes B and // queue 2 submits a read. Its refresh's copy waits for queue 1 (producer_waits): queue 2 cannot // complete while the gate is closed, queue 1 reads A and queue 2 reads B. -// xq.write (copy only) queue 1 waits through its wrapper (slot 17) on a title fence, then submits a read; -// the CPU writes B and queue 2 submits a read. The refresh must not wait for queue 1 (counted as a -// producer wait skip): queue 2 completes while queue 1 still waits, then the CPU reaches the fence -// and queue 1 reads B too. +// xq.write (copy only) queue 1 waits through its wrapper (slot 17) on a title fence, then submits a read of +// A; the CPU writes B and queue 2 submits a read. Its refresh has no safe completion order (it would +// have to wait for queue 1, behind the unreached fence), so the submission is refused: unsafe refresh +// refusals +1 and logged, its result slot keeps P. The title's Signal through queue 2's wrapper (slot +// 16) releases queue 1, which reads A; the refused recording submitted again on queue 2 reads B. // order (copy only) two threads refresh one buffer, parked through x2w_d3d12_linear_buffer_test_pause: // thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes // first and parks before publishing; A executes (the backing ends with C) and publishes, B publishes @@ -113,7 +114,8 @@ // gpuw-at-record (copy) case gpuw.discard (the buffer stops being refreshed when the copy is recorded), // skip-producer-wait (copy) case war (the refresh's copy lands before queue 1's earlier read), // publish-out-of-order (copy) case order (B's older publish is applied after A's: no further refresh), -// copy-after-retire (copy) case retire (no probe before staging: the fault guard catches the read). +// copy-after-retire (copy) case retire (no probe before staging: the fault guard catches the read), +// accept-unsafe-refresh (copy) case xq.write (the refresh skips the blocked queue: queue 2 runs and both read B). // // Refreshes run on an internal COPY queue that the DLL exports to fixtures // (x2w_d3d12_linear_buffer_internal_queue); cases c, contention and gate2q.held hold it behind a fence @@ -522,6 +524,19 @@ struct Gpu { } return got; } + // The CPU writes `tag` ^ key into result slot `slot` (indexed as the region at r0), so a read that never + // ran leaves it there. + bool fill_output(UINT slot, Tag tag) + { + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + if (FAILED(readback->Map(0, &none, &mapped))) return false; + auto* w = reinterpret_cast(static_cast(mapped) + slot * region_bytes); + for (UINT i = 0; i < words; ++i) w[i] = pattern(tag, r0 / 4 + i) ^ key; + const D3D12_RANGE written{slot * region_bytes, (slot + 1) * region_bytes}; + readback->Unmap(0, &written); + return true; + } unsigned debug_errors() { if (!info) return 0; @@ -1199,10 +1214,13 @@ struct Run { std::to_string(after.producer_waits - before.producer_waits)); } - // xq.write: queue 1 waits through its wrapper (queue slot 17) on a title fence, then submits a read; the CPU - // writes B and queue 2 submits a read. The refresh must not wait for queue 1 (the fence is reached only - // later, here by the CPU once queue 2 is done; a title can equally signal it from queue 2): queue 2 completes - // while queue 1 still waits, both read B, and the skip is counted. + // xq.write: queue 1 waits through its wrapper (queue slot 17) on a title fence F, then submits a read of A + // (nothing to refresh). The CPU writes B and queue 2 submits a read. Its refresh would have to wait for + // queue 1, which sits behind F, and F may be reached only by later work (here the title signals it from + // queue 2): there is no safe completion order, so the submission must be refused, with nothing of it + // executed (its result slot keeps the fixture's P) and the refusal counted and logged. The title then + // signals F through queue 2's wrapper (queue slot 16): queue 1 must complete and read A. The refused + // recording, submitted again on queue 2 once queue 1 is done, must read B, with no further refusal. void case_xq_write(Pool& pool) { const char* name = "xq.write"; @@ -1219,31 +1237,47 @@ struct Run { return row(pool, name, false, "slot 133 -> " + hex(x.hr)); l0.read(x.backing.Get()); l0.close(); - if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read l1.read(x.backing.Get(), 1); l1.close(); l2.read(x.backing.Get(), 2); l2.close(); + if (!gpu.fill_output(2, P)) return row(pool, name, false, "result slot could not be filled"); const X2wLinearBufferTotals before = totals(); if (FAILED(static_cast(invoke(gpu.guest_queue.Get(), 17, arg(fence.Get()), 1)))) return row(pool, name, false, "queue wait (slot 17) failed"); - const UINT64 v1 = l1.submit(); + const UINT64 v1 = l1.submit(); // queue 1, behind F write(memory.buffer(), r0, B, words); - const UINT64 v2 = l2.submit_on(q2); - const bool q2_done = wait_fence(q2.fence.Get(), v2); + const UINT64 v2 = l2.submit_on(q2); // needs a refresh of B: refused + // The lane's own fence after the refused lists: queue 2 itself was never blocked. + const bool q2_progress = wait_fence(q2.fence.Get(), v2); const bool q1_pending = gpu.done->GetCompletedValue() < v1; - invoke(fence.Get(), 10, 1); // the title's fence, from the CPU (fence slot 10) + const X2wLinearBufferTotals mid = totals(); + const Tally refused = tally(gpu.read_output(2).data(), r0 / 4, key); + const bool logged = log_has("refused: its refresh would have to wait for queue", "no safe completion order"); + // The title's ordinary Signal through queue 2's wrapper releases queue 1. + const HRESULT signal_hr = static_cast(invoke(q2.guest.Get(), 16, arg(fence.Get()), 1)); const bool q1_done = gpu.wait(v1); - if (!q2_done && !wait_fence(q2.fence.Get(), v2)) return row(pool, name, false, "fence timeout (queue 2)"); - const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + if (!q1_done) return row(pool, name, false, "queue 1 did not complete after the title's Signal (slot 16) " + hex(signal_hr)); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key); + // A later, safe submission: the refused recording again, with no submission behind a title Wait. + const UINT64 v3 = l2.submit_on(q2); + if (!wait_fence(q2.fence.Get(), v3)) return row(pool, name, false, "fence timeout (queue 2, resubmission)"); + const Tally t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + refresh_info(x); const X2wLinearBufferTotals after = totals(); - const bool pass = q2_done && q1_pending && q1_done && t1.count[B] == words && t2.count[B] == words && - after.producer_wait_skips > before.producer_wait_skips; + const UINT64 refusals = mid.unsafe_refresh_refusals - before.unsafe_refresh_refusals; + const bool pass = q1_pending && q2_progress && refusals == 1 && refused.count[P] == words && logged && SUCCEEDED(signal_hr) && + t1.count[A] == words && t2.count[B] == words && after.unsafe_refresh_refusals == mid.unsafe_refresh_refusals && + !x.info.stale && x.info.refresh_failures == 0; row(pool, name, pass, - std::string("queue 1 behind a title Wait (slot 17); queue 2 ") + - (q2_done ? "completed" : "DID NOT COMPLETE (the refresh waited for queue 1: deadlock)") + " while queue 1 " + - (q1_pending ? "still waited" : "HAD RUN") + " and read " + t2.text() + "; queue 1 " + (q1_done ? "then read " : "DID NOT COMPLETE, read ") + - t1.text() + "; producer wait skips +" + std::to_string(after.producer_wait_skips - before.producer_wait_skips)); + std::string("queue 1 ") + (q1_pending ? "behind a title Wait (slot 17)" : "NOT HELD by its title Wait") + + " with a read of A; after the CPU wrote B, queue 2's read was " + (refusals == 1 ? "refused" : "NOT REFUSED") + + " (refusals +" + std::to_string(refusals) + ", log line " + (logged ? "present" : "MISSING") + "), its slot " + + refused.text() + " (expected P: nothing ran), queue 2 " + (q2_progress ? "progressed" : "STUCK") + + "; the title's Signal on queue 2 (slot 16) -> " + hex(signal_hr) + ", queue 1 then read " + t1.text() + + " (expected A); the refused recording resubmitted on queue 2 read " + t2.text() + " (expected B), refusals +" + + std::to_string(after.unsafe_refresh_refusals - mid.unsafe_refresh_refusals) + (x.info.stale ? ", STALE" : "")); } // order: two threads' refreshes of one buffer, driven through the pause hook. Thread A stages C and parks @@ -1730,7 +1764,7 @@ int main(int argc, char** argv) std::printf("totals: placements %llu (shared %llu, copied %llu, kept default %llu), feature queries %llu, heap opens %llu " "(failed %llu, cache hits %llu), placements failed %llu, submissions %llu, refreshes %llu, bytes copied %llu, " "staging created %llu reused %llu, unreadable %llu, refresh failures %llu, consumer waits %llu, producer waits %llu " - "(skipped %llu), gpu written %llu, reordered publishes %llu, copy faults %llu, last refusal %s, last refresh failure %s\n", + "(unsafe refreshes refused %llu), gpu written %llu, reordered publishes %llu, copy faults %llu, last refusal %s, last refresh failure %s\n", static_cast(t.placements), static_cast(t.shared), static_cast(t.copied), static_cast(t.kept_default), static_cast(t.feature_queries), static_cast(t.heap_opens), @@ -1740,7 +1774,7 @@ int main(int argc, char** argv) static_cast(t.staging_created), static_cast(t.staging_reused), static_cast(t.unreadable), static_cast(t.refresh_failures), static_cast(t.consumer_waits), static_cast(t.producer_waits), - static_cast(t.producer_wait_skips), static_cast(t.gpu_written), + static_cast(t.unsafe_refresh_refusals), static_cast(t.gpu_written), static_cast(t.reordered_publishes), static_cast(t.copy_faults), hex(t.last_refusal_hr).c_str(), hex(t.last_refresh_hr).c_str()); { @@ -1781,7 +1815,7 @@ int main(int argc, char** argv) : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" : mutant == "refresh-gpu-written" ? "gpuw" : mutant == "gpuw-at-record" ? "gpuw.discard" : mutant == "skip-producer-wait" ? "war" : mutant == "publish-out-of-order" ? "order" - : mutant == "copy-after-retire" ? "retire" : nullptr; + : mutant == "copy-after-retire" ? "retire" : mutant == "accept-unsafe-refresh" ? "xq.write" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results) From c777de19baef3548dc8ce653144948c2e2906d72 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 22:53:03 +0100 Subject: [PATCH 17/18] docs: record the linear-buffer refusal of a refresh with no safe completion order Replace the producer-wait skip in the runtime notes with the refusal: when it applies, what a refused submission leaves in place, its log line and the unsafe_refresh_refusals counter. In the experiment notes, rewrite the xq.write oracle, drop the skip results and the overlap caveat, and record the c6a0c8a9 runs and the accept-unsafe-refresh control. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 9 +++++++-- docs/startup-runtime.md | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 83059a911c..f58f7749b6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9688,7 +9688,7 @@ A title run motivated the fallback. An earlier revision returned the refusal fro | gpuw | `copy` only: a list `CopyBufferRegion` (list slot 15) writes G into the buffer, and the title then changes its first and last words. The next read must still see G (no refresh spans the written words), and info and totals must report it as GPU-written. | | gpuw.discard | `copy` only (review repro): the same copy is recorded and closed, then the list is reset without a submission, and the CPU writes B. The next read must see B, and the buffer must not be reported GPU-written. | | war | `copy` only: a read of A on queue 1 behind a title gate (on the desktop queue), then the CPU writes B and queue 2 submits a read. Queue 2 must not complete while the gate is closed, queue 1 must read A, queue 2 must read B, and `producer_waits` must grow. | -| xq.write | `copy` only: queue 1 waits through its wrapper (queue slot 17) on a title fence and submits a read; the CPU writes B and queue 2 submits a read. Queue 2 must complete while queue 1 still waits (no deadlock), both must read B once the CPU reaches the fence, and `producer_wait_skips` must grow. | +| xq.write | `copy` only: queue 1 waits through its wrapper (queue slot 17) on a title fence and submits a read of A; the CPU writes B and queue 2 submits a read. That refresh would have to wait for queue 1, behind the unreached fence, so queue 2's submission must be refused: `unsafe_refresh_refusals` +1, the refusal logged, and its result slot must keep the fixture's P. The title then signals the fence through queue 2's wrapper (queue slot 16). Queue 1 must complete and read A, and the refused recording, submitted again on queue 2, must read B with no further refusal. | | order | `copy` only: two threads refresh one buffer, parked through `x2w_d3d12_linear_buffer_test_pause`. Thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes its copy first and parks before publishing; A executes (the backing ends with C) and publishes, and B publishes last. The next submission must refresh D and read it, with `reordered_publishes` +1. | | retire | `copy` only: a submission that reads Y snapshots the changed X and Y and parks before staging. The title releases X and frees its pages. X must be skipped as unreadable, with no copy fault and no failed refresh, and Y must read C. | | lease | `lease` only: an XMem buffer must keep the default backing (not aliased: it reads zero) with the deferral `0x800700aa` reported. A private buffer must still be copied and read B. | @@ -9732,7 +9732,12 @@ The review of `bfdd583f` found four more problems. A list copy into a copied buf - `publish-out-of-order` applies every publish in lock order. order then reads C, `reordered_publishes` +0 (2 of 2). - `copy-after-retire` skips the probe right before staging. In retire, the fault guard catches the read of X's freed pages: copy faults +1, one refresh failure `0x800703E6` (2 of 2). -On Windows 11 build 26300.9974 at `981b519c`, in-box WARP (`1414:008c`, driver 10.0.26100.9818) and the AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), debug layer off: all 16 path entries pass, with no skips, in the dev and release presets. Every new row passes in both pools on both adapters: gpuw.discard B, `gpu_written` 0; war queue 1 A and queue 2 B, producer waits +1; xq.write queue 2 completes while queue 1 waits, both B, skips +1; order D, reordered publishes +1; retire unreadable +1, copy faults 0, Y C; contention S1 B and S2 C. All twelve controls fail their targeted rows (2 of 2, gate 1 of 1). The producer wait can idle the GPU between submissions, because every earlier submission counts as a user of every copied backing. A title fence reached while a refresh's copy executes, after the refresh skipped the queue behind it, can still overlap that queue's read. +On Windows 11 build 26300.9974 at `981b519c`, in-box WARP (`1414:008c`, driver 10.0.26100.9818) and the AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), debug layer off: all 16 path entries pass, with no skips, in the dev and release presets. Every new row passes in both pools on both adapters: gpuw.discard B, `gpu_written` 0; war queue 1 A and queue 2 B, producer waits +1; order D, reordered publishes +1; retire unreadable +1, copy faults 0, Y C; contention S1 B and S2 C. All twelve controls fail their targeted rows (2 of 2, gate 1 of 1). The producer wait can idle the GPU between submissions, because every earlier submission counts as a user of every copied backing. + +The review of `58971a4a` rejected that revision's handling of xq.write, which skipped a queue behind an unreached title fence. Skipping does not establish that the fence stays blocked until the copy finishes, because another producer can reach it while the copy runs. A submission whose refresh would have to wait for such a submission (on any queue, including its own) or for one without a user fence value is now refused before anything is enqueued (`unsafe_refresh_refusals`, logged): no refresh, no consumer `Wait`, none of its lists and no user fence `Signal`. The staging buffers, the refresh list and every buffer's upload record stay as they were, so a later safe submission copies whatever still differs. A recorded copy's GPU write stays pending on the refused recording. xq.write now drives this case (table above), and one control is added: +- `accept-unsafe-refresh` restores the skip. In xq.write, queue 2's read is not refused and reads B, and queue 1 reads B after its fence instead of A (2 of 2). Neither queue hangs. + +On Windows 11 build 26300.9974 at `c6a0c8a9`, with the same adapters and drivers and the debug layer off, all 16 path entries pass with no skips in the dev and release presets, and all thirteen controls fail their targeted rows (2 of 2, gate 1 of 1). In both pools on both adapters, xq.write refuses queue 2's read (refusals +1, log line present) and leaves its result slot at P in all 1,024 words, and queue 2's own fence is reached. After the title's `Signal` through queue 2's wrapper (queue slot 16, `S_OK`), queue 1 completes and reads A. The refused recording, submitted again on queue 2, reads B with no further refusal and no stale or failed refresh. war (queue 1 A, queue 2 B, producer waits +1), gate2q, gate2q.held and xq pass as before. A refused submission's work does not run; the log line and the counter are how a run shows it. The producer wait can still idle the GPU between submissions. A proven disjoint resource or an immutable per-submission backing could let more of these cases run; neither is implemented. Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. A copied buffer that a submitted list copy wrote keeps the GPU's bytes and stops following the title memory, as the default backing does. Sharing XMem views through the section lease (#2280) instead of copying them is a follow-up. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 77811d6648..efd89c9f8c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2926,7 +2926,7 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - **Internal queue.** Every refresh runs on one internal COPY queue per device, which never waits on a title fence. It signals an internal fence value, and each buffer remembers the value of its last refresh. - **Consumer wait.** Every submission through a queue wrapper, of any type (direct, compute or copy), first makes its queue `Wait` for the highest such value among the live copied buffers that has not completed. A consumer on any queue therefore runs after every refresh enqueued before it, wherever that refresh came from. So when one CPU write is followed by submissions on two queues, both read the new bytes, even if the first is still held behind a title fence. - **Producer wait.** A refresh's copy is also ordered behind earlier GPU access to the backing. Simultaneous access allows concurrent operations on one buffer only on disjoint ranges, so the copy must not overlap an earlier submission that still reads or writes it. Each queue wrapper signals a user fence of its own after the title's lists. Before a refresh's copy executes, the internal queue `Wait`s for every queue's latest user fence value that has not completed (`producer_waits`). The wrappers cannot tell which buffers a submission reads, because titles bind them by GPU virtual address, so every earlier submission counts as a user of every copied backing. This conservative choice can idle the GPU between a frame's submissions and the next refresh. - - **No cycle through title fences.** A queue whose latest submission sits behind a title `Wait` (queue slot 17) on a fence that has not been reached is not waited for (`producer_wait_skips`, logged). A later submission that waits for this refresh may be the one that signals that fence, such as queue 2 signalling a fence that queue 1 waits on, and waiting would deadlock both queues. That submission has not started; it runs after the title's fence and reads the CPU's newer bytes, as unified memory does on the console. Not closed: if that fence is reached while the copy still executes, the read can overlap the copy. A title `Wait` issued on the desktop queue past the wrapper is not seen, and that queue is waited for. + - **Unsafe refresh refused.** A submission whose refresh has no safe completion order is refused (`unsafe_refresh_refusals`, logged). That is the case when the refresh would have to wait for an earlier submission, on any queue including its own, that sits behind a title `Wait` (queue slot 17) on a fence that has not been reached, or for one whose user fence `Signal` failed. Waiting could deadlock: the fence may be signalled only by work that itself waits for the refresh, such as queue 2 signalling a fence that queue 1 waits on. Not waiting would let the copy overlap that read, because the blocked queue is not known to stay blocked until the copy finishes; the CPU or another queue may reach the fence meanwhile. The decision is made right before the refresh would be enqueued, and nothing of the submission reaches the GPU: no refresh, no consumer `Wait`, none of the title's lists and no user fence `Signal`. The staging buffers and refresh list are free again, no buffer's upload record or refresh state changes, and a recorded copy's GPU write stays pending on its recording. The next submission copies whatever still differs. The title's own `Signal` and `Wait` on its queues do not pass through this path, so a later `Signal` still releases the earlier queue. A submission with no changed bytes is never refused. A title `Wait` issued on the desktop queue past the wrapper is not seen, and that queue is waited for. - **Own refresh.** A submission also waits for the refresh it enqueued itself, even if the title released that buffer meanwhile. - **Staging reuse.** A staging buffer is reused only after the internal fence value of the copy that read it has completed. - **No internal queue.** If the internal queue or its fence cannot be created, copied placements keep the default backing with that HRESULT recorded. @@ -2943,7 +2943,7 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - when the mesh XMem lease path is on (`X2W_MESH86_XMEM_SRV` or `X2W_MESH_INDIRECT_XMEM`) and the placement is one it takes: XMem pages (`MEM_MAPPED`) with console flags 0. `HRESULT_FROM_WIN32(ERROR_BUSY)` (`0x800700aa`) means the placement was deferred to the lease path, which mirrors and publishes that default copied placement. The two never back one placement. - A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. -A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. `x2w_d3d12_linear_buffer_totals` counts `kept_default` and `refresh_failures`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. A refused submission logs `x2w-d3d12 linear buffers: submission on queue refused: its refresh would have to wait for queue (), so it has no safe completion order; none of its lists ran` (the first eight). `x2w_d3d12_linear_buffer_totals` counts `kept_default`, `refresh_failures` and `unsafe_refresh_refusals`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. From ee56e734fa9f92ef357e83de5a31424c5f128620 Mon Sep 17 00:00:00 2001 From: The Void Date: Wed, 25 Nov 2026 23:41:50 +0100 Subject: [PATCH 18/18] gpu: order a queue's title waits and user fence values under one lock A title Wait (queue slot 17) and ExecuteCommandLists on the same queue from two threads could be recorded in the opposite order to the desktop queue: a submission behind the desktop Wait took its user fence value before note_title_wait ran, so the Wait was recorded as preceding only later submissions. Another queue's refresh was then accepted and waited for the blocked submission, and that queue's own Signal of the fence sat behind the refresh. Each queue's linear-buffer record now has an order lock (SRWLOCK; users_ becomes a deque so records never move). Slot 17 holds it from the desktop Wait through note_title_wait; a submission holds it from the title's ExecuteCommandLists through after_submit, taken before draw_lock and allocator_lock in render mode and with no other lock held. It is not held across the refresh, nothing under it waits on the CPU for the GPU, and the title's Signal does not take it. The fixture adds xq.race: the Wait is parked through a new pause point (3) between the desktop Wait and its record while another thread submits the read of A on queue 1. Queue 2's read must still be refused and queue 2 must still signal the fence; waits are bounded with a CPU Signal of the fence as cleanup. Control unlocked-title-wait skips the lock in slot 17 and reproduces the review's pending lanes with zero refusals. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 7 +- docs/experiments.md | 6 + docs/startup-runtime.md | 3 +- src/startup_stubs/d3d12_xs_device.cpp | 39 +++++-- src/startup_stubs/linear_buffer_backing.h | 85 +++++++++++++-- tests/linear_buffer_backing_check.cpp | 127 +++++++++++++++++++++- 6 files changed, 244 insertions(+), 23 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index be03e1b292..d3cc8761ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2648,8 +2648,8 @@ endforeach() # queues after one CPU write (both must see it), and follows a title-owned cross-queue fence without # deadlock. It also counts the backings in the D3D12 budget, keeps a buffer a submitted list copy wrote # (and refreshes one whose copy was discarded), orders a refresh behind an earlier read on another queue, -# refuses a submission whose refresh would have to wait for a queue behind an unreached title Wait, -# publishes two threads' refreshes in execution order, skips a buffer released and freed mid-refresh, and +# refuses a submission whose refresh would have to wait for a queue behind an unreached title Wait (also +# when that Wait and the submission behind it arrive on two threads), publishes two threads' refreshes in execution order, skips a buffer released and freed mid-refresh, and # defers XMem placements to the mesh XMem lease path when that is on. Each mutant removes one guarantee in # the DLL and must fail its case. add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) @@ -2664,7 +2664,8 @@ foreach(adapter IN ITEMS warp hardware) endforeach() foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature copy:refusal_silent contention:hold_lock copy:skip_consumer_wait copy:refresh_gpu_written copy:gpuw_at_record - copy:skip_producer_wait copy:publish_out_of_order copy:copy_after_retire copy:accept_unsafe_refresh) + copy:skip_producer_wait copy:publish_out_of_order copy:copy_after_retire copy:accept_unsafe_refresh + copy:unlocked_title_wait) string(REPLACE ":" ";" parts "${control}") list(GET parts 0 path) list(GET parts 1 mutant) diff --git a/docs/experiments.md b/docs/experiments.md index e3b6cf3e39..beac00ff6a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9885,6 +9885,7 @@ A title run motivated the fallback. An earlier revision returned the refusal fro | gpuw.discard | `copy` only (review repro): the same copy is recorded and closed, then the list is reset without a submission, and the CPU writes B. The next read must see B, and the buffer must not be reported GPU-written. | | war | `copy` only: a read of A on queue 1 behind a title gate (on the desktop queue), then the CPU writes B and queue 2 submits a read. Queue 2 must not complete while the gate is closed, queue 1 must read A, queue 2 must read B, and `producer_waits` must grow. | | xq.write | `copy` only: queue 1 waits through its wrapper (queue slot 17) on a title fence and submits a read of A; the CPU writes B and queue 2 submits a read. That refresh would have to wait for queue 1, behind the unreached fence, so queue 2's submission must be refused: `unsafe_refresh_refusals` +1, the refusal logged, and its result slot must keep the fixture's P. The title then signals the fence through queue 2's wrapper (queue slot 16). Queue 1 must complete and read A, and the refused recording, submitted again on queue 2, must read B with no further refusal. | +| xq.race | `copy` only (review repro): xq.write with queue 1's title `Wait` and its read of A issued from two threads. Thread W's `Wait` (queue slot 17) is parked through `x2w_d3d12_linear_buffer_test_pause` (point 3) after the desktop `Wait` and before it is recorded. Meanwhile thread S submits the read of A on queue 1 and gets up to 1 s to return before W resumes. The read sits behind the fence on the desktop queue, so after the CPU writes B, queue 2's read must be refused (refusals +1, its result slot keeps P, queue 2's own fence is reached). The title's `Signal` through queue 2's wrapper (queue slot 16) must succeed, queue 1 must complete and read A, and the refused recording, submitted again, must read B. If queue 2 or queue 1 does not complete within 3 s, the fixture signals the fence from the CPU so both queues drain, and the row fails. | | order | `copy` only: two threads refresh one buffer, parked through `x2w_d3d12_linear_buffer_test_pause`. Thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes its copy first and parks before publishing; A executes (the backing ends with C) and publishes, and B publishes last. The next submission must refresh D and read it, with `reordered_publishes` +1. | | retire | `copy` only: a submission that reads Y snapshots the changed X and Y and parks before staging. The title releases X and frees its pages. X must be skipped as unreadable, with no copy fault and no failed refresh, and Y must read C. | | lease | `lease` only: an XMem buffer must keep the default backing (not aliased: it reads zero) with the deferral `0x800700aa` reported. A private buffer must still be copied and read B. | @@ -9935,6 +9936,11 @@ The review of `58971a4a` rejected that revision's handling of xq.write, which sk On Windows 11 build 26300.9974 at `c6a0c8a9`, with the same adapters and drivers and the debug layer off, all 16 path entries pass with no skips in the dev and release presets, and all thirteen controls fail their targeted rows (2 of 2, gate 1 of 1). In both pools on both adapters, xq.write refuses queue 2's read (refusals +1, log line present) and leaves its result slot at P in all 1,024 words, and queue 2's own fence is reached. After the title's `Signal` through queue 2's wrapper (queue slot 16, `S_OK`), queue 1 completes and reads A. The refused recording, submitted again on queue 2, reads B with no further refusal and no stale or failed refresh. war (queue 1 A, queue 2 B, producer waits +1), gate2q, gate2q.held and xq pass as before. A refused submission's work does not run; the log line and the counter are how a run shows it. The producer wait can still idle the GPU between submissions. A proven disjoint resource or an immutable per-submission backing could let more of these cases run; neither is implemented. +The review of `7ecb6cfd` reproduced a race when queue slot 17 and `ExecuteCommandLists` overlap on one queue. With a pause after the desktop `Wait(F, 1)` and before `note_title_wait`, another thread's read of A on queue 1 took its user fence value first. The `Wait` was then recorded as preceding only later submissions, even though the desktop queue held it ahead of that read. Queue 2's refresh was accepted and waited for queue 1, queue 2's own `Signal(F, 1)` sat behind that refresh, and both queues stayed pending until a CPU `Signal` of F. Each queue's linear-buffer record now has an order lock. Slot 17 holds it from the desktop `Wait` through `note_title_wait`. A submission holds it from the title's `ExecuteCommandLists` through its user fence `Signal`, in render mode before `draw_lock` and `allocator_lock`. A queue's waits and user values are therefore recorded in the order its desktop queue received them. The lock is not held across the refresh, so its staging waits and fixture pauses run without it. Nothing under it waits on the CPU for the GPU, and the title's `Signal` does not take it, so a queue whose submission was refused can still signal the fence. The fixture adds xq.race (table above) and one control: +- `unlocked-title-wait` lets slot 17 run without the order lock. In xq.race, S's read returns while W is parked, and queue 2's read is not refused (refusals +0). Queue 2 and queue 1 then stay pending after the title's `Signal` on queue 2. After the fixture's CPU `Signal` of F, both drain: queue 1 reads A and queue 2 reads B (2 of 2). + +On Windows 11 build 26300 at `7ecb6cfd` plus this change, with in-box WARP (`1414:008c`, driver 10.0.26100.9818) and the AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010) and the debug layer off, all 16 path entries pass with no skips in the dev and release presets. All fourteen controls fail their targeted rows (2 of 2, gate 1 of 1). In both pools on both adapters, xq.race parks W, and S does not return while W is parked. Queue 2's read is refused (refusals +1) and its slot keeps P in all 1,024 words, and queue 2's own fence is reached. The title's `Signal` on queue 2 returns `S_OK`, queue 1 completes and reads A, and the resubmission reads B with no further refusal. xq.write and the other rows pass as before. `ctest --preset release --no-tests=error -R '^linear_buffer_backing_copy_(warp|hardware)$' --repeat until-fail:20` passed 20 of 20 runs on each adapter, which is 80 xq.race rows with none failed. The `unlocked_title_wait` control, repeated with `--repeat until-fail:5`, failed its rows in all 5 runs as expected. + Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing__.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. A copied buffer that a submitted list copy wrote keeps the GPU's bytes and stops following the title memory, as the default backing does. Sharing XMem views through the section lease (#2280) instead of copying them is a follow-up. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. #### Xbox frame events and token wait semantics (#874) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index b393c0ebf4..65f76efd09 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2981,6 +2981,7 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - **Consumer wait.** Every submission through a queue wrapper, of any type (direct, compute or copy), first makes its queue `Wait` for the highest such value among the live copied buffers that has not completed. A consumer on any queue therefore runs after every refresh enqueued before it, wherever that refresh came from. So when one CPU write is followed by submissions on two queues, both read the new bytes, even if the first is still held behind a title fence. - **Producer wait.** A refresh's copy is also ordered behind earlier GPU access to the backing. Simultaneous access allows concurrent operations on one buffer only on disjoint ranges, so the copy must not overlap an earlier submission that still reads or writes it. Each queue wrapper signals a user fence of its own after the title's lists. Before a refresh's copy executes, the internal queue `Wait`s for every queue's latest user fence value that has not completed (`producer_waits`). The wrappers cannot tell which buffers a submission reads, because titles bind them by GPU virtual address, so every earlier submission counts as a user of every copied backing. This conservative choice can idle the GPU between a frame's submissions and the next refresh. - **Unsafe refresh refused.** A submission whose refresh has no safe completion order is refused (`unsafe_refresh_refusals`, logged). That is the case when the refresh would have to wait for an earlier submission, on any queue including its own, that sits behind a title `Wait` (queue slot 17) on a fence that has not been reached, or for one whose user fence `Signal` failed. Waiting could deadlock: the fence may be signalled only by work that itself waits for the refresh, such as queue 2 signalling a fence that queue 1 waits on. Not waiting would let the copy overlap that read, because the blocked queue is not known to stay blocked until the copy finishes; the CPU or another queue may reach the fence meanwhile. The decision is made right before the refresh would be enqueued, and nothing of the submission reaches the GPU: no refresh, no consumer `Wait`, none of the title's lists and no user fence `Signal`. The staging buffers and refresh list are free again, no buffer's upload record or refresh state changes, and a recorded copy's GPU write stays pending on its recording. The next submission copies whatever still differs. The title's own `Signal` and `Wait` on its queues do not pass through this path, so a later `Signal` still releases the earlier queue. A submission with no changed bytes is never refused. A title `Wait` issued on the desktop queue past the wrapper is not seen, and that queue is waited for. + - **Queue order lock.** A title can call slot 17 and `ExecuteCommandLists` on one queue from two threads at once. Each queue's linear-buffer record has an order lock, so the record of which submissions sit behind which title `Wait` matches the desktop queue's order. Slot 17 holds it from the desktop `Wait` through recording that `Wait`. A submission holds it from the title's `ExecuteCommandLists` through its user fence `Signal`, before `draw_lock` and `allocator_lock` in render mode. Without it, a submission could reach the desktop queue behind a `Wait` but take its user value before that `Wait` was recorded. Another queue's refresh would then wait for that blocked submission instead of being refused. The lock is not held across the refresh, so staging waits and fixture pauses run without it. Nothing under it waits on the CPU for the GPU. The title's `Signal` does not take it, so a queue whose submission was refused can still signal the fence its blocked peer waits on. - **Own refresh.** A submission also waits for the refresh it enqueued itself, even if the title released that buffer meanwhile. - **Staging reuse.** A staging buffer is reused only after the internal fence value of the copy that read it has completed. - **No internal queue.** If the internal queue or its fence cannot be created, copied placements keep the default backing with that HRESULT recorded. @@ -2997,7 +2998,7 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee - when the mesh XMem lease path is on (`X2W_MESH86_XMEM_SRV` or `X2W_MESH_INDIRECT_XMEM`) and the placement is one it takes: XMem pages (`MEM_MAPPED`) with console flags 0. `HRESULT_FROM_WIN32(ERROR_BUSY)` (`0x800700aa`) means the placement was deferred to the lease path, which mirrors and publishes that default copied placement. The two never back one placement. - A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of failed
; the submission runs with its last upload (stale)`) and every one is counted. -A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. A refused submission logs `x2w-d3d12 linear buffers: submission on queue refused: its refresh would have to wait for queue (), so it has no safe completion order; none of its lists ran` (the first eight). `x2w_d3d12_linear_buffer_totals` counts `kept_default`, `refresh_failures` and `unsafe_refresh_refusals`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=
share=
->
shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal
, use=... type=... existing-heaps=
share=
)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. A refused submission logs `x2w-d3d12 linear buffers: submission on queue refused: its refresh would have to wait for queue (), so it has no safe completion order; none of its lists ran` (the first eight). `x2w_d3d12_linear_buffer_totals` counts `kept_default`, `refresh_failures` and `unsafe_refresh_refusals`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. Point 3 instead parks the next title `Wait` (queue slot 17) after the desktop `Wait` and before it is recorded, while it holds that queue's order lock. `X2W_TEST_LINEAR_BUFFER_MUTANT=` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 4f434443be..db590c6e08 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1620,8 +1620,9 @@ extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBu if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); } // Fixtures: the next refresh that reaches `point` (0 before staging, 1 after the title bytes are staged, -// 2 after its copy was executed, before it is published) sets the `reached` event, then waits up to 20 s -// for `resume`. Null events disarm the point. False with the switch off or for an unknown point. +// 2 after its copy was executed, before it is published), or for point 3 the next title Wait (queue slot 17) +// after its desktop Wait and before it is recorded, sets the `reached` event, then waits up to 20 s for +// `resume`. Null events disarm the point. False with the switch off or for an unknown point. extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_test_pause(unsigned point, void* reached, void* resume) { return x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off && @@ -3657,6 +3658,15 @@ void linear_submitted(ID3D12CommandQueue* queue) { if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().after_submit(queue); } +// The queue's order lock (linear_buffer_backing.h), so its title waits and user fence values are recorded in +// the order the desktop queue receives them: held by a submission from its ExecuteCommandLists through +// linear_submitted, and by queue slot 17 from the desktop Wait through note_title_wait. Taken before +// draw_lock and allocator_lock and with no other lock held; nothing while the switch is off. +x2w_startup::LinearBuffers::QueueOrder linear_queue_order(ID3D12CommandQueue* queue, bool title_wait) +{ + if (x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) return {}; + return linear_buffers().queue_order(queue, title_wait); +} // Queue slot 10, desktop ExecuteCommandLists(count, lists). void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) @@ -3673,6 +3683,9 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) // wait with it. A refused submission runs nothing: its recordings stay closed and submittable, // with their pending GPU writes (committed only after an executed submission). if (count && !linear_refresh(queue)) return; + // From here through linear_submitted, a title Wait on this queue (slot 17) on another thread is + // recorded either before this submission's user value or after it, as the desktop queue gets them. + auto order = linear_queue_order(queue, false); // Pin the closed recording and its allocator through submission bookkeeping. AcquireSRWLockExclusive(&draw_lock); AcquireSRWLockExclusive(&allocator_lock); @@ -3723,6 +3736,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) if (!ready.empty()) linear_submitted(queue); ReleaseSRWLockExclusive(&allocator_lock); ReleaseSRWLockExclusive(&draw_lock); + order.release(); check_device("CommandQueue execute", 35); return; } @@ -3735,8 +3749,11 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); auto* queue = static_cast(self->own().real); if (!linear_refresh(queue)) return; - queue->ExecuteCommandLists(count, real.data()); - if (count) linear_submitted(queue); + { + const auto order = linear_queue_order(queue, false); // as in render mode above + queue->ExecuteCommandLists(count, real.data()); + if (count) linear_submitted(queue); + } if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); } @@ -3852,11 +3869,17 @@ u64 __stdcall queue_wait(Wrapper* self, u64 rdx, u64 r8, u64 r9) Wrapper* fence = as_wrapper(reinterpret_cast(rdx)); if (!fence || fence->own().kind != fence_kind) return queue_dynamic<17>(self, rdx, r8, r9); InterlockedExchange(&self->own().queue_wait_seen, 1); - const HRESULT hr = static_cast(self->own().real)->Wait(static_cast(fence->own().real), r8); + auto* queue = static_cast(self->own().real); // X2W_D3D12_LINEAR_BUFFERS: until this wait is reached, a submission whose refresh would have to wait for a - // submission behind it is refused. - if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) - linear_buffers().note_title_wait(static_cast(self->own().real), static_cast(fence->own().real), r8); + // submission behind it is refused. The queue's order lock spans the desktop Wait and its record, so a + // submission on this queue from another thread takes its user value wholly before or after both. + HRESULT hr; + { + const auto order = linear_queue_order(queue, true); + hr = queue->Wait(static_cast(fence->own().real), r8); + if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().note_title_wait(queue, static_cast(fence->own().real), r8); + } static LONG calls; if (first_calls(calls, 2)) log("x2w-d3d12 CommandQueue::slot17(fence=%p, value=0x%llx) -> Wait 0x%08lx", static_cast(fence), r8, diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 04cee16f58..929a7eca87 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -74,6 +74,24 @@ // changed bytes to refresh is never refused; it waits only for refreshes already enqueued, none of which // waits for a blocked queue. // +// The refusal is only as good as the record of which submissions sit behind which title Wait, and a +// title can call slot 17 and ExecuteCommandLists on one queue from two threads at once. Each queue's +// record therefore has an order lock (queue_order), so its title waits and user fence values are +// recorded in the order the desktop queue received them. Slot 17 holds it from the desktop Wait through +// note_title_wait; a submission holds it from the title's ExecuteCommandLists through after_submit's +// user fence Signal. Without it a submission could reach the desktop queue behind a Wait yet take its +// user value before that Wait was recorded, which would then count only later submissions as behind it: +// another queue's refresh would wait for the blocked submission instead of being refused. The lock is +// not held across the refresh (its staging waits and fixture pauses run without it), and nothing that +// waits on the CPU for the GPU runs under it, since a desktop Wait, ExecuteCommandLists and Signal only +// enqueue. The title's Signal (slot 16, or a shape-dispatched Signal) does not take it, so a queue whose +// submission was refused can still signal the fence its blocked peer waits on. The order is: a queue's +// order lock, then draw_lock and allocator_lock (render mode), then mutex_; mutex_ is never held while it +// is taken (queue_order looks the lock up under mutex_ and takes it after releasing mutex_). A refresh +// decision that runs while a Wait on another queue has been enqueued but not yet recorded is still safe: +// that Wait precedes only submissions whose user value is not yet assigned, and a refresh waits only for +// values already assigned. +// // A staging buffer is reused only after the internal fence value of the copy that read it has // completed (title fences do not matter: only that copy reads it). If the internal queue or its fence // cannot be created, the copy cannot order its consumers: placements keep the default backing and @@ -138,9 +156,12 @@ // then catches the read of a released buffer's freed pages) // accept-unsafe-refresh a refresh with no safe completion order is enqueued without waiting for the // blocked queue instead of refusing the submission (its copy may overlap that read) +// unlocked-title-wait queue slot 17 does not take the queue's order lock (a submission on another +// thread can take its user value between the desktop Wait and its record) // x2w_d3d12_linear_buffer_test_pause parks the next refresh at one point (before staging, after // staging, after its copy executed), so a fixture can order two -// threads' refreshes or release a buffer while one is parked +// threads' refreshes or release a buffer while one is parked; +// or the next title Wait between the desktop Wait and its record // x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes // X2W_TEST_LINEAR_STAGING_LIMIT= the staging pool holds n buffers instead of 256 // X2W_TEST_LINEAR_REFRESH_FAIL= staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY @@ -153,6 +174,7 @@ #include #include #include +#include #include #include #include @@ -518,7 +540,8 @@ class LinearBuffers { // After the title's lists were executed on `queue` (a queue wrapper): signals that queue's user fence, // so a later refresh can be ordered behind this submission (the producer wait). Nothing before the // first copied placement: earlier submissions cannot name a copied backing that did not exist yet. - // Not called for a refused submission: its lists did not run, so no user value stands for them. + // Not called for a refused submission: its lists did not run, so no user value stands for them. The + // caller holds the queue's order lock from its ExecuteCommandLists through this call. void after_submit(ID3D12CommandQueue* queue) { std::lock_guard lock(mutex_); @@ -550,9 +573,10 @@ class LinearBuffers { // The title enqueued Wait(fence, value) on `queue` (queue slot 17, already forwarded). Recorded until the // fence reaches the value: a refresh that would have to wait for a submission behind it is refused (see - // the producer wait). + // the producer wait). The caller holds the queue's order lock from the desktop Wait through this call. void note_title_wait(ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64 value) { + pause_at(pause_title_wait); if (!fence || fence->GetCompletedValue() >= value) return; std::lock_guard lock(mutex_); UserQueue* user = user_queue(queue); @@ -568,12 +592,54 @@ class LinearBuffers { } } + // A queue's order lock, held until destroyed or release() (an empty one holds nothing). + class QueueOrder { + public: + QueueOrder() = default; + explicit QueueOrder(SRWLOCK* lock) : lock_(lock) + { + if (lock_) AcquireSRWLockExclusive(lock_); + } + QueueOrder(QueueOrder&& other) noexcept : lock_(other.lock_) { other.lock_ = nullptr; } + QueueOrder(const QueueOrder&) = delete; + QueueOrder& operator=(const QueueOrder&) = delete; + QueueOrder& operator=(QueueOrder&&) = delete; + ~QueueOrder() { release(); } + void release() + { + if (lock_) ReleaseSRWLockExclusive(lock_); + lock_ = nullptr; + } + + private: + SRWLOCK* lock_ = nullptr; + }; + + // Takes the order lock of `queue` (see the order lock above): queue slot 17 (title_wait) across the + // desktop Wait and note_title_wait, a queue wrapper's submission across the title's ExecuteCommandLists + // and after_submit. The caller holds none of this file's locks, nor draw_lock or allocator_lock. A queue + // whose record cannot be stored shares one fallback lock. + [[nodiscard]] QueueOrder queue_order(ID3D12CommandQueue* queue, bool title_wait) + { + // Mutant: slot 17 takes no lock, so a submission on another thread can take its user value between + // the desktop Wait and its record. + if (title_wait && linear_detail::mutant("unlocked-title-wait")) return QueueOrder{}; + SRWLOCK* lock = &order_fallback_; + { + std::lock_guard guard(mutex_); + if (UserQueue* user = user_queue(queue)) lock = &user->order; + } + return QueueOrder(lock); + } + // Fixtures only (x2w_d3d12_linear_buffer_test_pause): the next refresh that reaches `point` sets // `reached`, then waits up to 20 s for `resume`, holding no lock. One shot per arming. The points: // before its staging (after the snapshot), after the title bytes are staged (before its copy is - // executed), and after the copy is executed and signalled (before it is published). Null events - // disarm the point, so a fixture can close its events when no refresh came. - enum PausePoint : unsigned { pause_before_stage, pause_after_stage, pause_after_execute, pause_points }; + // executed), and after the copy is executed and signalled (before it is published). The last point + // parks the next title Wait (queue slot 17) after the desktop Wait and before note_title_wait records + // it, holding that queue's order lock (and nothing else). Null events disarm the point, so a fixture can + // close its events when nothing came. + enum PausePoint : unsigned { pause_before_stage, pause_after_stage, pause_after_execute, pause_title_wait, pause_points }; bool arm_pause(unsigned point, HANDLE reached, HANDLE resume) { if (point >= pause_points) return false; @@ -654,8 +720,10 @@ class LinearBuffers { UINT64 value, before; }; // A queue wrapper's desktop queue, its user fence (signalled after each submission of the title's - // lists) and the title waits it may still sit behind. Kept for the process, as the queues are. + // lists), the title waits it may still sit behind and its order lock (queue_order). Kept for the + // process, as the queues are, at a stable address (users_ is a deque that only grows). struct UserQueue { + SRWLOCK order = SRWLOCK_INIT; ID3D12CommandQueue* queue = nullptr; ID3D12Fence* fence = nullptr; UINT64 value = 0; // the latest submission's user fence value (0: none yet) @@ -1169,7 +1237,8 @@ class LinearBuffers { std::vector> internal_lists_; std::vector> staging_; std::vector heaps_; - std::vector users_; // under mutex_ + std::deque users_; // under mutex_; elements never move (their order locks are held outside it) + SRWLOCK order_fallback_ = SRWLOCK_INIT; // the order lock of a queue whose record could not be stored struct Pause { HANDLE reached = nullptr, resume = nullptr; }; diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index 1cd4571fd0..a735c1ef8d 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -89,6 +89,11 @@ // have to wait for queue 1, behind the unreached fence), so the submission is refused: unsafe refresh // refusals +1 and logged, its result slot keeps P. The title's Signal through queue 2's wrapper (slot // 16) releases queue 1, which reads A; the refused recording submitted again on queue 2 reads B. +// xq.race (copy only) xq.write with queue 1's title Wait and its read of A on two threads: the Wait is parked +// through x2w_d3d12_linear_buffer_test_pause (point 3) after the desktop Wait and before it is recorded, +// and the read is submitted meanwhile. The read is behind the fence on the desktop queue, so queue 2's +// read must still be refused, queue 2 must still signal the fence, queue 1 must read A and the +// resubmission B. A queue that does not complete within 3 s is released by a CPU Signal of the fence. // order (copy only) two threads refresh one buffer, parked through x2w_d3d12_linear_buffer_test_pause: // thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes // first and parks before publishing; A executes (the backing ends with C) and publishes, B publishes @@ -115,12 +120,15 @@ // skip-producer-wait (copy) case war (the refresh's copy lands before queue 1's earlier read), // publish-out-of-order (copy) case order (B's older publish is applied after A's: no further refresh), // copy-after-retire (copy) case retire (no probe before staging: the fault guard catches the read), -// accept-unsafe-refresh (copy) case xq.write (the refresh skips the blocked queue: queue 2 runs and both read B). +// accept-unsafe-refresh (copy) case xq.write (the refresh skips the blocked queue: queue 2 runs and both read B), +// unlocked-title-wait (copy) case xq.race (slot 17 takes no order lock: the read takes its user value before the +// Wait is recorded, queue 2's refresh is accepted and waits for queue 1, and both stay pending until the CPU +// signals the fence). // // Refreshes run on an internal COPY queue that the DLL exports to fixtures // (x2w_d3d12_linear_buffer_internal_queue); cases c, contention and gate2q.held hold it behind a fence // of their own to keep a refresh in flight. Cases order and retire park a refresh on its thread through -// x2w_d3d12_linear_buffer_test_pause. +// x2w_d3d12_linear_buffer_test_pause, and xq.race parks a title Wait. // The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). // X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. // Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter @@ -397,6 +405,17 @@ bool wait_fence(ID3D12Fence* fence, UINT64 value) if (event) CloseHandle(event); return ok; } +// Polls instead of registering an event, for a wait that is expected to time out in a negative control (a +// registration left on a closed handle could later set an unrelated event that reuses it). +bool poll_fence(ID3D12Fence* fence, UINT64 value, DWORD timeout_ms) +{ + const ULONGLONG deadline = GetTickCount64() + timeout_ms; + while (fence->GetCompletedValue() < value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; +} struct Gpu { ComPtr desktop, guest; @@ -1280,6 +1299,106 @@ struct Run { std::to_string(after.unsafe_refresh_refusals - mid.unsafe_refresh_refusals) + (x.info.stale ? ", STALE" : "")); } + // xq.race: xq.write with the title Wait and the read of A on queue 1 issued from two threads at once (the + // review repro). Thread W calls slot 17 Wait(F, 1) on queue 1 and parks through the pause hook (point 3) + // after the desktop Wait and before the wait is recorded. While it is parked, thread S submits the read of A + // on queue 1; the fixture gives it up to 1 s to return before W resumes (S must not take a user value that + // the wait would then be recorded after). Once both returned the CPU writes B and queue 2 submits a read: + // queue 1's read is behind F on the desktop queue, so this refresh has no safe completion order and must be + // refused, as in xq.write (refusals +1, its slot keeps P, queue 2's own fence is reached). The title's + // Signal(F, 1) through queue 2's wrapper must succeed and release queue 1, which reads A; the refused + // recording submitted again then reads B. Every wait is bounded: when queue 2 or queue 1 does not complete, + // the fixture signals F from the CPU (the same fence) so both drain, and the row fails. + void case_xq_race(Pool& pool) + { + const char* name = "xq.race"; + Lane q2; + Memory memory; + ComPtr fence; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A) || + FAILED(static_cast(invoke(gpu.guest.Get(), 36, 0, D3D12_FENCE_FLAG_NONE, arg(&__uuidof(ID3D12Fence)), + arg(fence.GetAddressOf())))) || !fence) + return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + if (!gpu.fill_output(1, P) || !gpu.fill_output(2, P)) return row(pool, name, false, "result slot could not be filled"); + HANDLE parked = CreateEventW(nullptr, TRUE, FALSE, nullptr), go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE s_returned = CreateEventW(nullptr, TRUE, FALSE, nullptr); + const auto close_events = [&] { + x2w_d3d12_linear_buffer_test_pause(3, nullptr, nullptr); // disarm, if no wait reached it + for (HANDLE h : {parked, go, s_returned}) + if (h) CloseHandle(h); + }; + if (!parked || !go || !s_returned || !x2w_d3d12_linear_buffer_test_pause(3, parked, go)) { + close_events(); + return row(pool, name, false, "pause hook not available"); + } + const X2wLinearBufferTotals before = totals(); + HRESULT wait_hr = E_FAIL; + std::thread tw([&] { wait_hr = static_cast(invoke(gpu.guest_queue.Get(), 17, arg(fence.Get()), 1)); }); + const bool w_parked = WaitForSingleObject(parked, 5000) == WAIT_OBJECT_0; + UINT64 v1 = 0; + std::thread ts([&] { + v1 = l1.submit(); // queue 1: the unchanged read of A, behind F on the desktop queue + SetEvent(s_returned); + }); + // With the order lock S cannot return while W is parked; without it, it returns at once. + const bool s_returned_while_parked = WaitForSingleObject(s_returned, 1000) == WAIT_OBJECT_0; + SetEvent(go); + tw.join(); + ts.join(); // bounded: W's park ends after 20 s at most, and S waits only for W + close_events(); + write(memory.buffer(), r0, B, words); + const UINT64 v2 = l2.submit_on(q2); // needs a refresh of B, which would wait for queue 1: must be refused + const bool q2_progress = poll_fence(q2.fence.Get(), v2, 3000); + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + const X2wLinearBufferTotals mid = totals(); + const Tally refused = tally(gpu.read_output(2).data(), r0 / 4, key); + // The title's Signal through queue 2's wrapper releases queue 1. + const HRESULT signal_hr = static_cast(invoke(q2.guest.Get(), 16, arg(fence.Get()), 1)); + const bool q1_done = poll_fence(gpu.done.Get(), v1, 3000); + const UINT64 refusals = mid.unsafe_refresh_refusals - before.unsafe_refresh_refusals; + std::string text = std::string("W ") + (w_parked ? "parked" : "DID NOT PARK") + " between its desktop Wait and its record (slot 17 -> " + + hex(wait_hr) + "); S's read of A on queue 1 " + + (s_returned_while_parked ? "RETURNED WHILE W WAS PARKED" : "waited for W") + "; after the CPU wrote B, queue 2's read was " + + (refusals == 1 ? "refused" : "NOT REFUSED") + " (refusals +" + std::to_string(refusals) + "), its slot " + + refused.text() + " (expected P), queue 2 " + (q2_progress ? "progressed" : "STUCK") + + "; the title's Signal on queue 2 (slot 16) -> " + hex(signal_hr) + ", queue 1 " + + (q1_done ? "completed" : "STILL PENDING"); + if (!q2_progress || !q1_done) { + // Cleanup: the CPU reaches F (fence slot 10), so both queues drain before the next case. + invoke(fence.Get(), 10, 1); + const bool drained = wait_fence(gpu.done.Get(), v1) && wait_fence(q2.fence.Get(), v2); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + return row(pool, name, false, + text + "; after a CPU Signal of F both " + (drained ? "drained" : "STILL DID NOT DRAIN") + ": queue 1 read " + t1.text() + + ", queue 2 read " + t2.text()); + } + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key); + // A later, safe submission: the refused recording again, with no submission behind a title Wait. + const UINT64 v3 = l2.submit_on(q2); + if (!wait_fence(q2.fence.Get(), v3)) return row(pool, name, false, text + "; fence timeout (queue 2, resubmission)"); + const Tally t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = w_parked && SUCCEEDED(wait_hr) && q1_pending && q2_progress && refusals == 1 && refused.count[P] == words && + SUCCEEDED(signal_hr) && t1.count[A] == words && t2.count[B] == words && + after.unsafe_refresh_refusals == mid.unsafe_refresh_refusals && !x.info.stale && x.info.refresh_failures == 0; + row(pool, name, pass, + text + " and read " + t1.text() + " (expected A); the refused recording resubmitted on queue 2 read " + t2.text() + + " (expected B), refusals +" + std::to_string(after.unsafe_refresh_refusals - mid.unsafe_refresh_refusals) + + (x.info.stale ? ", STALE" : "")); + } + // order: two threads' refreshes of one buffer, driven through the pause hook. Thread A stages C and parks // before its copy is executed; the CPU writes D; thread B stages D, executes its copy first (the lower // internal value) and parks before publishing; A then executes (the higher value: the backing ends with C) @@ -1754,6 +1873,7 @@ int main(int argc, char** argv) run.case_gpuw_discard(pool); run.case_war(pool); run.case_xq_write(pool); + run.case_xq_race(pool); run.case_order(pool); run.case_retire(pool); // last: it frees the pages of one buffer } @@ -1815,7 +1935,8 @@ int main(int argc, char** argv) : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" : mutant == "refresh-gpu-written" ? "gpuw" : mutant == "gpuw-at-record" ? "gpuw.discard" : mutant == "skip-producer-wait" ? "war" : mutant == "publish-out-of-order" ? "order" - : mutant == "copy-after-retire" ? "retire" : mutant == "accept-unsafe-refresh" ? "xq.write" : nullptr; + : mutant == "copy-after-retire" ? "retire" : mutant == "accept-unsafe-refresh" ? "xq.write" + : mutant == "unlocked-title-wait" ? "xq.race" : nullptr; if (!target) return 2; unsigned targeted = 0, failed = 0; for (const auto& [name, pass] : run.results)