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
41 changes: 41 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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_<warp|hardware>` 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
Expand Down
75 changes: 58 additions & 17 deletions src/startup_stubs/d3d12_capture.inl
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,43 @@ std::vector<std::uint8_t>& view_materialized() { static std::vector<std::uint8_t
std::unordered_map<u64, std::uint32_t>& view_ids() { static std::unordered_map<u64, std::uint32_t> 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 : &note_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()
Expand Down Expand Up @@ -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<const Wrapper*>(w),
Expand All @@ -355,17 +393,20 @@ void retire_placement(Wrapper* w)
{
// Keep immutable capture data available to resource_info() readers.
AcquireSRWLockExclusive(&note_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<u64>(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<u64>(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(&note_lock);
}
Expand All @@ -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(&note_lock);
TableReadLock tables;
const u64 end = start + bytes;
for (const auto& group : placement_index) {
if (group.by_start.empty()) continue;
Expand All @@ -397,23 +438,23 @@ PlacedVertexView placed_buffer_range(const Wrapper* device, u64 start, u64 bytes
}
if (result.reject) break;
}
ReleaseSRWLockShared(&note_lock);
return result;
}
const ResourceInfo* resource_info(const Wrapper* w)
{
AcquireSRWLockShared(&note_lock);
TableReadLock tables;
const auto found = resource_infos().find(w);
const ResourceInfo* info = found == resource_infos().end() ? nullptr : &found->second;
ReleaseSRWLockShared(&note_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(&note_lock);
heap_infos().push_back(HeapInfo{reinterpret_cast<u64>(w), type, count, increment, logical_count, title_cpu, desktop_cpu, desktop_gpu, title_sampler_cpu,
static_cast<std::uint32_t*>(VirtualAlloc(nullptr, (u64{count} + 1) * 4, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))});
{
TableWriteLock tables;
heap_infos().push_back(HeapInfo{reinterpret_cast<u64>(w), type, count, increment, logical_count, title_cpu, desktop_cpu, desktop_gpu, title_sampler_cpu,
static_cast<std::uint32_t*>(VirtualAlloc(nullptr, (u64{count} + 1) * 4, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))});
}
ReleaseSRWLockExclusive(&note_lock);
}

Expand Down
3 changes: 1 addition & 2 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -3627,15 +3627,14 @@ 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(&note_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;
if (!pass.source_view_heap && heap.logical_count > heap.count) continue;
table = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, heap.increment, gpu_handle);
if (table.address) break;
}
ReleaseSRWLockShared(&note_lock);
return table;
}

Expand Down
3 changes: 1 addition & 2 deletions src/startup_stubs/d3d12_memory_srv.inl
Original file line number Diff line number Diff line change
Expand Up @@ -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(&note_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;
Expand All @@ -136,7 +136,6 @@ bool memory_srv_destination(u64 handle)
break;
}
}
ReleaseSRWLockShared(&note_lock);
return valid;
}

Expand Down
66 changes: 64 additions & 2 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<const Wrapper*>(w), reinterpret_cast<u64>(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<TableWriteLock> 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<const Wrapper*>(w), reinterpret_cast<u64>(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(&registry_lock);
Expand Down Expand Up @@ -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<const Job*>(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(&note_lock);
const HANDLE thread = CreateThread(nullptr, 0, lookups, &job, 0, nullptr);
const bool done = thread && WaitForSingleObject(thread, hold_ms) == WAIT_OBJECT_0;
ReleaseSRWLockExclusive(&note_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)
{
Expand Down
20 changes: 20 additions & 0 deletions tests/cmake/startup_table_lock.cmake
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading