diff --git a/CMakeLists.txt b/CMakeLists.txt index eb977a69d6..d3cc8761ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2638,6 +2638,42 @@ 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, 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). 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 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 (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) +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 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() +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:unlocked_title_wait) + 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 7c81370a70..beac00ff6a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9853,6 +9853,96 @@ 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. 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; +- 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`), `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 | +|---|---| +| 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. 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. | +| 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. | +| 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. | +| 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. + +| 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; 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 | +| `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. + +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). +- `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. +- `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). + +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; 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. + +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) 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 673534dbfe..65f76efd09 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1343,6 +1343,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 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 | @@ -2957,6 +2958,50 @@ 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 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 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. + - **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. + - 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 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; + - 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 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. 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. + ## 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 06a1eb1c16..db590c6e08 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" @@ -962,6 +963,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. @@ -994,6 +1002,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)); @@ -1593,6 +1603,40 @@ 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 || !w->own().real || + 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 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), 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 && + 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) +{ + 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) { @@ -3598,6 +3642,32 @@ 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 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. 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) +{ + 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) +{ + 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) { @@ -3608,6 +3678,14 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) // 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. 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); @@ -3618,7 +3696,6 @@ 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) { const UINT ready_count = static_cast(native_lists.size()); @@ -3656,8 +3733,10 @@ 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); + order.release(); check_device("CommandQueue execute", 35); return; } @@ -3668,7 +3747,13 @@ 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); + if (!linear_refresh(queue)) return; + { + 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); } @@ -3784,7 +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. 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, @@ -4307,6 +4402,40 @@ 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); + if (release_retired_enabled()) w->own().retire_never = static_cast(RetireNever::buffer); + 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) { @@ -4379,6 +4508,37 @@ 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)) { + const bool uav = (sanitized(*desc).Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; + ID3D12Resource* resource = nullptr; + bool shared = false; + x2w_budget::Ticket* linear_heap_budget = nullptr; + // 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, + 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()); + // 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), + " (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; HRESULT hr = S_OK; @@ -4427,34 +4587,11 @@ 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; - Wrapper* w = wrap(resource, resource_kind); - if (release_retired_enabled()) w->own().retire_never = static_cast(RetireNever::buffer); - 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; + 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); } #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..929a7eca87 --- /dev/null +++ b/src/startup_stubs/linear_buffer_backing.h @@ -0,0 +1,1256 @@ +#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 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. +// +// 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 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. A submission whose recording writes a copied buffer +// (gpu_written, below) is ordered behind that buffer's earlier refreshes by the same Wait. +// +// 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. +// +// 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. +// +// 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 +// 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 +// 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 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. +// +// 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. +// +// 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 +// 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 +// 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 +// 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 +// 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) +// 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; +// 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 + +#include +#include + +#include +#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" +#include "startup_stubs/resource_budget.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 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; + 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{}; + 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, 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. + 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; + } + + // 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"); } + + // 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 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, x2w_budget::Ticket** backing_budget, X2wLinearBufferInfo* report) + { + *out = nullptr; + *shared = false; + *backing_budget = nullptr; + 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, + backing_budget); + } + 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 (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 + : 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_shared(); + 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 (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)) { + if (resource) resource->Release(); + *backing_budget = nullptr; + record.info.path = kept_default_path; + record.info.refusal_hr = hr; + record.info.backing = nullptr; + if (report) *report = record.info; + return hr; + } + 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&) { + } + } + + // 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; + 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) + { + 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); + } + + // 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. 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 (and the refusal + // decision next to them). + [[nodiscard]] bool before_submit(ID3D12CommandQueue* queue) + { + struct Work { + ID3D12Resource* dest; + std::shared_ptr copy; + const unsigned char* source; + 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; + { + std::lock_guard lock(mutex_); + ++totals_.submissions; + bool any = false; + for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; + 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; + 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; + 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 { + work.push_back({resource, copy, source, first, last - first}); + } catch (const std::bad_alloc&) { + refresh_failed(resource, *copy, E_OUTOFMEMORY); + } + } + } + // This submission's own refreshes, including those of a buffer the title released meanwhile. + 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; + { + 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; + } + 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)); + } + 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. The + // caller holds the queue's order lock from its ExecuteCommandLists through this call. + 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))) { + // 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; + ++user->value; + } + + // 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 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); + if (!user) return; + prune_waits(*user); + try { + user->waits.push_back({fence, value, user->value + 1}); + fence->AddRef(); + } catch (const std::bad_alloc&) { + // 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; + } + } + + // 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). 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; + 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() + { + std::lock_guard lock(mutex_); + if (internal_queue_) internal_queue_->AddRef(); + return internal_queue_; + } + + 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->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; + } + 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, 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; + }; + struct Record { + X2wLinearBufferInfo info{}; + std::shared_ptr copy; // shared: a submission's snapshot outlives a discard + }; + struct Staging { + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + UINT64 bytes = 0, id = 0; + 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 { + ID3D12CommandAllocator* allocator = nullptr; + 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), 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) + 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; + 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() + { + 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; + } + + // 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) + { + 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, 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) { + 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, 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) + { + 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; + 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; + out->emplace_back(user.fence, user.value); + } + return safe; + } + + 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, x2w_budget::Ticket** budget) + { + 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, x2w_budget::backing_heap(heap, 0)}); + } catch (const std::bad_alloc&) { + heap->Release(); + return E_OUTOFMEMORY; + } + 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)); + 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; + } + + // The internal refresh queue and its fence, created once (under mutex_, from place()). + HRESULT internal_ready(ID3D12Device* device) + { + 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_; + } + queue->SetName(L"x2w linear-buffer refresh"); + internal_device_ = device; + internal_queue_ = queue; + internal_fence_ = fence; + return S_OK; + } + + // 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). *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, ID3D12CommandQueue* queue, bool* refused) + { + pause_at(pause_before_stage); + 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); + // 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; + } + if (any_staged) pause_at(pause_after_stage); + 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_); + // 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_); + 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(); + } + 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_; + } + } + } + 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), + // 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; + 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; + 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 && 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 && (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; + copy.last_staging = w.staging->id; + ++totals_.refreshes; + totals_.bytes_copied += w.bytes; + } + return value; + } + + static bool complete(const Staging& staging) + { + return staging.value == 0 || + (staging.value != ~UINT64{0} && staging.fence && staging.fence->GetCompletedValue() >= staging.value); + } + + // 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(UINT64 bytes, const std::vector& taken, Staging** out) + { + 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) { + 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 (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; + 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; + } + return DXGI_ERROR_WAS_STILL_DRAWING; + } + + // Called without mutex_ after acquire_staging reserved a place in the pool (creating_). + HRESULT create_staging(UINT64 bytes, Staging** out) + { + auto staging = std::make_unique(); + 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; + // 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); + std::lock_guard lock(mutex_); + --creating_; + if (FAILED(hr)) { + if (staging->buffer) staging->buffer->Release(); + return hr; + } + staging->mapped = static_cast(mapped); + 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_.back().get(); + return S_OK; + } + + // 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 = 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(); + 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; + } + auto list = std::make_unique(); + HRESULT hr = internal_device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&list->allocator)); + if (SUCCEEDED(hr)) + 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(); + return hr; + } + list->value = ~UINT64{0}; + std::lock_guard lock(mutex_); + try { + internal_lists_.push_back(std::move(list)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + *out = internal_lists_.back().get(); + return S_OK; + } + + // The submission runs without this buffer's refresh: its backing keeps the last upload. + void refresh_failed(ID3D12Resource* resource, Copied& copy, HRESULT 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_; + std::unordered_map records_; + 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_; + 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; + }; + 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; + 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, unsafe_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..107ca76e28 --- /dev/null +++ b/src/startup_stubs/linear_buffer_report.h @@ -0,0 +1,39 @@ +#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, 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: 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 submitted copy wrote it; it is no longer refreshed +}; + +struct X2wLinearBufferTotals { + 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 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 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 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/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 5ed62c7248..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,6 +165,25 @@ 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 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) + 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. x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& to, const CopyEndpoint& from, bool sync) { @@ -218,6 +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(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 && @@ -247,6 +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(self, 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 new file mode 100644 index 0000000000..a735c1ef8d --- /dev/null +++ b/tests/linear_buffer_backing_check.cpp @@ -0,0 +1,1952 @@ +// 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: 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 +// 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: +// 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): +// 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 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 +// 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: 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. +// 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 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. +// 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, 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). 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 +// 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 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. +// 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 +// 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 +// 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, 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), +// 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), +// 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, 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 +// reports no existing-heap support. +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#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_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); +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); } +)"; + +// 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, contention, lease }; +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"; + case Path::untracked: return "untracked"; + case Path::stale: return "stale"; + case Path::contention: return "contention"; + default: return "lease"; + } +} + +// ---- 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{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; + 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 ---- + +// 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; +} +// 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; + 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; + } + + // 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() + { + if (!gate_armed) ++gate_value; + gate_armed = true; + } + void open_gate() + { + 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; + 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; + } + // 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; + 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, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + gpu = &g; + 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[]{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())))) + 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); + } + // 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) + { + 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; + } + // 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() + { + 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; + const void* address = nullptr; + ComPtr wrapper; + ComPtr backing; + X2wLinearBufferInfo info{}; + bool linear = false; +}; + +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]); + 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 == 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 + 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; + 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; } + // 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; + } + // 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()); + 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 false; // untracked: kept_ok decides + } + } + // 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 || path == Path::untracked) && !default_aliases(pool)) 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); + 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); + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; GPU read " + t.text(); + 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 || path == Path::untracked) 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); + // 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()); + 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"); + // 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); + } + + // 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(); + // 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]; + 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. + 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"; + 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"); + } + + // 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")); + } + + // 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" : "")); + } + } + + // 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. + // 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)); + } + + // 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 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"; + 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(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(); // queue 1, behind F + write(memory.buffer(), r0, B, words); + 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; + 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 (!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 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 ") + (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" : "")); + } + + // 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) + // 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) + { + 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) + { + 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; + 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) + { + 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 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 that staging buffer's copy: 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); + // 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(); + 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[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; + 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 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]; + 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_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"); + SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr + : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention || + path == Path::lease ? L"copy" : L"1"); + 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. + 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'; + 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, 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; + } + if (path == Path::contention) { + 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); + 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.case_gate2q(pool, false); + run.case_gate2q(pool, true); + 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_xq_race(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); + } + 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, consumer waits %llu, producer waits %llu " + "(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), + 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.refresh_failures), + static_cast(t.consumer_waits), static_cast(t.producer_waits), + 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()); + { + 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::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 && 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)); + } + 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" : mutant == "refusal-silent" ? "b" + : 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" + : mutant == "unlocked-title-wait" ? "xq.race" : 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; +}