From 503b41cebd7ab40e4c3b270c77fa18ec64bfd48d Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:12:55 +0100 Subject: [PATCH] startup: opt-in content view tokens so view records can be freed (X2W_D3D12_VIEW_CONTENT_TOKENS) With X2W_D3D12_VIEW_CONTENT_TOKENS=1, note_view writes a CBV or a buffer SRV into title descriptor memory as a token that carries the view (address and size; resource, range, stride, format, flags) instead of a record id. A copy the title makes with its own memory copy then needs no record, so the record is named only by shadow slots, which the stand-in sees change. When the last one lets go, the record is parked: it keeps its contents and its view_ids entry, so the same view created again finds it, and the oldest parked record is reused once more than 65536 are parked. Draw and dispatch readers resolve both token kinds through token_view(). Off under X2W_D3D12_CAPTURE. Unset, nothing changes. Tests: startup_view_content_token (encoding, no device), startup_view_content_{off,on}_{warp,hardware} (token copies survive overwrites and record reuse; records bounded; revival). startup_view_alloc_* runs with the switch off: it reads record ids from tokens. Refs #1199 Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 64 +++- src/startup_stubs/d3d12_capture.inl | 159 +++++++++- src/startup_stubs/d3d12_compute_dispatch.inl | 10 +- src/startup_stubs/d3d12_draw.inl | 37 +-- src/startup_stubs/d3d12_xs_device.cpp | 65 ++++ src/startup_stubs/view_content_token.h | 113 +++++++ tests/cmake/startup_view_alloc.cmake | 3 + tests/cmake/startup_view_content.cmake | 26 ++ tests/startup_view_content.cpp | 296 +++++++++++++++++++ tests/startup_view_content_token_check.cpp | 135 +++++++++ 10 files changed, 859 insertions(+), 49 deletions(-) create mode 100644 src/startup_stubs/view_content_token.h create mode 100644 tests/cmake/startup_view_content.cmake create mode 100644 tests/startup_view_content.cpp create mode 100644 tests/startup_view_content_token_check.cpp diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4b1a3e002d..377397f418 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1652,6 +1652,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_VIEW_CONTENT_TOKENS=1` | opt-in: constant buffer views and buffer shader-resource views are written into title descriptor memory as tokens that carry the view itself instead of a record id, and their records are freed and reused once no shadow slot names them, so the record count stays bounded ([details](#d3d12-view-content-tokens)). Off under `X2W_D3D12_CAPTURE`. Unset, every view keeps an id token and records are never removed | | `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) | @@ -1966,7 +1967,8 @@ ctest --preset dev --no-tests=error -R '^startup_view_alloc_' --output-on-failur The stand-in keeps one record per distinct view: slot, resource, counter, description bytes and whether the desktop view was created. Records are not -removed. `X2W_D3D12_VIEW_CENSUS=1` shows which slot adds them. It changes no +removed, except under `X2W_D3D12_VIEW_CONTENT_TOKENS=1` +([D3D12 view content tokens](#d3d12-view-content-tokens)). `X2W_D3D12_VIEW_CENSUS=1` shows which slot adds them. It changes no record, id or descriptor binding. The heartbeat adds a line: @@ -2004,6 +2006,66 @@ cmake --build --preset dev --target startup_view_census ctest --preset dev --no-tests=error -R "^startup_view_census" -V ``` +## D3D12 view content tokens + +`note_view` writes a 32-byte token into the title's descriptor memory, so a +descriptor the title copies with its own memory copy still names its view. By +default the token holds the id of the view's record. The title can keep such a +copy for any time, so no record can be freed: an id that was reused would make +an old copy name another view. The records grow with every distinct view; in a +startup run of the main executable, mostly buffer SRV windows into one buffer and +CBVs at new addresses (#1199). + +With the opt-in `X2W_D3D12_VIEW_CONTENT_TOKENS=1`, a constant buffer view +(slot 17) and a buffer shader-resource view (slot 18, `NONE` or `RAW` flags) are +written as content tokens instead (`src/startup_stubs/view_content_token.h`): + +| Word | Id token | Content token | +|---|---|---| +| 0 | `X2WV` magic | `X2WV` magic | +| 1 | record id (below 2^31) | bit 31 set; created flag; SRV format, `RAW` flag, component mapping | +| 2 | slot | slot (bits 0-7); SRV `StructureByteStride` (bits 8-31) | +| 3 | 0 | 0 (formatted-buffer readers put their own word 3 in their copy) | +| 4-5 | resource | CBV: `BufferLocation`; SRV: resource | +| 6-7 | 0 | CBV: `SizeInBytes`; SRV: `FirstElement`, `NumElements` | + +A view that does not fit (a texture, a counter, `FirstElement` of 2^32 or more, a +format value of 1024 or more) keeps an id token. The draw and dispatch readers +resolve both kinds through `token_view()`; a content token decodes without +`note_lock`, with its description's padding bytes zero. A reader that still +compared the id alone would see an unknown id and refuse the binding. + +A record behind a content token is then named only by shadow slots, which the +stand-in sees change: `note_view`, `note_copy`, the out-of-memory drop and the +release of a heap's views under `X2W_D3D12_RELEASE_RETIRED`. When the last shadow +slot stops naming it, the record is parked: it keeps its contents and its +`view_ids` entry, so the same view created again finds it. A new record takes the +oldest parked one once more than 65536 are parked (about 10 MB of records and map +nodes), and only then leaves `view_ids`. The fixture lowers that number through the +fixture-only export `x2w_d3d12_set_view_parked_keep`. Without `X2W_D3D12_RELEASE_RETIRED`, the +shadow slots of a destroyed heap keep their references, so those records stay. +The switch is off under `X2W_D3D12_CAPTURE`, whose `VIEW` chunks are written once +per id. The heartbeat adds: + +`x2w-d3d12 view content tokens: written ; records (ids , parked ), parked , reused , revived ` + +`startup_view_content_token` checks the encoding without a device: round trips, +the refused views, padding bytes, and a decode that ignores word 3. +`startup_view_content__` puts a buffer SRV, a CBV and a +texture SRV into a heap over title memory, keeps copies of their tokens in plain +memory and copies the buffer SRV into a second descriptor with +`CopyDescriptorsSimple`. It then creates 5000 other buffer SRVs into the first +descriptor, re-creates the first view, and lets its record be reused. Every copy +must still name the view it was made from, as created; with the switch on the +record count must stay bounded and the re-created view must find its parked +record, with it off the records must grow by one per view. `startup_view_alloc_*` +covers the id tokens only (it reads ids from tokens) and runs with the switch +off. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_view_content' --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..7f590156d7 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -90,6 +90,87 @@ 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_VIEW_CONTENT_TOKENS=1 (opt-in, #1199, view_content_token.h): a view that fits a content token is named in +// title memory by its content, so its record is only named by shadow slots. Such a record (freeable) is parked when +// the last shadow slot stops naming it: it keeps its contents and its view_ids entry, so the same view created again +// finds it (revived), and it waits in a queue, oldest first. A new record takes the oldest parked one once more than +// view_parked_keep records are parked; only then does its view_ids entry go. Off under +// X2W_D3D12_CAPTURE, whose VIEW chunks are written once per id. Every field: note_lock held. +bool view_content_tokens() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_VIEW_CONTENT_TOKENS") && + !GetEnvironmentVariableA("X2W_D3D12_CAPTURE", nullptr, 0); + return on; +} +// Parked records kept findable before the oldest is reused: about 10 MB of records and map nodes. Only the fixture +// export x2w_d3d12_set_view_parked_keep changes it. +std::uint32_t view_parked_keep = 65536; +struct ViewLife { + u64 hash; // the record's view_ids key + std::uint32_t shadow_refs; // shadow slots that name the record + std::uint32_t prev, next; // parked queue links: id + 1, 0 at either end + std::uint8_t freeable, parked; +}; +std::vector& view_life() { static std::vector v; return v; } // per record, only when switched on +std::uint32_t view_parked_head, view_parked_tail, view_parked_count; // head: oldest; id + 1, 0: empty +LONG64 views_freed, views_reused, views_revived, content_tokens_written; + +void unlink_parked(std::uint32_t id) +{ + ViewLife& life = view_life()[id]; + (life.prev ? view_life()[life.prev - 1].next : view_parked_head) = life.next; + (life.next ? view_life()[life.next - 1].prev : view_parked_tail) = life.prev; + life.prev = life.next = 0; + life.parked = 0; + --view_parked_count; +} +// A record no shadow slot names any more joins the back of the parked queue, contents and view_ids entry kept. +// Allocates nothing. +void park_view_record(std::uint32_t id) +{ + ViewLife& life = view_life()[id]; + life.parked = 1; + life.prev = view_parked_tail; + life.next = 0; + (view_parked_tail ? view_life()[view_parked_tail - 1].next : view_parked_head) = id + 1; + view_parked_tail = id + 1; + ++view_parked_count; + ++views_freed; +} +// The same view was created again while its record was parked. +void revive_view_record(std::uint32_t id) +{ + unlink_parked(id); + ++views_revived; +} +// The oldest parked record, out of the queue and out of view_ids, with its contents cleared, once more than +// view_parked_keep are parked; otherwise 0. Returns id + 1. Allocates nothing. +std::uint32_t take_parked_record() +{ + if (!view_content_tokens() || view_parked_count <= view_parked_keep || !view_parked_head) return 0; + const std::uint32_t id = view_parked_head - 1; + unlink_parked(id); + ViewLife& life = view_life()[id]; + const auto found = view_ids().find(life.hash); + if (found != view_ids().end() && found->second == id) view_ids().erase(found); + view_records()[id] = ViewRecord{}; + view_materialized()[id] = 0; + life = ViewLife{}; + return id + 1; +} +void shadow_ref_add(std::uint32_t id_plus_one) +{ + if (!view_content_tokens() || !id_plus_one || id_plus_one - 1 >= view_life().size()) return; + ++view_life()[id_plus_one - 1].shadow_refs; +} +void shadow_ref_drop(std::uint32_t id_plus_one) +{ + if (!view_content_tokens() || !id_plus_one || id_plus_one - 1 >= view_life().size()) return; + ViewLife& life = view_life()[id_plus_one - 1]; + if (life.shadow_refs) --life.shadow_refs; + if (!life.shadow_refs && life.freeable && !life.parked) park_view_record(id_plus_one - 1); +} + // 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() @@ -183,6 +264,32 @@ void view_refs_leave_class(std::uint32_t slot, u64 resource, u64 counter, Retire constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV" +// The view a token in title descriptor memory names (words[0] == view_token_magic): decoded from a content token, or +// copied from the record its id names (takes note_lock shared). False when neither names a view. +bool token_view(const std::uint32_t* words, ViewRecord& record, bool* materialized = nullptr) +{ + if (x2w_startup::is_view_content(words)) { + x2w_startup::ContentView view; + if (!x2w_startup::decode_view_content(words, view)) return false; + record = ViewRecord{}; + record.id = ~0u; + record.slot = view.slot; + record.resource = view.resource; + record.desc_bytes = view.desc_bytes; + std::memcpy(record.desc, view.desc, view.desc_bytes); + if (materialized) *materialized = view.created; + return true; + } + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) { + record = view_records()[words[1]]; + if (materialized) *materialized = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + return known; +} + bool title_backed(u64 title_handle, u64 bytes) { bool inside = false; @@ -207,10 +314,8 @@ bool descriptor_has_live_view(u64 desktop_handle, u64 title_handle) std::uint32_t words[8]; std::memcpy(words, reinterpret_cast(title_handle), sizeof(words)); if (words[0] != view_token_magic) return false; - AcquireSRWLockShared(¬e_lock); - live = words[1] < view_records().size() && view_materialized()[words[1]]; - ReleaseSRWLockShared(¬e_lock); - return live; + ViewRecord record; + return token_view(words, record, &live) && live; } void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std::size_t bytes, @@ -429,21 +534,35 @@ void reserve_one_view_entry(std::vector& v, ViewAllocation site) // Adds a new record to the three view containers, or to none of them (note_lock held). Everything that can allocate // comes first: the two reservations change no size, and a failed try_emplace leaves the map unchanged. The two // push_back calls then have room and cannot fail. Returns the name of the container that could not allocate, or null. -const char* store_view(const ViewRecord& record, std::uint8_t created, u64 hash) +// With view_content_tokens(), a record.id below the container size reuses a record take_parked_record() emptied +// (only the map node allocates), and view_life gets the record's hash and freeable flag. +const char* store_view(const ViewRecord& record, std::uint8_t created, u64 hash, bool freeable = false) { + const bool reuse = record.id < view_records().size(); const char* growing = "view_records"; try { - reserve_one_view_entry(view_records(), view_records_site); - growing = "view_materialized"; - reserve_one_view_entry(view_materialized(), view_materialized_site); + if (!reuse) { + reserve_one_view_entry(view_records(), view_records_site); + if (view_content_tokens()) reserve_one_view_entry(view_life(), view_records_site); + growing = "view_materialized"; + reserve_one_view_entry(view_materialized(), view_materialized_site); + } growing = "view_ids"; view_allocation_gate(view_ids_site); view_ids().try_emplace(hash, record.id); } catch (const std::bad_alloc&) { return growing; } + if (reuse) { + view_records()[record.id] = record; + view_materialized()[record.id] = created; + view_life()[record.id] = ViewLife{hash, 0, 0, 0, static_cast(freeable), 0}; + ++views_reused; + return nullptr; + } view_records().push_back(record); view_materialized().push_back(created); + if (view_content_tokens()) view_life().push_back(ViewLife{hash, 0, 0, 0, static_cast(freeable), 0}); return nullptr; } @@ -459,6 +578,7 @@ void drop_unrecorded_view(const ViewRecord& record, bool materialized, const cha if (prev && prev - 1 < view_records().size() && view_materialized()[prev - 1]) view_refs_release(view_records()[prev - 1].slot, view_records()[prev - 1].resource, view_records()[prev - 1].counter); + shadow_ref_drop(prev); } if (materialized) view_refs_leave_class(record.slot, record.resource, record.counter, RetireLeft::view); ReleaseSRWLockExclusive(¬e_lock); @@ -494,13 +614,20 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast(data)[i]) * 1099511628211ull; }; mix(&record.slot, 4); mix(&record.resource, 8); mix(&record.counter, 8); mix(record.desc, sizeof(record.desc)); mix(&created, 1); + std::uint32_t content[8] = {}; + const bool freeable = view_content_tokens() && + x2w_startup::encode_view_content(view_token_magic, record.slot, resource, counter, record.desc, record.desc_bytes, + materialized, content); AcquireSRWLockExclusive(¬e_lock); ++views_noted; const auto found = view_ids().find(hash); if (found != view_ids().end()) { record.id = found->second; + if (view_content_tokens() && record.id < view_life().size() && view_life()[record.id].parked) + revive_view_record(record.id); } else { - record.id = static_cast(view_records().size()); + const std::uint32_t taken = take_parked_record(); + record.id = taken ? taken - 1 : static_cast(view_records().size()); const bool census = view_census_enabled(); std::size_t capacity_before = 0, buckets_before = 0; bool records_full = false, ids_full = false; @@ -523,7 +650,8 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ log("%s (new slot %u)", line, record.slot); } } - if (const char* container = store_view(record, created, hash)) { + if (const char* container = store_view(record, created, hash, freeable)) { + if (taken) park_view_record(record.id); // emptied, not in view_ids: never found, taken again later drop_unrecorded_view(record, materialized, container); return; } @@ -540,21 +668,29 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ // The same view written to the same slot again keeps its id and changes no reference count. A different view // takes over the slot: the new record adds its refs, the previous materialized record drops its own. if (prev != record.id + 1) { + shadow_ref_add(record.id + 1); if (materialized) view_refs_add(static_cast(slot), resource, counter); if (prev && prev - 1 < view_records().size() && view_materialized()[prev - 1]) view_refs_release(view_records()[prev - 1].slot, view_records()[prev - 1].resource, view_records()[prev - 1].counter); + shadow_ref_drop(prev); } } else if (view_slot_names_resource(static_cast(slot)) && resource) { // A descriptor no shadow slot tracks cannot hold the view: the use takes the resource out of the class. view_refs_leave_class(static_cast(slot), resource, counter, RetireLeft::view); } + // A freeable record no shadow slot names (an untracked destination): its content token is all that names it. + if (view_content_tokens() && record.id < view_life().size() && view_life()[record.id].freeable && + !view_life()[record.id].shadow_refs && !view_life()[record.id].parked) + park_view_record(record.id); + if (freeable) ++content_tokens_written; ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; if (dest_title != dest_desktop && title_backed(dest_title, token_bytes) && x2w_local::writable(reinterpret_cast(dest_title), token_bytes)) { std::uint32_t token[8] = {view_token_magic, record.id, static_cast(slot), 0, static_cast(resource), static_cast(resource >> 32), 0, 0}; + if (freeable) std::memcpy(token, content, sizeof(token)); std::memcpy(reinterpret_cast(dest_title), token, token_bytes); } } @@ -574,12 +710,14 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, if (src_id && src_id - 1 < view_records().size() && view_materialized()[src_id - 1]) view_refs_add(view_records()[src_id - 1].slot, view_records()[src_id - 1].resource, view_records()[src_id - 1].counter); + shadow_ref_add(src_id); } for (UINT i = 0; i < count; ++i) { const std::uint32_t old_id = to[i]; if (old_id && old_id - 1 < view_records().size() && view_materialized()[old_id - 1]) view_refs_release(view_records()[old_id - 1].slot, view_records()[old_id - 1].resource, view_records()[old_id - 1].counter); + shadow_ref_drop(old_id); } std::memmove(to, from, u64{count} * 4); } else { @@ -588,6 +726,7 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, if (old_id && old_id - 1 < view_records().size() && view_materialized()[old_id - 1]) view_refs_release(view_records()[old_id - 1].slot, view_records()[old_id - 1].resource, view_records()[old_id - 1].counter); + shadow_ref_drop(old_id); } std::memset(to, 0, u64{count} * 4); } diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index ce571a0f8f..81d87a0ce2 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -659,15 +659,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& // a null view would read zeros or drop the program's stores without a trace. ViewRecord record{}; bool known = false, created = false; - if (words[0] == view_token_magic) { - AcquireSRWLockShared(¬e_lock); - known = words[1] < view_records().size(); - if (known) { - record = view_records()[words[1]]; - created = view_materialized()[words[1]] != 0; - } - ReleaseSRWLockShared(¬e_lock); - } + if (words[0] == view_token_magic) known = token_view(words, record, &created); Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr : output ? static_cast(wrapper->own().real) : sampled_address_texture(wrapper); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1933d5f78e..6290db031a 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2241,11 +2241,7 @@ bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16 std::memcpy(words, reinterpret_cast(entry), 32); if (words[0] != view_token_magic) return refuse(i, "missing view token", 0); ViewRecord record{}; - bool known = false; - AcquireSRWLockShared(¬e_lock); - known = words[1] < view_records().size(); - if (known) record = view_records()[words[1]]; - ReleaseSRWLockShared(¬e_lock); + const bool known = token_view(words, record); if (!known || record.slot != 18) return refuse(i, "view slot", static_cast(record.slot)); Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); ID3D12Resource* texture = sampled_address_texture(resource); @@ -2525,9 +2521,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (why) *why = nullptr; if (words[0] == view_token_magic) { ViewRecord record{}; - AcquireSRWLockShared(¬e_lock); - if (words[1] < view_records().size()) record = view_records()[words[1]]; - ReleaseSRWLockShared(¬e_lock); + token_view(words, record); if (record.slot == 17 && record.desc_bytes >= 12) { UINT size = 0; std::memcpy(&address, record.desc, 8); @@ -2665,10 +2659,7 @@ const char* formatted_buffer_word3(std::uint32_t* words, std::uint32_t& format) { if (words[0] == view_token_magic) { ViewRecord record{}; - AcquireSRWLockShared(¬e_lock); - const bool known = words[1] < view_records().size(); - if (known) record = view_records()[words[1]]; - ReleaseSRWLockShared(¬e_lock); + const bool known = token_view(words, record); if (!known || record.slot != 18 || record.desc_bytes < 40) return "missing hardware descriptor"; D3D12_SHADER_RESOURCE_VIEW_DESC view; std::memcpy(&view, record.desc, 40); @@ -2742,10 +2733,7 @@ bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding std::memcpy(words, reinterpret_cast(entry), 32); if (words[0] != view_token_magic) return refuse(i, "table entry holds no view", words[0]); ViewRecord record{}; - AcquireSRWLockShared(¬e_lock); - const bool known = words[1] < view_records().size(); - if (known) record = view_records()[words[1]]; - ReleaseSRWLockShared(¬e_lock); + const bool known = token_view(words, record); if (!known) return refuse(i, "unknown view token", words[1]); if (record.slot != 19) return refuse(i, "table entry is not an unordered-access view", record.slot); Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); @@ -2798,9 +2786,8 @@ bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding if (!srv_entry || !x2w_local::readable(reinterpret_cast(srv_entry), 32)) continue; std::memcpy(srv_words, reinterpret_cast(srv_entry), 32); if (srv_words[0] != view_token_magic) continue; - AcquireSRWLockShared(¬e_lock); - const u64 srv_resource = srv_words[1] < view_records().size() ? view_records()[srv_words[1]].resource : 0; - ReleaseSRWLockShared(¬e_lock); + ViewRecord srv_record{}; + const u64 srv_resource = token_view(srv_words, srv_record) ? srv_record.resource : 0; if (srv_resource && srv_resource == record.resource) return refuse(i, "the texture is also an SRV of this draw", s); } out[i].resource = texture; @@ -3098,12 +3085,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // A texture: the title's descriptor memory carries the id of the view it created there. ViewRecord record{}; bool known = false; - if (words[0] == view_token_magic) { - AcquireSRWLockShared(¬e_lock); - known = words[1] < view_records().size(); - if (known) record = view_records()[words[1]]; - ReleaseSRWLockShared(¬e_lock); - } + if (words[0] == view_token_magic) known = token_view(words, record); Wrapper* resource = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -3236,10 +3218,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // A view the title created: a constant buffer view names its memory directly; a buffer // shader-resource view names a range of its resource's title memory. ViewRecord record{}; - AcquireSRWLockShared(¬e_lock); - buffer_token_known = words[1] < view_records().size(); - if (buffer_token_known) record = view_records()[words[1]]; - ReleaseSRWLockShared(¬e_lock); + buffer_token_known = token_view(words, record); if (record.slot == 17 && record.desc_bytes >= 12) { std::uint32_t size = 0; std::memcpy(&address, record.desc, 8); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 56dbe26c48..91ca58e0ff 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -32,6 +32,7 @@ #include "startup_stubs/depth_state_apply.h" #include "startup_stubs/d16_image_format.h" #include "startup_stubs/formatted_buffer.h" +#include "startup_stubs/view_content_token.h" #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" @@ -6060,6 +6061,7 @@ void retire_drop_heap_views(Wrapper* heap) if (id - 1 < view_records().size() && view_materialized()[id - 1]) view_refs_release(view_records()[id - 1].slot, view_records()[id - 1].resource, view_records()[id - 1].counter); + shadow_ref_drop(id); } } ReleaseSRWLockExclusive(¬e_lock); @@ -6583,6 +6585,61 @@ extern "C" __declspec(dllexport) void x2w_d3d12_view_probe(unsigned long long ti } } +// Fixture export (startup_view_content): the view a 32-byte token names as the draw and dispatch readers resolve it +// (token_view), or the view the shadow slot of a title handle names when token is null. +struct ResolvedViewProbe { + unsigned known, slot, desc_bytes, materialized; + unsigned long long resource; + unsigned char desc[64]; +}; +extern "C" __declspec(dllexport) void x2w_d3d12_resolve_view(const void* token, unsigned long long title_handle, + ResolvedViewProbe* out) +{ + *out = {}; + ViewRecord record{}; + bool materialized = false, known = false; + if (token) { + std::uint32_t words[8]; + std::memcpy(words, token, sizeof(words)); + known = words[0] == view_token_magic && token_view(words, record, &materialized); + } else if (const std::uint32_t id = shadow_id(desktop_cpu_handle(title_handle))) { + AcquireSRWLockShared(¬e_lock); + known = id - 1 < view_records().size(); + if (known) { + record = view_records()[id - 1]; + materialized = view_materialized()[id - 1] != 0; + } + ReleaseSRWLockShared(¬e_lock); + } + if (!known) return; + out->known = 1; + out->slot = record.slot; + out->desc_bytes = record.desc_bytes; + out->materialized = materialized; + out->resource = record.resource; + std::memcpy(out->desc, record.desc, sizeof(out->desc)); +} +// Fixture export (startup_view_content): how many parked view records stay findable before the oldest is reused +// (default 65536), so a short fixture reaches the reuse. +extern "C" __declspec(dllexport) void x2w_d3d12_set_view_parked_keep(unsigned keep) +{ + AcquireSRWLockExclusive(¬e_lock); + view_parked_keep = keep; + ReleaseSRWLockExclusive(¬e_lock); +} +// Fixture export (startup_view_content): content tokens written, records parked (freed), reused and revived since the +// process started. +extern "C" __declspec(dllexport) void x2w_d3d12_view_content_counts(long long* written, long long* freed, long long* reused, + long long* revived) +{ + AcquireSRWLockShared(¬e_lock); + *written = content_tokens_written; + *freed = views_freed; + *reused = views_reused; + *revived = views_revived; + ReleaseSRWLockShared(¬e_lock); +} + // Fixture-only: the next `count` wrapper allocations fail as an exhausted heap would (#2653). extern "C" __declspec(dllexport) void x2w_d3d12_fail_wraps(LONG count) { @@ -7697,6 +7754,14 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "(region-information proofs %lld, region queries %lld)", views_noted, views_distinct, descriptors_copied, static_cast(heap_infos().size()), static_cast(placed_buffer_calls), static_cast(placed_buffer_region_info), static_cast(placed_buffer_queries)); + if (view_content_tokens()) { + AcquireSRWLockShared(¬e_lock); + const u64 records = view_records().size(), ids = view_ids().size(); + ReleaseSRWLockShared(¬e_lock); + log("x2w-d3d12 view content tokens: written %lld; records %llu (ids %llu, parked %u), parked %lld, reused %lld, " + "revived %lld", content_tokens_written, records, ids, view_parked_count, views_freed, views_reused, + views_revived); + } { char line[640]; if (view_census_line(line, sizeof(line))) log("%s", line); diff --git a/src/startup_stubs/view_content_token.h b/src/startup_stubs/view_content_token.h new file mode 100644 index 0000000000..56bd2dca51 --- /dev/null +++ b/src/startup_stubs/view_content_token.h @@ -0,0 +1,113 @@ +// Content view tokens (opt-in X2W_D3D12_VIEW_CONTENT_TOKENS=1, #1199): the 32-byte token note_view writes into title +// descriptor memory carries the view itself instead of a view record id, for the two kinds that fit: a constant +// buffer view and a buffer shader-resource view. A copy the title makes with its own memory copy then still names +// the view after the record behind the shadow slot is gone, so such records can be freed once no shadow slot names +// them (docs/startup-runtime.md#d3d12-view-content-tokens). +// +// Layout (32-bit words): [0] view token magic, [1] content_bit | flags, [2] slot (bits 0-7), [3] always 0, then +// slot 17: [4..5] BufferLocation, [6] SizeInBytes +// slot 18: [4..5] resource wrapper (where an id token keeps it), [6] FirstElement, [7] NumElements, and +// StructureByteStride in word 2 bits 8-31 +// with word 1 holding the created bit, and for slot 18 the format (bits 0-9), the raw flag (bit 10) and the component +// mapping (bits 11-23). An id token's word 1 is a record index below 2^31, so the content bit never appears there. +// Word 3 stays 0 as in an id token: the formatted-buffer readers put the word they build there in their copy. +#pragma once + +#include + +#include +#include +#include + +namespace x2w_startup { + +constexpr std::uint32_t view_content_bit = 0x80000000u; +constexpr std::uint32_t view_content_created = 0x40000000u; +constexpr std::size_t cbv_desc_bytes = 16; +constexpr std::size_t buffer_srv_desc_bytes = 40; +static_assert(sizeof(D3D12_CONSTANT_BUFFER_VIEW_DESC) == cbv_desc_bytes, "desktop CBV description layout"); +static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == buffer_srv_desc_bytes, "desktop SRV description layout"); + +struct ContentView { + std::uint32_t slot = 0; + std::uint64_t resource = 0; + std::uint32_t desc_bytes = 0; + unsigned char desc[buffer_srv_desc_bytes] = {}; + bool created = false; +}; + +inline bool is_view_content(const std::uint32_t* words) +{ + return (words[1] & view_content_bit) != 0; +} + +// Fills token and returns true when the view fits a content token; otherwise leaves token alone. +inline bool encode_view_content(std::uint32_t magic, std::uint32_t slot, std::uint64_t resource, std::uint64_t counter, + const unsigned char* desc, std::size_t desc_bytes, bool created, std::uint32_t (&token)[8]) +{ + if (counter || !desc) return false; + std::uint32_t out[8] = {magic, view_content_bit | (created ? view_content_created : 0u), slot, 0, 0, 0, 0, 0}; + if (slot == 17) { + if (resource || desc_bytes != cbv_desc_bytes) return false; + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv; + std::memcpy(&cbv, desc, sizeof(cbv)); + out[4] = static_cast(cbv.BufferLocation); + out[5] = static_cast(cbv.BufferLocation >> 32); + out[6] = cbv.SizeInBytes; + } else if (slot == 18) { + if (!resource || desc_bytes != buffer_srv_desc_bytes) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv; + std::memcpy(&srv, desc, sizeof(srv)); + if (srv.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || srv.Buffer.FirstElement > 0xffffffffull || + static_cast(srv.Format) >= (1u << 10) || srv.Shader4ComponentMapping >= (1u << 13) || + srv.Buffer.StructureByteStride >= (1u << 24) || + (srv.Buffer.Flags != D3D12_BUFFER_SRV_FLAG_NONE && srv.Buffer.Flags != D3D12_BUFFER_SRV_FLAG_RAW)) + return false; + out[1] |= static_cast(srv.Format) | (srv.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW ? 1u << 10 : 0u) | + srv.Shader4ComponentMapping << 11; + out[2] |= srv.Buffer.StructureByteStride << 8; + out[4] = static_cast(resource); + out[5] = static_cast(resource >> 32); + out[6] = static_cast(srv.Buffer.FirstElement); + out[7] = srv.Buffer.NumElements; + } else { + return false; + } + std::memcpy(token, out, sizeof(out)); + return true; +} + +// The view a content token names, with the description's padding bytes zero. Word 3 is not read. False for an id token +// or a word 2 that names no content kind. +inline bool decode_view_content(const std::uint32_t* words, ContentView& view) +{ + if (!is_view_content(words)) return false; + view = ContentView{}; + view.slot = words[2] & 0xffu; + view.created = (words[1] & view_content_created) != 0; + const std::uint64_t pointer = words[4] | static_cast(words[5]) << 32; + if (view.slot == 17) { + if (words[2] != 17) return false; + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; + cbv.BufferLocation = pointer; + cbv.SizeInBytes = words[6]; + view.desc_bytes = static_cast(cbv_desc_bytes); + std::memcpy(view.desc, &cbv, sizeof(cbv)); + return true; + } + if (view.slot != 18) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = static_cast(words[1] & 0x3ffu); + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = (words[1] >> 11) & 0x1fffu; + srv.Buffer.FirstElement = words[6]; + srv.Buffer.NumElements = words[7]; + srv.Buffer.StructureByteStride = words[2] >> 8; + srv.Buffer.Flags = (words[1] & (1u << 10)) ? D3D12_BUFFER_SRV_FLAG_RAW : D3D12_BUFFER_SRV_FLAG_NONE; + view.resource = pointer; + view.desc_bytes = static_cast(buffer_srv_desc_bytes); + std::memcpy(view.desc, &srv, sizeof(srv)); + return true; +} + +} // namespace x2w_startup diff --git a/tests/cmake/startup_view_alloc.cmake b/tests/cmake/startup_view_alloc.cmake index 46e6da25b2..fae4c3fcd0 100644 --- a/tests/cmake/startup_view_alloc.cmake +++ b/tests/cmake/startup_view_alloc.cmake @@ -14,6 +14,9 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME ${alloc_test} COMMAND startup_view_alloc ${backend} ${site} control) endif() set(alloc_env "X2W_D3D12_BUDGET=1;X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1") + # The fixture reads record ids from title-memory tokens and fills view_records until it grows, so it covers the + # id tokens only (X2W_D3D12_VIEW_CONTENT_TOKENS is covered by startup_view_content_*). + list(APPEND alloc_env "X2W_D3D12_VIEW_CONTENT_TOKENS=0") list(APPEND alloc_env "X2W_D3D12_DEBUG=0" "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/${alloc_test}.log") set_tests_properties(${alloc_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${alloc_env}") if(mode STREQUAL "control") diff --git a/tests/cmake/startup_view_content.cmake b/tests/cmake/startup_view_content.cmake new file mode 100644 index 0000000000..e07ee9d294 --- /dev/null +++ b/tests/cmake/startup_view_content.cmake @@ -0,0 +1,26 @@ +# #1199, X2W_D3D12_VIEW_CONTENT_TOKENS (docs/startup-runtime.md#d3d12-view-content-tokens). +# startup_view_content_token: the token encoding and decoding without a device (src/startup_stubs/view_content_token.h). +add_executable(startup_view_content_token_check tests/startup_view_content_token_check.cpp) +target_include_directories(startup_view_content_token_check PRIVATE src) +target_compile_features(startup_view_content_token_check PRIVATE cxx_std_17) +add_test(NAME startup_view_content_token COMMAND startup_view_content_token_check) +# startup_view_content__: title-side and shadow copies of buffer SRV, CBV and texture SRV tokens keep +# naming their view while the descriptor is overwritten 5000 times; with the switch on the buffer views' records are +# parked, revived and reused, and the record count stays bounded. +add_executable(startup_view_content tests/startup_view_content.cpp) +target_compile_features(startup_view_content PRIVATE cxx_std_17) +target_link_libraries(startup_view_content PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS off on) + set(content_test startup_view_content_${mode}_${backend}) + add_test(NAME ${content_test} COMMAND startup_view_content ${backend} ${mode}) + set(content_env "X2W_D3D12_BUDGET=1;X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1") + list(APPEND content_env "X2W_D3D12_DEBUG=0" "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/${content_test}.log") + if(mode STREQUAL "on") + list(APPEND content_env "X2W_D3D12_VIEW_CONTENT_TOKENS=1") + else() + list(APPEND content_env "X2W_D3D12_VIEW_CONTENT_TOKENS=0") + endif() + set_tests_properties(${content_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${content_env}") + endforeach() +endforeach() diff --git a/tests/startup_view_content.cpp b/tests/startup_view_content.cpp new file mode 100644 index 0000000000..b7331ba5ac --- /dev/null +++ b/tests/startup_view_content.cpp @@ -0,0 +1,296 @@ +// Content view tokens (X2W_D3D12_VIEW_CONTENT_TOKENS=1, prototype; view_content_token.h, d3d12_capture.inl). A buffer +// SRV, a CBV and a texture SRV go into a descriptor heap over title memory the fixture owns. The fixture keeps copies +// of their tokens in plain memory, as a title copies descriptors with its own memory copy, and copies the buffer SRV +// into a second descriptor with CopyDescriptorsSimple. Then 5000 other buffer SRVs are created into the first +// descriptor. In both modes every copy still resolves to the view it was made from, through the token readers' +// path (token_view) and through the second descriptor's shadow slot. With the switch on, the buffer views' records +// are freed and reused, so the record count stays bounded; with it off, it grows by one per view. +// +// startup_view_content +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1, plus X2W_D3D12_VIEW_CONTENT_TOKENS=1 for "on") +#include + +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +struct ViewStoreProbe { + unsigned long long records, materialized, ids, records_capacity, materialized_capacity; + unsigned shadow, view_refs, retire_when_idle; +}; +struct ResolvedViewProbe { + unsigned known, slot, desc_bytes, materialized; + unsigned long long resource; + unsigned char desc[64]; +}; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_view_probe(unsigned long long, void*, ViewStoreProbe*); +extern "C" __declspec(dllimport) void x2w_d3d12_resolve_view(const void*, unsigned long long, ResolvedViewProbe*); +extern "C" __declspec(dllimport) void x2w_d3d12_view_content_counts(long long*, long long*, long long*, long long*); +extern "C" __declspec(dllimport) void x2w_d3d12_set_view_parked_keep(unsigned); + +namespace { + +constexpr std::uint32_t token_magic = 0x56573258; // "X2WV" +constexpr std::uint32_t content_bit = 0x80000000u; +constexpr UINT descriptors = 8; +constexpr UINT overwrites = 5000; + +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; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_window(UINT64 first, UINT count) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv; + std::memset(&srv, 0, sizeof(srv)); + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.FirstElement = first; + srv.Buffer.NumElements = count; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return srv; +} + +struct Token { + std::uint32_t words[8]; +}; + +// The view a token copy or a descriptor's shadow slot names must be exactly `slot`, `resource` and `desc`. +// A CBV is recorded as not created (the stand-in keeps it title-side); every SRV here must be created. +template +void expect_view(const ResolvedViewProbe& got, unsigned slot, const void* resource, const Desc& desc, const char* what) +{ + const unsigned created = slot == 17 ? 0u : 1u; + const bool same = got.known && got.slot == slot && got.resource == reinterpret_cast(resource) && + got.desc_bytes == sizeof(desc) && !std::memcmp(got.desc, &desc, sizeof(desc)) && + got.materialized == created; + if (!same) + std::printf(" %s: known %u slot %u resource 0x%llx desc_bytes %u created %u\n", what, got.known, got.slot, + got.resource, got.desc_bytes, got.materialized); + expect(same, what); +} + +ResolvedViewProbe resolve(const Token& token) +{ + ResolvedViewProbe out{}; + x2w_d3d12_resolve_view(token.words, 0, &out); + return out; +} +ResolvedViewProbe resolve_shadow(UINT64 handle) +{ + ResolvedViewProbe out{}; + x2w_d3d12_resolve_view(nullptr, handle, &out); + return out; +} +ViewStoreProbe probe(UINT64 handle) +{ + ViewStoreProbe p{}; + x2w_d3d12_view_probe(handle, nullptr, &p); + return p; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (std::strcmp(argv[2], "off") && std::strcmp(argv[2], "on"))) + return 2; + const bool on = std::strcmp(argv[2], "on") == 0; + std::setvbuf(stdout, nullptr, _IONBF, 0); + wchar_t value[4]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_D3D12_VIEW_CONTENT_TOKENS", value, 4); + if (on != (length == 1 && value[0] == L'1')) { + std::puts("FAIL: X2W_D3D12_VIEW_CONTENT_TOKENS does not match the mode argument"); + 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; + // No parked records kept back, so the 5000 views reach the reuse (the stand-in keeps 65536). + x2w_d3d12_set_view_parked_keep(0); + const UINT stride = invoke(guest.Get(), 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!stride || UINT64{stride} * descriptors > 0x1000) return 3; + + void* memory = VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!memory) return 3; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, descriptors}, reinterpret_cast(memory), + UINT64{stride} * descriptors}; + ComPtr heap; + if (FAILED(invoke(guest.Get(), 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()))) return 3; + const auto handle = [&](UINT index) { return reinterpret_cast(memory) + UINT64{stride} * index; }; + const auto token_at = [&](UINT index) { + Token t; + std::memcpy(t.words, reinterpret_cast(handle(index)), sizeof(t.words)); + return t; + }; + + D3D12_HEAP_PROPERTIES default_heap{}; + default_heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC buffer_desc{}; + buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer_desc.Width = 0x40000; + buffer_desc.Height = buffer_desc.DepthOrArraySize = buffer_desc.MipLevels = 1; + buffer_desc.SampleDesc.Count = 1; + buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + 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 iid = __uuidof(ID3D12Resource); + ComPtr buffer, texture; + if (FAILED(invoke(guest.Get(), 27, &default_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COMMON, + static_cast(nullptr), &iid, reinterpret_cast(buffer.GetAddressOf()))) || + FAILED(invoke(guest.Get(), 27, &default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RESOURCE_STATE_COMMON, + static_cast(nullptr), &iid, reinterpret_cast(texture.GetAddressOf())))) + return 3; + const auto srv = [&](IUnknown* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC& desc, UINT index) { + invoke(guest.Get(), 18, static_cast(resource), &desc, handle(index)); + }; + + // 0: a buffer SRV, 1: a CBV, 2: a texture SRV; title-side copies of their tokens; 3: a shim-side copy of 0. + const D3D12_SHADER_RESOURCE_VIEW_DESC first = raw_window(0, 16); + srv(buffer.Get(), first, 0); + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; + cbv.BufferLocation = 0x00000123456789a0ull; + cbv.SizeInBytes = 256; + invoke(guest.Get(), 17, &cbv, handle(1)); + D3D12_SHADER_RESOURCE_VIEW_DESC texture_view; + std::memset(&texture_view, 0, sizeof(texture_view)); + texture_view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + texture_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + texture_view.Texture2D.MipLevels = 1; + srv(texture.Get(), texture_view, 2); + const Token buffer_copy = token_at(0), cbv_copy = token_at(1), texture_copy = token_at(2); + invoke(guest.Get(), 24, 1u, handle(3), handle(0), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + for (const Token* t : {&buffer_copy, &cbv_copy, &texture_copy}) + expect(t->words[0] == token_magic, "a descriptor holds no view token"); + expect(((buffer_copy.words[1] & content_bit) != 0) == on, "the buffer SRV token's kind does not match the mode"); + expect(((cbv_copy.words[1] & content_bit) != 0) == on, "the CBV token's kind does not match the mode"); + expect(!(texture_copy.words[1] & content_bit), "the texture SRV got a content token"); + expect(!std::memcmp(token_at(3).words, buffer_copy.words, sizeof(Token)), "the copied descriptor holds another token"); + const unsigned long long records_before = probe(handle(0)).records; + long long written0 = 0, freed0 = 0, reused0 = 0, revived0 = 0; + x2w_d3d12_view_content_counts(&written0, &freed0, &reused0, &revived0); + + for (UINT k = 1; k <= overwrites; ++k) srv(buffer.Get(), raw_window(UINT64{k} * 4, 16), 0); + const unsigned long long records_after = probe(handle(0)).records; + long long written = 0, freed = 0, reused = 0, revived = 0; + x2w_d3d12_view_content_counts(&written, &freed, &reused, &revived); + std::printf("records %llu -> %llu over %u buffer views; content tokens written %lld, records freed %lld, reused %lld\n", + records_before, records_after, overwrites, written - written0, freed - freed0, reused - reused0); + if (on) { + expect(records_after <= records_before + 8, "the records grew with content tokens"); + expect(written - written0 >= overwrites && freed - freed0 >= overwrites - 1 && reused - reused0 >= overwrites - 2, + "the buffer views' records were not freed and reused"); + } else { + expect(records_after >= records_before + overwrites, "the records did not grow by one per view without the switch"); + expect(written == 0 && freed == 0 && reused == 0, "content tokens or freed records without the switch"); + } + + // Every copy still names the view it was made from. + expect_view(resolve(buffer_copy), 18, buffer.Get(), first, "the title-side copy of the buffer SRV token"); + expect_view(resolve(cbv_copy), 17, nullptr, cbv, "the title-side copy of the CBV token"); + expect_view(resolve(texture_copy), 18, texture.Get(), texture_view, "the title-side copy of the texture SRV token"); + expect_view(resolve_shadow(handle(3)), 18, buffer.Get(), first, "the copied descriptor's shadow slot"); + expect_view(resolve_shadow(handle(0)), 18, buffer.Get(), raw_window(UINT64{overwrites} * 4, 16), + "the overwritten descriptor's shadow slot"); + expect_view(resolve(token_at(0)), 18, buffer.Get(), raw_window(UINT64{overwrites} * 4, 16), + "the overwritten descriptor's token"); + + // The last shadow slot naming the first view lets it go; its title-side copy still resolves. + srv(buffer.Get(), raw_window(8, 8), 3); + long long freed_last = 0; + x2w_d3d12_view_content_counts(&written, &freed_last, &reused, &revived); + if (on) expect(freed_last == freed + 1, "the first view's record was not freed with its last shadow slot"); + expect_view(resolve(buffer_copy), 18, buffer.Get(), first, "the title-side copy after the last shadow slot let go"); + + // The same view created again while its record is parked finds that record: no new record, one revival. + const unsigned long long records_parked = probe(handle(0)).records; + long long revived_before = 0, reused_before = 0; + x2w_d3d12_view_content_counts(&written, &freed, &reused_before, &revived_before); + srv(buffer.Get(), first, 6); + x2w_d3d12_view_content_counts(&written, &freed, &reused, &revived); + expect_view(resolve_shadow(handle(6)), 18, buffer.Get(), first, "the re-created first view's shadow slot"); + expect_view(resolve(token_at(6)), 18, buffer.Get(), first, "the re-created first view's token"); + std::printf("re-created first view: revived %lld -> %lld, reused %lld -> %lld, records %llu -> %llu\n", revived_before, + revived, reused_before, reused, records_parked, probe(handle(0)).records); + if (on) + expect(revived == revived_before + 1 && reused == reused_before && probe(handle(0)).records == records_parked, + "the re-created first view did not revive its parked record"); + + // Padding bytes do not make another content token. + D3D12_SHADER_RESOURCE_VIEW_DESC padded = raw_window(40000, 16); + std::memset(reinterpret_cast(&padded) + 12, 0xcd, 4); + srv(buffer.Get(), padded, 4); + srv(buffer.Get(), raw_window(40000, 16), 5); + expect(!std::memcmp(token_at(4).words, token_at(5).words, sizeof(Token)) == on, + "views that differ only in padding bytes: content tokens differ, or id tokens match"); + + // The first view's record is parked again and then reused for other views (the fixture keeps none back); the + // title-side copy of its token must still name it. + srv(buffer.Get(), raw_window(16, 8), 6); + for (UINT k = 0; k < 4; ++k) srv(buffer.Get(), raw_window(UINT64{k} * 4 + 32, 4), 0); + expect_view(resolve(buffer_copy), 18, buffer.Get(), first, "the title-side copy after its record was reused"); + + if (failures) return 1; + std::printf("PASS (%s)\n", argv[2]); + return 0; +} diff --git a/tests/startup_view_content_token_check.cpp b/tests/startup_view_content_token_check.cpp new file mode 100644 index 0000000000..394cdda316 --- /dev/null +++ b/tests/startup_view_content_token_check.cpp @@ -0,0 +1,135 @@ +// Checks src/startup_stubs/view_content_token.h without a device: which views fit a content token, and that the +// decoded view equals the created one with its padding bytes zero. +#include "startup_stubs/view_content_token.h" + +#include +#include +#include + +namespace { +using x2w_startup::ContentView; +constexpr std::uint32_t magic = 0x56573258; +int failures; + +void fail(const char* name, const char* what) +{ + std::printf("FAIL %s: %s\n", name, what); + ++failures; +} + +template +void round_trip(const char* name, std::uint32_t slot, std::uint64_t resource, const Desc& desc, bool created) +{ + std::uint32_t token[8] = {}; + if (!x2w_startup::encode_view_content(magic, slot, resource, 0, reinterpret_cast(&desc), + sizeof(desc), created, token)) + return fail(name, "not encoded"); + if (token[0] != magic || !x2w_startup::is_view_content(token) || (token[2] & 0xffu) != slot || token[3]) + return fail(name, "token header"); + ContentView view; + if (!x2w_startup::decode_view_content(token, view)) return fail(name, "not decoded"); + // The formatted-buffer readers write their own word 3 into the copy they decode. + std::uint32_t scribbled[8]; + std::memcpy(scribbled, token, sizeof(scribbled)); + scribbled[3] = 0xdeadbeefu; + ContentView again; + if (!x2w_startup::decode_view_content(scribbled, again) || again.slot != view.slot || again.resource != view.resource || + again.created != view.created || again.desc_bytes != view.desc_bytes || std::memcmp(again.desc, view.desc, sizeof(view.desc))) + return fail(name, "word 3 changes the decoded view"); + if (view.slot != slot || view.resource != resource || view.created != created || view.desc_bytes != sizeof(desc)) + return fail(name, "decoded fields"); + if (std::memcmp(view.desc, &desc, sizeof(desc))) return fail(name, "decoded description"); +} + +template +void refused(const char* name, std::uint32_t slot, std::uint64_t resource, std::uint64_t counter, const Desc& desc) +{ + std::uint32_t token[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + if (x2w_startup::encode_view_content(magic, slot, resource, counter, reinterpret_cast(&desc), + sizeof(desc), true, token)) + return fail(name, "encoded"); + if (token[0] != 1 || token[7] != 8) fail(name, "token changed"); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_srv(std::uint64_t first, UINT count) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.FirstElement = first; + srv.Buffer.NumElements = count; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return srv; +} +} // namespace + +int main() +{ + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; + cbv.BufferLocation = 0x00000123456789a0ull; + cbv.SizeInBytes = 0x1100; + round_trip("cbv", 17, 0, cbv, true); + round_trip("cbv not created", 17, 0, cbv, false); + + round_trip("raw srv", 18, 0x000001f5249d7fe0ull, raw_srv(0xfffffff0u, 72), true); + D3D12_SHADER_RESOURCE_VIEW_DESC structured{}; + structured.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + structured.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0); + structured.Buffer.FirstElement = 17; + structured.Buffer.NumElements = 4096; + structured.Buffer.StructureByteStride = 48; + round_trip("structured srv", 18, 0x7ff612340000ull, structured, true); + D3D12_SHADER_RESOURCE_VIEW_DESC typed = structured; + typed.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + typed.Buffer.StructureByteStride = 0; + round_trip("typed srv", 18, 0x7ff612340000ull, typed, true); + + // Padding bytes do not survive: two views that differ only there get the same token. + D3D12_SHADER_RESOURCE_VIEW_DESC padded = raw_srv(64, 16), clean = raw_srv(64, 16); + std::memset(reinterpret_cast(&padded) + 12, 0xcd, 4); + std::memset(reinterpret_cast(&padded) + 36, 0xcd, 4); + std::uint32_t a[8], b[8]; + if (!x2w_startup::encode_view_content(magic, 18, 0x1000, 0, reinterpret_cast(&padded), 40, true, a) || + !x2w_startup::encode_view_content(magic, 18, 0x1000, 0, reinterpret_cast(&clean), 40, true, b) || + std::memcmp(a, b, sizeof(a))) + fail("padding", "padded and clean views differ"); + // A view that differs in any kept field gets another token. + const D3D12_SHADER_RESOURCE_VIEW_DESC other = raw_srv(65, 16); + if (!x2w_startup::encode_view_content(magic, 18, 0x1000, 0, reinterpret_cast(&other), 40, true, b) || + !std::memcmp(a, b, sizeof(a))) + fail("first element", "different views share a token"); + + refused("first element above 32 bits", 18, 0x1000, 0, raw_srv(0x100000000ull, 4)); + D3D12_SHADER_RESOURCE_VIEW_DESC texture{}; + texture.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + texture.Texture2D.MipLevels = 1; + refused("texture srv", 18, 0x1000, 0, texture); + refused("srv without resource", 18, 0, 0, raw_srv(0, 4)); + refused("srv with counter", 18, 0x1000, 0x2000, raw_srv(0, 4)); + D3D12_SHADER_RESOURCE_VIEW_DESC wide_format = typed; + wide_format.Format = static_cast(1024); + refused("format above 10 bits", 18, 0x1000, 0, wide_format); + D3D12_SHADER_RESOURCE_VIEW_DESC wide_stride = structured; + wide_stride.Buffer.StructureByteStride = 1u << 24; + refused("stride above 24 bits", 18, 0x1000, 0, wide_stride); + refused("cbv with resource", 17, 0x1000, 0, cbv); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + refused("uav", 19, 0x1000, 0, uav); + D3D12_SAMPLER_DESC sampler{}; + refused("sampler", 22, 0, 0, sampler); + std::uint32_t short_desc[8] = {}; + if (x2w_startup::encode_view_content(magic, 17, 0, 0, reinterpret_cast(&cbv), 12, true, short_desc)) + fail("short cbv description", "encoded"); + + // An id token is not a content token. + const std::uint32_t id_token[8] = {magic, 0x7fffffffu, 18, 0, 0x1000, 0, 0, 0}; + ContentView view; + if (x2w_startup::is_view_content(id_token) || x2w_startup::decode_view_content(id_token, view)) + fail("id token", "read as content"); + + if (failures) return 1; + std::printf("view content tokens: all checks passed\n"); + return 0; +}