From 008720e4a3493dd4970e0db98f6ff4c690d61637 Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:02:17 +0100 Subject: [PATCH] startup: opt-in table lock so resource and heap lookups stop queueing on note_lock X2W_D3D12_TABLE_LOCK=1 gives resource_infos, the slot 133 placement index and heap_infos their own lock. resource_info, placed_buffer_range, memory_srv_destination and resolve_title_table read only those tables and take table_lock shared; every table writer takes note_lock, then table_lock. Without the switch nothing changes. startup_table_lock checks that the lookups return while note_lock is held exclusive, with the expected answers, that a heap creation waits for table_lock, and that lookups racing heap and texture creation find every new entry; the control variants run without the switch and must see the opposite waits. Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 41 +++++ src/startup_stubs/d3d12_capture.inl | 75 +++++++-- src/startup_stubs/d3d12_draw.inl | 3 +- src/startup_stubs/d3d12_memory_srv.inl | 3 +- src/startup_stubs/d3d12_xs_device.cpp | 66 +++++++- tests/cmake/startup_table_lock.cmake | 20 +++ tests/startup_table_lock.cpp | 222 +++++++++++++++++++++++++ 7 files changed, 407 insertions(+), 23 deletions(-) create mode 100644 tests/cmake/startup_table_lock.cmake create mode 100644 tests/startup_table_lock.cpp diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8c4a1625fb..d2b35d1aa1 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1659,6 +1659,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | +| `X2W_D3D12_TABLE_LOCK=1` | opt-in: the resource, slot 133 placement and descriptor heap tables get their own lock, so the four lookups that read only them stop queueing on the view-record lock behind view creation and descriptor copies ([details](#d3d12-table-lock)). Unset, they take that lock as before | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_D3D12_TABLE_ALIAS=1` | opt-in, render mode: a translated draw's table buffer view whose whole range lies in a slot 133 placed buffer that aliases title memory binds that alias instead of a per-draw frame copy, so the GPU reads the bytes at execution and the view is not cut at 16 MiB (`startup_table_alias_*`). Unset, every table buffer view is copied as before. See [Copies of title memory within a frame](#copies-of-title-memory-within-a-frame) | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | @@ -2011,6 +2012,46 @@ cmake --build --preset dev --target startup_view_census ctest --preset dev --no-tests=error -R "^startup_view_census" -V ``` +## D3D12 table lock + +One reader-writer lock (`note_lock`) guards the view records, the descriptor +shadows and the tables of resources, slot 133 placements and descriptor heaps. +View creation and descriptor copies take it exclusively for every call. Four +lookups read only the resource, placement and heap tables: +`resource_info`, `placed_buffer_range`, `memory_srv_destination` and +`resolve_title_table`. Without the switch they take `note_lock` shared and +queue behind those writers. + +With the opt-in `X2W_D3D12_TABLE_LOCK=1` those tables also have their own lock +(`table_lock`). A table writer (a new resource or heap, a published or retired +placement) takes `note_lock` and then `table_lock`, both exclusively, so code +that holds `note_lock` still sees fixed tables. The four lookups take only +`table_lock` shared. The fields they read do not change after an entry is added, +except a placement's kind, which only `retire_placement`, a table writer, +changes. Nothing else changes: the same lookups return the same entries, and +code that reads the view records or shadows still takes `note_lock`. The switch +is logged once, on the first lookup: +`x2w-d3d12 X2W_D3D12_TABLE_LOCK=1: resource, placement and heap tables have their own lock`. + +`startup_table_lock_` holds `note_lock` exclusively through the +fixture-only export `x2w_d3d12_table_lock_probe` while another thread runs the +four lookups for a committed texture and a shader-visible heap. The lookups +must return while the lock is held and give the expected answers: the texture +has a record, a handle inside the heap is a valid destination and one past it +is not, the heap's GPU start resolves to a table, and the heap's descriptor +memory is no placed buffer. Four threads then repeat the lookups while the +fixture creates 16 heaps and 64 textures, and every one of them must be found +afterwards; that part is a smoke test, which a writer without `table_lock` +passed five times out of five. That writers take `table_lock` is checked +directly: while the fixture-only export `x2w_d3d12_table_lock_hold` holds it +shared for 2 s, a heap creation must wait for it. The `control` variants run +without the switch and must see the lookups wait for `note_lock` and the heap +creation return at once; every other expectation is the same. + +```powershell +ctest --preset dev --no-tests=error -R "^startup_table_lock_" --output-on-failure +``` + ## Wrapper allocation failure Every object the D3D12 stand-in returns is a wrapper allocated in `wrap()`. When that allocation (or its diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 4f8e00c18e..756fec8eab 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -90,6 +90,43 @@ std::vector& view_materialized() { static std::vector& view_ids() { static std::unordered_map m; return m; } // content hash -> view id LONG64 views_noted, views_distinct, descriptors_copied; +// X2W_D3D12_TABLE_LOCK=1 (opt-in): resource_infos, the placement index and heap_infos also have their own lock, so the +// lookups that read only those tables (resource_info, placed_buffer_range, memory_srv_destination, resolve_title_table) +// stop queueing on note_lock behind the view and copy writers. Late in a load they are about 5*10^5 shared takes per +// second. A table writer takes note_lock, then table_lock, both exclusive, so code that holds note_lock still sees +// fixed tables; with the switch the lookups take table_lock shared only. The fields read there do not change after an +// entry is added, except ResourceInfo::placement (retire_placement, a writer). +SRWLOCK table_lock = SRWLOCK_INIT; +bool table_lock_on() +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_D3D12_TABLE_LOCK"); + if (value) log("x2w-d3d12 X2W_D3D12_TABLE_LOCK=1: resource, placement and heap tables have their own lock"); + return value; + }(); + return on; +} +// Taken by a table writer while it holds note_lock exclusive; nothing without the switch. +class TableWriteLock { +public: + TableWriteLock() noexcept : on_(table_lock_on()) { if (on_) AcquireSRWLockExclusive(&table_lock); } + ~TableWriteLock() { if (on_) ReleaseSRWLockExclusive(&table_lock); } + TableWriteLock(const TableWriteLock&) = delete; + TableWriteLock& operator=(const TableWriteLock&) = delete; +private: + bool on_; +}; +// Taken by a lookup that reads only those tables: table_lock shared with the switch, note_lock shared without it. +class TableReadLock { +public: + TableReadLock() noexcept : lock_(table_lock_on() ? &table_lock : ¬e_lock) { AcquireSRWLockShared(lock_); } + ~TableReadLock() { ReleaseSRWLockShared(lock_); } + TableReadLock(const TableReadLock&) = delete; + TableReadLock& operator=(const TableReadLock&) = delete; +private: + SRWLOCK* lock_; +}; + // X2W_D3D12_VIEW_CENSUS=1 (diagnostic only, docs/startup-runtime.md): new distinct view records by slot, and one line // before an insertion that is expected to grow view_records or the view_ids buckets. All fields: note_lock held. bool view_census_enabled() @@ -346,6 +383,7 @@ void note_resource(Wrapper* w, const D3D12_RESOURCE_DESC* console, u64 bytes) { if (!w || !console) return; x2w_startup::ExclusiveNoteLock guard(note_lock); + TableWriteLock tables; const ResourceInfo info{*console, bytes}; // Record and index change together or not at all (store_indexed); mode 2 leaves the index out. x2w_startup::store_indexed(resource_address_index(), resource_infos(), static_cast(w), @@ -355,17 +393,20 @@ void retire_placement(Wrapper* w) { // Keep immutable capture data available to resource_info() readers. AcquireSRWLockExclusive(¬e_lock); - const auto found = resource_infos().find(w); - if (found != resource_infos().end() && found->second.placement != Placement::none) { - auto& group = placement_group(found->second.bytes); - const auto [first, last] = group.by_start.equal_range(reinterpret_cast(w->own().title_memory)); - for (auto it = first; it != last; ++it) { - if (it->second == w) { - group.by_start.erase(it); - break; + { + TableWriteLock tables; + const auto found = resource_infos().find(w); + if (found != resource_infos().end() && found->second.placement != Placement::none) { + auto& group = placement_group(found->second.bytes); + const auto [first, last] = group.by_start.equal_range(reinterpret_cast(w->own().title_memory)); + for (auto it = first; it != last; ++it) { + if (it->second == w) { + group.by_start.erase(it); + break; + } } + found->second.placement = Placement::none; } - found->second.placement = Placement::none; } ReleaseSRWLockExclusive(¬e_lock); } @@ -375,7 +416,7 @@ PlacedVertexView placed_buffer_range(const Wrapper* device, u64 start, u64 bytes PlacedVertexView result{}; if (!start || !bytes) return result; if (bytes > ~u64{} - start) return {nullptr, nullptr, true}; - AcquireSRWLockShared(¬e_lock); + TableReadLock tables; const u64 end = start + bytes; for (const auto& group : placement_index) { if (group.by_start.empty()) continue; @@ -397,23 +438,23 @@ PlacedVertexView placed_buffer_range(const Wrapper* device, u64 start, u64 bytes } if (result.reject) break; } - ReleaseSRWLockShared(¬e_lock); return result; } const ResourceInfo* resource_info(const Wrapper* w) { - AcquireSRWLockShared(¬e_lock); + TableReadLock tables; const auto found = resource_infos().find(w); - const ResourceInfo* info = found == resource_infos().end() ? nullptr : &found->second; - ReleaseSRWLockShared(¬e_lock); - return info; + return found == resource_infos().end() ? nullptr : &found->second; } void note_heap(Wrapper* w, UINT type, UINT count, UINT logical_count, UINT increment, u64 title_cpu, u64 desktop_cpu, u64 desktop_gpu, u64 title_sampler_cpu) { AcquireSRWLockExclusive(¬e_lock); - heap_infos().push_back(HeapInfo{reinterpret_cast(w), type, count, increment, logical_count, title_cpu, desktop_cpu, desktop_gpu, title_sampler_cpu, - static_cast(VirtualAlloc(nullptr, (u64{count} + 1) * 4, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))}); + { + TableWriteLock tables; + heap_infos().push_back(HeapInfo{reinterpret_cast(w), type, count, increment, logical_count, title_cpu, desktop_cpu, desktop_gpu, title_sampler_cpu, + static_cast(VirtualAlloc(nullptr, (u64{count} + 1) * 4, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))}); + } ReleaseSRWLockExclusive(¬e_lock); } diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1933d5f78e..92f94793b4 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -3627,7 +3627,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* x2w_startup::ViewTable resolve_title_table(const Pass& pass, u64 gpu_handle) { x2w_startup::ViewTable table; - AcquireSRWLockShared(¬e_lock); + TableReadLock tables; for (const HeapInfo& heap : heap_infos()) { if (heap.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) continue; if (pass.source_view_heap && heap.wrapper != pass.source_view_heap) continue; @@ -3635,7 +3635,6 @@ x2w_startup::ViewTable resolve_title_table(const Pass& pass, u64 gpu_handle) table = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, heap.increment, gpu_handle); if (table.address) break; } - ReleaseSRWLockShared(¬e_lock); return table; } diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 80af4ca834..9d98b3eaee 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -126,7 +126,7 @@ bool desktop_address_view_supported(Wrapper* device, const D3D12_RESOURCE_DESC& bool memory_srv_destination(u64 handle) { bool valid = false; - AcquireSRWLockShared(¬e_lock); + TableReadLock tables; for (const auto& heap : heap_infos()) { if (heap.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !heap.increment) continue; const u64 base = heap.title_cpu ? heap.title_cpu : heap.desktop_cpu; @@ -136,7 +136,6 @@ bool memory_srv_destination(u64 handle) break; } } - ReleaseSRWLockShared(¬e_lock); return valid; } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 56dbe26c48..b17341d732 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5760,8 +5760,13 @@ HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE 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); }); + // X2W_D3D12_TABLE_LOCK: publish_placement calls the record getter first, with note_lock held, so table_lock is + // taken in note_lock -> table_lock order like every other table writer; it is released once publish returns. + std::optional tables; + const HRESULT hr = x2w_startup::publish_placement(note_lock, [&tables]() -> auto& { tables.emplace(); return resource_infos(); }, + group.by_start, group.max_width, static_cast(w), reinterpret_cast(address), record, + [&] { index_resource(w, record); }); + tables.reset(); if (FAILED(hr)) { // The caller has never received this wrapper; release its desktop resource and storage. AcquireSRWLockExclusive(®istry_lock); @@ -6813,6 +6818,63 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_resource_index_probe(void* resou return indexed ? TRUE : FALSE; } +// Fixture probe (startup_table_lock, X2W_D3D12_TABLE_LOCK): the table lookups for one resource and one descriptor +// handle. With hold_ms > 0 they run on another thread while this one holds note_lock exclusive for up to hold_ms; +// held_done says whether they returned in that time (they can only with the switch). With hold_ms == 0 they run on +// the calling thread and note_lock is not taken here. +struct TableLockProbe { + BOOL held_done; // the lookups returned while note_lock was held + BOOL resource_known; // resource_info found the resource's record + BOOL destination_valid; // memory_srv_destination accepted the CPU handle + BOOL table_resolved; // resolve_title_table found a table at the GPU handle + BOOL placed_owner; // placed_buffer_range found a placed buffer at the CPU handle's address +}; +extern "C" __declspec(dllexport) void x2w_d3d12_table_lock_probe(void* device, void* resource, unsigned long long cpu_handle, + unsigned long long gpu_handle, unsigned hold_ms, + TableLockProbe* out) +{ + struct Job { + const Wrapper* device; + const Wrapper* resource; + u64 cpu_handle, gpu_handle; + TableLockProbe* out; + } job{as_wrapper(device), as_wrapper(resource), cpu_handle, gpu_handle, out}; + *out = {}; + const auto lookups = [](void* context) -> DWORD { + const Job& j = *static_cast(context); + Pass pass{}; + j.out->resource_known = j.resource && resource_info(j.resource) ? TRUE : FALSE; + j.out->destination_valid = memory_srv_destination(j.cpu_handle) ? TRUE : FALSE; + j.out->table_resolved = resolve_title_table(pass, j.gpu_handle).address ? TRUE : FALSE; + const PlacedVertexView placed = placed_buffer_range(j.device, j.cpu_handle, 1); + j.out->placed_owner = placed.owner || placed.reject ? TRUE : FALSE; + return 0; + }; + if (!hold_ms) { + lookups(&job); + return; + } + AcquireSRWLockExclusive(¬e_lock); + const HANDLE thread = CreateThread(nullptr, 0, lookups, &job, 0, nullptr); + const bool done = thread && WaitForSingleObject(thread, hold_ms) == WAIT_OBJECT_0; + ReleaseSRWLockExclusive(¬e_lock); + if (thread) { + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + } + out->held_done = done ? TRUE : FALSE; +} + +// Fixture export (startup_table_lock): holds table_lock shared for hold_ms and sets `held` once it has it, so the +// fixture can check that a table writer waits for table_lock (only with the switch). +extern "C" __declspec(dllexport) void x2w_d3d12_table_lock_hold(HANDLE held, unsigned hold_ms) +{ + AcquireSRWLockShared(&table_lock); + SetEvent(held); + Sleep(hold_ms); + ReleaseSRWLockShared(&table_lock); +} + // The desktop pointer is not dereferenced: the fixture keeps its own desktop reference to a retired resource. extern "C" __declspec(dllexport) BOOL x2w_d3d12_texture_upload_probe(void* desktop_resource) { diff --git a/tests/cmake/startup_table_lock.cmake b/tests/cmake/startup_table_lock.cmake new file mode 100644 index 0000000000..eeee9da010 --- /dev/null +++ b/tests/cmake/startup_table_lock.cmake @@ -0,0 +1,20 @@ +# X2W_D3D12_TABLE_LOCK: the resource, placement and heap lookups run while note_lock is held exclusive. `control` runs +# without the switch and must see them wait for note_lock; every other expectation is the same. +add_executable(startup_table_lock tests/startup_table_lock.cpp) +target_compile_features(startup_table_lock PRIVATE cxx_std_17) +target_link_libraries(startup_table_lock PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS on control) + set(table_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + if(mode STREQUAL "on") + set(table_test startup_table_lock_${backend}) + add_test(NAME ${table_test} COMMAND startup_table_lock ${backend}) + list(APPEND table_env "X2W_D3D12_TABLE_LOCK=1") + else() + set(table_test startup_table_lock_control_${backend}) + add_test(NAME ${table_test} COMMAND startup_table_lock ${backend} control) + list(APPEND table_env "X2W_D3D12_TABLE_LOCK=") + endif() + set_tests_properties(${table_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${table_env}") + endforeach() +endforeach() diff --git a/tests/startup_table_lock.cpp b/tests/startup_table_lock.cpp new file mode 100644 index 0000000000..47f810dc6e --- /dev/null +++ b/tests/startup_table_lock.cpp @@ -0,0 +1,222 @@ +// X2W_D3D12_TABLE_LOCK=1 gives the resource, placement and heap tables their own lock: the lookups that read only +// them (resource_info, memory_srv_destination, resolve_title_table, placed_buffer_range) take it instead of note_lock +// (docs/startup-runtime.md#d3d12-table-lock). The fixture-only export x2w_d3d12_table_lock_probe runs them while it +// holds note_lock exclusive. +// +// startup_table_lock [control] +// (X2W_D3D12_TABLE_LOCK=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1; control: without X2W_D3D12_TABLE_LOCK) +// +// 1. Held: the lookups for a committed texture and a shader-visible heap return while note_lock is held. The +// control (switch off) must see them wait for it; that is the only expectation that differs. +// 2. Results: the texture is known, a handle in the heap is a valid destination and one past the heap is not, the +// heap's GPU start resolves to a table, and the heap's descriptor memory is no placed buffer. +// 3. Writers race readers: four threads repeat the lookups while this thread creates 16 heaps and 64 textures; every +// one of them is found afterwards. A smoke test: a writer that skipped table_lock passed it five times out of five. +// 4. Writers take table_lock: while x2w_d3d12_table_lock_hold holds it shared for 2 s, a heap creation waits for it. +// The control must see the creation return at once (without the switch a writer takes no table_lock). +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +struct TableLockProbe { + BOOL held_done, resource_known, destination_valid, table_resolved, placed_owner; +}; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_table_lock_probe(void*, void*, unsigned long long, unsigned long long, + unsigned, TableLockProbe*); +extern "C" __declspec(dllimport) void x2w_d3d12_table_lock_hold(HANDLE, unsigned); + +namespace { + +constexpr unsigned hold_ms = 10000; // far longer than the lookups take; the control waits this long once +constexpr unsigned writer_hold_ms = 2000, writer_waited_ms = 1000; // a heap creation takes well under 1 s + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +int failures; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Heap { + ComPtr object; + UINT64 cpu, gpu; +}; + +} // namespace + +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], "control"))) + return 2; + const bool control = argc == 3; + std::setvbuf(stdout, nullptr, _IONBF, 0); + char switch_value[4]{}; + const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_TABLE_LOCK", switch_value, sizeof(switch_value)) == 1 && + switch_value[0] == '1'; + if (switch_on == control) { + std::puts(control ? "FAIL: the control must run without X2W_D3D12_TABLE_LOCK" + : "FAIL: X2W_D3D12_TABLE_LOCK=1 is not set"); + return 2; + } + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) std::printf("adapter=%ls\n", adapter_desc.Description); + ComPtr guest; + std::array parameters{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())))) + return 3; + const UINT stride = invoke(guest.Get(), 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + const auto make_heap = [&](Heap& heap) { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (FAILED(invoke(guest.Get(), 14, &desc, &__uuidof(ID3D12DescriptorHeap), heap.object.GetAddressOf()))) + return false; + heap.cpu = invoke(heap.object.Get(), 9); + heap.gpu = invoke(heap.object.Get(), 10); + return heap.cpu != 0; + }; + D3D12_HEAP_PROPERTIES default_heap{}; + default_heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC texture_desc{}; + texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture_desc.Width = texture_desc.Height = 16; + texture_desc.DepthOrArraySize = texture_desc.MipLevels = 1; + texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_desc.SampleDesc.Count = 1; + const IID resource_iid = __uuidof(ID3D12Resource); + // Slot 76: the console CreateCommittedResource, which records the resource (slot 27 forwards to the desktop). + const auto make_texture = [&](ComPtr& texture) { + return SUCCEEDED(invoke(guest.Get(), 76, &default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, + D3D12_RESOURCE_STATE_COMMON, static_cast(nullptr), + &resource_iid, reinterpret_cast(texture.GetAddressOf()))); + }; + + Heap heap; + ComPtr texture; + if (!make_heap(heap) || !make_texture(texture)) return 3; + const auto probe = [&](void* resource, UINT64 cpu, UINT64 gpu, unsigned hold) { + TableLockProbe p{}; + x2w_d3d12_table_lock_probe(guest.Get(), resource, cpu, gpu, hold, &p); + return p; + }; + + // 1 and 2. + const TableLockProbe held = probe(texture.Get(), heap.cpu + stride, heap.gpu, hold_ms); + if (control) + expect(!held.held_done, "control: the table lookups returned while note_lock was held (they must wait)"); + else + expect(held.held_done, "the table lookups waited for note_lock"); + expect(held.resource_known, "the committed texture has no resource record"); + expect(held.destination_valid, "a handle inside the heap is not a valid destination"); + expect(held.table_resolved, "the heap's GPU start resolves to no table"); + expect(!held.placed_owner, "the heap's descriptor memory was taken for a placed buffer"); + const TableLockProbe outside = probe(nullptr, heap.cpu + 4ull * stride, heap.gpu, 0); + expect(!outside.destination_valid, "a handle one past the heap is a valid destination"); + expect(!outside.resource_known, "a null resource has a record"); + + // 3. + std::atomic stop{false}; + std::atomic lookups{0}; + std::vector readers; + for (int i = 0; i < 4; ++i) + readers.emplace_back([&] { + while (!stop.load(std::memory_order_relaxed)) { + probe(texture.Get(), heap.cpu, heap.gpu, 0); + lookups.fetch_add(1, std::memory_order_relaxed); + } + }); + std::vector heaps(16); + std::vector> textures(64); + bool created = true; + for (std::size_t i = 0; i < textures.size(); ++i) { + if (i % 4 == 0) created = make_heap(heaps[i / 4]) && created; + created = make_texture(textures[i]) && created; + } + stop = true; + for (auto& reader : readers) reader.join(); + std::printf("race: %ld lookups during 16 heap and 64 texture creations\n", lookups.load()); + if (!created) return 3; + int missing_textures = 0, missing_heaps = 0; + for (auto& t : textures) + if (!probe(t.Get(), 0, 0, 0).resource_known) ++missing_textures; + for (auto& h : heaps) { + const TableLockProbe p = probe(nullptr, h.cpu, h.gpu, 0); + if (!p.destination_valid || !p.table_resolved) ++missing_heaps; + } + std::printf("missing after the race: %d textures, %d heaps\n", missing_textures, missing_heaps); + expect(!missing_textures, "a texture created during the race has no resource record"); + expect(!missing_heaps, "a heap created during the race is not found"); + + // 4. + const HANDLE held_event = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!held_event) return 3; + std::thread holder([&] { x2w_d3d12_table_lock_hold(held_event, writer_hold_ms); }); + WaitForSingleObject(held_event, INFINITE); + const ULONGLONG writer_start = GetTickCount64(); + Heap late; + const bool late_created = make_heap(late); + const ULONGLONG writer_ms = GetTickCount64() - writer_start; + holder.join(); + CloseHandle(held_event); + std::printf("heap creation while table_lock was held: %llu ms\n", writer_ms); + if (!late_created) return 3; + if (control) + expect(writer_ms < writer_waited_ms, "control: a heap creation waited for table_lock (it must not take it)"); + else + expect(writer_ms >= writer_waited_ms, "a heap creation did not wait for table_lock"); + + if (failures) return 1; + std::puts(control ? "PASS (control: the lookups waited for note_lock)" : "PASS"); + return 0; +}