Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)$"
}
}
},
Expand Down
163 changes: 163 additions & 0 deletions docs/experiments/fence-cpu-signal-values.md
Original file line number Diff line number Diff line change
@@ -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).
45 changes: 42 additions & 3 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<std::uint64_t>(seen) < value || seen == -1) {
const LONG64 previous = InterlockedCompareExchange64(&fence->own().completed, static_cast<LONG64>(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
Expand Down Expand Up @@ -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<ID3D12Fence*>(self->own().real)->Signal(value);
fence_reached(self, value);
auto* fence = static_cast<ID3D12Fence*>(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<LONG64>(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<UINT64>(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<UINT64>(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)
Expand Down
37 changes: 37 additions & 0 deletions tests/cmake/startup_fence_values.cmake
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading