diff --git a/CMakePresets.json b/CMakePresets.json index e649592f3b..473532ee8e 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,6 +29,7 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", + "startup_fence_values", "startup_fence_values_controlled", "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check", "startup_present_planes", "startup_present_composite_warp", "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", @@ -49,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_fence_values(_controlled|_stale_control)?_warp|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference)$" } } }, diff --git a/docs/experiments/fence-cpu-signal-values.md b/docs/experiments/fence-cpu-signal-values.md new file mode 100644 index 0000000000..2d092cb301 --- /dev/null +++ b/docs/experiments/fence-cpu-signal-values.md @@ -0,0 +1,163 @@ +# CPU fence signal values + +The source-built `startup_fence_values` fixture compares a shim fence's method +result and cached completion word with its underlying desktop `ID3D12Fence`. +It signals `9`, `2`, `0`, then `7` on the CPU. Each successful CPU signal must +publish the observed desktop value synchronously, including a lower value and +zero. The cached word is read before the shim method, so a method read cannot +hide a stale word. + +The public [ID3D12Fence::Signal contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12fence-signal) +allows a CPU signal to set the completion value. The +[fence synchronization guidance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/user-mode-heap-synchronization) +also explicitly permits rewinding a fence. The shim previously applied an +atomic maximum and published the requested value even if the desktop call +failed. It now updates the cached word from the desktop observation after a +successful CPU signal; a failed call leaves the word unchanged. +Each fence serializes the native CPU signal, desktop observation and cached +publication with a fence-local SRW lock. `fence_reached` takes the same writer +lock and still applies an atomic maximum for queue callbacks; it does not +implement queued rewinds. Slot 8 keeps its aligned, lock-free 64-bit cached +read, matching the direct read through slot 12. Readers may see the previous +published value while a signal is in progress. + +The writer lock follows the serialization fix contributed in +[PR #3350](https://github.com/R0Y00/Xbox2Windows/pull/3350), whose commits are +preserved in this branch. The regression below addresses the controlled +interleaving requested in the review of +[PR #3279](https://github.com/R0Y00/Xbox2Windows/pull/3279). + +## Controlled concurrent publication + +The production fixture retains 128 pairs of barrier-started CPU signals as a +stress check. A separate `startup_fence_values_controlled` executable uses a +test-only build of the same shim sources, isolated under `fence-test-controls/`: + +1. Caller A executes desktop `Signal(1)`, captures `GetCompletedValue() == 1`, + then pauses before publishing the captured value. +2. Caller B enters the shim with value 2. The hook acknowledges its attempt + immediately before the writer lock, and the fixture allows 250 ms for it + to complete while A remains paused. +3. The fixture releases A regardless of whether B completed, waits for both + callers with a bound, then reads the cached address before slot 8. +4. With serialization, B waits for A and the final native, method and address + values must all be 2. With serialization disabled in the test DLL, B + completes while A is paused, then A publishes its stale 1 over B's 2. + +The `--stale-control` mode succeeds only when that exact stale outcome occurs: +native 2, method 1, address 1, both calls successful, all scheduling handshakes +completed, and B finished during the pause. Its printed `FAIL` describes the +deliberately broken invariant; the final line confirms the negative control +reproduced it. Missing handshakes, timeouts and unrelated errors fail the test. +Each event wait is bounded; a caller that cannot join within the final bound +terminates the fixture with a failure code. The test never requires B to +finish before releasing A in the fixed case. + +`X2W_FENCE_TEST_CONTROLS` is a compile definition on the separate fixture DLL +only. The production DLL exports no scheduling hook and has no unlocked mode. + +## Reproduction + +From an x64 Windows developer PowerShell at the repository root: + +```powershell +. .\tools\dev.ps1 +cmake --preset dev -DINTAKE_PYTHON=C:/path/to/python.exe +cmake --build --preset dev --target startup_fence_values startup_fence_values_controlled startup_queue_wait --parallel 4 +ctest --preset dev --no-tests=error -V -R '^startup_(fence_values(_controlled|_stale_control)?_(warp|hardware)|queue_wait_warp)$' +cmake --preset release -DINTAKE_PYTHON=C:/path/to/python.exe +cmake --build --preset release --target startup_fence_values startup_fence_values_controlled startup_queue_wait --parallel 4 +ctest --preset release --no-tests=error -V -R '^startup_(fence_values(_controlled|_stale_control)?_(warp|hardware)|queue_wait_warp)$' +``` + +The test registrations enable `X2W_D3D12_PERMISSIVE`, `X2W_D3D12_LIST_NOOP`, +`X2W_D3D12_RENDER`, and `X2W_D3D12_DEBUG`. The CPU-only fixture creates no +command queue and submits no GPU commands. Hardware enumeration returns skip +code 77 if no suitable adapter is available; a skip is not a pass. +The `pr` build preset builds both fence executables; its test filter includes +the production, controlled and negative-control WARP cases. Run GPU tests +serially. + +## Historical sequential result (2026-11-28) + +Measured on 2026-11-28 against base commit +`240e0fb9c460f24d51683abe2d4cce2800b136c1`, with the focused CPU fix applied, +using MSVC 19.43.34810, x64 Debug, and Windows 10 Pro 10.0.19045. The D3D12 +debug layer reported enabled in every run. + +| Adapter | DXGI driver version integer | CPU signals | Result | +| --- | --- | --- | --- | +| Microsoft Basic Render Driver (WARP) | 2814751014983330 | 9, 2, 0, 7 | Native, method, and cached word agree for all four | +| NVIDIA GeForce RTX 4070 Ti SUPER | 9007199255731302 | 9, 2, 0, 7 | Native, method, and cached word agree for all four | + +On the unmodified base, WARP reported native values `9, 2, 0, 7`, but the shim +method and cached word remained `9, 9, 9, 9`. With the fix, both registered fence +tests passed. The existing `startup_queue_wait_warp` test also passed. These +results cover only the sequential CPU signal contract. They predate the +writer lock and both concurrent regressions. A failed desktop signal was not +induced in this run. + +## Concurrent regression result (2026-11-30) + +Code revision `ed554820bed30737fba887ee991611b8fd761e92`, based on main +`44a3ad5aa9c679cc039b8cb8275738dd6e4405d2`, was tested on Windows 10 Pro +10.0.19045 with MSVC 19.43.34810, x64 Debug and Release. Documentation-only +updates follow that code revision. The debug layer was enabled in every case. + +| Adapter | DXGI driver version integer | Configurations | Controlled fixed result | Unlocked negative control | +| --- | --- | --- | --- | --- | +| Microsoft Basic Render Driver (WARP) | 2814751014983330 | Debug, Release | B blocked while A paused; desktop/method/address = 2/2/2 | B completed while A paused; desktop/method/address = 2/1/1 | +| NVIDIA GeForce RTX 4070 Ti SUPER | 9007199255731302 | Debug, Release | B blocked while A paused; desktop/method/address = 2/2/2 | B completed while A paused; desktop/method/address = 2/1/1 | + +Each configuration passed all 7 selected checks, with zero skips: the production +fixture, controlled fixture and exact negative control on both adapters, plus +`startup_queue_wait_warp`. The production and controlled fixtures also passed +the 128-pair stress check and the sequential `9, 2, 0, 7` check. A failed native +`Signal` was not induced; that HRESULT guard remains a code-reviewed path. + +`dumpbin /exports` confirmed the scheduling export is absent from the production +DLL and present in the isolated fixture DLL. Parsing +`ctest --preset pr --show-only=json-v1` without a command-line filter confirmed +all three WARP cases are selected by the PR preset. Local logs are generated +under `out/`, not committed. These source-built tests establish the CPU fence +behavior under test; they do not measure full startup or frame rate. + +## Separate queued rewind limitation + +The same fixture provides an optional diagnostic, deliberately excluded from +the passing CTest registrations: + +```powershell +$env:X2W_D3D12_PERMISSIVE = '1' +$env:X2W_D3D12_LIST_NOOP = '1' +$env:X2W_D3D12_RENDER = '1' +$env:X2W_D3D12_DEBUG = '1' +.\out\build\dev\startup_fence_values.exe warp --queue-rewind +``` + +After the CPU sequence ends at `7`, the diagnostic blocks a queue, enqueues +`Signal(3)` and an independent marker, then releases the blocker. The marker +proves that the queue reached its signal. The diagnostic polls only the cached +word before reading the shim method. On WARP with this CPU-only fix, the desktop +fence became `3` while the method and cached word remained `7`, and the diagnostic +returned failure as expected for this unresolved behavior. +The diagnostic was repeated on 2026-11-30 with the writer-lock revision above, +Release and WARP: desktop 3, method 7, address 7, exit 1. This is an expected +diagnostic failure and is not counted among the 7 passing checks. + +Replacing the queued callback's atomic maximum with an assignment is insufficient: +an event registered for target `3` is already satisfied while the fence is `7`, +before the queue executes the lower signal. Sampling the desktop fence in that +early callback is also insufficient. Queued completion publication needs an +independent queue-order completion mechanism, such as a private monotonic marker. +That behavior is outside this CPU signal fix. + +Mixed CPU/queue signals have another unresolved interleaving: a queue callback +can retain an earlier larger target, run after a successful CPU rewind, then +publish that old target over the CPU value through `fence_reached`. This +interleaving was identified from the callback path and was not induced in the +CPU-only tests. A writer lock prevents overlapping publications but cannot +establish the queue event's true completion order. The passing CPU tests +create no queue and make no claim about pending callbacks or concurrent CPU +and queue producers. These remaining cases are tracked in +[issue #3280](https://github.com/R0Y00/Xbox2Windows/issues/3280). diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 652f22f90b..1fbe39a9dc 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -195,6 +195,7 @@ struct alignas(16) WrapperOwn { // Fence: the completed value the title polls through the address from slot 12 (monitorx/mwaitx). // Updated when the fence is signaled; GPU work counts as complete at once while lists are no-ops. volatile LONG64 completed; + SRWLOCK fence_lock; // Serializes CPU/native fence observations and publication to the title address. bool list_open; // CommandList (render mode): recording between reset and close x2w_upload::Arena* list_uploads; // Current recording's allocations, owned by its desktop allocator. ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. @@ -250,12 +251,14 @@ struct Wrapper { void fence_reached(Wrapper* fence, std::uint64_t value) noexcept { + AcquireSRWLockExclusive(&fence->own().fence_lock); LONG64 seen = fence->own().completed; while (static_cast(seen) < value || seen == -1) { const LONG64 previous = InterlockedCompareExchange64(&fence->own().completed, static_cast(value), seen); if (previous == seen) break; seen = previous; } + ReleaseSRWLockExclusive(&fence->own().fence_lock); } // Descriptor heaps created over title memory: title CPU handles in [title, title + bytes) map to @@ -5138,14 +5141,50 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } // Fence slot 10, desktop Signal(value) (also used by the DirectStorage stand-in's EnqueueSignal). +#ifdef X2W_FENCE_TEST_CONTROLS +// Only the separate fixture DLL compiles these controls. Configured before starting callers, +// cleared after joining them; the production shim has neither hooks nor an unlocked mode. +using FenceSignalHook = void (WINAPI*)(void*, UINT64, BOOL); +struct FenceSignalControl { + FenceSignalHook hook{}; + void* context{}; + bool unlocked{}; +} fence_signal_control; +extern "C" __declspec(dllexport) void x2w_d3d12_fence_signal_control( + FenceSignalHook hook, void* context, BOOL unlocked) +{ + fence_signal_control = {hook, context, unlocked != FALSE}; +} +#endif HRESULT __stdcall fence_signal(Wrapper* self, UINT64 value) { - const HRESULT hr = static_cast(self->own().real)->Signal(value); - fence_reached(self, value); + auto* fence = static_cast(self->own().real); +#ifdef X2W_FENCE_TEST_CONTROLS + const bool serialize = !fence_signal_control.unlocked; + if (fence_signal_control.hook) fence_signal_control.hook(fence_signal_control.context, value, FALSE); +#else + constexpr bool serialize = true; +#endif + if (serialize) AcquireSRWLockExclusive(&self->own().fence_lock); + const HRESULT hr = fence->Signal(value); + // Serialize Signal, observation and publication against other writers on this wrapper. + // A CPU Signal may rewind, including to zero; a failed call leaves the shadow unchanged. + if (SUCCEEDED(hr)) { + const UINT64 observed = fence->GetCompletedValue(); +#ifdef X2W_FENCE_TEST_CONTROLS + if (fence_signal_control.hook) fence_signal_control.hook(fence_signal_control.context, value, TRUE); +#endif + InterlockedExchange64(&self->own().completed, static_cast(observed)); + } + if (serialize) ReleaseSRWLockExclusive(&self->own().fence_lock); return hr; } // Fence slot 8, desktop GetCompletedValue(). -UINT64 __stdcall fence_completed_value(Wrapper* self) { return static_cast(self->own().completed); } +UINT64 __stdcall fence_completed_value(Wrapper* self) +{ + // Aligned 64-bit load on x64, matching the lock-free title read through slot 12. + return static_cast(self->own().completed); +} // Fence slot 12 (Xbox order): (value, ptr, flag) -> address of the completed value, which the title // reads and waits on directly; all ones there means device removed. volatile LONG64* __stdcall fence_completed_address(Wrapper* self, u64 value, u64 r8, u64 r9) diff --git a/tests/cmake/startup_fence_values.cmake b/tests/cmake/startup_fence_values.cmake new file mode 100644 index 0000000000..76b5ca7c78 --- /dev/null +++ b/tests/cmake/startup_fence_values.cmake @@ -0,0 +1,37 @@ +add_executable(startup_fence_values tests/startup_fence_values.cpp) +target_compile_features(startup_fence_values PRIVATE cxx_std_17) +target_link_libraries(startup_fence_values PRIVATE d3d12_xs_shim d3d12 dxgi) + +# Compile the real shim with hooks into a separate directory; production exports no hook +# and cannot bypass its writer lock. Keep its .def library name and isolate the import lib too. +get_target_property(fence_shim_sources d3d12_xs_shim SOURCES) +add_library(d3d12_fence_test_controls SHARED ${fence_shim_sources}) +foreach(property IN ITEMS INCLUDE_DIRECTORIES COMPILE_DEFINITIONS COMPILE_FEATURES + COMPILE_OPTIONS LINK_LIBRARIES LINK_OPTIONS MSVC_RUNTIME_LIBRARY) + get_target_property(fence_property d3d12_xs_shim ${property}) + if(fence_property) + set_property(TARGET d3d12_fence_test_controls PROPERTY ${property} "${fence_property}") + endif() +endforeach() +target_compile_definitions(d3d12_fence_test_controls PRIVATE X2W_FENCE_TEST_CONTROLS) +set_target_properties(d3d12_fence_test_controls PROPERTIES OUTPUT_NAME d3d12_xs + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fence-test-controls" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fence-test-controls" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fence-test-controls") +add_executable(startup_fence_values_controlled tests/startup_fence_values.cpp) +target_compile_features(startup_fence_values_controlled PRIVATE cxx_std_17) +target_compile_definitions(startup_fence_values_controlled PRIVATE X2W_FENCE_TEST_CONTROLS) +target_link_libraries(startup_fence_values_controlled PRIVATE d3d12_fence_test_controls d3d12 dxgi) +set_target_properties(startup_fence_values_controlled PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fence-test-controls") +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_fence_values_${backend} COMMAND startup_fence_values ${backend}) + add_test(NAME startup_fence_values_controlled_${backend} COMMAND startup_fence_values_controlled ${backend}) + # This mode succeeds only on the exact stale desktop=2/method=1/address=1 outcome, + # with both callers successful and every scheduling handshake completed in time. + add_test(NAME startup_fence_values_stale_control_${backend} + COMMAND startup_fence_values_controlled ${backend} --stale-control) + set_tests_properties(startup_fence_values_${backend} startup_fence_values_controlled_${backend} + startup_fence_values_stale_control_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() diff --git a/tests/startup_fence_values.cpp b/tests/startup_fence_values.cpp new file mode 100644 index 0000000000..abc76f20bd --- /dev/null +++ b/tests/startup_fence_values.cpp @@ -0,0 +1,273 @@ +// Compare the console fence's method and completed-value address with the desktop fence. +// Signals deliberately decrease the value: a fence is not an atomic maximum. +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +#ifdef X2W_FENCE_TEST_CONTROLS +extern "C" __declspec(dllimport) void x2w_d3d12_fence_signal_control( + void (WINAPI*)(void*, UINT64, BOOL), void*, BOOL); +#endif + +namespace { +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + // The temporary private-data bridge is also used by startup_resource_budget. + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool wait_value(ID3D12Fence* fence, UINT64 value) +{ + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return done && fence->GetCompletedValue() == value; +} + +bool shadow_is(volatile LONG64* shadow, UINT64 value) +{ + const ULONGLONG end = GetTickCount64() + 10000; + do { + if (static_cast(*shadow) == value) return true; + Sleep(1); + } while (GetTickCount64() < end); + return false; +} + +#ifdef X2W_FENCE_TEST_CONTROLS +struct SignalSchedule { + HANDLE captured = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE attempting = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE first_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE second_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + std::atomic timed_out{}; + ~SignalSchedule() + { + for (HANDLE event : {captured, release, attempting, first_done, second_done}) + if (event) CloseHandle(event); + } + static void WINAPI hook(void* context, UINT64 value, BOOL before_publish) + { + auto& schedule = *static_cast(context); + if (value == 1 && before_publish) { + SetEvent(schedule.captured); + if (WaitForSingleObject(schedule.release, 5000) != WAIT_OBJECT_0) + schedule.timed_out = true; + } else if (value == 2 && !before_publish) { + SetEvent(schedule.attempting); + } + } +}; + +bool controlled_signals(IUnknown* fence, ID3D12Fence* real, volatile LONG64* shadow, bool unlocked) +{ + SignalSchedule schedule; + if (!schedule.captured || !schedule.release || !schedule.attempting || + !schedule.first_done || !schedule.second_done || FAILED(invoke(fence, 10, UINT64{0}))) + return false; + x2w_d3d12_fence_signal_control(&SignalSchedule::hook, &schedule, unlocked); + HRESULT first = E_PENDING, second = E_PENDING; + std::thread one([&] { + first = invoke(fence, 10, UINT64{1}); + SetEvent(schedule.first_done); + }); + const bool captured = WaitForSingleObject(schedule.captured, 5000) == WAIT_OBJECT_0; + std::thread two([&] { + second = invoke(fence, 10, UINT64{2}); + SetEvent(schedule.second_done); + }); + const bool attempting = WaitForSingleObject(schedule.attempting, 5000) == WAIT_OBJECT_0; + // With the writer lock B must wait; without it B finishes while A holds observation 1. + // Never require B to finish before releasing A: that would deadlock the correct version. + const DWORD second_while_paused = WaitForSingleObject(schedule.second_done, 250); + SetEvent(schedule.release); + const HANDLE done[]{schedule.first_done, schedule.second_done}; + if (WaitForMultipleObjects(2, done, TRUE, 5000) != WAIT_OBJECT_0) { + std::puts("FAIL: controlled CPU callers did not finish within the bound"); + std::fflush(stdout); + std::_Exit(6); // Do not hang in join if a future lock regression deadlocks. + } + one.join(); + two.join(); + x2w_d3d12_fence_signal_control(nullptr, nullptr, FALSE); + const UINT64 native = real->GetCompletedValue(); + const UINT64 direct = static_cast(*shadow); // Address first, before slot 8. + const UINT64 observed = invoke(fence, 8); + const bool schedule_ok = captured && attempting && !schedule.timed_out && + SUCCEEDED(first) && SUCCEEDED(second); + const bool correct = schedule_ok && second_while_paused == WAIT_TIMEOUT && + native == 2 && direct == 2 && observed == 2; + const bool stale = schedule_ok && second_while_paused == WAIT_OBJECT_0 && + native == 2 && direct == 1 && observed == 1; + std::printf("controlled CPU signals: desktop=%llu method=%llu address=%llu " + "second_while_paused=%s schedule=%s %s\n", native, observed, direct, + second_while_paused == WAIT_OBJECT_0 ? "completed" : + second_while_paused == WAIT_TIMEOUT ? "blocked" : "wait-failed", + schedule_ok ? "OK" : "FAIL", correct ? "PASS" : "FAIL"); + if (unlocked) + std::printf("unlocked negative control: %s\n", stale ? "stale publication reproduced" : "FAIL"); + return unlocked ? stale : correct; +} +#endif +} + +int main(int argc, char** argv) +{ + bool stale_control = false; +#ifdef X2W_FENCE_TEST_CONTROLS + stale_control = argc == 3 && !std::strcmp(argv[2], "--stale-control"); +#endif + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "--queue-rewind") && !stale_control)) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (!std::strcmp(argv[1], "warp")) { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 77; + } else { + for (UINT i = 0;; ++i) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, + IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } + DXGI_ADAPTER_DESC desc{}; + if (FAILED(adapter->GetDesc(&desc))) return 3; + LARGE_INTEGER driver{}; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%llu\n", desc.Description, static_cast(driver.QuadPart)); + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf()))) || + FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 3; + + ComPtr fence; + if (FAILED(invoke(guest.Get(), 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, + &__uuidof(ID3D12Fence), fence.GetAddressOf()))) return 4; + const auto real = desktop_object(guest.Get(), device.Get(), fence.Get()); + if (!real) return 4; + auto* shadow = invoke(fence.Get(), 12, UINT64{0}, UINT64{0}, UINT64{0}); + if (!shadow) return 4; + + unsigned failures = 0; + +#ifdef X2W_FENCE_TEST_CONTROLS + const bool controlled_ok = controlled_signals(fence.Get(), real.Get(), shadow, stale_control); + if (stale_control) return controlled_ok ? 0 : 1; + failures += !controlled_ok; +#endif + + // Two callers cross a barrier, then each Signal its own value. The fixture repeats this + // so a stale post-call observation cannot disagree with the native fence or method. + std::atomic concurrent_failures{}; + for (unsigned pair = 0; pair < 128; ++pair) { + std::atomic ready{}; + std::atomic go{}; + auto caller = [&](UINT64 value) { + ++ready; + while (!go.load()) std::this_thread::yield(); + if (FAILED(invoke(fence.Get(), 10, value))) ++concurrent_failures; + }; + std::thread one(caller, UINT64{1}); + std::thread two(caller, UINT64{2}); + while (ready.load() != 2) std::this_thread::yield(); + go.store(true); + one.join(); + two.join(); + + const UINT64 native = real->GetCompletedValue(); + const UINT64 direct = static_cast(*shadow); + const UINT64 observed = invoke(fence.Get(), 8); + if (native != direct || native != observed) ++concurrent_failures; + } + const UINT64 concurrent_native = real->GetCompletedValue(); + std::printf("concurrent CPU signals: native=%llu method=%llu address=%llu %s\n", + concurrent_native, invoke(fence.Get(), 8), + static_cast(*shadow), concurrent_failures.load() ? "FAIL" : "PASS"); + failures += concurrent_failures.load() ? 1 : 0; + + for (const UINT64 value : {UINT64{9}, UINT64{2}, UINT64{0}, UINT64{7}}) { + if (FAILED(invoke(fence.Get(), 10, value))) return 5; + const UINT64 native = real->GetCompletedValue(); + // CPU Signal must publish synchronously, before a method read could refresh the word. + const UINT64 direct = static_cast(*shadow); + const UINT64 observed = invoke(fence.Get(), 8); + const bool ok = native == value && observed == native && direct == native; + std::printf("cpu Signal(%llu): desktop=%llu method=%llu address=%llu %s\n", value, + native, observed, direct, ok ? "PASS" : "FAIL"); + failures += !ok; + } + if (argc == 2) { + std::printf("CPU fence values: %u failures\n", failures); + return failures ? 1 : 0; + } + // Optional diagnostic for the separate, unresolved queued-rewind/address contract. + // Not registered as a passing CTest: a target-value event is already satisfied before + // a lower queue signal executes, so a private monotonic queue marker is needed. + // The queue cannot reach its lower signal until the CPU releases the blocker. + ComPtr blocker, marker, queue; + for (auto* output : {blocker.GetAddressOf(), marker.GetAddressOf()}) + if (FAILED(invoke(guest.Get(), 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, + &__uuidof(ID3D12Fence), output))) return 4; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + if (FAILED(invoke(guest.Get(), 8, &queue_desc, &__uuidof(ID3D12CommandQueue), queue.GetAddressOf()))) return 4; + const auto real_marker = desktop_object(guest.Get(), device.Get(), marker.Get()); + if (!real_marker) return 4; + if (FAILED(invoke(queue.Get(), 17, blocker.Get(), UINT64{1})) || + FAILED(invoke(queue.Get(), 16, fence.Get(), UINT64{3})) || + FAILED(invoke(queue.Get(), 16, marker.Get(), UINT64{1}))) return 5; + Sleep(25); + if (real->GetCompletedValue() != 7 || static_cast(*shadow) != 7) { + std::puts("FAIL: pending queue signal changed the completed value"); + ++failures; + } + if (FAILED(invoke(blocker.Get(), 10, UINT64{1})) || !wait_value(real_marker.Get(), 1)) return 5; + // Read only the address until the callback publishes: GetCompletedValue must not hide a stale address. + const bool published = shadow_is(shadow, 3); + const UINT64 native = real->GetCompletedValue(), observed = invoke(fence.Get(), 8); + const bool ok = published && native == 3 && observed == native; + std::printf("queue Signal(3): desktop=%llu method=%llu address=%llu %s\n", native, + observed, static_cast(*shadow), ok ? "PASS" : "FAIL"); + failures += !ok; + std::printf("fence values: %u failures\n", failures); + return failures ? 1 : 0; +}