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
4 changes: 2 additions & 2 deletions CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check",
"xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check",
"xmem_page_runs_device_check", "linear_buffer_backing_check",
"bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock",
"bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", "startup_fence_rewind",
"native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check"
]
},
Expand All @@ -50,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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$"
"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_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|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_fence_rewind_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|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|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$"
}
}
},
Expand Down
127 changes: 99 additions & 28 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,10 @@ 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; // Fence: serializes Signal() and completion shadow updates
SRWLOCK queue_order_lock; // CommandQueue: pairs queue->Signal(fence) with queue_order_fence
ID3D12Fence* queue_order_fence; // CommandQueue: strictly monotonic tracker for queued signal completion
u64 queue_order_next; // CommandQueue: next monotonic value on queue_order_fence
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 @@ -295,14 +299,25 @@ struct Wrapper {
WrapperOwn& own() const { return const_cast<WrapperOwn*>(reinterpret_cast<const WrapperOwn*>(this))[-1]; }
};

void fence_reached(Wrapper* fence, std::uint64_t value) noexcept
// Reads the actual desktop fence value and updates the cached completion word under fence_lock.
// Using the desktop value instead of a cached target prevents delayed callbacks or concurrent CPU
// signals from publishing a stale value over a newer advance or rewind (#3280).
void publish_fence_completed(Wrapper* fence) noexcept
{
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;
}
if (!fence || !fence->own().real) return;
AcquireSRWLockExclusive(&fence->own().fence_lock);
const UINT64 actual = static_cast<ID3D12Fence*>(fence->own().real)->GetCompletedValue();
InterlockedExchange64(&fence->own().completed, static_cast<LONG64>(actual));
ReleaseSRWLockExclusive(&fence->own().fence_lock);
}

// Direct publication for the non-render no-op path where no GPU work is submitted.
void publish_fence_value(Wrapper* fence, std::uint64_t value) noexcept
{
if (!fence) return;
AcquireSRWLockExclusive(&fence->own().fence_lock);
InterlockedExchange64(&fence->own().completed, static_cast<LONG64>(value));
ReleaseSRWLockExclusive(&fence->own().fence_lock);
}

// Descriptor heaps created over title memory: title CPU handles in [title, title + bytes) map to
Expand Down Expand Up @@ -2537,31 +2552,89 @@ HRESULT __stdcall list_close(Wrapper* self)
return hr;
}

// A fence signalled on a queue completes when the desktop GPU reaches it.
// A fence signalled on a queue completes when the desktop GPU reaches a strictly monotonic
// per-queue order fence signalled immediately after the guest fence. Waiting on the order fence
// prevents SetEventOnCompletion from firing early when the guest fence rewinds below its current
// completed value (#3280).
struct PendingSignal {
Wrapper* fence;
UINT64 value;
ID3D12Fence* order_fence;
HANDLE event;
HMODULE module;
};
void CALLBACK signal_reached(PTP_CALLBACK_INSTANCE, void* context, PTP_WAIT wait, TP_WAIT_RESULT)
void CALLBACK signal_reached(PTP_CALLBACK_INSTANCE instance, void* context, PTP_WAIT wait, TP_WAIT_RESULT)
{
auto* pending = static_cast<PendingSignal*>(context);
fence_reached(pending->fence, pending->value);
FreeLibraryWhenCallbackReturns(instance, pending->module);
publish_fence_completed(pending->fence);
if (pending->order_fence) pending->order_fence->Release();
CloseHandle(pending->event);
delete pending;
CloseThreadpoolWait(wait);
}
void complete_when_reached(Wrapper* fence, UINT64 value)
HRESULT queue_signal_and_track(Wrapper* queue_wrapper, Wrapper* fence, UINT64 value, bool async_track)
{
auto* pending = new PendingSignal{fence, value, CreateEventW(nullptr, FALSE, FALSE, nullptr)};
if (FAILED(static_cast<ID3D12Fence*>(fence->own().real)->SetEventOnCompletion(value, pending->event))) {
fence_reached(fence, value);
CloseHandle(pending->event);
delete pending;
return;
auto* queue = static_cast<ID3D12CommandQueue*>(queue_wrapper->own().real);
auto* desktop_fence = static_cast<ID3D12Fence*>(fence->own().real);
if (!async_track) {
const HRESULT hr = queue->Signal(desktop_fence, value);
if (SUCCEEDED(hr)) publish_fence_value(fence, value);
return hr;
}
PTP_WAIT wait = CreateThreadpoolWait(&signal_reached, pending, nullptr);
SetThreadpoolWait(wait, pending->event, nullptr);
ID3D12Fence* order_fence = nullptr;
u64 order_seq = 0;
HRESULT hr = E_FAIL;
HRESULT order_hr = E_FAIL;
{
AcquireSRWLockExclusive(&queue_wrapper->own().queue_order_lock);
hr = queue->Signal(desktop_fence, value);
if (SUCCEEDED(hr)) {
if (!queue_wrapper->own().queue_order_fence) {
ID3D12Device* dev = nullptr;
if (SUCCEEDED(queue->GetDevice(IID_PPV_ARGS(&dev))) && dev) {
dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&queue_wrapper->own().queue_order_fence));
dev->Release();
}
}
if (queue_wrapper->own().queue_order_fence) {
order_seq = ++queue_wrapper->own().queue_order_next;
order_hr = queue->Signal(queue_wrapper->own().queue_order_fence, order_seq);
if (SUCCEEDED(order_hr)) {
order_fence = queue_wrapper->own().queue_order_fence;
order_fence->AddRef();
}
}
}
ReleaseSRWLockExclusive(&queue_wrapper->own().queue_order_lock);
}
if (FAILED(hr)) return hr;
if (FAILED(order_hr) || !order_fence) {
publish_fence_completed(fence);
return hr;
}
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
HMODULE module = nullptr;
auto* pending = event ? new (std::nothrow) PendingSignal{fence, order_fence, event, nullptr} : nullptr;
PTP_WAIT wait = nullptr;
if (pending &&
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
reinterpret_cast<LPCWSTR>(&signal_reached), &module)) {
pending->module = module;
wait = CreateThreadpoolWait(&signal_reached, pending, nullptr);
if (wait) {
SetThreadpoolWait(wait, event, nullptr);
if (SUCCEEDED(order_fence->SetEventOnCompletion(order_seq, event))) return hr;
SetThreadpoolWait(wait, nullptr, nullptr);
WaitForThreadpoolWaitCallbacks(wait, TRUE);
CloseThreadpoolWait(wait);
}
FreeLibrary(module);
}
delete pending;
if (event) CloseHandle(event);
order_fence->Release();
publish_fence_completed(fence);
return hr;
}

// The queued diagnostic readback's ownership: the submitted surface and queue references, the
Expand Down Expand Up @@ -5831,8 +5904,11 @@ 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)
{
AcquireSRWLockExclusive(&self->own().fence_lock);
const HRESULT hr = static_cast<ID3D12Fence*>(self->own().real)->Signal(value);
fence_reached(self, value);
const UINT64 actual = static_cast<ID3D12Fence*>(self->own().real)->GetCompletedValue();
InterlockedExchange64(&self->own().completed, static_cast<LONG64>(actual));
ReleaseSRWLockExclusive(&self->own().fence_lock);
return hr;
}
// Fence slot 8, desktop GetCompletedValue().
Expand Down Expand Up @@ -5891,13 +5967,8 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9)
static LONG calls;
const bool log_it = first_calls(calls, 2);
if (Wrapper* fence = as_wrapper(reinterpret_cast<void*>(rdx)); fence && fence->own().kind == fence_kind) {
const HRESULT hr = static_cast<ID3D12CommandQueue*>(self->own().real)->Signal(static_cast<ID3D12Fence*>(fence->own().real), r8);
if (SUCCEEDED(hr)) {
if (render_mode() || InterlockedCompareExchange(&self->own().queue_wait_seen, 0, 0))
complete_when_reached(fence, r8);
else
fence_reached(fence, r8);
}
const bool async_track = render_mode() || InterlockedCompareExchange(&self->own().queue_wait_seen, 0, 0) != 0;
const HRESULT hr = queue_signal_and_track(self, fence, r8, async_track);
if (log_it)
log("x2w-d3d12 CommandQueue::slot%d(fence=%p, value=0x%llx) -> Signal 0x%08lx", N, static_cast<void*>(fence), r8,
static_cast<unsigned long>(hr));
Expand Down
9 changes: 9 additions & 0 deletions tests/cmake/startup_fence_rewind.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Queued and CPU fence rewinds through the D3D12 stand-in (Fixes #3280).
add_executable(startup_fence_rewind tests/startup_fence_rewind.cpp)
target_compile_features(startup_fence_rewind PRIVATE cxx_std_17)
target_link_libraries(startup_fence_rewind PRIVATE d3d12_xs_shim d3d12 dxgi)
foreach(backend IN ITEMS warp hardware)
add_test(NAME startup_fence_rewind_${backend} COMMAND startup_fence_rewind ${backend})
set_tests_properties(startup_fence_rewind_${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