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_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check",
"xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control",
"xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check",
Expand All @@ -48,7 +49,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_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|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)$"
"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_warp|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|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)$"
}
}
},
Expand Down
90 changes: 90 additions & 0 deletions docs/experiments/fence-cpu-signal-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# 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. A later or equal callback retains the
existing value through the same publication path.

## 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_queue_wait --parallel 4
ctest --preset dev --no-tests=error -V -R '^startup_(fence_values|queue_wait)_warp$'
ctest --preset dev --no-tests=error -V -R '^startup_fence_values_hardware$'
```

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.

## Measured result

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 the CPU signal contract and a two-caller barrier regression, not
full startup or queued signals. A failed desktop signal was not induced in this run.

## 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.

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 this
run. The passing CPU tests create no queue and make no claim about pending
callbacks or concurrent CPU and queue producers. The shim completion method
reads the lock-protected cached word; direct address reads remain atomically
published by the same fence-local lock on success.
21 changes: 18 additions & 3 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,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 @@ -230,12 +231,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 @@ -4675,12 +4678,24 @@ 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).
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);
AcquireSRWLockExclusive(&self->own().fence_lock);
const HRESULT hr = fence->Signal(value);
// A CPU Signal is synchronous and may rewind the fence. Publish the desktop observation
// atomically with the native call, including zero; a failed Signal leaves it unchanged.
if (SUCCEEDED(hr))
InterlockedExchange64(&self->own().completed, static_cast<LONG64>(fence->GetCompletedValue()));
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)
{
AcquireSRWLockShared(&self->own().fence_lock);
const UINT64 value = static_cast<UINT64>(self->own().completed);
ReleaseSRWLockShared(&self->own().fence_lock);
return value;
}
// 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
8 changes: 8 additions & 0 deletions tests/cmake/startup_fence_values.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
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)
foreach(backend IN ITEMS warp hardware)
add_test(NAME startup_fence_values_${backend} COMMAND startup_fence_values ${backend})
set_tests_properties(startup_fence_values_${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()
181 changes: 181 additions & 0 deletions tests/startup_fence_values.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// 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 <d3d12.h>
#include <dxgi1_6.h>
#include <wrl/client.h>

#include <array>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <thread>

using Microsoft::WRL::ComPtr;
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**);

namespace {
template<class Result = HRESULT, class... Args>
Result invoke(IUnknown* object, unsigned slot, Args... args)
{
using Call = Result (WINAPI*)(IUnknown*, Args...);
return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...);
}

template<class T>
ComPtr<T> 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<T> output;
if (FAILED(invoke(guest, 5, &key, object))) return output;
ComPtr<IUnknown> reference;
UINT bytes = sizeof(IUnknown*);
const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf());
invoke(guest, 5, &key, static_cast<IUnknown*>(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<UINT64>(*shadow) == value) return true;
Sleep(1);
} while (GetTickCount64() < end);
return false;
}
}

int main(int argc, char** argv)
{
if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) ||
(argc == 3 && std::strcmp(argv[2], "--queue-rewind"))) return 2;
ComPtr<IDXGIFactory6> factory;
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3;
ComPtr<IDXGIAdapter> adapter;
if (!std::strcmp(argv[1], "warp")) {
if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 77;
} else {
for (UINT i = 0;; ++i) {
ComPtr<IDXGIAdapter1> 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<unsigned long long>(driver.QuadPart));
ComPtr<IUnknown> guest;
ComPtr<ID3D12Device> device;
std::array<unsigned char, 64> parameters{};
if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device),
reinterpret_cast<void**>(guest.GetAddressOf()))) ||
FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 3;

ComPtr<IUnknown> fence;
if (FAILED(invoke(guest.Get(), 36, UINT64{0}, D3D12_FENCE_FLAG_NONE,
&__uuidof(ID3D12Fence), fence.GetAddressOf()))) return 4;
const auto real = desktop_object<ID3D12Fence>(guest.Get(), device.Get(), fence.Get());
if (!real) return 4;
auto* shadow = invoke<volatile LONG64*>(fence.Get(), 12, UINT64{0}, UINT64{0}, UINT64{0});
if (!shadow) return 4;

unsigned failures = 0;

// 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<unsigned> concurrent_failures{};
for (unsigned pair = 0; pair < 128; ++pair) {
std::atomic<unsigned> ready{};
std::atomic<bool> 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<UINT64>(*shadow);
const UINT64 observed = invoke<UINT64>(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<UINT64>(fence.Get(), 8),
static_cast<UINT64>(*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<UINT64>(*shadow);
const UINT64 observed = invoke<UINT64>(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<IUnknown> 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<ID3D12Fence>(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<UINT64>(*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<UINT64>(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<UINT64>(*shadow), ok ? "PASS" : "FAIL");
failures += !ok;
std::printf("fence values: %u failures\n", failures);
return failures ? 1 : 0;
}
Loading