From ec7318d80e2397ac50573b3a03c786860bf435b8 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 03:47:29 +0100 Subject: [PATCH 01/19] native: translate GPU-selected heap textures through view tokens in compute A compute program that loads a texture with s_load_dwordx8 from the directly indexed resource heap at an SGPR offset chosen by GPU data is now translated when every use of the eight words is the T# of a supported image instruction (1D, 2D or 2D-array load, load_mip, sample_l, sample_lz, 2D gather4_lz, get_resinfo). The shader reads the 32-byte view token at the guest byte address, checks the magic, the view id range and the dimension recorded for the id, and samples ResourceDescriptorHeap[base(dimension) + id] (a null slot otherwise, counting one miss per wave). The manifest names the runtime- provided views and words (heaptok, heaptokdims, heaptokmiss, five heaptok words); the runtime reader still refuses them by name, so dispatch behaviour is unchanged. Not independently design-approved: see the PR description. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 2 + .../experiments/native-heap-token-textures.md | 53 +++ src/direct_compute_cache.cpp | 40 +- src/gfx1013_compute_native.cpp | 167 ++++++- src/gfx1013_compute_native.h | 13 +- src/gfx1013_direct_compute.inl | 118 ++++- src/native_compute_output.h | 2 +- src/native_compute_pipeline.cpp | 9 +- src/native_compute_pipeline.h | 1 + src/startup_stubs/d3d12_compute_dispatch.inl | 6 + tests/cmake/native_heap_token_texture.cmake | 15 + tests/native_compile_dxil_watch_check.py | 3 +- tests/native_compute_manifest_reasons.cpp | 49 +- tests/native_heap_token_texture.cpp | 437 ++++++++++++++++++ tests/native_heap_token_texture_check.py | 318 +++++++++++++ tests/native_startup_request_cache_check.py | 9 +- tests/startup_compute_dispatch_check.py | 9 +- .../startup_compute_dispatch_texture_check.py | 4 + tools/startup/triage_run.py | 1 + 19 files changed, 1235 insertions(+), 21 deletions(-) create mode 100644 docs/experiments/native-heap-token-textures.md create mode 100644 tests/cmake/native_heap_token_texture.cmake create mode 100644 tests/native_heap_token_texture.cpp create mode 100644 tests/native_heap_token_texture_check.py diff --git a/docs/experiments.md b/docs/experiments.md index 3fff98730d..de7bdfc6dc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18031,3 +18031,5 @@ ctest --preset dev --no-tests=error -j1 -R '^native_pixel_atomic_(warp|hardware) ``` Repeat with the release preset. The source-built fixture verifies 13 actual draws and four refusal controls per adapter/configuration, including contention, guard words, active out-of-view, odd raster edges and real WQM quad-neighbor reads with and without GLC. WQM+GLC records returned old values through a second exact atomic in a private lane slot and checks a valid serialization of the varying addends. Local RX 7900 XT/WARP Debug/Release integration over main 4b0350e passed 52 draws, 3328 DWORD and 1664 pixel comparisons, and 16 refusal controls. The debug layer was unavailable; actual title rendering is not established. + +See [GPU-selected heap textures through view tokens in native compute](experiments/native-heap-token-textures.md) (#3023 stage 3, translator only) for the `heaptok` manifest lines the runtime still refuses. diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md new file mode 100644 index 0000000000..e554728108 --- /dev/null +++ b/docs/experiments/native-heap-token-textures.md @@ -0,0 +1,53 @@ +# GPU-selected heap textures through view tokens in native compute (translator, #3023 stage 3, PR 1) + +Issue #3023. The native compute translator accepts a texture that the program loads with `s_load_dwordx8` from the directly +indexed resource heap at a byte offset chosen by GPU data (a "heap token texture"). This change is the translator, the +manifest writer, the reader refusal and the fixtures. The runtime still refuses the new manifest lines by name ("heap token +textures are not bound yet"), so no dispatch behaviour changes. The runtime side (binding the token memory, the dimension +table and the host descriptor ranges) is a later change. + +## Why a token + +The guest computes the descriptor address itself and the title copies descriptors with its own memory copies, so the +translator cannot mirror heap slots. What the title keeps at the descriptor address of a registered view is a 32-byte view +token: word 0 the magic `0x56573258`, word 1 the view id (a content token has bit 31 set and is not an id). The shader reads +those two words at the guest byte address and maps the id to a host descriptor. + +## What the translator does + +- A program is eligible when every reached `s_load_dwordx8` from the resource heap with an SGPR offset (a token load) is + used only as the T# of `image_load`, `image_load_mip`, `image_sample_l`, `image_sample_lz`, `image_gather4_lz` (2D) or + `image_get_resinfo` of a 1D, 2D or 2D-array view, without D16. A copy, a numeric read, an image field read, a store, a + comparison, cube or 3D use or a partial use makes the program not eligible; it then keeps today's analysis and its + refusal text. An eligible program is analysed a second time with the byte address kept in the destination SGPRs + (`heap_tokens` in `transfer()` and `parse()`). +- The load handler requires an immediate offset and a proven SGPR offset (`constant` or `masked`) that are multiples of 4, + writes `so + imm` to the eight words, and bypasses the heap view contract: the contract exists because the runtime cannot + vouch for the view kind of a GPU-selected slot, and this route checks it on every execution. +- Per image instruction of dimension `d`: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 1 + d`; + the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null]` (kind 1, 2 or 7, `nonuniform` false: every lane loads + the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`). +- Five more `b0` words follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views + (root parameter `compute_heap_token`): the token memory (`heap_token_srv`, a raw SRV), the dimension table + (`heap_token_dims_srv`, a raw SRV with one uint per view id: 0 none, else 1 + the image dimension) and the miss counter + (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module + names the registers while it is lowered. +- Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, `udsrc K heaptok base1d|base2d|base2da|count|null`. + `native_compute_output_revision` is 2. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. + +## Tests + +- `native_heap_token_texture_controls`: compiles source-written requests; checks the published manifest, the module's heap + handle, wave-first-lane and atomic add, and each consumer or address shape that keeps today's refusal text or gets a new one + (`heap token byte offset has no proven 4-byte aligned range`, `unaligned heap token immediate byte offset`). +- `native_heap_token_texture_warp` and `_hardware`: the rig runs 1D, 2D and 2D-array programs on a host heap with one range + per dimension; a valid token gives the texel of its view and no miss; a wrong magic, an id equal to the count, the largest + id, an id of another dimension, a content token, id 0 and an empty token give the null texel and one miss per wave. WARP has + no 32-lane waves and reports 77. +- `native_compute_manifest_reasons` covers the writer; `startup_compute_dispatch_texture` the reader refusal. + +## Open + +The null slot has one word; a null view of another dimension than the instruction's is not defined by D3D12 for dynamic +indexing, so the runtime change has to provide a null slot that every dimension may read (the fixture uses a null view of the +dimension under test). diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index ab7ff78833..b7f97527e5 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -101,6 +101,7 @@ Bytes encode(const NativeComputeShader &program) { for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) word(out, n); word(out, program.sampler_heap); + word(out, program.heap_token_words); word(out, static_cast(program.stride_srvs.size())); for (unsigned srv : program.stride_srvs) word(out, srv); @@ -135,14 +136,17 @@ NativeComputeShader decode(std::string_view bytes) { unsigned n = in.count(1000000); shader.bindings.reserve(n); for (unsigned j = 0; j < n; ++j) { - auto kind = static_cast(in.count(static_cast(ComputeViewKind::root_buffer_uav))); + auto kind = static_cast(in.count(static_cast(ComputeViewKind::heap_token_miss_uav))); ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); b.requires_identity_dst_sel = in.count(1) != 0; const bool sampler_heap = kind == ComputeViewKind::heap_sampler; + const bool token = kind == ComputeViewKind::heap_token_srv || kind == ComputeViewKind::heap_token_dims_srv || + kind == ComputeViewKind::heap_token_miss_uav; if (!b.array_count || b.array_position >= b.array_count || (sampler_heap ? b.root_parameter != compute_sampler_heap - : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) + : token ? b.root_parameter != compute_heap_token + : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) throw std::runtime_error("invalid cached binding"); shader.bindings.push_back(b); } @@ -154,6 +158,7 @@ NativeComputeShader decode(std::string_view bytes) { shader.constants.push_back(c); } shader.sampler_heap = in.count(1) != 0; + shader.heap_token_words = in.count(1) != 0; n = in.count(32); for (unsigned j = 0; j < n; ++j) shader.stride_srvs.push_back(in.count(31)); @@ -898,9 +903,10 @@ static const char *view_kind_name(ComputeViewKind kind) { "comparison_texture_srv", "half2_texture_uav", "half4_texture_uav", "cube_sample_srv", "cube_comparison_srv", "indexed_atomic_uav", "d16_sample_srv", "byte_window_srv", "heap_buffer_srv", "heap_sampler", "uint_texture_uav", "float_texture_uav", "float2_texture_uav", "float3_texture_uav", "packed_d16_x_uav", - "indexed_raw_srv", "heap_typed_srv", "root_buffer_uav"}; + "indexed_raw_srv", "heap_typed_srv", "root_buffer_uav", "heap_token_srv", "heap_token_dims_srv", + "heap_token_miss_uav"}; // ponytail: catches a renamed last kind, not one appended after it; extend both together. - static_assert(std::size(names) == static_cast(ComputeViewKind::root_buffer_uav) + 1); + static_assert(std::size(names) == static_cast(ComputeViewKind::heap_token_miss_uav) + 1); const auto index = static_cast(kind); return index < std::size(names) ? names[index] : "unknown"; } @@ -936,7 +942,7 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("more than 8 root constants in one root parameter"); ud_count += block.count; } - ud_count += static_cast(program.stride_srvs.size()); + ud_count += static_cast(program.stride_srvs.size()) + (program.heap_token_words ? 5u : 0u); if (ud_count > 32) return refuse("more than 32 user data words"); @@ -950,7 +956,25 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh unsigned srv_count = 0, uav_count = 0; std::ostringstream srv_lines, uav_lines, sampler_lines; + unsigned token_views[3]{}; for (const auto &b : sorted) { + // The runtime-provided views of GPU-selected heap textures: the view token memory, the dimension table and the + // miss counter. They take table registers like any view; the runtime reader does not bind them yet. + const bool token_view = b.kind == ComputeViewKind::heap_token_srv || b.kind == ComputeViewKind::heap_token_dims_srv || + b.kind == ComputeViewKind::heap_token_miss_uav; + if (token_view != (b.root_parameter == compute_heap_token)) + return refuse("heap token view with another root parameter"); + if (token_view) { + if (!program.heap_token_words || b.array_count != 1) + return refuse("heap token view without heap token words"); + const bool miss = b.kind == ComputeViewKind::heap_token_miss_uav; + if (b.shader_register != (miss ? uav_count++ : srv_count++)) + return refuse(miss ? "UAV registers not contiguous" : "SRV registers not contiguous"); + ++token_views[b.kind == ComputeViewKind::heap_token_srv ? 0 : b.kind == ComputeViewKind::heap_token_dims_srv ? 1 : 2]; + (miss ? uav_lines : srv_lines) << (miss ? "uav " : "srv ") << b.shader_register + << (miss ? " heaptokmiss" : b.kind == ComputeViewKind::heap_token_srv ? " heaptok" : " heaptokdims") << '\n'; + continue; + } if (b.root_parameter == compute_resource_heap) return refuse("resource heap view"); if (b.root_parameter == compute_sampler_heap) @@ -1069,6 +1093,12 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("stride words from a view that is not one raw vector SRV"); out << "udsrc " << ud_index++ << " stride " << srv << '\n'; } + if (program.heap_token_words) { + if (token_views[0] != 1 || token_views[1] != 1 || token_views[2] != 1) + return refuse("heap token words without the three heap token views"); + for (const char *word : {"base1d", "base2d", "base2da", "count", "null"}) + out << "udsrc " << ud_index++ << " heaptok " << word << '\n'; + } out << srv_lines.str() << uav_lines.str() << sampler_lines.str() << "native " << native_compute_output_revision << '\n'; return out.str(); diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 65ff47aece..a3732e5b14 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -685,7 +685,7 @@ static std::optional byte_descriptor_field(const Inst &i, const State &s return {}; } State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_window, bool direct, - bool narrow_wave64 = false) { + bool narrow_wave64 = false, bool heap_tokens = false) { auto set = [&](unsigned n, Symbol v) { if (n >= s.size()) refuse(i.pc, "invalid SGPR"); @@ -752,7 +752,8 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win Symbol v{}; if (heap_address) { v = {Symbol::Type::indexed_descriptor, compute_resource_heap, (i.b & 0xfffff) + 4 * j, base.index_mask, i.pc}; - } else if (graphics && i.op == 3 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + } else if ((graphics || (heap_tokens && offset_reg != 125)) && i.op == 3 && + base.type == Symbol::Type::table && base.value == compute_resource_heap) { const bool fixed = offset_reg == 125 || index.type == Symbol::Type::constant; const Word offset = (i.b & 0xfffff) + (offset_reg != 125 && fixed ? index.value : 0); v = {Symbol::Type::indexed_descriptor, base.value, offset + 4*j, @@ -916,7 +917,7 @@ std::map fixed_vertex_loads(const string &code) { return found ? result : std::map{}; } Program parse(const string &code, unsigned entry, const State &initial, bool graph, bool graphics=false, bool wave64=false, bool fixed_vertex=false, - bool heap_window=false, bool narrow_wave64=false) { + bool heap_window=false, bool narrow_wave64=false, bool heap_tokens=false) { Program p; p.graphics_wave64 = graphics && wave64; if ((entry & 3) || entry >= code.size() || code.size() > 1u << 20) @@ -965,7 +966,7 @@ Program parse(const string &code, unsigned entry, const State &initial, bool gra auto k = work.front(); work.pop_front(); auto &i = p.code[k]; - auto after = transfer(i, p.before[k], wave64, graphics, heap_window, graph, narrow_wave64); + auto after = transfer(i, p.before[k], wave64, graphics, heap_window, graph, narrow_wave64, heap_tokens); auto merge = [&](size_t t) { bool changed = !p.reached[t]; auto &in = p.before[t]; @@ -1737,6 +1738,143 @@ void lower_blocks(Emit &e) { out << "}\n"; } } +// GPU-selected heap textures (view tokens). A consumer of a token load: the image instruction and its dimension. +struct HeapTokenLoad { + unsigned pc, dim; +}; +// SGPR ranges {first, count} an instruction may read, widened where the operand width is not known exactly. Anything +// that cannot be listed (indexed SGPR moves) reads everything. +static std::vector> conservative_sgpr_reads(const Inst &i) { + std::vector> out; + auto add = [&](unsigned first, unsigned count) { + if (first < 106) out.emplace_back(first, count); + }; + const bool wide = i.name.find("64") != Name::npos; + switch (i.enc) { + case Encoding::Sop1: case Encoding::Sop2: case Encoding::Sopc: case Encoding::Sopk: case Encoding::Vop1: + case Encoding::Vop2: case Encoding::Vopc: case Encoding::Vop3: case Encoding::Mix: case Encoding::QuadCompare: + for (unsigned k = 0; k < 3; ++k) + add(i.src[k], wide ? 2 : 1); + if (i.enc == Encoding::Sopk) add(i.dst, 1); + break; + case Encoding::Smem: + add(i.src[0], i.op >= 8 ? 4 : 2); + add(i.b >> 25, 1); + break; + case Encoding::Mubuf: + if (i.name.substr(0, 7) == "global_") add((i.b >> 16) & 127, 2); + else add(((i.b >> 16) & 31) * 4, 4); + add(i.b >> 24, 1); + break; + case Encoding::Image: + add(((i.b >> 21) & 31) * 4, 4); + break; + default: + break; + } + if (i.name.find("movrel") != Name::npos) + out.emplace_back(0, 106); + return out; +} +// The pre-pass of the heap token route. Every reached s_load_dwordx8 from the resource heap with an SGPR offset is a +// token load. The program is eligible when every later read of the eight words (until they are overwritten) is the +// T# of an image_load, image_load_mip, image_sample_l, image_sample_lz, image_gather4_lz (2D) or image_get_resinfo of +// dimension 1D, 2D or 2D array, without D16; a copy, a numeric read, a store, a comparison, cube or 3D use, a +// partial use or a read of the words by an instruction this function cannot place makes it not eligible. `p` is +// the analysis with heap_tokens set. Returns false when there is no token load. +static bool heap_token_eligible(const Program &p, std::vector &consumers) { + consumers.clear(); + std::vector loads; + for (size_t n = 0; n < p.code.size(); ++n) { + const auto &i = p.code[n]; + if (!p.reached[n] || i.enc != Encoding::Smem || i.op != 3 || (i.b >> 25) == 125) continue; + const auto &base = p.before[n].at(i.src[0]); + if (base.type == Symbol::Type::table && base.value == compute_resource_heap) + loads.push_back(n); + } + if (loads.empty()) return false; + // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. + for (size_t n = 0; n < p.code.size(); ++n) { + const auto &i = p.code[n]; + if (p.reached[n] && i.enc == Encoding::Smem && i.op == 2 && (i.b >> 25) == 125 && + p.before[n].at(i.src[0]).type == Symbol::Type::heap_offset) + return false; + } + for (const size_t l : loads) { + const auto &load = p.code[l]; + if (load.dst + 8 > 106) return false; + // The instructions that can run after this load. A word of the load that reaches one of them without being + // overwritten, but not as the exact token symbol (a join with a path that skipped the load loses it), is a read + // the second analysis could not place: the load is not eligible. + std::vector after(p.code.size()); + { + std::vector pending; + const auto visit = [&](size_t n) { + if (!after[n]) { after[n] = true; pending.push_back(n); } + }; + const auto successors = [&](size_t n) { + const auto &i = p.code[n]; + if (i.branch()) { + const auto t = p.at.find(i.target()); + if (t != p.at.end()) visit(t->second); + } + if (i.name != "s_endpgm" && !(i.branch() && i.op == 2) && n + 1 < p.code.size()) visit(n + 1); + }; + successors(l); + while (!pending.empty()) { + const size_t n = pending.back(); + pending.pop_back(); + successors(n); + } + } + for (size_t n = 0; n < p.code.size(); ++n) { + if (n == l || !p.reached[n]) continue; + const auto &state = p.before[n]; + std::array token{}; + bool any = false; + for (unsigned r = 0; r < 106; ++r) { + const auto &s = state[r]; + token[r] = s.type == Symbol::Type::indexed_descriptor && s.value == compute_resource_heap && + s.definition == load.pc; + any |= token[r]; + } + const auto &i = p.code[n]; + if (after[n]) { + auto reads = conservative_sgpr_reads(i); + if (i.enc == Encoding::Image) reads.emplace_back(((i.b >> 16) & 31) * 4, 8); + for (const auto &[first, count] : reads) + for (unsigned r = first; r < first + count && r < 106; ++r) + if (r >= load.dst && r < load.dst + 8 && !token[r] && !state[r].numeric() && + !(state[r].type == Symbol::Type::indexed_descriptor && state[r].value == compute_resource_heap)) + return false; + } + if (!any) continue; + if (i.enc == Encoding::Image) { + const unsigned base = ((i.b >> 16) & 31) * 4; + unsigned held = 0; + for (unsigned j = 0; j < 8; ++j) held += base + j < 106 && token[base + j]; + if (held) { + const unsigned dim = (i.a >> 3) & 7; + const bool op_ok = i.op == 0 || i.op == 1 || i.op == 14 || i.op == 36 || i.op == 39 || + (i.op == 71 && dim == 1); + if (held != 8 || !op_ok || (dim != 0 && dim != 1 && dim != 5) || (i.b >> 31)) return false; + for (unsigned j = 1; j < 8; ++j) { + auto expected = state[base]; + expected.offset += 4 * j; + if (!(state[base + j] == expected)) return false; + } + if (std::none_of(consumers.begin(), consumers.end(), + [&](const auto &c) { return c.pc == i.pc && c.dim == dim; })) + consumers.push_back({i.pc, dim}); + } + } + for (const auto &[first, count] : conservative_sgpr_reads(i)) + for (unsigned r = first; r < first + count && r < 106; ++r) + if (token[r]) return false; + } + } + return true; +} #include "gfx1013_direct_compute.inl" #include "gfx1013_direct_graphics.inl" #include "gfx1013_direct_mesh.inl" @@ -1872,6 +2010,25 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi const bool heap_window = direct_dxil && (heap_view == HeapViewContract::raw_buffer || heap_view == HeapViewContract::raw_and_typed_dword); auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64); + // A GPU-selected texture loaded with s_load_dwordx8 from the resource heap: when every such load is only used as the + // T# of a supported image instruction, translate the program on the analysis that keeps the byte address. + std::vector token_consumers; + bool heap_tokens = false; + bool token_candidate = false; + for (size_t n = 0; direct_dxil && !stage && n < program.code.size() && !token_candidate; ++n) { + const auto &i = program.code[n]; + if (program.reached[n] && i.enc == Encoding::Smem && i.op == 3 && (i.b >> 25) != 125) { + const auto &base = program.before[n].at(i.src[0]); + token_candidate = base.type == Symbol::Type::table && base.value == compute_resource_heap; + } + } + if (token_candidate) { + auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, true); + if (heap_token_eligible(tokens, token_consumers)) { + program = std::move(tokens); + heap_tokens = true; + } + } Emit emit{{}, program,layout->Desc_1_1}; emit.result.constants = constants; if (!lds) @@ -1885,6 +2042,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi compiler.narrow_wave64 = narrow_wave64; compiler.heap_view = heap_view; compiler.heap_window = heap_window; + compiler.heap_tokens = heap_tokens; + compiler.heap_token_consumers = token_consumers; for (size_t i = 0; i < program.code.size(); ++i) { const auto& inst = program.code[i]; if (!program.reached[i]) continue; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 23855e0e1c..cfc75d84a0 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -49,7 +49,13 @@ enum class ComputeViewKind { indexed_raw_srv, // Fixed-stride record read. required_bytes is one complete record and its checked stride. heap_typed_srv, // A one-channel 32-bit typed buffer read the same way (HeapViewContract::typed_dword). // A raw buffer bound as a root UAV. The guest address is the root pointer plus a VGPR offset. - root_buffer_uav + root_buffer_uav, + // Runtime-provided bindings of GPU-selected heap textures (view tokens). heap_token_srv: raw view over the title view-heap + // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, else 1 + image dimension); the miss UAV + // is one raw dword counting the waves that read the null slot. + heap_token_srv, + heap_token_dims_srv, + heap_token_miss_uav }; inline unsigned exact_texture_uav_channels(ComputeViewKind kind) { switch (kind) { @@ -65,6 +71,8 @@ inline bool accepts_cbv_window(ComputeViewKind kind) { inline constexpr unsigned compute_resource_heap = ~0u; // the directly indexed sampler heap; entry n is title byte offset 16 * n inline constexpr unsigned compute_sampler_heap = ~0u - 1; +// The root parameter of the runtime-provided heap token bindings (not title tables). +inline constexpr unsigned compute_heap_token = ~0u - 2; // A binding of the whole descriptor heap: it has no table register and no root parameter. inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv || kind == ComputeViewKind::heap_typed_srv; @@ -81,6 +89,7 @@ inline bool compute_uav(ComputeViewKind kind) { return kind == ComputeViewKind::texture_uav || kind == ComputeViewKind::half_scalar_uav || kind == ComputeViewKind::half2_texture_uav || kind == ComputeViewKind::half4_texture_uav || kind == ComputeViewKind::uint_texture_uav || kind == ComputeViewKind::root_buffer_uav || + kind == ComputeViewKind::heap_token_miss_uav || exact_texture_uav_channels(kind) || compute_buffer_uav(kind); } struct ComputeViewBinding { @@ -141,6 +150,8 @@ struct NativeComputeShader { std::vector constants; // Additional b0 words, after root constants, read from these bound SRVs. std::vector stride_srvs; + // Five more b0 words after the stride words: base1d, base2d, base2da, count, null (heap token textures). + bool heap_token_words = false; std::string hlsl, dxil_ir; std::vector bindings; std::vector samplers; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 5c95a73e10..c3c31b8935 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -88,6 +88,14 @@ struct DirectCompute { unsigned mode_bits = 0xf0; std::vector scc_live; std::map,string> descriptor_strides; + // GPU-selected heap textures through view tokens (the program passed heap_token_eligible). The registers are taken + // before the program is lowered, because the DXIL names them; the five words are base1d, base2d, base2da, count, null. + bool heap_tokens = false; + std::vector heap_token_consumers; + std::array heap_token_values; + unsigned token_srv = 0, token_dims_srv = 0, token_miss_uav = 0; + // The views and words exist only when a program uses a token texture (an unused token load needs none). + bool token_bindings() const { return heap_tokens && !heap_token_consumers.empty(); } unsigned label_number = 0; bool pixel_stage = false; bool pixel_heap_enabled = false; @@ -342,7 +350,7 @@ struct DirectCompute { initialize_constants(); } void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { - unsigned words = static_cast(descriptor_strides.size()); + unsigned words = static_cast(descriptor_strides.size()) + (token_bindings() ? 5u : 0u); for (const auto &block : analysis.result.constants) words += block.count; if (words) { @@ -366,6 +374,9 @@ struct DirectCompute { } for (auto &entry : descriptor_strides) entry.second = ir.binary("and",word_at(pos++),"16383"); + for (auto &value : heap_token_values) + if (token_bindings()) + value = word_at(pos++); } } // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer, typed_dword and raw_and_typed_dword @@ -718,6 +729,24 @@ struct DirectCompute { write(i.dst + j, index); return; } + if (heap_tokens && !pixel_stage && low.type == Symbol::Type::table && low.value == compute_resource_heap && + i.op == 3 && so != 125) { + // A view token read from the title's heap memory at the guest byte address so + imm (see + // heap_token_texture). The contract gate (refuse_heap_contract) does not apply: this route checks the + // magic, the view id and the dimension on every execution instead of trusting a captured view type. + if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) + refuse(i.pc, "invalid heap token texture descriptor address"); + const Word offset = i.b & 0xfffff; + if (offset & 3) refuse(i.pc, "unaligned heap token immediate byte offset"); + if (so >= limit) refuse(i.pc, "heap token byte offset register"); + const auto value = s.at(so); + if ((value.type != Symbol::Type::masked && value.type != Symbol::Type::constant) || + (value.value & 3) || value.value > UINT_MAX - offset) + refuse(i.pc, "heap token byte offset has no proven 4-byte aligned range"); + const auto address = ir.binary("add", operand32(i, so), to_string(offset)); + for (unsigned j = 0; j < 8; ++j) write(i.dst + j, address); + return; + } if (pixel_heap_enabled && low.type == Symbol::Type::table && low.value == compute_resource_heap && i.op == 3) { if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) refuse(i.pc, "invalid pixel heap texture descriptor address"); @@ -1007,6 +1036,84 @@ struct DirectCompute { ir.features |= 0x40000000; return ir.heap_handle(physical,dim==1?2u:7u,1033,false,key.nonuniform); } + // A texture chosen by GPU data from the resource heap, read through its view token. The title's own descriptor words + // are not read: the s_load_dwordx8 left the byte address so + imm of the token in all eight words. The token is 32 + // bytes of title heap memory: word 0 the magic, word 1 the view id (a content token has bit 31 set and is not an id). + // The texture is ResourceDescriptorHeap[base(dimension) + id] when the magic and the id range hold and the dimension + // table says the id names a view of this instruction's dimension (1 + SQ dim code); otherwise the null slot is read + // and the first lane of the wave counts one miss. The index comes from words every lane loads from the same address, + // so it is dynamically uniform. + string heap_token_texture(const Inst &i, const State &s, unsigned base, unsigned dim) { + const auto sym = s.at(base); + if (!heap_tokens || sym.type != Symbol::Type::indexed_descriptor || sym.value != compute_resource_heap || + base + 8 > 106 || (sym.offset & 3) || (dim != 0 && dim != 1 && dim != 5)) + refuse(i.pc, "unproven heap token texture descriptor"); + for (unsigned j = 1; j < 8; ++j) { + auto expected = sym; + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) refuse(i.pc, "mixed heap token texture descriptor words"); + } + // Only a token load (s_load_dwordx8 from the resource heap) defines such a symbol here; a descriptor address built + // by s_add_u32 (heap_offset_address) does too, and is refused. + const auto defined = analysis.program.at.find(sym.definition); + if (defined == analysis.program.at.end() || analysis.program.code[defined->second].enc != Encoding::Smem || + analysis.program.code[defined->second].op != 3) + refuse(i.pc, "heap token texture descriptor is not a token load"); + if (std::none_of(heap_token_consumers.begin(), heap_token_consumers.end(), + [&](const auto &c) { return c.pc == i.pc && c.dim == dim; })) + refuse(i.pc, "heap token consumer was not listed by the pre-pass"); + // 16: the module reads raw buffers (the token memory and the dimension table), as for every raw view above; + // 0x40000000: it reads ResourceDescriptorHeap. Same flags as heap_resource, see tests/native_heap_handle_probe_check.py. + ir.features |= 16 | 0x40000000; + const auto tokens = ir.handle({0, token_srv, 11}); + const auto dims = ir.handle({0, token_dims_srv, 11}); + const auto address = read(base); + const auto load_word = [&](const string &handle, const string &at) { + const auto ret = load_buffer(handle, at, true, 1); + return ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", 0"); + }; + const auto magic = load_word(tokens, address); + const auto id = load_word(tokens, ir.binary("add", address, "4")); + const auto &count = heap_token_values[3]; + const auto in_range = cmp("ult", id, count); + const auto clamped = select(in_range, id, ir.binary("sub", count, "1")); + const auto recorded = load_word(dims, ir.binary("shl", clamped, "2")); + auto valid = ir.value("and i1 " + cmp("eq", magic, to_string(0x56573258u)) + ", " + in_range); + valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(1 + dim))); + const auto &first = heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2]; + const auto slot = select(valid, ir.binary("add", first, id), heap_token_values[4]); + // One count per wave and execution that reads the null slot. + ir.uses_wave = true; + const auto first_lane = ir.invoke("i1", "waveIsFirstLane", 110, {}, "nounwind"); + const auto missed = ir.value("and i1 " + ir.value("xor i1 " + valid + ", true") + ", " + first_lane); + const auto tag = to_string(label_number++); + ir.body << " br i1 " << missed << ", label %tokenMiss" << tag << ", label %tokenMissEnd" << tag << "\ntokenMiss" + << tag << ":\n"; + const auto counter = ir.handle({1, token_miss_uav, 11}); + ir.invoke("i32", "atomicBinOp.i32", 78, + {{"%dx.types.Handle", counter}, {"i32", "0"}, {"i32", "0"}, {"i32", "undef"}, {"i32", "undef"}, + {"i32", "1"}}, + "nounwind"); + ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; + constexpr unsigned dx_kind[]{1, 2, 0, 0, 0, 7}; + return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); + } + // The runtime-provided bindings and words of the token route. Taken before lowering because the DXIL names them. + void prepare_heap_tokens() { + if (!token_bindings()) return; + auto &r = analysis.result; + unsigned words = 5 + static_cast(descriptor_strides.size()); + for (const auto &block : r.constants) words += block.count; + if (words > 32) + refuse(analysis.program.code.front().pc, "heap token words exceed the 32-word compute entry layout"); + r.heap_token_words = true; + token_srv = analysis.srv++; + token_dims_srv = analysis.srv++; + token_miss_uav = analysis.uav++; + r.bindings.push_back({ComputeViewKind::heap_token_srv, compute_heap_token, 0, token_srv, 0}); + r.bindings.push_back({ComputeViewKind::heap_token_dims_srv, compute_heap_token, 0, token_dims_srv, 0}); + r.bindings.push_back({ComputeViewKind::heap_token_miss_uav, compute_heap_token, 0, token_miss_uav, 4}); + } string texture_dimensions(const string &handle, const string &mip) { return ir.invoke("%dx.types.Dimensions", "getDimensions", 72, {{"%dx.types.Handle", handle}, {"i32", mip}}, "nounwind readonly"); @@ -1182,7 +1289,8 @@ struct DirectCompute { constexpr unsigned dx_kind[]{1, 2, 4, 5, 6, 7, 3, 8}; constexpr unsigned coord_count[]{1, 2, 3, 3, 2, 3, 2, 3}; const unsigned coords = coord_count[dim]; - const bool indexed = pixel_stage && !store && s.at(base).type == Symbol::Type::indexed_descriptor; + const bool indexed = (pixel_stage || (heap_tokens && s.at(base).value == compute_resource_heap)) && !store && + s.at(base).type == Symbol::Type::indexed_descriptor; const bool exact_store = store && !half && !graphics_input && (dim == 1 || dim == 2 || dim == 5) && (mask == 1 || mask == 3 || mask == 7); // Read-only image ops ignore GLC (bit 13, 0x2000) and DLC (bit 7, 0x0080) cache hints; @@ -1219,7 +1327,10 @@ struct DirectCompute { : compare ? ComputeViewKind::comparison_texture_srv : ComputeViewKind::texture_srv; string h; - if (selected || (indexed && s[base].value==compute_resource_heap)) { + if (heap_tokens && !pixel_stage && indexed) { + if (kind != ComputeViewKind::texture_srv) refuse(i.pc,"unsupported heap token texture view class"); + h=heap_token_texture(i,s,base,dim); + } else if (selected || (indexed && s[base].value==compute_resource_heap)) { if (kind != ComputeViewKind::texture_srv) refuse(i.pc,"unsupported pixel heap texture view class"); h=pixel_heap_texture(i,s,base,dim,selected); } else { @@ -5152,6 +5263,7 @@ struct DirectCompute { if (uses_lds) ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; prepare_descriptor_strides(); + prepare_heap_tokens(); const auto &p = analysis.program; mode_bits = 0xf0; bool mode_write = false, conditional = false; diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 24b8ccd3ba..186e4261d8 100644 --- a/src/native_compute_output.h +++ b/src/native_compute_output.h @@ -5,7 +5,7 @@ namespace x2w { // Bump whenever a native translation of an unchanged request can change meaning. -constexpr unsigned native_compute_output_revision = 1; +constexpr unsigned native_compute_output_revision = 2; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index f0f51b1299..b3201a1dd6 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -50,6 +50,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade pipeline.uav_count = counts[1]; pipeline.constants = std::move(program.constants); pipeline.stride_srvs = std::move(program.stride_srvs); + pipeline.token_words = program.heap_token_words ? 5u : 0u; for (const auto &block : pipeline.constants) pipeline.constant_words += block.count; pipeline.srv_count = counts[0]; @@ -69,7 +70,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade D3D12_DESCRIPTOR_RANGE ranges[2]{}; for (const auto &b : pipeline.bindings) pipeline.atomic_views += b.kind == ComputeViewKind::indexed_atomic_uav; - const auto b0_words = pipeline.constant_words + static_cast(pipeline.stride_srvs.size()); + const auto b0_words = pipeline.constant_words + static_cast(pipeline.stride_srvs.size()) + pipeline.token_words; if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + b0_words + 2 * pipeline.atomic_views > D3D12_MAX_ROOT_COST) throw UnsupportedComputeShader("indexed atomic view metadata exceeds root parameter budget"); @@ -95,7 +96,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param.Constants = {b.shader_register + 1, 0, 2}; } - const UINT root_flags = (pipeline.heap_indexed ? 0x400u : 0u) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + const UINT root_flags = (pipeline.heap_indexed || pipeline.token_words ? 0x400u : 0u) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | (pipeline.sampler_heap_indexed ? 0x800u : 0u); // SAMPLER_HEAP_DIRECTLY_INDEXED D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast(samplers.size()), samplers.data(), static_cast(root_flags)}; @@ -121,6 +122,8 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript throw std::runtime_error("compute root constants missing"); if (atomic.size() != atomic_views) throw std::runtime_error("indexed atomic view metadata missing"); + // The heap token words (token_words) are not bound here: no runtime reads them yet (the manifest reader refuses the + // lines), and a caller that needs them, as the fixture does, sets them after bind(). if (strides.size() != stride_srvs.size()) throw std::runtime_error("compute descriptor stride metadata missing"); const bool views = srv_count || uav_count || heap_indexed; @@ -149,7 +152,7 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript list->SetComputeRoot32BitConstants(parameter, constant_words, words, 0); if (!strides.empty()) list->SetComputeRoot32BitConstants(parameter, static_cast(strides.size()), strides.data(), constant_words); - if (constant_words || !strides.empty()) ++parameter; + if (constant_words || !strides.empty() || token_words) ++parameter; for (const auto &shape : atomic) { const unsigned pair[]{shape.stride, shape.count}; list->SetComputeRoot32BitConstants(parameter++, 2, pair, 0); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index 6dc3d8044e..b95f8756db 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,6 +17,7 @@ struct NativeComputePipeline { unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; + unsigned token_words = 0; // heap token texture words (base1d, base2d, base2da, count, null) after the stride words unsigned instructions = 0; bool cache_hit = false, frontend_cache_hit = false; bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 9356b70f3f..cfa61a3d5f 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -348,6 +348,12 @@ const char* load_compute_translation(ComputeTranslation& tr) }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; + // GPU-selected heap textures (view tokens): published by the translator, not bound by this runtime yet. + if ((std::sscanf(line.c_str(), "srv %u heaptok%n", &i, &used) == 1 && whole()) || + (std::sscanf(line.c_str(), "srv %u heaptokdims%n", &i, &used) == 1 && whole()) || + (std::sscanf(line.c_str(), "uav %u heaptokmiss%n", &i, &used) == 1 && whole()) || + (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole())) + return "heap token textures are not bound yet"; if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) tr.uds.push_back({a, b}); else if (std::sscanf(line.c_str(), "udsrc %u %15s %d%n", &i, name, &a, &used) == 3 && whole() && i == tr.uds.size() && diff --git a/tests/cmake/native_heap_token_texture.cmake b/tests/cmake/native_heap_token_texture.cmake new file mode 100644 index 0000000000..495ce5eed9 --- /dev/null +++ b/tests/cmake/native_heap_token_texture.cmake @@ -0,0 +1,15 @@ +# GPU-selected heap textures in compute through view tokens, translated natively (#3023 stage 3, PR 1). +# _controls compiles source-written requests (manifest lines, refusals); the fixture runs the translated programs on a host +# heap with one range per dimension. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_heap_token_texture tests/native_heap_token_texture.cpp tests/desktop_gpu.cpp) + target_include_directories(native_heap_token_texture PRIVATE src tests) + target_link_libraries(native_heap_token_texture PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_heap_token_texture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS controls warp hardware) + add_test(NAME native_heap_token_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_heap_token_texture_check.py" + "$" "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_heap_token_texture_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + endforeach() +endif() diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py index 67b1ab2c9a..bb8f0b93f8 100644 --- a/tests/native_compile_dxil_watch_check.py +++ b/tests/native_compile_dxil_watch_check.py @@ -25,6 +25,7 @@ TARGET_MASKS, VS_WORDS, compile_compute_root, + native_revision, compile_graphics_table_root, compute_program_words, describe_psin, @@ -115,7 +116,7 @@ def main(argv: list[str]) -> int: current_manifest = cs_manifest.read_bytes() old_manifest = b"".join(line for line in current_manifest.splitlines(keepends=True) if not line.startswith(b"native ")) - assert current_manifest.splitlines().count(b"native 1") == 1 + assert current_manifest.splitlines().count(b"native %d" % native_revision()) == 1 assert not cs_hlsl.exists() dummy_cso = b"DXBC" + b"\0" * 20 + struct.pack("c_str() : reason.c_str()); failures += !ok; } - std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 3); + // The views and words of GPU-selected heap textures are published by name, in register order with the other views. + { + auto program = base(); + program.heap_token_words = true; + program.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); + program.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); + program.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); + reason = "unset"; + const auto manifest = format_compute_runtime_manifest(program, &reason); + const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 7\nudsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\nudsrc 2 heaptok base1d\nudsrc 3 heaptok base2d\n" + "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null\n" + "srv 0 buf table 1 64\nsrv 1 heaptok\nsrv 2 heaptokdims\nuav 0 table 1 32\n" + "uav 1 heaptokmiss\nnative " + std::to_string(native_compute_output_revision) + "\n"; + const bool ok = manifest && *manifest == wanted && reason == "unset"; + std::printf("%s publishes the heap token views and words\n", ok ? "ok " : "FAIL"); + if (!ok) + std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; + } + std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 4); return failures ? 1 : 0; } diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp new file mode 100644 index 0000000000..b54bb4089e --- /dev/null +++ b/tests/native_heap_token_texture.cpp @@ -0,0 +1,437 @@ +// Native compute fixture: GPU-selected heap textures read through view tokens (#3023 stage 3, PR 1). +// +// usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER MODE +// REQ.c67 a source-built compute request (tests/native_heap_token_texture_check.py) whose root has +// CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED and one SRV+UAV table. The program reads the byte address of a token +// from t0 (a raw buffer), loads the texture with s_load_dwordx8 from the resource heap at that address and +// samples (2D) or loads (1D, 2D array) it at a fixed coordinate; lane L writes its texel to u0 at 16 * L. +// MODE tex2d | tex1d | tex2da the dimension of the instruction under test +// The rig binds what the manifest names for the runtime-provided views: the token memory (a raw SRV over a buffer of +// eight 32-byte tokens), the dimension table (one uint per view id), the miss counter (a raw UAV) and the five words +// base1d, base2d, base2da, count, null. The shader indexes a host heap with one range per dimension, one slot per view id +// (ids 1 2D, 2 2D array, 3 1D; id 0 and every other slot are null views of the range's dimension). +// Cases (token at byte address 32 * case): a valid id, a wrong magic, an id equal to the count, the largest id, an id of +// another dimension, a content token (bit 31), id 0, an empty token. A valid token gives the texel of its view and no +// miss; every other case gives the null texel and one miss per wave (the dispatch is three groups of one wave). +// Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "direct_compute_cache.h" +#include "native_compute_pipeline.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr unsigned lanes = 32, groups = 3, count = 4; +constexpr unsigned base_1d = 8, base_2d = 16, base_2da = 24, null_slot = 0, table_start = 32; +constexpr std::uint32_t magic = 0x56573258u, sentinel = 0x69696969u; +using Texel = std::array; + +enum class Dim { d1, d2, d2a }; +Texel texel_1d(int x) { return {1000.f + x, 2000.f + x, 3000.f + x, 4000.f}; } +Texel texel_2d(int x, int y) { return {10.f * x + 1, 10.f * y + 2, 100.f + x + 4 * y, 1000.f}; } +Texel texel_2da(int x, int y, int slice) { return {10.f * x + y + 100.f * slice, 500.f + slice, 600.f + x, 700.f + y}; } + +struct Mode { + Dim dim; + unsigned valid_id, mismatch_id; + Texel expected; +}; +bool make_mode(const std::wstring &name, Mode &mode) { + if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; + else if (name == L"tex1d") mode = {Dim::d1, 3, 1, texel_1d(1)}; + else if (name == L"tex2da") mode = {Dim::d2a, 2, 1, texel_2da(1, 2, 1)}; + else return false; + return true; +} + +struct Gpu { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + UINT increment = 0; + ComPtr views; + ComPtr selector, tokens, dims, output, misses, readback, clear_output, clear_misses; + ComPtr tex1d, tex2d, tex2da; + + ~Gpu() { + if (event) CloseHandle(event); + } + int open(const std::wstring &adapter) { + ComPtr factory; + ComPtr chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + { + D3D12_ROOT_SIGNATURE_DESC probe{0, nullptr, 0, nullptr, static_cast(0x400)}; + ComPtr blob; + ComPtr root; + if (FAILED(D3D12SerializeRootSignature(&probe, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&root)))) { + std::puts("adapter refuses a root with the heap-indexing flag 0x400"); + return 77; + } + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + return 0; + } + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + template void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + check(device->GetDeviceRemovedReason(), "device removed"); + } + static D3D12_RESOURCE_BARRIER barrier(ID3D12Resource *resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + return b; + } + D3D12_CPU_DESCRIPTOR_HANDLE cpu(unsigned slot) const { + auto handle = views->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T(slot) * increment; + return handle; + } + ComPtr upload_buffer(const std::vector &words) { + auto buffer = make_buffer(device.Get(), words.size() * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(buffer->Map(0, nullptr, &mapped), "upload map"); + std::memcpy(mapped, words.data(), words.size() * 4); + buffer->Unmap(0, nullptr); + return buffer; + } + void rewrite(ID3D12Resource *buffer, const std::vector &words) { + void *mapped = nullptr; + check(buffer->Map(0, nullptr, &mapped), "rewrite map"); + std::memcpy(mapped, words.data(), words.size() * 4); + buffer->Unmap(0, nullptr); + } + // A texture whose texel (x, y, slice) is f(x, y, slice), one mip. + ComPtr texture(D3D12_RESOURCE_DIMENSION dimension, UINT width, UINT height, UINT slices, + const std::function &f) { + D3D12_RESOURCE_DESC td{}; + td.Dimension = dimension; + td.Width = width; + td.Height = height; + td.DepthOrArraySize = static_cast(slices); + td.MipLevels = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.SampleDesc.Count = 1; + auto result = resource(device.Get(), td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + std::vector footprints(slices); + UINT64 total = 0; + device->GetCopyableFootprints(&td, 0, slices, 0, footprints.data(), nullptr, nullptr, &total); + auto upload = make_buffer(device.Get(), total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(upload->Map(0, nullptr, &mapped), "texture upload map"); + for (UINT s = 0; s < slices; ++s) + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + std::memcpy(static_cast(mapped) + footprints[s].Offset + + y * footprints[s].Footprint.RowPitch + x * sizeof(Texel), + f(int(x), int(y), int(s)).data(), sizeof(Texel)); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { + for (UINT s = 0; s < slices; ++s) { + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, + dst{result.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = footprints[s]; + dst.SubresourceIndex = s; + l->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + auto to_read = barrier(result.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + l->ResourceBarrier(1, &to_read); + }); + return result; + } + void srv(unsigned slot, ID3D12Resource *resource_or_null, D3D12_SRV_DIMENSION dimension) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + desc.ViewDimension = dimension; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (dimension == D3D12_SRV_DIMENSION_TEXTURE1D) desc.Texture1D.MipLevels = 1; + else if (dimension == D3D12_SRV_DIMENSION_TEXTURE2D) desc.Texture2D.MipLevels = 1; + else { + desc.Texture2DArray.MipLevels = 1; + desc.Texture2DArray.ArraySize = resource_or_null ? 2 : 1; + } + device->CreateShaderResourceView(resource_or_null, &desc, cpu(slot)); + } + void raw_srv(unsigned slot, ID3D12Resource *buffer, UINT words) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(buffer, &desc, cpu(slot)); + } + void raw_uav(unsigned slot, ID3D12Resource *buffer, UINT words) { + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(buffer, nullptr, &desc, cpu(slot)); + } +}; + +// What the manifest says about the runtime-provided views and words. +struct Layout { + int selector = -1, out = -1, tokens = -1, dims = -1, miss = -1; + std::map words; // base1d ... null -> user data index + unsigned srv_count = 0; +}; +bool parse_manifest(const std::string &text, Layout &layout) { + std::istringstream in(text); + std::string line; + while (std::getline(in, line)) { + std::istringstream words(line); + std::vector w; + for (std::string token; words >> token;) w.push_back(token); + if (w.size() >= 3 && w[0] == "srv") { + ++layout.srv_count; + const int n = std::stoi(w[1]); + if (w[2] == "buf" && line == "srv " + w[1] + " buf table 0 0") layout.selector = n; + if (w[2] == "heaptok" && w.size() == 3) layout.tokens = n; + if (w[2] == "heaptokdims" && w.size() == 3) layout.dims = n; + } else if (w.size() >= 3 && w[0] == "uav") { + const int n = std::stoi(w[1]); + if (w[2] == "heaptokmiss" && w.size() == 3) layout.miss = n; + if (line == "uav " + w[1] + " table 0 32") layout.out = n; + } else if (w.size() == 4 && w[0] == "udsrc" && w[2] == "heaptok") + layout.words[w[3]] = static_cast(std::stoul(w[1])); + } + return layout.selector >= 0 && layout.out >= 0 && layout.tokens >= 0 && layout.dims >= 0 && layout.miss >= 0 && + layout.words.size() == 5; +} + +bool same_bits(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } + +int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::filesystem::path &marker, Gpu &gpu, + const std::wstring &name, const std::wstring &) { + Mode mode{}; + if (!make_mode(name, mode)) { + std::puts("unknown mode"); + return 2; + } + const std::string label = std::string(name.begin(), name.end()); + bool hit = false; + const auto program = x2w::prepare_direct_compute(marker, 0, false, cache, hit); + std::string reason; + const auto manifest = x2w::format_compute_runtime_manifest(program, &reason); + Layout layout; + if (!manifest || !parse_manifest(*manifest, layout)) { + std::printf("FAIL: the manifest does not name the token views and words (%s)\n%s\n", reason.c_str(), + manifest ? manifest->c_str() : "(none)"); + return 1; + } + std::printf("pass: %s the manifest names the token views and words\n", label.c_str()); + + x2w::ShaderDxilCompiler compiler(sdk); + auto pipeline = x2w::create_native_compute_pipeline(gpu.device.Get(), compiler, marker, 0, cache, true); + if (pipeline.srv_count != layout.srv_count || pipeline.uav_count != 2) { + std::printf("FAIL: pipeline srv=%u uav=%u, manifest srv=%u\n", pipeline.srv_count, pipeline.uav_count, + layout.srv_count); + return 1; + } + + // Resources. Descriptors below table_start are the host heap the shader indexes; the table follows. + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + check(gpu.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&gpu.views)), "view heap"); + gpu.tex1d = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 4, 1, 1, [](int x, int, int) { return texel_1d(x); }); + gpu.tex2d = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, [](int x, int y, int) { return texel_2d(x, y); }); + gpu.tex2da = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 2, + [](int x, int y, int s) { return texel_2da(x, y, s); }); + const auto dimension = mode.dim == Dim::d1 ? D3D12_SRV_DIMENSION_TEXTURE1D + : mode.dim == Dim::d2 ? D3D12_SRV_DIMENSION_TEXTURE2D : D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + gpu.srv(null_slot, nullptr, dimension); // the null slot has the dimension of the instruction under test + for (unsigned id = 0; id < count; ++id) { + gpu.srv(base_1d + id, id == 3 ? gpu.tex1d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE1D); + gpu.srv(base_2d + id, id == 1 ? gpu.tex2d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2D); + gpu.srv(base_2da + id, id == 2 ? gpu.tex2da.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + } + gpu.selector = make_buffer(gpu.device.Get(), 16, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + std::vector token_words(8 * 8, 0xdeadbeefu); + const std::uint32_t tokens[8][2] = {{magic, mode.valid_id}, {magic + 1, mode.valid_id}, {magic, count}, + {magic, 0xffffffffu}, {magic, mode.mismatch_id}, + {magic, 0x80000000u | mode.valid_id}, {magic, 0}, {0, 0}}; + for (unsigned c = 0; c < 8; ++c) { + token_words[c * 8] = tokens[c][0]; + token_words[c * 8 + 1] = tokens[c][1]; + } + gpu.tokens = gpu.upload_buffer(token_words); + gpu.dims = gpu.upload_buffer({0, 2, 6, 1}); // 1 + the SQ image dimension: 2D 2, 2D array 6, 1D 1 + gpu.output = make_buffer(gpu.device.Get(), lanes * sizeof(Texel), D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + gpu.misses = make_buffer(gpu.device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + gpu.readback = make_buffer(gpu.device.Get(), 1024, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + gpu.clear_output = gpu.upload_buffer(std::vector(lanes * 4, sentinel)); + gpu.clear_misses = gpu.upload_buffer({0}); + // The table: t-registers first, then u-registers, as bind() lays it out. + const unsigned uav_start = table_start + pipeline.srv_count; + gpu.raw_srv(table_start + layout.selector, gpu.selector.Get(), 4); + gpu.raw_srv(table_start + layout.tokens, gpu.tokens.Get(), 64); + gpu.raw_srv(table_start + layout.dims, gpu.dims.Get(), 4); + gpu.raw_uav(uav_start + layout.out, gpu.output.Get(), lanes * 4); + gpu.raw_uav(uav_start + layout.miss, gpu.misses.Get(), 1); + auto first = gpu.views->GetGPUDescriptorHandleForHeapStart(); + first.ptr += UINT64(table_start) * gpu.increment; + const std::map values{{"base1d", base_1d}, {"base2d", base_2d}, {"base2da", base_2da}, + {"count", count}, {"null", null_slot}}; + + auto dispatch = [&](unsigned address, std::vector &out, std::uint32_t &missed) { + gpu.rewrite(gpu.selector.Get(), {address, 0, 0, 0}); + gpu.run([&](ID3D12GraphicsCommandList *l) { + D3D12_RESOURCE_BARRIER to_copy[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)}; + l->ResourceBarrier(2, to_copy); + l->CopyBufferRegion(gpu.output.Get(), 0, gpu.clear_output.Get(), 0, lanes * sizeof(Texel)); + l->CopyBufferRegion(gpu.misses.Get(), 0, gpu.clear_misses.Get(), 0, 4); + D3D12_RESOURCE_BARRIER to_uav[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + l->ResourceBarrier(2, to_uav); + pipeline.bind(l, gpu.views.Get(), first, gpu.increment); + // The b0 parameter follows the SRV and UAV tables; the token words are user data entries. + for (const auto &[word, k] : layout.words) { + const std::uint32_t value = values.at(word); + l->SetComputeRoot32BitConstants(2, 1, &value, k); + } + l->Dispatch(groups, 1, 1); + D3D12_RESOURCE_BARRIER to_source[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + l->ResourceBarrier(2, to_source); + l->CopyBufferRegion(gpu.readback.Get(), 0, gpu.output.Get(), 0, lanes * sizeof(Texel)); + l->CopyBufferRegion(gpu.readback.Get(), 512, gpu.misses.Get(), 0, 4); + D3D12_RESOURCE_BARRIER back[2]{ + Gpu::barrier(gpu.output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + Gpu::barrier(gpu.misses.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + l->ResourceBarrier(2, back); + }); + void *mapped = nullptr; + D3D12_RANGE range{0, 1024}; + check(gpu.readback->Map(0, &range, &mapped), "readback map"); + out.resize(lanes * 4); + std::memcpy(out.data(), mapped, lanes * sizeof(Texel)); + std::memcpy(&missed, static_cast(mapped) + 512, 4); + D3D12_RANGE written{}; + gpu.readback->Unmap(0, &written); + }; + + const char *const cases[8] = {"valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", + "id_zero", "no_token"}; + for (unsigned c = 0; c < 8; ++c) { + std::vector out; + std::uint32_t missed = 0; + dispatch(c * 32, out, missed); + const Texel expected = c == 0 ? mode.expected : Texel{0, 0, 0, 0}; + for (unsigned lane = 0; lane < lanes; ++lane) { + Texel got; + std::memcpy(got.data(), &out[lane * 4], sizeof got); + if (!same_bits(got, expected)) { + std::printf("FAIL: %s %s: lane %u is (%g, %g, %g, %g), expected (%g, %g, %g, %g)\n", label.c_str(), + cases[c], lane, got[0], got[1], got[2], got[3], expected[0], expected[1], expected[2], + expected[3]); + return 1; + } + } + const std::uint32_t expected_misses = c == 0 ? 0 : groups; + if (missed != expected_misses) { + std::printf("FAIL: %s %s: %u misses, expected %u (one per wave)\n", label.c_str(), cases[c], missed, + expected_misses); + return 1; + } + std::printf("pass: %s %s: %s in all %u lanes, %u misses (%u waves)\n", label.c_str(), cases[c], + c == 0 ? "the texel of the view" : "the null texel", lanes, missed, groups); + } + return 0; +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 6) { + std::fputs("usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER tex2d|tex1d|tex2da\n", stderr); + return 2; + } + Gpu gpu; + try { + if (int skip = gpu.open(argv[4])) return skip; + return run_mode(argv[1], argv[2], argv[3], gpu, argv[5], argv[4]); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py new file mode 100644 index 0000000000..cf2651ec12 --- /dev/null +++ b/tests/native_heap_token_texture_check.py @@ -0,0 +1,318 @@ +"""GPU-selected heap textures in compute through view tokens, translated natively (#3023 stage 3, PR 1). + +usage: native_heap_token_texture_check.py FIXTURE COMPILE_DXIL SDK ADAPTER (ADAPTER: controls | warp | hardware) + +A guest program loads a 32-byte texture descriptor with s_load_dwordx8 from the directly indexed resource heap at a byte +offset chosen by GPU data (a raw SRV, t0), and samples or loads it. The translator does not read descriptor words: it +reads the view token that the title keeps at that heap address (word 0 the magic, word 1 the view id), checks the magic, +the id range and the dimension recorded for the id, and uses ResourceDescriptorHeap[base(dimension) + id] (the null slot +otherwise, counting one miss per wave). The published manifest names the runtime-provided views and words; the runtime +reader still refuses them by name. + + controls compiles source-written requests: the published manifest, the module's handles, and every consumer or address + shape that must keep today's refusal text (or get the new text), each with a control that compiles. + warp/ runs the fixture `native_heap_token_texture` (valid 1D, 2D and 2D-array views; wrong magic, id out of range, + hardware a view of another dimension, a content token and an empty token read the null slot and count one miss per + wave). Exit 77 when the fixture reports a capability skip (WARP has no 32-lane waves). + +Instruction words were assembled once with LLVM 15 (clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding); the comment on each line is the assembler source. The test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +# Same helper as native_sampler_heap_check.py: writes req_.c67 and its parts. +from native_compute_clear_check import write_request + +ROOT = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +ROOT_NO_HEAP = "DescriptorTable(SRV(t0), UAV(u0))" +HEAP_REFUSAL = "direct resource-heap load requires the selected GPU slot and its view type" +UNPROVEN = "heap token byte offset has no proven 4-byte aligned range" +UNALIGNED_IMMEDIATE = "unaligned heap token immediate byte offset" + +BASES = [ + 0xbe880304, # s_mov_b32 s8, s4 (s[8:9]: the table pointer, high word constant 0) + 0xbe890380, # s_mov_b32 s9, 0 + 0xbe8a0305, # s_mov_b32 s10, s5 (s[10:11]: the resource heap base, high word constant 0) + 0xbe8b0380, # s_mov_b32 s11, 0 +] +TABLE_LOADS = [ + 0xf4080304, 0xfa000000, # s_load_dwordx4 s[12:15], s[8:9], 0x0 (t0: the selector, a raw buffer) + 0xf4080604, 0xfa000020, # s_load_dwordx4 s[24:27], s[8:9], 0x20 (u0: the output) +] +SELECTOR_HEAD = [ + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0xf4200406, 0xfa000000, # s_buffer_load_dword s16, s[12:15], 0x0 (the byte address of the token) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) +] +MASK = [ + 0x8711ff10, 0x0000fffc, # s_and_b32 s17, s16, 0xfffc (proves a 4-byte aligned range) +] +SELECTOR = [*SELECTOR_HEAD, *MASK] +TOKEN_LOAD = [ + 0xf40c0805, 0x22000000, # s_load_dwordx8 s[32:39], s[10:11], s17 (the texture: a view token in the title heap) +] +SAMPLER = [ + 0xbea803ff, 0x00000092, # s_mov_b32 s40, 0x92 (static sampler: clamp x, y and z, point) + 0xbea90380, # s_mov_b32 s41, 0 + 0xbeaa0380, # s_mov_b32 s42, 0 + 0xbeab0380, # s_mov_b32 s43, 0 + 0x34100084, # v_lshlrev_b32_e32 v8, 4, v0 +] +COMPARISON_SAMPLER = [ + 0xbea803ff, 0x08001012, # s_mov_b32 s40, 0x8001012 + 0xbea903ff, 0x00fff000, # s_mov_b32 s41, 0xfff000 + 0xbeaa03ff, 0x04000000, # s_mov_b32 s42, 0x4000000 + 0xbeab0380, # s_mov_b32 s43, 0 + 0x34100084, # v_lshlrev_b32_e32 v8, 4, v0 +] +COORDS_2D = [ + 0x7e0202ff, 0x3ec00000, # v_mov_b32_e32 v1, 0x3ec00000 (u = 0.375: texel 1 of 4) + 0x7e0402ff, 0x3f200000, # v_mov_b32_e32 v2, 0x3f200000 (v = 0.625: texel 2 of 4) +] +COORDS_1D = [ + 0x7e020281, # v_mov_b32_e32 v1, 1 +] +COORDS_2DA = [ + 0x7e020281, # v_mov_b32_e32 v1, 1 + 0x7e040282, # v_mov_b32_e32 v2, 2 + 0x7e060281, # v_mov_b32_e32 v3, 1 +] +FILL_V3 = [ + 0x7e0602f2, # v_mov_b32_e32 v3, 1.0 +] +WAIT = [0xbf8cc07f] # s_waitcnt lgkmcnt(0) +STORE = [ + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xe0781000, 0x80060408, # buffer_store_dwordx4 v[4:7], v8, s[24:27], 0 offen + 0xbf810000, # s_endpgm +] +END = [0xbf810000] # s_endpgm + +SAMPLE_2D = [0xf09c0f08, 0x01480401] # image_sample_lz v[4:7], v[1:2], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D +LOAD_1D = [0xf0000f00, 0x00080401] # image_load v[4:7], v1, s[32:39] dmask:0xf dim:SQ_RSRC_IMG_1D +LOAD_2DA = [0xf0000f28, 0x00080401] # image_load v[4:7], v[1:3], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +JOIN = [ + 0xbf068010, # s_cmp_eq_u32 s16, 0 + 0xbf850002, # s_cbranch_scc1 2 (skips the token load) +] +HEAP_ADDRESS = [ + 0x8014110a, # s_add_u32 s20, s10, s17 + 0x82158080, # s_addc_u32 s21, 0, 0 + 0xf4080b0a, 0xfa000000, # s_load_dwordx4 s[44:47], s[20:21], 0x0 (a heap descriptor address built by an add) +] +SAMPLE_2D_PARTIAL = [0xf09c0f08, 0x01470401] # image_sample_lz v[4:7], v[1:2], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D +ALL_OPS = [ + 0xf0900f08, 0x01480401, # image_sample_l v[4:7], v[1:3], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf0040f08, 0x00080c01, # image_load_mip v[12:15], v[1:3], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf11c0108, 0x01481001, # image_gather4_lz v[16:19], v[1:2], s[32:39], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D + 0xf0380f08, 0x00081401, # image_get_resinfo v[20:23], v1, s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf09c0f08, 0x01480401, # image_sample_lz v[4:7], v[1:2], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D +] + + +def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SELECTOR): + return [*BASES, *TABLE_LOADS, *selector, *load, *sampler, *coords, *WAIT, *op, *store] + + +PROGRAMS = { + "tex2d": full(COORDS_2D, SAMPLE_2D), + "tex1d": full(COORDS_1D, LOAD_1D), + "tex2da": full(COORDS_2DA, LOAD_2DA), + "all_ops": full([*COORDS_2D, *FILL_V3], ALL_OPS), + # A token load that is never used. + "unused": [*BASES, *TABLE_LOADS, *SELECTOR, *TOKEN_LOAD, *END], +} +# Uses that keep today's refusal: the token words are not only the T# of a supported image instruction. +CONSUMER_CONTROLS = { + "copy": full(COORDS_2D, [0xbeac0320, *SAMPLE_2D]), # s_mov_b32 s44, s32 + # image_store v[4:7], v[1:2], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D + "store": full(COORDS_2D, [0xf0200f08, 0x00080401], store=END), + # image_sample_c_lz v8, v[1:3], s[32:39], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D + "comparison": full([*COORDS_2D, *FILL_V3], [0xf0bc0108, 0x01480801], sampler=COMPARISON_SAMPLER, store=END), + # image_sample_lz v[4:7], v[1:3], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_CUBE + "cube": full([*COORDS_2D, *FILL_V3], [0xf09c0f18, 0x01480401], store=END), + # the same with dim:SQ_RSRC_IMG_3D + "volume": full([*COORDS_2D, *FILL_V3], [0xf09c0f10, 0x01480401], store=END), + "numeric": full(COORDS_2D, [0x872cff20, 0x000000ff, *SAMPLE_2D]), # s_and_b32 s44, s32, 0xff + # the token load runs on one path only: after the join the words are not the token symbol any more + "join": full(COORDS_2D, SAMPLE_2D, load=[*JOIN, *TOKEN_LOAD]), + # the T# holds four words of the token load and four others + "partial": full(COORDS_2D, SAMPLE_2D_PARTIAL), + # a descriptor address formed by s_add_u32 next to a token load + "heap_address": full(COORDS_2D, SAMPLE_2D, load=[*HEAP_ADDRESS, *TOKEN_LOAD]), + "join_copy": full(COORDS_2D, [0xbeac0320, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_mov_b32 s44, s32 after the join + "numeric_join": full(COORDS_2D, [0x872cff20, 0x000000ff, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_and_b32 s44, s32, 0xff + "field": full(COORDS_2D, [0x93acff21, 0x000e0010, *SAMPLE_2D]), # s_bfe_u32 s44, s33, 0xe0010 (an image field read) +} +# Address shapes. Each program is eligible, so it reaches the load and is refused there. +ADDRESS_CONTROLS = { + # s_load_dwordx8 s[32:39], s[10:11], s16: the offset register is not masked + "unmasked": (full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x20000000], selector=SELECTOR_HEAD), UNPROVEN), + # s_and_b32 s17, s16, 0xfffe: bit 1 may be set + "misaligned": (full(COORDS_2D, SAMPLE_2D, selector=[*SELECTOR_HEAD, 0x8711ff10, 0x0000fffe]), UNPROVEN), + # s_load_dwordx8 s[32:39], s[10:11], s17 offset:0x2 + "immediate2": (full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x22000002]), UNALIGNED_IMMEDIATE), + # s_load_dwordx8 s[32:39], s[10:11], 0x20: no SGPR offset keeps the contract refusal + "immediate_only": (full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0xfa000020]), HEAP_REFUSAL), + # s_load_dwordx4 s[32:35], s[10:11], s17: a four-word heap load keeps the contract refusal + "x4": (full(COORDS_2D, SAMPLE_2D, load=[0xf4080805, 0x22000000]), HEAP_REFUSAL), +} +ACCEPTED_ADDRESS = { + # s_load_dwordx8 s[32:39], s[10:11], s17 offset:0x20 + "immediate": full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x22000020]), +} + +EXPECTED_MANIFEST = """x2w-manifest 2 +stage cs +group 32 1 1 +ud 5 +udsrc 0 heaptok base1d +udsrc 1 heaptok base2d +udsrc 2 heaptok base2da +udsrc 3 heaptok count +udsrc 4 heaptok null +srv 0 heaptok +srv 1 heaptokdims +srv 2 buf table 0 0 +uav 0 heaptokmiss +uav 1 table 0 32 +smpl 0 00000092 00000000 00000000 00000000 +native 2 +""" + +FIXTURE_CASES = ("valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", "id_zero", "no_token") + + +def main(): + fixture, compile_dxil, sdk, adapter = sys.argv[1:5] + ok_lines = 0 + + def require(condition, message): + nonlocal ok_lines + if not condition: + print("FAIL: " + message) + sys.exit(1) + ok_lines += 1 + print("ok: " + message) + + def run(command, expect_skip=False): + result = subprocess.run([str(part) for part in command], capture_output=True, timeout=300) + out = result.stdout.decode("utf-8", "replace") + err = result.stderr.decode("utf-8", "replace") + print("$ " + " ".join(pathlib.Path(str(c)).name if i == 0 else str(c) for i, c in enumerate(command))) + for text in (out, err): + for line in text.strip().splitlines()[-60:]: + print(" " + line) + print(f" -> exit {result.returncode}") + if result.returncode == 77 and expect_skip: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + with tempfile.TemporaryDirectory(prefix="x2w_heap_token_") as scratch: + base = pathlib.Path(scratch) + roots = {} + + def root(text): + if text not in roots: + source = base / f"root{len(roots)}.hlsl" + source.write_text(f'#define RS "{text}"') + binary = base / f"root{len(roots)}.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + roots[text] = binary.read_bytes() + return roots[text] + + counter = 0 + + def request(name, words, root_text=ROOT): + nonlocal counter + counter += 1 + folder = base / f"req_{counter}_{name}" + folder.mkdir() + user = 6 if root_text == ROOT else 5 # four reserved SGPRs, the table, and the resource heap + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, user << 1) + return write_request(folder, words, root(root_text), sa) + + def compile_request(marker): + output = marker.with_suffix(".cso") + code, out, err = run([compile_dxil, sdk, marker.parent / "cache", "gfx1013-direct-cs@0", marker, output]) + return code, out, err, output + + if adapter != "controls": + for mode in ("tex2d", "tex1d", "tex2da"): + marker = request(mode, PROGRAMS[mode]) + cache = base / f"cache_{mode}" + cache.mkdir() + code, out, err = run([fixture, sdk, cache, marker, adapter, mode], expect_skip=True) + require(code == 0, f"fixture mode {mode} exits 0") + for case in FIXTURE_CASES: + require(f"pass: {mode} {case}:" in out, f"{mode}: case {case} held") + require(f"pass: {mode} the manifest names the token views and words" in out, + f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and five heaptok words") + print(f"{ok_lines} assertions held") + return + + # 1. The accepted programs compile, and the module reads the token and the heap. + for name in ("tex2d", "tex1d", "tex2da", "all_ops", "unused"): + marker = request(name, PROGRAMS[name]) + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists(), f"{name}: compiles") + if name == "unused": + # An eligible load without a consumer needs no token view or word. + out_dir = base / "unused_out" + code, out, err = run([compile_dxil, sdk, base / "cache_unused", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() + require(code == 0 and "heaptok" not in text, "unused: a token load without a consumer publishes no token line") + continue + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, + text=True).stdout + require("@dx.op.createHandleFromHeap(i32 218" in listing, f"{name}: the texture comes from createHandleFromHeap") + require("@dx.op.waveIsFirstLane(i32 110)" in listing, f"{name}: the miss is counted by the first lane (op 110)") + require("@dx.op.atomicBinOp.i32(i32 78" in listing, f"{name}: the miss counter is an atomic add (op 78)") + require(listing.count("@dx.op.rawBufferLoad.i32(") >= 3, + f"{name}: the module loads the token words and the dimension") + require(", 1448555096" in listing, f"{name}: the module compares the view token magic") + marker = request("tex2d", PROGRAMS["tex2d"]) + + # 2. The published manifest. + out_dir = base / "requests_out" + code, out, err = run([compile_dxil, sdk, base / "cache_requests", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + manifest = out_dir / (marker.stem[len("req_"):] + ".txt") + require(code == 0 and manifest.exists(), "--requests publishes a manifest for a heap token program") + require(manifest.read_text() == EXPECTED_MANIFEST, "the manifest names the token views and the five token words") + # Control: a program without a token load publishes no token line. + plain = request("plain", [*BASES, *TABLE_LOADS, 0xbf810000]) + plain_out = base / "plain_out" + code, out, err = run([compile_dxil, sdk, base / "cache_plain", "gfx1013-direct-cs@0", "--requests", + plain.parent, plain_out]) + text = (plain_out / (plain.stem[len("req_"):] + ".txt")).read_text() + require(code == 0 and "heaptok" not in text, "control: a program without a token load has no token line") + + # 3. Consumers that make the load not eligible keep today's refusal text. + for name, words in CONSUMER_CONTROLS.items(): + code, out, err, output = compile_request(request("c_" + name, words)) + require(code != 0 and HEAP_REFUSAL in err and not output.exists(), + f"{name}: refused with \"{HEAP_REFUSAL}\" and no .cso") + # 4. Address shapes. + for name, (words, text) in ADDRESS_CONTROLS.items(): + code, out, err, output = compile_request(request("a_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"{name}: refused with \"{text}\" and no .cso") + for name, words in ACCEPTED_ADDRESS.items(): + code, out, err, output = compile_request(request("a_" + name, words)) + require(code == 0 and output.exists(), f"control: {name} compiles") + # 5. Without the heap flag there is no heap base to load from. + code, out, err, output = compile_request(request("noheap", PROGRAMS["tex2d"], ROOT_NO_HEAP)) + require(code != 0 and not output.exists(), "a root without the heap flag does not compile the token program") + + print(f"{ok_lines} assertions held") + + +if __name__ == "__main__": + main() diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py index ad2c8b0d43..dfc2be935a 100644 --- a/tests/native_startup_request_cache_check.py +++ b/tests/native_startup_request_cache_check.py @@ -30,6 +30,13 @@ COMPUTE_RSRC2 = C.USER7 | C.TGID_X | C.TGID_Y | C.TGID_Z | C.tidig(3) + + +def native_revision(): + """native_compute_output_revision of src/native_compute_output.h: the marker a current native manifest ends with.""" + import re + header = Path(__file__).resolve().parent.parent / "src" / "native_compute_output.h" + return int(re.search(r"native_compute_output_revision\s*=\s*(\d+)", header.read_text()).group(1)) def fullscreen_vs_words() -> bytes: vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src vop2 = lambda op, dst, src0, vsrc1: op << 25 | dst << 17 | vsrc1 << 9 | src0 @@ -191,7 +198,7 @@ def check_controls(cli: Path, sdk: Path) -> int: "udsrc 1 rootconst 0 1\n" "srv 0 buf table 1 64\n" "uav 0 table 1 32\n" - "native 1\n" + f"native {native_revision()}\n" ) assert G.pending_keys(str(cache), skip_failed=False) == [], "published entries not recognised as complete" diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index 5d81322f4d..b7eb8d25a9 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -40,6 +40,13 @@ from startup_stream_check import gfx2hlsl as G + + +def native_revision(): + """native_compute_output_revision of src/native_compute_output.h: the marker a current native manifest ends with.""" + import re + header = Path(__file__).resolve().parent.parent / "src" / "native_compute_output.h" + return int(re.search(r"native_compute_output_revision\s*=\s*(\d+)", header.read_text()).group(1)) def dispatch(directory, consumer, env, mode, *, probe=False): out = directory / 'out.bin' out.unlink(missing_ok=True) @@ -118,7 +125,7 @@ def main(consumer, dxc, adapter): assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + reason)) == 1, result.stderr[-3000:] # Reuse working bytecode to isolate the manifest gate from native adapter requirements. - manifest.write_bytes(python_manifest + b'native 1\n') + manifest.write_bytes(python_manifest + b'native %d\n' % native_revision()) got, result = dispatch(directory, consumer, env, 'dispatch') assert got == expected and not lines(result, 'refused:'), result.stderr[-3000:] hlsl.write_bytes(python_hlsl) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 19d435a25b..ffb9c940a6 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -172,6 +172,10 @@ def check_manifest_refusal(case, variant, reason): 'out-of-order static sampler', original) check_manifest_refusal('out-of-order static sampler', original + 'smp 1 0 0 0 0\n', 'a sampler that is not a plain static one') + # The translator's heap token texture lines (GPU-selected textures read through view tokens) are named, not bound. + for case, line in (('heap token view', 'srv 1 heaptok\n'), ('heap token dimension table', 'srv 1 heaptokdims\n'), + ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token word', 'udsrc 3 heaptok null\n')): + check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') assert original.count('\nud 3\n') == 1, ('entry count mismatch', original) check_manifest_refusal('entry count mismatch', original.replace('\nud 3\n', '\nud 4\n'), 'entry value, input or output count') diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index db6557928e..03bcb1a896 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -217,6 +217,7 @@ 'entry value, input or output count', 'formatted D16 write has an incompatible typed buffer UAV', 'formatted D16 write needs the original typed buffer view', + 'heap token textures are not bound yet', 'manifest version', 'native translation from another compiler revision; rebuild it', 'native translation without a revision; rebuild it', From f58b05fede7649063e3f7448f86c5568d3eef234 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 09:49:56 +0100 Subject: [PATCH 02/19] native: translate GPU-selected heap raw buffers through view tokens in compute Refs #3023 #3224. Builds on the heap token textures of #3544. A raw buffer V# loaded with s_load_dwordx4 from the directly indexed resource heap at a GPU-selected byte offset (an SGPR offset, or an address formed by s_add_u32) is read through the view token the title keeps at that address, like the token textures. Reads of that V# in the byte-window form (buffer_load_dword{,x2,x3,x4} with OFFEN, the s_bfe/s_max/s_mul/s_and/s_or rewrite) and scalar buffer loads from it are translated; every other use keeps today's path and refusal text. - Each s_load_dwordx4 candidate is judged on its own; a candidate that fails is dropped and does not take the texture route off the program. An s_add_u32 heap address that is not an eligible candidate keeps the old rejection. - The shader checks magic, id range and the dimension table entry 0x20 (raw buffer view) on every execution and reads ResourceDescriptorHeap[baseraw + id], or the null raw view with one counted miss per wave. - A program with an eligible buffer load publishes seven token words (baseraw and nullraw after the five of the textures): NativeComputeShader:: heap_token_word_count replaces heap_token_words. Texture-only programs keep five words and byte-identical modules and manifests (revision line aside). - native_compute_output_revision 2 -> 3. - The dispatch reader names baseraw and nullraw and still refuses every heaptok line: programs of this change stay refused at dispatch until the runtime binds the views (PR 2). Tests: native_heap_token_texture_controls (eligible forms, controls with today's text, address shapes, loop, mixed texture and buffer), native_heap_token_texture_{warp,hardware} (rawbuf, rawbuf_waterfall, sbuf), native_compute_manifest_reasons, startup_compute_dispatch_texture. The design was frozen by the owner without independent approval (see the PR). Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 2 +- .../experiments/native-heap-token-textures.md | 71 +++++- src/direct_compute_cache.cpp | 19 +- src/gfx1013_compute_native.cpp | 231 +++++++++++++----- src/gfx1013_compute_native.h | 8 +- src/gfx1013_direct_compute.inl | 126 ++++++++-- src/native_compute_output.h | 2 +- src/native_compute_pipeline.cpp | 2 +- src/native_compute_pipeline.h | 2 +- src/startup_stubs/d3d12_compute_dispatch.inl | 11 +- tests/native_compute_manifest_reasons.cpp | 39 ++- tests/native_heap_token_texture.cpp | 103 ++++++-- tests/native_heap_token_texture_check.py | 214 +++++++++++++++- .../startup_compute_dispatch_texture_check.py | 7 +- 14 files changed, 721 insertions(+), 116 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index de7bdfc6dc..8cf0c8371c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18032,4 +18032,4 @@ ctest --preset dev --no-tests=error -j1 -R '^native_pixel_atomic_(warp|hardware) Repeat with the release preset. The source-built fixture verifies 13 actual draws and four refusal controls per adapter/configuration, including contention, guard words, active out-of-view, odd raster edges and real WQM quad-neighbor reads with and without GLC. WQM+GLC records returned old values through a second exact atomic in a private lane slot and checks a valid serialization of the varying addends. Local RX 7900 XT/WARP Debug/Release integration over main 4b0350e passed 52 draws, 3328 DWORD and 1664 pixel comparisons, and 16 refusal controls. The debug layer was unavailable; actual title rendering is not established. -See [GPU-selected heap textures through view tokens in native compute](experiments/native-heap-token-textures.md) (#3023 stage 3, translator only) for the `heaptok` manifest lines the runtime still refuses. +See [GPU-selected heap textures through view tokens in native compute](experiments/native-heap-token-textures.md) (#3023 stage 3, translator only) for the `heaptok` manifest lines the runtime still refuses. The same page covers GPU-selected raw buffers read through view tokens (`baseraw` and `nullraw` words). diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index e554728108..e0c6ddee5e 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -33,7 +33,7 @@ those two words at the guest byte address and maps the id to a host descriptor. (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module names the registers while it is lowered. - Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, `udsrc K heaptok base1d|base2d|base2da|count|null`. - `native_compute_output_revision` is 2. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. + `native_compute_output_revision` is 3 (see Revision below). The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. ## Tests @@ -51,3 +51,72 @@ those two words at the guest byte address and maps the id to a host descriptor. The null slot has one word; a null view of another dimension than the instruction's is not defined by D3D12 for dynamic indexing, so the runtime change has to provide a null slot that every dimension may read (the fixture uses a null view of the dimension under test). + +# GPU-selected raw buffers through view tokens (PR 1c) + +The same token route also reads a raw buffer that the program loads as a V# with `s_load_dwordx4` from the resource heap at +a GPU-selected byte offset, or through an address formed by `s_add_u32` (a waterfall loop over a lane-selected slot, #3224). +Only reads of that V# in the byte-window form and scalar buffer loads from it are translated; everything else keeps today's +path and refusal text. Like the texture route, this translates only where no heap view contract applies +(`HeapViewContract::none`); under a contract the existing `heap_buffer_srv` path is unchanged. + +## What the translator does + +- Candidates are the reached `s_load_dwordx4` from the resource heap with an SGPR offset, and the same load through an + address formed by `s_add_u32` whose high word is the carry of that add (the emitter writes it as 0). Each candidate is + judged on its own (`heap_token_buffer_eligible`). It is eligible when its four words are read only as (a) the V# of a raw + `buffer_load_dword`, `x2`, `x3` or `x4` with OFFEN and without IDXEN, with words 1 to 3 the rewritten fields of the same + load (the byte window: stride cleared, byte count, raw out-of-bounds mode), (b) the base of an `s_buffer_load_dword{,x2,x4,x8,x16}` + of the four unrewritten words, (c) the `s_bfe_u32`, `s_max_u32`, `s_mul_i32`, `s_and_b32` and `s_or_b32` of the rewrite + itself. A copy or numeric read of a word or of a rewritten field, a store, IDXEN, a typed, format or `tbuffer` load, a V# + without the rewrite, a partial V# and a word that a join lost make the candidate not eligible. It is then dropped and keeps + today's path and text; it does not take the texture route off the program. An address formed by `s_add_u32` that is not an + eligible candidate keeps the old rejection of the program for the texture route. +- The analysis of a program with a candidate runs with the byte-window tracking (`heap_window`). If no candidate is + eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to + the same module and manifest (only the revision line changes). +- The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap + slot 0, not a slot index) to the four words. It requires an address that is a multiple of 32: `imm % 32 == 0`, an SGPR + offset that is constant or masked with `(mask & 31) == 0`, no overflow; on an added address `imm == 0` and the same mask. +- The consumer reads the token at that address: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 0x20`, and + uses `ResourceDescriptorHeap[valid ? baseraw + id : nullraw]` as a raw buffer. A miss is counted as for textures. No + `heap_buffer_srv` binding is created. +- Two more `b0` words follow the five texture words, only in a program with an eligible buffer load: `baseraw`, `nullraw` + (`NativeComputeShader::heap_token_word_count` is 0, 5 or 7). The manifest names them `udsrc K heaptok baseraw|nullraw`. +- The dimension table gains the code `0x20`: a raw buffer view (next to 0 none, else 1 + the image dimension). + The production writer of that table is the runtime change (PR 2); the fixture writes it for its two raw ids. + +## Revision + +`native_compute_output_revision` is 3. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not +`native_compute_pipeline.cpp` or `native_compute_output.h`, and the manifest of a program with a token buffer has a new +shape, so the marker is bumped by hand. A request the previous translator refused published nothing, so it is translated +again by the next run (checked: the previous `compile_dxil` refuses the fixture request and leaves its cache empty, the +new one compiles it from the same cache folder). + +## Runtime assumptions and failure modes + +- A1: a token in the bound view heap's memory names the view the title created for that slot. The runtime (PR 2) builds the + raw view per id from the view record, so its byte range is that view's range. +- Failure modes, all read the null raw view (zeros) and count a miss, never a wrong-kind view: no token (the title wrote a raw + V# itself, or the slot was never written because the token write is gated on a title-backed writable view), a wrong magic, + `id >= count`, a content token (word 1 carries flags), a texture id (dimension code not 0x20). +- Not caught: a stale token whose id was released and re-used for another buffer view; the shader then reads the new buffer. + PR 2 must not re-use ids while a stale token can exist (no id reuse, or a generation in word 2 or 3 that this route checks + once PR 2 defines it). +- A2: an out-of-bounds raw buffer read returns 0 (the D3D12 raw buffer bounds rule, an external specification not verified in + this repository; the fixture checks it for lanes past the end of the first raw view on one adapter). +- The runtime reader still refuses every `heaptok` line ("heap token textures are not bound yet"), including `baseraw` and + `nullraw`; programs of this change stay refused at dispatch until PR 2. + +## Tests + +- `native_heap_token_texture_controls`: eligible programs (SGPR offset, added address, scalar buffer load, other widths, an + immediate offset, a texture next to a buffer) and the published manifest; controls that keep today's text (plain V# without + the rewrite, IDXEN, format, `tbuffer`, store, a numeric read of word 2, a copy of a rewritten word, a partial V#, a join, an + immediate offset that breaks the descriptor layout), the new address texts, a window load in a loop + (`heap byte window loaded inside a loop`), and the mixed cases (a texture on the token route next to a buffer load that + keeps today's refusal). +- `native_heap_token_texture_warp` and `_hardware`: modes `rawbuf`, `rawbuf_waterfall` and `sbuf` with two raw views (64 and + 128 dwords) and a texture id in the dimension table: valid tokens read the view (lanes past the first view get 0), every + other case gives zeros and one miss per wave. Results are compared as dwords. diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index b7f97527e5..b8de014ef8 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -101,7 +101,7 @@ Bytes encode(const NativeComputeShader &program) { for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) word(out, n); word(out, program.sampler_heap); - word(out, program.heap_token_words); + word(out, program.heap_token_word_count); word(out, static_cast(program.stride_srvs.size())); for (unsigned srv : program.stride_srvs) word(out, srv); @@ -158,7 +158,9 @@ NativeComputeShader decode(std::string_view bytes) { shader.constants.push_back(c); } shader.sampler_heap = in.count(1) != 0; - shader.heap_token_words = in.count(1) != 0; + shader.heap_token_word_count = in.count(7); + if (shader.heap_token_word_count != 0 && shader.heap_token_word_count != 5 && shader.heap_token_word_count != 7) + throw std::runtime_error("invalid cached heap token word count"); n = in.count(32); for (unsigned j = 0; j < n; ++j) shader.stride_srvs.push_back(in.count(31)); @@ -942,7 +944,7 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("more than 8 root constants in one root parameter"); ud_count += block.count; } - ud_count += static_cast(program.stride_srvs.size()) + (program.heap_token_words ? 5u : 0u); + ud_count += static_cast(program.stride_srvs.size()) + program.heap_token_word_count; if (ud_count > 32) return refuse("more than 32 user data words"); @@ -965,7 +967,7 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh if (token_view != (b.root_parameter == compute_heap_token)) return refuse("heap token view with another root parameter"); if (token_view) { - if (!program.heap_token_words || b.array_count != 1) + if (!program.heap_token_word_count || b.array_count != 1) return refuse("heap token view without heap token words"); const bool miss = b.kind == ComputeViewKind::heap_token_miss_uav; if (b.shader_register != (miss ? uav_count++ : srv_count++)) @@ -1093,11 +1095,14 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("stride words from a view that is not one raw vector SRV"); out << "udsrc " << ud_index++ << " stride " << srv << '\n'; } - if (program.heap_token_words) { + if (program.heap_token_word_count) { + if (program.heap_token_word_count != 5 && program.heap_token_word_count != 7) + return refuse("heap token words are five, or seven with a token buffer"); if (token_views[0] != 1 || token_views[1] != 1 || token_views[2] != 1) return refuse("heap token words without the three heap token views"); - for (const char *word : {"base1d", "base2d", "base2da", "count", "null"}) - out << "udsrc " << ud_index++ << " heaptok " << word << '\n'; + const char *const names[]{"base1d", "base2d", "base2da", "count", "null", "baseraw", "nullraw"}; + for (unsigned k = 0; k < program.heap_token_word_count; ++k) + out << "udsrc " << ud_index++ << " heaptok " << names[k] << '\n'; } out << srv_lines.str() << uav_lines.str() << sampler_lines.str() << "native " << native_compute_output_revision << '\n'; diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index a3732e5b14..ddbf00d6c0 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1742,6 +1742,11 @@ void lower_blocks(Emit &e) { struct HeapTokenLoad { unsigned pc, dim; }; +// GPU-selected heap raw buffers (view tokens). A consumer of an eligible s_load_dwordx4 from the resource heap: the raw +// MUBUF load or scalar buffer load at `pc` that reads the V# of the heap load at `load`. +struct HeapTokenBufferLoad { + unsigned pc, load; +}; // SGPR ranges {first, count} an instruction may read, widened where the operand width is not known exactly. Anything // that cannot be listed (indexed SGPR moves) reads everything. static std::vector> conservative_sgpr_reads(const Inst &i) { @@ -1776,57 +1781,44 @@ static std::vector> conservative_sgpr_reads(const out.emplace_back(0, 106); return out; } -// The pre-pass of the heap token route. Every reached s_load_dwordx8 from the resource heap with an SGPR offset is a -// token load. The program is eligible when every later read of the eight words (until they are overwritten) is the -// T# of an image_load, image_load_mip, image_sample_l, image_sample_lz, image_gather4_lz (2D) or image_get_resinfo of -// dimension 1D, 2D or 2D array, without D16; a copy, a numeric read, a store, a comparison, cube or 3D use, a -// partial use or a read of the words by an instruction this function cannot place makes it not eligible. `p` is -// the analysis with heap_tokens set. Returns false when there is no token load. -static bool heap_token_eligible(const Program &p, std::vector &consumers) { - consumers.clear(); - std::vector loads; - for (size_t n = 0; n < p.code.size(); ++n) { - const auto &i = p.code[n]; - if (!p.reached[n] || i.enc != Encoding::Smem || i.op != 3 || (i.b >> 25) == 125) continue; - const auto &base = p.before[n].at(i.src[0]); - if (base.type == Symbol::Type::table && base.value == compute_resource_heap) - loads.push_back(n); - } - if (loads.empty()) return false; - // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. - for (size_t n = 0; n < p.code.size(); ++n) { +// The instructions that can run after p.code[l] (its transitive successors; the load itself only through a loop). +static std::vector instructions_after(const Program &p, size_t l) { + std::vector after(p.code.size()); + std::vector pending; + const auto visit = [&](size_t n) { + if (!after[n]) { after[n] = true; pending.push_back(n); } + }; + const auto successors = [&](size_t n) { const auto &i = p.code[n]; - if (p.reached[n] && i.enc == Encoding::Smem && i.op == 2 && (i.b >> 25) == 125 && - p.before[n].at(i.src[0]).type == Symbol::Type::heap_offset) - return false; + if (i.branch()) { + const auto t = p.at.find(i.target()); + if (t != p.at.end()) visit(t->second); + } + if (i.name != "s_endpgm" && !(i.branch() && i.op == 2) && n + 1 < p.code.size()) visit(n + 1); + }; + successors(l); + while (!pending.empty()) { + const size_t n = pending.back(); + pending.pop_back(); + successors(n); } + return after; +} +// The texture rules of the heap token route. `loads` are the reached s_load_dwordx8 from the resource heap with an SGPR +// offset (token loads). The program is eligible when every later read of the eight words (until they are overwritten) is +// the T# of an image_load, image_load_mip, image_sample_l, image_sample_lz, image_gather4_lz (2D) or image_get_resinfo of +// dimension 1D, 2D or 2D array, without D16; a copy, a numeric read, a store, a comparison, cube or 3D use, a +// partial use or a read of the words by an instruction this function cannot place makes it not eligible. `p` is +// the analysis with heap_tokens set. +static bool heap_token_texture_eligible(const Program &p, const std::vector &loads, + std::vector &consumers) { for (const size_t l : loads) { const auto &load = p.code[l]; if (load.dst + 8 > 106) return false; // The instructions that can run after this load. A word of the load that reaches one of them without being // overwritten, but not as the exact token symbol (a join with a path that skipped the load loses it), is a read // the second analysis could not place: the load is not eligible. - std::vector after(p.code.size()); - { - std::vector pending; - const auto visit = [&](size_t n) { - if (!after[n]) { after[n] = true; pending.push_back(n); } - }; - const auto successors = [&](size_t n) { - const auto &i = p.code[n]; - if (i.branch()) { - const auto t = p.at.find(i.target()); - if (t != p.at.end()) visit(t->second); - } - if (i.name != "s_endpgm" && !(i.branch() && i.op == 2) && n + 1 < p.code.size()) visit(n + 1); - }; - successors(l); - while (!pending.empty()) { - const size_t n = pending.back(); - pending.pop_back(); - successors(n); - } - } + const auto after = instructions_after(p, l); for (size_t n = 0; n < p.code.size(); ++n) { if (n == l || !p.reached[n]) continue; const auto &state = p.before[n]; @@ -1875,6 +1867,108 @@ static bool heap_token_eligible(const Program &p, std::vector &co } return true; } +// The buffer rules of the heap token route for one candidate: p.code[l] is an s_load_dwordx4 from the resource heap (an +// SGPR offset, or an address formed by s_add_u32), the V# of a GPU-selected raw buffer. It is eligible when its four words +// are read only as (a) the V# of a raw MUBUF dword-family load with OFFEN and without IDXEN, in the byte-window form +// (word 0 the token, words 1 to 3 the rewritten fields of this load), (b) the base of a scalar buffer load, or (c) by the +// SALU instructions of the byte-window rewrite (byte_descriptor_field). Every other read of a word or of a field derived +// from it, a copy included, makes the candidate not eligible, as does a word that a join lost before such a read. The +// consumers of an eligible candidate are appended to `consumers`; a candidate without a consumer is not eligible. +static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector &consumers) { + using T = Symbol::Type; + const auto &load = p.code[l]; + if (load.dst + 4 > 106) return false; + const unsigned immediate = load.b & 0xfffff; + const auto is_token = [&](const Symbol &s, unsigned word) { + return s.type == T::indexed_descriptor && s.value == compute_resource_heap && s.definition == load.pc && + s.offset == immediate + 4 * word; + }; + const auto is_field = [&](const Symbol &s, T type) { + return s.type == type && s.value == compute_resource_heap && s.definition == load.pc; + }; + // A word of this load or a field derived from it. + const auto of_load = [&](const Symbol &s) { + return (s.type == T::indexed_descriptor && s.value == compute_resource_heap && s.definition == load.pc) || + is_field(s, T::stride) || is_field(s, T::byte_stride) || is_field(s, T::zero_stride_word) || + is_field(s, T::byte_count) || is_field(s, T::clear_oob) || is_field(s, T::byte_oob); + }; + const auto after = instructions_after(p, l); + std::vector found; + for (size_t n = 0; n < p.code.size(); ++n) { + if (n == l || !p.reached[n]) continue; + const auto &i = p.code[n]; + const auto &state = p.before[n]; + auto reads = conservative_sgpr_reads(i); + if (i.enc == Encoding::Image) reads.emplace_back(((i.b >> 16) & 31) * 4, 8); + bool reads_load = false; + for (const auto &[first, count] : reads) + for (unsigned r = first; r < first + count && r < 106; ++r) { + // A word of the load that reaches a read through a join with a path that skipped the load: the second + // analysis could not place it. + if (after[n] && r >= load.dst && r < load.dst + 4 && state[r].type == T::unbound) return false; + reads_load |= of_load(state[r]); + } + if (!reads_load) continue; + if (i.enc == Encoding::Mubuf && i.name == "buffer_load_dword" && (i.a & 0x1000) && !(i.a & 0x2000)) { + const unsigned base = ((i.b >> 16) & 31) * 4, soffset = i.b >> 24; + if (base + 4 > 106 || !is_token(state[base], 0) || !is_field(state[base + 1], T::zero_stride_word) || + !is_field(state[base + 2], T::byte_count) || !is_field(state[base + 3], T::byte_oob) || + (soffset < 106 && of_load(state[soffset]))) + return false; + found.push_back({i.pc, load.pc}); + } else if (i.enc == Encoding::Smem && i.op >= 8 && i.op <= 12) { + const unsigned base = i.src[0], soffset = i.b >> 25; + if (base + 4 > 106 || (soffset < 106 && of_load(state[soffset]))) + return false; + for (unsigned j = 0; j < 4; ++j) + if (!is_token(state[base + j], j)) return false; + found.push_back({i.pc, load.pc}); + } else if (!(i.enc == Encoding::Sop2 && byte_descriptor_field(i, state, true))) + return false; + } + if (found.empty()) return false; + consumers.insert(consumers.end(), found.begin(), found.end()); + return true; +} +// The pre-pass of the heap token route. `p` is the analysis with heap_tokens set. Texture rules: every reached +// s_load_dwordx8 from the resource heap with an SGPR offset is a token load, and one that fails them makes the PROGRAM not +// eligible (heap_token_texture_eligible). Buffer rules, when `buffers` is set: every reached s_load_dwordx4 from the +// resource heap with an SGPR offset, or through an address formed by s_add_u32, is a candidate judged on its own +// (heap_token_buffer_eligible); a candidate that fails is dropped and keeps the path without tokens, except that an address +// formed by s_add_u32 which is not an eligible candidate makes the program not eligible, as it always did. Without +// `buffers` every such address makes the program not eligible. Returns true when the route is taken: there are token +// textures, all eligible, or at least one eligible buffer load. +static bool heap_token_eligible(const Program &p, bool buffers, std::vector &consumers, + std::vector &buffer_consumers) { + consumers.clear(); + buffer_consumers.clear(); + std::vector textures, candidates; + for (size_t n = 0; n < p.code.size(); ++n) { + const auto &i = p.code[n]; + if (!p.reached[n] || i.enc != Encoding::Smem || (i.op != 2 && i.op != 3)) continue; + const auto &base = p.before[n].at(i.src[0]); + if (i.op == 2 && (i.b >> 25) == 125 && base.type == Symbol::Type::heap_offset) { + // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. + if (!buffers || !heap_offset_address(p.before[n], i.src[0])) return false; + candidates.push_back(n); + } else if ((i.b >> 25) != 125 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + if (i.op == 3) textures.push_back(n); + else if (buffers) candidates.push_back(n); + } + } + if (textures.empty() && candidates.empty()) return false; + if (!heap_token_texture_eligible(p, textures, consumers)) { + consumers.clear(); + return false; + } + for (const size_t l : candidates) + if (!heap_token_buffer_eligible(p, l, buffer_consumers) && (p.code[l].b >> 25) == 125) { + consumers.clear(); + buffer_consumers.clear(); + return false; + } + return !textures.empty() || !buffer_consumers.empty(); +} #include "gfx1013_direct_compute.inl" #include "gfx1013_direct_graphics.inl" #include "gfx1013_direct_mesh.inl" @@ -2012,21 +2106,47 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64); // A GPU-selected texture loaded with s_load_dwordx8 from the resource heap: when every such load is only used as the // T# of a supported image instruction, translate the program on the analysis that keeps the byte address. + // A GPU-selected raw buffer (s_load_dwordx4 from the resource heap, with an SGPR offset or through an address formed by + // s_add_u32) takes the same route when no heap view contract covers it: its V# is the byte window of a view token. It is + // judged on an analysis that tracks the byte window rewrite (heap_window); a program with no eligible buffer load is + // analysed again exactly as before. std::vector token_consumers; + std::vector buffer_consumers; bool heap_tokens = false; - bool token_candidate = false; - for (size_t n = 0; direct_dxil && !stage && n < program.code.size() && !token_candidate; ++n) { + bool token_candidate = false, buffer_candidate = false; + for (size_t n = 0; direct_dxil && !stage && n < program.code.size(); ++n) { const auto &i = program.code[n]; - if (program.reached[n] && i.enc == Encoding::Smem && i.op == 3 && (i.b >> 25) != 125) { - const auto &base = program.before[n].at(i.src[0]); - token_candidate = base.type == Symbol::Type::table && base.value == compute_resource_heap; - } + if (!program.reached[n] || i.enc != Encoding::Smem || (i.op != 2 && i.op != 3)) continue; + const auto &base = program.before[n].at(i.src[0]); + if (i.op == 3 && (i.b >> 25) != 125) + token_candidate |= base.type == Symbol::Type::table && base.value == compute_resource_heap; + else if (i.op == 2 && heap_view == HeapViewContract::none) + buffer_candidate |= (base.type == Symbol::Type::table && base.value == compute_resource_heap && + (i.b >> 25) != 125) || + ((i.b >> 25) == 125 && base.type == Symbol::Type::heap_offset); } - if (token_candidate) { - auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, true); - if (heap_token_eligible(tokens, token_consumers)) { - program = std::move(tokens); - heap_tokens = true; + bool compiler_window = heap_window; + if (token_candidate || buffer_candidate) { + auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window || buffer_candidate, + narrow_wave64, true); + if (heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers)) { + if (!buffer_consumers.empty()) { + program = std::move(tokens); + heap_tokens = true; + compiler_window = true; + } else if (!buffer_candidate || heap_window) { + program = std::move(tokens); + heap_tokens = true; + } else { + // Token textures only: the analysis of the program as before this route knew buffers. + auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, + true); + std::vector none; + if (heap_token_eligible(textures, false, token_consumers, none)) { + program = std::move(textures); + heap_tokens = true; + } + } } } Emit emit{{}, program,layout->Desc_1_1}; @@ -2041,9 +2161,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi compiler.wave64 = wave64; compiler.narrow_wave64 = narrow_wave64; compiler.heap_view = heap_view; - compiler.heap_window = heap_window; + compiler.heap_window = compiler_window; compiler.heap_tokens = heap_tokens; compiler.heap_token_consumers = token_consumers; + compiler.heap_token_buffer_consumers = buffer_consumers; for (size_t i = 0; i < program.code.size(); ++i) { const auto& inst = program.code[i]; if (!program.reached[i]) continue; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index cfc75d84a0..c86f6ec4bc 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -51,7 +51,8 @@ enum class ComputeViewKind { // A raw buffer bound as a root UAV. The guest address is the root pointer plus a VGPR offset. root_buffer_uav, // Runtime-provided bindings of GPU-selected heap textures (view tokens). heap_token_srv: raw view over the title view-heap - // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, else 1 + image dimension); the miss UAV + // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, 0x20 a raw buffer view, else 1 + image + // dimension; the runtime that fills the table names the raw buffer views); the miss UAV // is one raw dword counting the waves that read the null slot. heap_token_srv, heap_token_dims_srv, @@ -150,8 +151,9 @@ struct NativeComputeShader { std::vector constants; // Additional b0 words, after root constants, read from these bound SRVs. std::vector stride_srvs; - // Five more b0 words after the stride words: base1d, base2d, base2da, count, null (heap token textures). - bool heap_token_words = false; + // More b0 words after the stride words, 0, 5 or 7: base1d, base2d, base2da, count, null (heap token textures), then + // baseraw, nullraw when a GPU-selected raw buffer is read through its view token. + unsigned heap_token_word_count = 0; std::string hlsl, dxil_ir; std::vector bindings; std::vector samplers; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index c3c31b8935..1385cfe0bd 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -90,12 +90,27 @@ struct DirectCompute { std::map,string> descriptor_strides; // GPU-selected heap textures through view tokens (the program passed heap_token_eligible). The registers are taken // before the program is lowered, because the DXIL names them; the five words are base1d, base2d, base2da, count, null. + // A program with an eligible raw buffer load (heap_token_buffer_consumers) has two more, in this order: baseraw + // (the first raw view id's slot) and nullraw (a raw buffer view of no bytes, read when the token does not hold a + // raw view). bool heap_tokens = false; std::vector heap_token_consumers; - std::array heap_token_values; + std::vector heap_token_buffer_consumers; + std::array heap_token_values; unsigned token_srv = 0, token_dims_srv = 0, token_miss_uav = 0; - // The views and words exist only when a program uses a token texture (an unused token load needs none). - bool token_bindings() const { return heap_tokens && !heap_token_consumers.empty(); } + // The views and words exist only when a program uses a token texture or buffer (an unused token load needs none). + bool token_bindings() const { + return heap_tokens && (!heap_token_consumers.empty() || !heap_token_buffer_consumers.empty()); + } + // The number of token words: 5, or 7 with a token buffer. + unsigned token_word_count() const { + return !token_bindings() ? 0u : heap_token_buffer_consumers.empty() ? 5u : 7u; + } + // The load at `pc` is an eligible raw buffer load of the token route. + bool heap_token_buffer_load(unsigned pc) const { + return heap_tokens && std::any_of(heap_token_buffer_consumers.begin(), heap_token_buffer_consumers.end(), + [pc](const auto &c) { return c.load == pc; }); + } unsigned label_number = 0; bool pixel_stage = false; bool pixel_heap_enabled = false; @@ -350,7 +365,7 @@ struct DirectCompute { initialize_constants(); } void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { - unsigned words = static_cast(descriptor_strides.size()) + (token_bindings() ? 5u : 0u); + unsigned words = static_cast(descriptor_strides.size()) + token_word_count(); for (const auto &block : analysis.result.constants) words += block.count; if (words) { @@ -374,9 +389,8 @@ struct DirectCompute { } for (auto &entry : descriptor_strides) entry.second = ir.binary("and",word_at(pos++),"16383"); - for (auto &value : heap_token_values) - if (token_bindings()) - value = word_at(pos++); + for (unsigned k = 0; k < token_word_count(); ++k) + heap_token_values[k] = word_at(pos++); } } // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer, typed_dword and raw_and_typed_dword @@ -397,6 +411,11 @@ struct DirectCompute { // picks the path: typed_buffer_srv is typed, every other kind is raw. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); + // A raw buffer that passed the pre-pass of the token route: the contract gate does not apply, the token is checked + // on every execution instead (heap_token_buffer). + if (!pixel_stage && symbol.type == Symbol::Type::indexed_descriptor && symbol.value == compute_resource_heap && + heap_token_buffer_load(symbol.definition)) + return heap_token_buffer(i, s, base, kind); refuse_heap_contract(i.pc); const bool typed = heap_view == HeapViewContract::typed_dword || (heap_view == HeapViewContract::raw_and_typed_dword && @@ -747,6 +766,39 @@ struct DirectCompute { for (unsigned j = 0; j < 8; ++j) write(i.dst + j, address); return; } + if (!pixel_stage && i.op == 2 && heap_token_buffer_load(i.pc)) { + // The V# of a GPU-selected raw buffer: the view token at the guest byte address, kept in all four words (see + // heap_token_buffer). A token is 32 bytes of title heap memory, so the address is a multiple of 32. The + // address is the byte offset from heap slot 0, not the slot index. + const Word offset = i.b & 0xfffff; + if (i.dst + 4 > 106) refuse(i.pc, "invalid heap token buffer descriptor address"); + string address; + if (so != 125) { + // The SGPR-offset form: the resource heap pointer (high word zero) and a byte offset in so. + if (low.type != Symbol::Type::table || low.value != compute_resource_heap || + !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant, 0})) + refuse(i.pc, "invalid heap token buffer descriptor address"); + if (offset % 32) refuse(i.pc, "unaligned heap token buffer immediate byte offset"); + if (so >= limit) refuse(i.pc, "heap token byte offset register"); + const auto value = s.at(so); + const bool aligned = (value.type == Symbol::Type::constant && value.value % 32 == 0) || + (value.type == Symbol::Type::masked && (value.value & 31) == 0); + if (!aligned || value.value > UINT_MAX - offset) + refuse(i.pc, "heap token buffer byte offset has no proven 32-byte aligned range"); + address = ir.binary("add", operand32(i, so), to_string(offset)); + } else { + // The address formed by s_add_u32: its high word is the carry of that add, which the emitter writes as 0 + // (the heap base is slot 0), and its low word is the byte offset. + if (!heap_offset_address(s, i.src[0])) + refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); + if (offset) refuse(i.pc, "heap token buffer load with an immediate offset on an added address"); + if ((low.index_mask & 31) != 0) + refuse(i.pc, "heap token buffer byte offset has no proven 32-byte aligned range"); + address = read(i.src[0]); + } + for (unsigned j = 0; j < 4; ++j) write(i.dst + j, address); + return; + } if (pixel_heap_enabled && low.type == Symbol::Type::table && low.value == compute_resource_heap && i.op == 3) { if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) refuse(i.pc, "invalid pixel heap texture descriptor address"); @@ -1062,6 +1114,16 @@ struct DirectCompute { if (std::none_of(heap_token_consumers.begin(), heap_token_consumers.end(), [&](const auto &c) { return c.pc == i.pc && c.dim == dim; })) refuse(i.pc, "heap token consumer was not listed by the pre-pass"); + const auto slot = heap_token_slot(base, 1 + dim, heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2], + heap_token_values[4]); + constexpr unsigned dx_kind[]{1, 2, 0, 0, 0, 7}; + return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); + } + // The heap slot a view token names. The token is read at the byte address held by SGPR `base` (every lane loads the + // same words, so the slot is dynamically uniform): the slot is first + id when the magic and the id range hold and the + // dimension table records `recorded` for the id (texture: 1 + the SQ dimension code; raw buffer: 0x20), and `null` + // otherwise, in which case the first lane of the wave counts one miss. + string heap_token_slot(unsigned base, unsigned recorded_code, const string &first, const string &null) { // 16: the module reads raw buffers (the token memory and the dimension table), as for every raw view above; // 0x40000000: it reads ResourceDescriptorHeap. Same flags as heap_resource, see tests/native_heap_handle_probe_check.py. ir.features |= 16 | 0x40000000; @@ -1079,9 +1141,8 @@ struct DirectCompute { const auto clamped = select(in_range, id, ir.binary("sub", count, "1")); const auto recorded = load_word(dims, ir.binary("shl", clamped, "2")); auto valid = ir.value("and i1 " + cmp("eq", magic, to_string(0x56573258u)) + ", " + in_range); - valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(1 + dim))); - const auto &first = heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2]; - const auto slot = select(valid, ir.binary("add", first, id), heap_token_values[4]); + valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(recorded_code))); + const auto slot = select(valid, ir.binary("add", first, id), null); // One count per wave and execution that reads the null slot. ir.uses_wave = true; const auto first_lane = ir.invoke("i1", "waveIsFirstLane", 110, {}, "nounwind"); @@ -1095,18 +1156,55 @@ struct DirectCompute { {"i32", "1"}}, "nounwind"); ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; - constexpr unsigned dx_kind[]{1, 2, 0, 0, 0, 7}; - return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); + return slot; + } + // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token names a + // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a word of + // the heap load (the s_load_dwordx4 left the token's byte address in all four words; the byte-window rewrite only + // changes what the analysis knows about words 1 to 3). + string heap_token_buffer(const Inst &i, const State &s, unsigned base, ComputeViewKind kind) { + const auto &symbol = s.at(base); + const bool window = kind == ComputeViewKind::byte_window_srv; + if (!window && kind != ComputeViewKind::buffer_srv) + refuse(i.pc, "a heap token raw buffer is read as a raw MUBUF dword load or a scalar buffer load only"); + if (std::none_of(heap_token_buffer_consumers.begin(), heap_token_buffer_consumers.end(), + [&](const auto &c) { return c.pc == i.pc && c.load == symbol.definition; })) + refuse(i.pc, "heap token consumer was not listed by the pre-pass"); + const auto defined = analysis.program.at.find(symbol.definition); + if (defined == analysis.program.at.end() || analysis.program.code[defined->second].enc != Encoding::Smem || + analysis.program.code[defined->second].op != 2 || base + 4 > 106) + refuse(i.pc, "heap token raw buffer descriptor is not a four-word heap load"); + if (symbol.offset % 32 || symbol.type != Symbol::Type::indexed_descriptor) + refuse(i.pc, "unaligned heap descriptor"); + // The same precaution as for a heap descriptor without tokens: the words are compared by the pc of their heap load, + // which a loop around that load executes again for another selection. + if (window) + for (const auto &inst : analysis.program.code) + if (inst.branch() && inst.target() <= symbol.definition && symbol.definition <= inst.pc) + refuse(i.pc, "heap byte window loaded inside a loop"); + constexpr Symbol::Type window_words[] = {Symbol::Type::indexed_descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = symbol; + if (window) + expected.type = window_words[j]; // field() already cleared the word offset + else + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + const auto slot = heap_token_slot(base, 0x20, heap_token_values[5], heap_token_values[6]); + return ir.heap_handle(slot, 11, 0, false, false); } // The runtime-provided bindings and words of the token route. Taken before lowering because the DXIL names them. void prepare_heap_tokens() { if (!token_bindings()) return; auto &r = analysis.result; - unsigned words = 5 + static_cast(descriptor_strides.size()); + unsigned words = token_word_count() + static_cast(descriptor_strides.size()); for (const auto &block : r.constants) words += block.count; if (words > 32) refuse(analysis.program.code.front().pc, "heap token words exceed the 32-word compute entry layout"); - r.heap_token_words = true; + r.heap_token_word_count = token_word_count(); token_srv = analysis.srv++; token_dims_srv = analysis.srv++; token_miss_uav = analysis.uav++; diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 186e4261d8..9b4b0825e1 100644 --- a/src/native_compute_output.h +++ b/src/native_compute_output.h @@ -5,7 +5,7 @@ namespace x2w { // Bump whenever a native translation of an unchanged request can change meaning. -constexpr unsigned native_compute_output_revision = 2; +constexpr unsigned native_compute_output_revision = 3; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index b3201a1dd6..1fabf667f8 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -50,7 +50,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade pipeline.uav_count = counts[1]; pipeline.constants = std::move(program.constants); pipeline.stride_srvs = std::move(program.stride_srvs); - pipeline.token_words = program.heap_token_words ? 5u : 0u; + pipeline.token_words = program.heap_token_word_count; for (const auto &block : pipeline.constants) pipeline.constant_words += block.count; pipeline.srv_count = counts[0]; diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index b95f8756db..1041af8c1e 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,7 +17,7 @@ struct NativeComputePipeline { unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; - unsigned token_words = 0; // heap token texture words (base1d, base2d, base2da, count, null) after the stride words + unsigned token_words = 0; // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) unsigned instructions = 0; bool cache_hit = false, frontend_cache_hit = false; bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index cfa61a3d5f..5f17e02623 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -348,11 +348,18 @@ const char* load_compute_translation(ComputeTranslation& tr) }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; - // GPU-selected heap textures (view tokens): published by the translator, not bound by this runtime yet. + // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this runtime + // yet. The reader knows the seven word names (baseraw and nullraw belong to raw buffers); every such line is + // refused here until a runtime fills the views and words. + const auto token_word = [&] { + for (const char *known : {"base1d", "base2d", "base2da", "count", "null", "baseraw", "nullraw"}) + if (!std::strcmp(name, known)) return true; + return false; + }; if ((std::sscanf(line.c_str(), "srv %u heaptok%n", &i, &used) == 1 && whole()) || (std::sscanf(line.c_str(), "srv %u heaptokdims%n", &i, &used) == 1 && whole()) || (std::sscanf(line.c_str(), "uav %u heaptokmiss%n", &i, &used) == 1 && whole()) || - (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole())) + (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole() && token_word())) return "heap token textures are not bound yet"; if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) tr.uds.push_back({a, b}); diff --git a/tests/native_compute_manifest_reasons.cpp b/tests/native_compute_manifest_reasons.cpp index 6ac83e92d5..7b72462b9f 100644 --- a/tests/native_compute_manifest_reasons.cpp +++ b/tests/native_compute_manifest_reasons.cpp @@ -134,29 +134,35 @@ int main() { p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); }}, {"heap token view with another root parameter", [](auto &p) { - p.heap_token_words = true; + p.heap_token_word_count = 5; p.bindings.push_back(view(K::heap_token_srv, 1, 1)); }}, {"heap token view with another root parameter", [](auto &p) { p.bindings.push_back(view(K::buffer_srv, 1, compute_heap_token)); }}, {"heap token words without the three heap token views", [](auto &p) { - p.heap_token_words = true; + p.heap_token_word_count = 5; p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); }}, {"SRV registers not contiguous", [](auto &p) { - p.heap_token_words = true; + p.heap_token_word_count = 5; p.bindings.push_back(view(K::heap_token_srv, 2, compute_heap_token)); }}, {"more than 32 user data words", [](auto &p) { p.constants.assign(3, {0, 0, 8}); p.stride_srvs = {}; - p.heap_token_words = true; + p.heap_token_word_count = 5; p.constants.push_back({0, 0, 4}); p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); p.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); }}, + {"heap token words are five, or seven with a token buffer", [](auto &p) { + p.heap_token_word_count = 6; + p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); + p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); + p.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); + }}, }; for (const auto &c : cases) { auto program = base(); @@ -242,7 +248,7 @@ int main() { // The views and words of GPU-selected heap textures are published by name, in register order with the other views. { auto program = base(); - program.heap_token_words = true; + program.heap_token_word_count = 5; program.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); program.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); program.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); @@ -259,6 +265,27 @@ int main() { std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); failures += !ok; } - std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 4); + // A program with a token buffer has seven words: baseraw and nullraw follow the five of the textures. + { + auto program = base(); + program.heap_token_word_count = 7; + program.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); + program.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); + program.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); + reason = "unset"; + const auto manifest = format_compute_runtime_manifest(program, &reason); + const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 9\nudsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\nudsrc 2 heaptok base1d\nudsrc 3 heaptok base2d\n" + "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null\n" + "udsrc 7 heaptok baseraw\nudsrc 8 heaptok nullraw\n" + "srv 0 buf table 1 64\nsrv 1 heaptok\nsrv 2 heaptokdims\nuav 0 table 1 32\n" + "uav 1 heaptokmiss\nnative " + std::to_string(native_compute_output_revision) + "\n"; + const bool ok = manifest && *manifest == wanted && reason == "unset"; + std::printf("%s publishes the seven heap token words of a token buffer\n", ok ? "ok " : "FAIL"); + if (!ok) + std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; + } + std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 5); return failures ? 1 : 0; } diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index b54bb4089e..807415b629 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -6,6 +6,11 @@ // from t0 (a raw buffer), loads the texture with s_load_dwordx8 from the resource heap at that address and // samples (2D) or loads (1D, 2D array) it at a fixed coordinate; lane L writes its texel to u0 at 16 * L. // MODE tex2d | tex1d | tex2da the dimension of the instruction under test +// rawbuf | rawbuf_waterfall | sbuf GPU-selected raw buffers (PR 1c): the program loads a raw buffer V# +// with s_load_dwordx4 from the resource heap at the token's address (rawbuf: an SGPR offset; +// rawbuf_waterfall: an address formed by s_add_u32), rewrites it to the byte window and lane L reads four +// dwords at byte 16 * L with buffer_load_dwordx4 (sbuf: s_buffer_load_dwordx4 of the unrewritten words, the +// same four dwords in every lane). The results are compared as dwords. // The rig binds what the manifest names for the runtime-provided views: the token memory (a raw SRV over a buffer of // eight 32-byte tokens), the dimension table (one uint per view id), the miss counter (a raw UAV) and the five words // base1d, base2d, base2da, count, null. The shader indexes a host heap with one range per dimension, one slot per view id @@ -13,6 +18,10 @@ // Cases (token at byte address 32 * case): a valid id, a wrong magic, an id equal to the count, the largest id, an id of // another dimension, a content token (bit 31), id 0, an empty token. A valid token gives the texel of its view and no // miss; every other case gives the null texel and one miss per wave (the dispatch is three groups of one wave). +// The raw modes bind baseraw and nullraw too. The host heap has raw views at baseraw + id: id 1 over a buffer of 64 +// dwords (value 0xA0000000 + index), id 2 over 128 dwords (0xB0000000 + index); id 0 and id 3 are null raw views, and the +// dimension table names id 3 a 2D texture. Case 8 is a valid token for id 2. Lanes 16 to 31 read past the 64 dwords of +// id 1 and get 0. Every other case gives zeros and one miss per wave. // Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. #include "desktop_gpu.h" #include "direct_compute_cache.h" @@ -36,7 +45,7 @@ constexpr unsigned base_1d = 8, base_2d = 16, base_2da = 24, null_slot = 0, tabl constexpr std::uint32_t magic = 0x56573258u, sentinel = 0x69696969u; using Texel = std::array; -enum class Dim { d1, d2, d2a }; +enum class Dim { d1, d2, d2a, raw }; Texel texel_1d(int x) { return {1000.f + x, 2000.f + x, 3000.f + x, 4000.f}; } Texel texel_2d(int x, int y) { return {10.f * x + 1, 10.f * y + 2, 100.f + x + 4 * y, 1000.f}; } Texel texel_2da(int x, int y, int slice) { return {10.f * x + y + 100.f * slice, 500.f + slice, 600.f + x, 700.f + y}; } @@ -45,14 +54,29 @@ struct Mode { Dim dim; unsigned valid_id, mismatch_id; Texel expected; + bool scalar = false; // raw modes: every lane gets the first four dwords (s_buffer_load) }; bool make_mode(const std::wstring &name, Mode &mode) { if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; else if (name == L"tex1d") mode = {Dim::d1, 3, 1, texel_1d(1)}; else if (name == L"tex2da") mode = {Dim::d2a, 2, 1, texel_2da(1, 2, 1)}; + else if (name == L"rawbuf" || name == L"rawbuf_waterfall") mode = {Dim::raw, 1, 3, {}}; + else if (name == L"sbuf") mode = {Dim::raw, 1, 3, {}, true}; else return false; return true; } +// The raw views of the raw modes: dwords of id 1 and id 2. +constexpr unsigned raw_base = 8, raw_dims_code = 0x20, raw_words_1 = 64, raw_words_2 = 128; +std::uint32_t raw_word(unsigned id, unsigned index) { + return (id == 1 ? 0xA0000000u : 0xB0000000u) + index; +} +// The four dwords lane `lane` gets for a valid token of raw view `id` (zero past the end of the view). +std::array raw_expected(unsigned id, unsigned lane, bool scalar) { + const unsigned words = id == 1 ? raw_words_1 : raw_words_2, first = scalar ? 0 : lane * 4; + std::array out{}; + for (unsigned k = 0; k < 4; ++k) out[k] = first + k < words ? raw_word(id, first + k) : 0; + return out; +} struct Gpu { ComPtr device; @@ -272,7 +296,7 @@ bool parse_manifest(const std::string &text, Layout &layout) { layout.words[w[3]] = static_cast(std::stoul(w[1])); } return layout.selector >= 0 && layout.out >= 0 && layout.tokens >= 0 && layout.dims >= 0 && layout.miss >= 0 && - layout.words.size() == 5; + (layout.words.size() == 5 || layout.words.size() == 7); } bool same_bits(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } @@ -290,7 +314,8 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file std::string reason; const auto manifest = x2w::format_compute_runtime_manifest(program, &reason); Layout layout; - if (!manifest || !parse_manifest(*manifest, layout)) { + const bool raw = mode.dim == Dim::raw; + if (!manifest || !parse_manifest(*manifest, layout) || layout.words.size() != (raw ? 7u : 5u)) { std::printf("FAIL: the manifest does not name the token views and words (%s)\n%s\n", reason.c_str(), manifest ? manifest->c_str() : "(none)"); return 1; @@ -314,23 +339,40 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file [](int x, int y, int s) { return texel_2da(x, y, s); }); const auto dimension = mode.dim == Dim::d1 ? D3D12_SRV_DIMENSION_TEXTURE1D : mode.dim == Dim::d2 ? D3D12_SRV_DIMENSION_TEXTURE2D : D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - gpu.srv(null_slot, nullptr, dimension); // the null slot has the dimension of the instruction under test - for (unsigned id = 0; id < count; ++id) { - gpu.srv(base_1d + id, id == 3 ? gpu.tex1d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE1D); - gpu.srv(base_2d + id, id == 1 ? gpu.tex2d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2D); - gpu.srv(base_2da + id, id == 2 ? gpu.tex2da.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + std::vector raw_1(raw_words_1), raw_2(raw_words_2); + for (unsigned k = 0; k < raw_words_1; ++k) raw_1[k] = raw_word(1, k); + for (unsigned k = 0; k < raw_words_2; ++k) raw_2[k] = raw_word(2, k); + ComPtr raw_buffer_1, raw_buffer_2; + if (raw) { + // The raw views: slot raw_base + id; id 0 and 3 and the null slot are raw views without a resource. + raw_buffer_1 = gpu.upload_buffer(raw_1); + raw_buffer_2 = gpu.upload_buffer(raw_2); + gpu.raw_srv(null_slot, nullptr, 1); + for (unsigned id = 0; id < count; ++id) + gpu.raw_srv(raw_base + id, id == 1 ? raw_buffer_1.Get() : id == 2 ? raw_buffer_2.Get() : nullptr, + id == 1 ? raw_words_1 : id == 2 ? raw_words_2 : 1); + } else { + gpu.srv(null_slot, nullptr, dimension); // the null slot has the dimension of the instruction under test + for (unsigned id = 0; id < count; ++id) { + gpu.srv(base_1d + id, id == 3 ? gpu.tex1d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE1D); + gpu.srv(base_2d + id, id == 1 ? gpu.tex2d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2D); + gpu.srv(base_2da + id, id == 2 ? gpu.tex2da.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + } } gpu.selector = make_buffer(gpu.device.Get(), 16, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); - std::vector token_words(8 * 8, 0xdeadbeefu); - const std::uint32_t tokens[8][2] = {{magic, mode.valid_id}, {magic + 1, mode.valid_id}, {magic, count}, + const unsigned case_count = raw ? 9 : 8; + std::vector token_words(case_count * 8, 0xdeadbeefu); + const std::uint32_t tokens[9][2] = {{magic, mode.valid_id}, {magic + 1, mode.valid_id}, {magic, count}, {magic, 0xffffffffu}, {magic, mode.mismatch_id}, - {magic, 0x80000000u | mode.valid_id}, {magic, 0}, {0, 0}}; - for (unsigned c = 0; c < 8; ++c) { + {magic, 0x80000000u | mode.valid_id}, {magic, 0}, {0, 0}, {magic, 2}}; + for (unsigned c = 0; c < case_count; ++c) { token_words[c * 8] = tokens[c][0]; token_words[c * 8 + 1] = tokens[c][1]; } gpu.tokens = gpu.upload_buffer(token_words); - gpu.dims = gpu.upload_buffer({0, 2, 6, 1}); // 1 + the SQ image dimension: 2D 2, 2D array 6, 1D 1 + // 1 + the SQ image dimension: 2D 2, 2D array 6, 1D 1; 0x20 a raw buffer view (ids 1 and 2), id 3 a 2D texture + gpu.dims = gpu.upload_buffer(raw ? std::vector{0, raw_dims_code, raw_dims_code, 2} + : std::vector{0, 2, 6, 1}); gpu.output = make_buffer(gpu.device.Get(), lanes * sizeof(Texel), D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); gpu.misses = make_buffer(gpu.device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, @@ -341,14 +383,15 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file // The table: t-registers first, then u-registers, as bind() lays it out. const unsigned uav_start = table_start + pipeline.srv_count; gpu.raw_srv(table_start + layout.selector, gpu.selector.Get(), 4); - gpu.raw_srv(table_start + layout.tokens, gpu.tokens.Get(), 64); + gpu.raw_srv(table_start + layout.tokens, gpu.tokens.Get(), static_cast(token_words.size())); gpu.raw_srv(table_start + layout.dims, gpu.dims.Get(), 4); gpu.raw_uav(uav_start + layout.out, gpu.output.Get(), lanes * 4); gpu.raw_uav(uav_start + layout.miss, gpu.misses.Get(), 1); auto first = gpu.views->GetGPUDescriptorHandleForHeapStart(); first.ptr += UINT64(table_start) * gpu.increment; const std::map values{{"base1d", base_1d}, {"base2d", base_2d}, {"base2da", base_2da}, - {"count", count}, {"null", null_slot}}; + {"count", count}, {"null", null_slot}, {"baseraw", raw_base}, + {"nullraw", null_slot}}; auto dispatch = [&](unsigned address, std::vector &out, std::uint32_t &missed) { gpu.rewrite(gpu.selector.Get(), {address, 0, 0, 0}); @@ -391,14 +434,28 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file gpu.readback->Unmap(0, &written); }; - const char *const cases[8] = {"valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", - "id_zero", "no_token"}; - for (unsigned c = 0; c < 8; ++c) { + const char *const cases[9] = {"valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", + "id_zero", "no_token", "second_view"}; + for (unsigned c = 0; c < case_count; ++c) { std::vector out; std::uint32_t missed = 0; dispatch(c * 32, out, missed); + const bool valid_case = c == 0 || (raw && c == 8); + for (unsigned lane = 0; raw && lane < lanes; ++lane) { + // Results as dwords: the buffer data are not floats. + const auto expected_words = valid_case ? raw_expected(c == 8 ? 2 : 1, lane, mode.scalar) + : std::array{}; + std::array got_words; + std::memcpy(got_words.data(), &out[lane * 4], sizeof got_words); + if (got_words != expected_words) { + std::printf("FAIL: %s %s: lane %u is (%08x, %08x, %08x, %08x), expected (%08x, %08x, %08x, %08x)\n", + label.c_str(), cases[c], lane, got_words[0], got_words[1], got_words[2], got_words[3], + expected_words[0], expected_words[1], expected_words[2], expected_words[3]); + return 1; + } + } const Texel expected = c == 0 ? mode.expected : Texel{0, 0, 0, 0}; - for (unsigned lane = 0; lane < lanes; ++lane) { + for (unsigned lane = 0; !raw && lane < lanes; ++lane) { Texel got; std::memcpy(got.data(), &out[lane * 4], sizeof got); if (!same_bits(got, expected)) { @@ -408,14 +465,16 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file return 1; } } - const std::uint32_t expected_misses = c == 0 ? 0 : groups; + const std::uint32_t expected_misses = valid_case ? 0 : groups; if (missed != expected_misses) { std::printf("FAIL: %s %s: %u misses, expected %u (one per wave)\n", label.c_str(), cases[c], missed, expected_misses); return 1; } std::printf("pass: %s %s: %s in all %u lanes, %u misses (%u waves)\n", label.c_str(), cases[c], - c == 0 ? "the texel of the view" : "the null texel", lanes, missed, groups); + valid_case ? (raw ? "the dwords of the view" : "the texel of the view") + : (raw ? "zeros" : "the null texel"), + lanes, missed, groups); } return 0; } @@ -423,7 +482,7 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file int wmain(int argc, wchar_t **argv) { if (argc != 6) { - std::fputs("usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER tex2d|tex1d|tex2da\n", stderr); + std::fputs("usage: native_heap_token_texture SDK CACHE REQ.c67 ADAPTER MODE\n", stderr); return 2; } Gpu gpu; diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index cf2651ec12..8e5f690966 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -166,6 +166,150 @@ def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SEL "immediate": full(COORDS_2D, SAMPLE_2D, load=[0xf40c0805, 0x22000020]), } +# GPU-selected raw buffers (PR 1c). The V# of the buffer is an s_load_dwordx4 from the resource heap, at a 32-byte aligned +# byte address chosen by GPU data (the same address form as the texture token), or through an address formed by s_add_u32. +MASK32 = [ + 0x8711ff10, 0x0000ffe0, # s_and_b32 s17, s16, 0xffe0 (proves a 32-byte aligned range) +] +SELECTOR32 = [*SELECTOR_HEAD, *MASK32] +BUFFER_LOAD = [0xf4080805, 0x22000000] # s_load_dwordx4 s[32:35], s[10:11], s17 (a raw buffer: a view token in the heap) +BUFFER_LOAD_IMM = [0xf4080805, 0x22000020] # s_load_dwordx4 s[32:35], s[10:11], s17 offset:0x20 +BUFFER_LOAD_IMM4 = [0xf4080805, 0x22000004] # s_load_dwordx4 s[32:35], s[10:11], s17 offset:0x4 +ADD_HEAP = [ + 0x8014110a, # s_add_u32 s20, s10, s17 + 0x82158080, # s_addc_u32 s21, 0, 0 +] +ADD_HEAP_UNMASKED = [ + 0x8014100a, # s_add_u32 s20, s10, s16 (the offset is not masked) + 0x82158080, # s_addc_u32 s21, 0, 0 +] +BUFFER_LOAD_ADDED = [0xf408080a, 0xfa000000] # s_load_dwordx4 s[32:35], s[20:21], 0x0 +BUFFER_LOAD_ADDED_IMM = [0xf408080a, 0xfa000020] # s_load_dwordx4 s[32:35], s[20:21], 0x20 +# The byte-window rewrite of the V# in s[32:35] (word 1 without stride, word 2 the byte count, word 3 the raw out-of-bounds +# mode), the sequence of the direct heap descriptor path. +REWRITE = [ + 0x93a4ff21, 0x000e0010, # s_bfe_u32 s36, s33, 0xe0010 + 0x84a48124, # s_max_u32 s36, s36, 1 + 0x93222422, # s_mul_i32 s34, s34, s36 + 0x8721ff21, 0xc000ffff, # s_and_b32 s33, s33, 0xc000ffff + 0x8723ff23, 0xcfffffff, # s_and_b32 s35, s35, 0xcfffffff + 0x8823ff23, 0x30000000, # s_or_b32 s35, s35, 0x30000000 +] +REWRITE_NO_WORD3 = REWRITE[:-4] # the rewrite without the out-of-bounds mode words +LANE = [0x34100084] # v_lshlrev_b32_e32 v8, 4, v0 +LOAD_X4 = [0xe0381000, 0x80080408] # buffer_load_dwordx4 v[4:7], v8, s[32:35], 0 offen +LOAD_X1 = [0xe0301000, 0x80080408] # buffer_load_dword v4, v8, s[32:35], 0 offen +LOAD_X3 = [0xe03c1000, 0x80080408] # buffer_load_dwordx3 v[4:6], v8, s[32:35], 0 offen +LOAD_X4_IDXEN = [0xe0382000, 0x80080408] # buffer_load_dwordx4 v[4:7], v8, s[32:35], 0 idxen +LOAD_FORMAT = [0xe00c1000, 0x80080408] # buffer_load_format_xyzw v[4:7], v8, s[32:35], 0 offen +LOAD_TBUFFER = [0xea6b1000, 0x80080408] # tbuffer_load_format_xyzw v[4:7], v8, s[32:35], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen +STORE_V = [0xe0781000, 0x80080408] # buffer_store_dwordx4 v[4:7], v8, s[32:35], 0 offen (a store through the V#) +SBUFFER_X4 = [0xf4280a10, 0xfa000000] # s_buffer_load_dwordx4 s[40:43], s[32:35], 0x0 +SBUFFER_VGPR = [0x7e080228, 0x7e0a0229, 0x7e0c022a, 0x7e0e022b] # v_mov_b32 v4..v7, s40..s43 +COPY_WORD2 = [0xbeac0322] # s_mov_b32 s44, s34 +NUMERIC_WORD2 = [0x872cff22, 0x000000ff] # s_and_b32 s44, s34, 0xff + + +def buffer_full(load, rewrite=REWRITE, consumer=LOAD_X4, selector=SELECTOR32, store=STORE, pre=(), between=()): + return [*BASES, *TABLE_LOADS, *selector, *pre, *load, *WAIT, *between, *rewrite, *LANE, *WAIT, *consumer, *store] + + +def loop_body(words): + """words as a single-block loop: a backward conditional branch to its first instruction.""" + return [*words, JOIN[0], 0xbf840000 | ((-(len(words) + 2)) & 0xffff)] # s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 top + + +BUFFER_PROGRAMS = { + "rawbuf": buffer_full(BUFFER_LOAD), + "rawbuf_waterfall": buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP), + "sbuf": [*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, *STORE], +} +# Eligible variants that must compile: the other dword widths, an immediate offset, and a texture next to a buffer. +BUFFER_ACCEPTED = { + "x1": buffer_full(BUFFER_LOAD, consumer=LOAD_X1), + "x3": buffer_full(BUFFER_LOAD, consumer=LOAD_X3), + "immediate": buffer_full(BUFFER_LOAD_IMM), + # s_buffer_load_dwordx4 s[40:43], s[32:35], s17: the SGPR offset of a scalar buffer load that is not the token's + "sbuf_offset": [*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, 0xf4280a10, 0x22000000, *WAIT, *SBUFFER_VGPR, + *LANE, *STORE], +} +# A texture and a buffer in one program: the V# of the buffer is s[48:51], its rewrite temporaries s52. +MIXED_BUFFER_LOAD = [0xf4080c05, 0x22000000] # s_load_dwordx4 s[48:51], s[10:11], s17 +MIXED_REWRITE = [ + 0x93b4ff31, 0x000e0010, # s_bfe_u32 s52, s49, 0xe0010 + 0x84b48134, # s_max_u32 s52, s52, 1 + 0x93323432, # s_mul_i32 s50, s50, s52 + 0x8731ff31, 0xc000ffff, # s_and_b32 s49, s49, 0xc000ffff + 0x8733ff33, 0xcfffffff, # s_and_b32 s51, s51, 0xcfffffff + 0x8833ff33, 0x30000000, # s_or_b32 s51, s51, 0x30000000 +] +MIXED_CONSUME = [ + 0x34180084, # v_lshlrev_b32_e32 v12, 4, v0 + 0xe0381000, 0x800c100c, # buffer_load_dwordx4 v[16:19], v12, s[48:51], 0 offen +] + + +def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, consume=MIXED_CONSUME, + buffer_first=False): + textures = [*texture_load, *SAMPLER, *COORDS_2D] + buffers = [*MIXED_BUFFER_LOAD, *WAIT, *buffer_rewrite, *consume] + order = [*buffers, *textures] if buffer_first else [*textures, *buffers] + return [*BASES, *TABLE_LOADS, *texture_selector, *order, *WAIT, *SAMPLE_2D, *STORE] + + +MIXED_PROGRAMS = { + "mixed": mixed(MIXED_REWRITE), +} +# An eligible texture next to a buffer load that is not eligible (its V# is read without the byte-window rewrite): the +# buffer load keeps today's result, and the texture stays on the token route. The refusal text says which load stopped +# the translation first (program order): a texture shape text only the token route has, or the heap contract text. +MIXED_CONTROLS = { + # the texture load is first and its offset register is not masked: the token route's text + "texture_first": (mixed([], texture_selector=SELECTOR_HEAD, texture_load=[0xf40c0805, 0x20000000]), UNPROVEN), + # the buffer load is first: the heap contract text of the load that keeps today's path + "buffer_first": (mixed([], buffer_first=True), HEAP_REFUSAL), +} + +BUFFER_UNMASKED = "heap token buffer byte offset has no proven 32-byte aligned range" +BUFFER_IMMEDIATE = "unaligned heap token buffer immediate byte offset" +BUFFER_ADDED_IMMEDIATE = "heap token buffer load with an immediate offset on an added address" +LOOP = "heap byte window loaded inside a loop" +# V# uses that make the buffer load not eligible: the refusal text is the one these programs get without the buffer route +# (checked against the base of this change). Two of them are refused before the heap load is reached. +IDXEN_REFUSAL = "raw buffer load needs a linear byte offset and no modifiers" +FORMAT_REFUSAL = "formatted load requires zero or a single linear index" +BUFFER_CONTROLS = { + "plain": (buffer_full(BUFFER_LOAD, rewrite=[]), HEAP_REFUSAL), # no byte-window rewrite + "idxen": (buffer_full(BUFFER_LOAD, consumer=LOAD_X4_IDXEN), IDXEN_REFUSAL), + "format": (buffer_full(BUFFER_LOAD, consumer=LOAD_FORMAT), FORMAT_REFUSAL), + "tbuffer": (buffer_full(BUFFER_LOAD, consumer=LOAD_TBUFFER), HEAP_REFUSAL), + "store": (buffer_full(BUFFER_LOAD, consumer=STORE_V, store=END), HEAP_REFUSAL), + # s_and_b32 s44, s34, 0xff before the rewrite + "numeric_word2": (buffer_full(BUFFER_LOAD, between=NUMERIC_WORD2), HEAP_REFUSAL), + # s_mov_b32 s44, s34 after the rewrite + "copy_field": (buffer_full(BUFFER_LOAD, consumer=[*COPY_WORD2, *LOAD_X4]), HEAP_REFUSAL), + "partial": (buffer_full(BUFFER_LOAD, rewrite=REWRITE_NO_WORD3), HEAP_REFUSAL), # word 3 is still the token + # the buffer load runs on one path only: after the join the words are not the token symbol any more + "join": (buffer_full([*JOIN, *BUFFER_LOAD]), HEAP_REFUSAL), + # the immediate offset 4 moves the words off the 32-byte descriptor layout the rewrite recognizes + "immediate4": (buffer_full(BUFFER_LOAD_IMM4), HEAP_REFUSAL), +} +# Address shapes. Each program is eligible, so it reaches the load and is refused there. +BUFFER_ADDRESS_CONTROLS = { + # s_load_dwordx4 s[32:35], s[10:11], s17 where s17 is s16: not masked + "unmasked": (buffer_full(BUFFER_LOAD, selector=SELECTOR_HEAD), BUFFER_UNMASKED), + # s_and_b32 s17, s16, 0xfffc: bit 2 to 4 may be set + "misaligned": (buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK]), BUFFER_UNMASKED), + # the scalar buffer load of the unrewritten words with s_load_dwordx4 ... offset:0x4 + "immediate4": ([*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD_IMM4, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, + *STORE], BUFFER_IMMEDIATE), + "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), BUFFER_UNMASKED), + "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), BUFFER_ADDED_IMMEDIATE), + # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load) + "loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *loop_body([*BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, *LOAD_X4]), + *STORE], LOOP), +} + EXPECTED_MANIFEST = """x2w-manifest 2 stage cs group 32 1 1 @@ -181,10 +325,29 @@ def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SEL uav 0 heaptokmiss uav 1 table 0 32 smpl 0 00000092 00000000 00000000 00000000 -native 2 +native 3 +""" +EXPECTED_BUFFER_MANIFEST = """x2w-manifest 2 +stage cs +group 32 1 1 +ud 7 +udsrc 0 heaptok base1d +udsrc 1 heaptok base2d +udsrc 2 heaptok base2da +udsrc 3 heaptok count +udsrc 4 heaptok null +udsrc 5 heaptok baseraw +udsrc 6 heaptok nullraw +srv 0 heaptok +srv 1 heaptokdims +srv 2 buf table 0 0 +uav 0 heaptokmiss +uav 1 table 0 32 +native 3 """ FIXTURE_CASES = ("valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", "id_zero", "no_token") +BUFFER_FIXTURE_CASES = FIXTURE_CASES + ("second_view",) def main(): @@ -254,6 +417,16 @@ def compile_request(marker): require(f"pass: {mode} {case}:" in out, f"{mode}: case {case} held") require(f"pass: {mode} the manifest names the token views and words" in out, f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and five heaptok words") + for mode in BUFFER_PROGRAMS: + marker = request(mode, BUFFER_PROGRAMS[mode]) + cache = base / f"cache_{mode}" + cache.mkdir() + code, out, err = run([fixture, sdk, cache, marker, adapter, mode], expect_skip=True) + require(code == 0, f"fixture mode {mode} exits 0") + for case in BUFFER_FIXTURE_CASES: + require(f"pass: {mode} {case}:" in out, f"{mode}: case {case} held") + require(f"pass: {mode} the manifest names the token views and words" in out, + f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and seven heaptok words") print(f"{ok_lines} assertions held") return @@ -311,6 +484,45 @@ def compile_request(marker): code, out, err, output = compile_request(request("noheap", PROGRAMS["tex2d"], ROOT_NO_HEAP)) require(code != 0 and not output.exists(), "a root without the heap flag does not compile the token program") + # 6. GPU-selected raw buffers. The eligible programs compile and publish seven token words; the module reads the + # token, checks it and reads the buffer from the heap. + for name, words in {**BUFFER_PROGRAMS, **BUFFER_ACCEPTED, **MIXED_PROGRAMS}.items(): + marker = request("b_" + name, words) + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists(), f"{name}: compiles") + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, + text=True).stdout + require("@dx.op.createHandleFromHeap(i32 218" in listing, f"{name}: the buffer comes from createHandleFromHeap") + require("@dx.op.waveIsFirstLane(i32 110)" in listing, f"{name}: the miss is counted by the first lane (op 110)") + require(listing.count("@dx.op.rawBufferLoad.i32(") >= 4, + f"{name}: the module loads the token words, the dimension and the data") + require(", 1448555096" in listing, + f"{name}: the module compares the view token magic") + out_dir = base / f"b_{name}_out" + code, out, err = run([compile_dxil, sdk, base / f"cache_b_{name}", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() + if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset"): + require(code == 0 and text == EXPECTED_BUFFER_MANIFEST, + f"{name}: the manifest names the token views and the seven token words, and no heap buffer view") + else: + require(code == 0 and "udsrc 6 heaptok nullraw\n" in text and "udsrc 4 heaptok null\n" in text and + "ud 7\n" in text, f"{name}: a texture and a buffer publish seven token words") + # Controls: a V# use that is not the byte window of a raw load or a scalar buffer load keeps today's refusal. + for name, (words, text) in BUFFER_CONTROLS.items(): + code, out, err, output = compile_request(request("bc_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"{name}: refused with \"{text}\" and no .cso") + # Mixed: a buffer load that is not eligible does not take the textures off the token route (and the reverse). + for name, (words, text) in MIXED_CONTROLS.items(): + code, out, err, output = compile_request(request("mc_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"mixed {name}: refused with \"{text}\" and no .cso") + for name, (words, text) in BUFFER_ADDRESS_CONTROLS.items(): + code, out, err, output = compile_request(request("ba_" + name, words)) + require(code != 0 and text in err and not output.exists(), f"buffer {name}: refused with \"{text}\" and no .cso") + # Texture-only programs keep their five words (the same program with a buffer has seven). + code, out, err, output = compile_request(request("t_only", PROGRAMS["tex2d"])) + require(code == 0, "control: the texture-only program still compiles") + print(f"{ok_lines} assertions held") diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index ffb9c940a6..7426b070d1 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -174,8 +174,13 @@ def check_manifest_refusal(case, variant, reason): 'a sampler that is not a plain static one') # The translator's heap token texture lines (GPU-selected textures read through view tokens) are named, not bound. for case, line in (('heap token view', 'srv 1 heaptok\n'), ('heap token dimension table', 'srv 1 heaptokdims\n'), - ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token word', 'udsrc 3 heaptok null\n')): + ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token word', 'udsrc 3 heaptok null\n'), + ('heap token raw buffer base', 'udsrc 3 heaptok baseraw\n'), + ('heap token raw buffer null', 'udsrc 3 heaptok nullraw\n')): check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') + # Control: a token word the reader does not know is not taken for one. + check_manifest_refusal('unknown heap token word', original + 'udsrc 3 heaptok bogus\n', + 'an entry value that is not a root constant or a buffer descriptor word') assert original.count('\nud 3\n') == 1, ('entry count mismatch', original) check_manifest_refusal('entry count mismatch', original.replace('\nud 3\n', '\nud 4\n'), 'entry value, input or output count') From 32b9f2672c3c36887e6d187b93c3c27dbbb4d175 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 10:33:06 +0100 Subject: [PATCH 03/19] native: judge the heap raw buffer address shape in the analysis Review fixes for the heap token buffer route. - heap_token_buffer_eligible now checks the address the lowering needs, on the state at the load: heap pointer high word is the constant 0, imm % 32 == 0, proven 32-byte aligned SGPR offset, no offset + imm overflow; on an added address imm == 0 and a masked offset. It also compares the V# words symbol for symbol as heap_token_buffer does. A candidate that fails is dropped (an added address keeps the old program-wide rejection) and keeps today's text. The lowering refusals stay as a safeguard. - When no buffer load is eligible, the textures are judged again on the analysis without the byte window, as before the route knew buffers. - Document the carry assumption of an added address (heap-relative model of the existing heap_offset path, no runtime carry check). - Tests: address-shape controls expect the heap contract text of the dropped load; new controls for overflow, a non-constant high word, an unread candidate next to a texture, and an accepted wide mask. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 10 ++- src/gfx1013_compute_native.cpp | 74 ++++++++++++++----- src/gfx1013_direct_compute.inl | 8 +- tests/native_heap_token_texture_check.py | 37 +++++++--- 4 files changed, 94 insertions(+), 35 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index e0c6ddee5e..5ff2669fad 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -76,8 +76,11 @@ path and refusal text. Like the texture route, this translates only where no hea eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to the same module and manifest (only the revision line changes). - The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap - slot 0, not a slot index) to the four words. It requires an address that is a multiple of 32: `imm % 32 == 0`, an SGPR - offset that is constant or masked with `(mask & 31) == 0`, no overflow; on an added address `imm == 0` and the same mask. + slot 0, not a slot index) to the four words. The analysis requires an address that is a multiple of 32, judged on the + state at the load: the heap pointer's high word is the constant 0, `imm % 32 == 0`, an SGPR offset that is constant or + masked with `(mask & 31) == 0`, and no overflow of offset plus immediate; on an added address `imm == 0` and the same mask. + A candidate without that shape is not eligible and keeps today's path and text (the lowering repeats the checks as a + safeguard). The words of the V# must also be exactly the symbols the lowering compares. - The consumer reads the token at that address: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 0x20`, and uses `ResourceDescriptorHeap[valid ? baseraw + id : nullraw]` as a raw buffer. A miss is counted as for textures. No `heap_buffer_srv` binding is created. @@ -96,6 +99,9 @@ new one compiles it from the same cache folder). ## Runtime assumptions and failure modes +- Carry of an added address: the high word of the `s_add_u32` pair is taken as 0. This relies on the same heap-relative + model as the existing heap_offset path (the model is relative to the heap base, so the high word is the carry of the byte + offset alone, which is 0 for offsets below 2^32; the emitter writes it as 0); no runtime carry check. - A1: a token in the bound view heap's memory names the view the title created for that slot. The runtime (PR 2) builds the raw view per id from the view record, so its byte range is that view's range. - Failure modes, all read the null raw view (zeros) and count a miss, never a wrong-kind view: no token (the title wrote a raw diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index ddbf00d6c0..910c893b38 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1879,6 +1879,25 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector 106) return false; const unsigned immediate = load.b & 0xfffff; + // The address shape the lowering of the load (heap_token_buffer_load site) requires, judged on the state at the load: a + // candidate that does not have it is not eligible, so that it keeps today's path and text. + { + const auto &before = p.before[l]; + const unsigned so = load.b >> 25; + if (so != 125) { + const auto &low = before.at(load.src[0]); + if (low.type != Symbol::Type::table || low.value != compute_resource_heap || + !(before.at(load.src[0] + 1) == Symbol{Symbol::Type::constant, 0}) || immediate % 32 || + so >= smem_sgpr_limit(true)) + return false; + const auto &value = before.at(so); + const bool aligned = (value.type == Symbol::Type::constant && value.value % 32 == 0) || + (value.type == Symbol::Type::masked && (value.value & 31) == 0); + if (!aligned || value.value > UINT_MAX - immediate) return false; + } else if (!heap_offset_address(before, load.src[0]) || immediate || + (before.at(load.src[0]).index_mask & 31) != 0) + return false; + } const auto is_token = [&](const Symbol &s, unsigned word) { return s.type == T::indexed_descriptor && s.value == compute_resource_heap && s.definition == load.pc && s.offset == immediate + 4 * word; @@ -1911,17 +1930,25 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector> 16) & 31) * 4, soffset = i.b >> 24; - if (base + 4 > 106 || !is_token(state[base], 0) || !is_field(state[base + 1], T::zero_stride_word) || - !is_field(state[base + 2], T::byte_count) || !is_field(state[base + 3], T::byte_oob) || - (soffset < 106 && of_load(state[soffset]))) + if (base + 4 > 106 || !is_token(state[base], 0) || (soffset < 106 && of_load(state[soffset]))) return false; + // The words the lowering compares (heap_token_buffer): word 0 and the three fields, symbol for symbol. + constexpr T window_words[] = {T::indexed_descriptor, T::zero_stride_word, T::byte_count, T::byte_oob}; + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = state[base]; + expected.type = window_words[j]; + if (!(state[base + j] == expected)) return false; + } found.push_back({i.pc, load.pc}); } else if (i.enc == Encoding::Smem && i.op >= 8 && i.op <= 12) { const unsigned base = i.src[0], soffset = i.b >> 25; if (base + 4 > 106 || (soffset < 106 && of_load(state[soffset]))) return false; - for (unsigned j = 0; j < 4; ++j) - if (!is_token(state[base + j], j)) return false; + for (unsigned j = 0; j < 4; ++j) { + Symbol expected = state[base]; + expected.offset += 4 * j; + if (!is_token(state[base + j], j) || !(state[base + j] == expected)) return false; + } found.push_back({i.pc, load.pc}); } else if (!(i.enc == Encoding::Sop2 && byte_descriptor_field(i, state, true))) return false; @@ -2127,26 +2154,35 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi } bool compiler_window = heap_window; if (token_candidate || buffer_candidate) { + // Judged on the analysis that tracks the byte window when there is a buffer candidate (buffer_candidate implies + // that no heap contract is set, so heap_window is false here). auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window || buffer_candidate, narrow_wave64, true); - if (heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers)) { - if (!buffer_consumers.empty()) { + const bool routed = heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers); + if (routed && !buffer_consumers.empty()) { + // At least one eligible buffer load: translate on the window analysis. + program = std::move(tokens); + heap_tokens = true; + compiler_window = true; + } else if (!buffer_candidate) { + // Textures only, as before this route knew buffers. + if (routed) { program = std::move(tokens); heap_tokens = true; - compiler_window = true; - } else if (!buffer_candidate || heap_window) { - program = std::move(tokens); + } + } else if (token_candidate) { + // No buffer load is eligible (dropped candidates keep today's path): judge the textures again on the analysis + // without the byte window, exactly as before this route knew buffers. + auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, + true); + std::vector none; + if (heap_token_eligible(textures, false, token_consumers, none)) { + program = std::move(textures); heap_tokens = true; - } else { - // Token textures only: the analysis of the program as before this route knew buffers. - auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, - true); - std::vector none; - if (heap_token_eligible(textures, false, token_consumers, none)) { - program = std::move(textures); - heap_tokens = true; - } } + } else { + // Buffer candidates only and none eligible: no token route, the program stays as parsed first. + token_consumers.clear(); } } Emit emit{{}, program,layout->Desc_1_1}; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 1385cfe0bd..2b5bd9bdae 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -787,8 +787,12 @@ struct DirectCompute { refuse(i.pc, "heap token buffer byte offset has no proven 32-byte aligned range"); address = ir.binary("add", operand32(i, so), to_string(offset)); } else { - // The address formed by s_add_u32: its high word is the carry of that add, which the emitter writes as 0 - // (the heap base is slot 0), and its low word is the byte offset. + // The address formed by s_add_u32. Assumption, no runtime carry check: the model of heap_offset and + // heap_carry is relative to the heap base (slot 0), so the high word is the carry of the byte offset + // alone, which is 0 for offsets below 2^32; the emitter writes it as 0 (see arithmetic()) and the + // existing lshr-5 path of the heap_offset address relies on the same model. The low word is the byte + // offset. The pre-pass (heap_token_buffer_eligible) already judged these shapes; these refusals are + // the safeguard. if (!heap_offset_address(s, i.src[0])) refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); if (offset) refuse(i.pc, "heap token buffer load with an immediate offset on an added address"); diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index 8e5f690966..2f70f7ab50 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -225,7 +225,7 @@ def loop_body(words): "sbuf": [*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, *STORE], } # Eligible variants that must compile: the other dword widths, an immediate offset, and a texture next to a buffer. -BUFFER_ACCEPTED = { +BUFFER_ACCEPTED = { # (mask_wide is added below, after its mask) "x1": buffer_full(BUFFER_LOAD, consumer=LOAD_X1), "x3": buffer_full(BUFFER_LOAD, consumer=LOAD_X3), "immediate": buffer_full(BUFFER_LOAD_IMM), @@ -268,11 +268,12 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, "texture_first": (mixed([], texture_selector=SELECTOR_HEAD, texture_load=[0xf40c0805, 0x20000000]), UNPROVEN), # the buffer load is first: the heap contract text of the load that keeps today's path "buffer_first": (mixed([], buffer_first=True), HEAP_REFUSAL), + # the buffer load is never read: not a consumer, so it is dropped and keeps today's text after the texture + "texture_unread": (mixed([], consume=[]), HEAP_REFUSAL), + "unread_first": (mixed([], consume=[], buffer_first=True), HEAP_REFUSAL), } -BUFFER_UNMASKED = "heap token buffer byte offset has no proven 32-byte aligned range" -BUFFER_IMMEDIATE = "unaligned heap token buffer immediate byte offset" -BUFFER_ADDED_IMMEDIATE = "heap token buffer load with an immediate offset on an added address" +MASK_WIDE = [0x8711ff10, 0xffffffe0] # s_and_b32 s17, s16, 0xffffffe0 (32-byte aligned, but up to 0xffffffe0) LOOP = "heap byte window loaded inside a loop" # V# uses that make the buffer load not eligible: the refusal text is the one these programs get without the buffer route # (checked against the base of this change). Two of them are refused before the heap load is reached. @@ -294,21 +295,33 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, # the immediate offset 4 moves the words off the 32-byte descriptor layout the rewrite recognizes "immediate4": (buffer_full(BUFFER_LOAD_IMM4), HEAP_REFUSAL), } -# Address shapes. Each program is eligible, so it reaches the load and is refused there. +# Address shapes. The analysis judges the address of the load (the state at the load, as the lowering uses it): a load whose +# address has no proven 32-byte aligned range, an immediate that is not a multiple of 32, a high word that is not the +# constant 0, an offset sum that may overflow, or an added address with an immediate or an unmasked offset is not eligible, +# so it keeps today's path and text (the heap contract text). The refusals of the lowering stay as a safeguard and are not +# reachable from a request. BUFFER_ADDRESS_CONTROLS = { # s_load_dwordx4 s[32:35], s[10:11], s17 where s17 is s16: not masked - "unmasked": (buffer_full(BUFFER_LOAD, selector=SELECTOR_HEAD), BUFFER_UNMASKED), + "unmasked": (buffer_full(BUFFER_LOAD, selector=SELECTOR_HEAD), HEAP_REFUSAL), # s_and_b32 s17, s16, 0xfffc: bit 2 to 4 may be set - "misaligned": (buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK]), BUFFER_UNMASKED), + "misaligned": (buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK]), HEAP_REFUSAL), # the scalar buffer load of the unrewritten words with s_load_dwordx4 ... offset:0x4 "immediate4": ([*BASES, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD_IMM4, *WAIT, *SBUFFER_X4, *WAIT, *SBUFFER_VGPR, *LANE, - *STORE], BUFFER_IMMEDIATE), - "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), BUFFER_UNMASKED), - "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), BUFFER_ADDED_IMMEDIATE), - # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load) + *STORE], HEAP_REFUSAL), + # offset:0x20 after a mask that allows 0xffffffe0: the sum may overflow + "overflow": (buffer_full(BUFFER_LOAD_IMM, selector=[*SELECTOR_HEAD, *MASK_WIDE]), HEAP_REFUSAL), + # s_mov_b32 s11, s5 instead of s_mov_b32 s11, 0: the high word of the heap pointer is not the constant 0 + "high_word": ([0xbe880304, 0xbe890380, 0xbe8a0305, 0xbe8b0305, *TABLE_LOADS, *SELECTOR32, *BUFFER_LOAD, *WAIT, + *REWRITE, *LANE, *WAIT, *LOAD_X4, *STORE], HEAP_REFUSAL), + "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), HEAP_REFUSAL), + "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), HEAP_REFUSAL), + # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load): eligible, + # refused by the lowering with its own text "loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *loop_body([*BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, *LOAD_X4]), *STORE], LOOP), } +# The same address with a proven range compiles (controls for the refusals above). +BUFFER_ACCEPTED["mask_wide"] = buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK_WIDE]) EXPECTED_MANIFEST = """x2w-manifest 2 stage cs @@ -502,7 +515,7 @@ def compile_request(marker): code, out, err = run([compile_dxil, sdk, base / f"cache_b_{name}", "gfx1013-direct-cs@0", "--requests", marker.parent, out_dir]) text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() - if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset"): + if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset", "mask_wide"): require(code == 0 and text == EXPECTED_BUFFER_MANIFEST, f"{name}: the manifest names the token views and the seven token words, and no heap buffer view") else: From 4a03fafdfd8b530752cd94e1751767e03be964f6 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 13:41:40 +0100 Subject: [PATCH 04/19] native: drop heap buffer candidates the lowering would refuse (loop, word budget) Review fixes, round 2. - A byte window load inside a loop is dropped by the analysis with the same query the lowering uses, instead of failing the whole program (textures included) at lowering. - When the seven token words do not fit the 32-word entry layout next to the descriptor strides and root constants (the strides are known only while lowering), the program is translated again with the buffer route off, so the buffer loads keep today's path and text. - Document that words 2 and 3 of the title's V# are not read and that PR 2 must make the raw view's range equal it (A1). - Tests: loop and texture + loop controls now expect today's text; 25 strides compile next to seven token words, 26 are refused with today's text. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 16 ++++++-- src/gfx1013_compute_native.cpp | 26 +++++++++--- src/gfx1013_direct_compute.inl | 3 ++ tests/native_heap_token_texture_check.py | 41 +++++++++++++++++-- 4 files changed, 73 insertions(+), 13 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index 5ff2669fad..7d7e14c50b 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -75,6 +75,9 @@ path and refusal text. Like the texture route, this translates only where no hea - The analysis of a program with a candidate runs with the byte-window tracking (`heap_window`). If no candidate is eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to the same module and manifest (only the revision line changes). +- The seven token words and the descriptor strides of the program must fit the 32-word entry layout. The strides are known + only while lowering, so a program that does not fit is translated again with the buffer route off: its buffer loads keep + today's path and text. - The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap slot 0, not a slot index) to the four words. The analysis requires an address that is a multiple of 32, judged on the state at the load: the heap pointer's high word is the constant 0, `imm % 32 == 0`, an SGPR offset that is constant or @@ -103,7 +106,9 @@ new one compiles it from the same cache folder). model as the existing heap_offset path (the model is relative to the heap base, so the high word is the carry of the byte offset alone, which is 0 for offsets below 2^32; the emitter writes it as 0); no runtime carry check. - A1: a token in the bound view heap's memory names the view the title created for that slot. The runtime (PR 2) builds the - raw view per id from the view record, so its byte range is that view's range. + raw view per id from the view record, so its byte range is that view's range. Words 2 (num_records) and 3 of the title's + own V# are not read: the raw view's range applies, and PR 2 must make it equal the range the title's V# describes. + Nothing in the translator or the shader checks that. - Failure modes, all read the null raw view (zeros) and count a miss, never a wrong-kind view: no token (the title wrote a raw V# itself, or the slot was never written because the token write is gated on a title-backed writable view), a wrong magic, `id >= count`, a content token (word 1 carries flags), a texture id (dimension code not 0x20). @@ -120,9 +125,12 @@ new one compiles it from the same cache folder). - `native_heap_token_texture_controls`: eligible programs (SGPR offset, added address, scalar buffer load, other widths, an immediate offset, a texture next to a buffer) and the published manifest; controls that keep today's text (plain V# without the rewrite, IDXEN, format, `tbuffer`, store, a numeric read of word 2, a copy of a rewritten word, a partial V#, a join, an - immediate offset that breaks the descriptor layout), the new address texts, a window load in a loop - (`heap byte window loaded inside a loop`), and the mixed cases (a texture on the token route next to a buffer load that - keeps today's refusal). + immediate offset that breaks the descriptor layout), address shapes without a proven range (overflow, a high word that is + not the constant 0, an unmasked or misaligned offset, an immediate on an added address; all dropped, today's text), a byte + window load in a loop (dropped by the analysis: the lowering would refuse it with `heap byte window loaded inside a loop` + and take the whole program down), the word budget (25 descriptor strides fit next to seven token words, 26 do not and the + buffer route is dropped), and the mixed cases (a texture on the token route next to a buffer load, an unread load or a + loop that keeps today's refusal). - `native_heap_token_texture_warp` and `_hardware`: modes `rawbuf`, `rawbuf_waterfall` and `sbuf` with two raw views (64 and 128 dwords) and a texture id in the dimension table: valid tokens read the view (lanes past the first view get 0), every other case gives zeros and one miss per wave. Results are compared as dwords. diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 910c893b38..8ac4b1b25e 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1888,7 +1888,7 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector= smem_sgpr_limit(true)) + so >= smem_sgpr_limit(true)) // as the lowering: smem_sgpr_limit(!graphics_input), true for compute return false; const auto &value = before.at(so); const bool aligned = (value.type == Symbol::Type::constant && value.value % 32 == 0) || @@ -1911,6 +1911,12 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector found; for (size_t n = 0; n < p.code.size(); ++n) { @@ -1930,7 +1936,7 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector> 16) & 31) * 4, soffset = i.b >> 24; - if (base + 4 > 106 || !is_token(state[base], 0) || (soffset < 106 && of_load(state[soffset]))) + if (in_loop || base + 4 > 106 || !is_token(state[base], 0) || (soffset < 106 && of_load(state[soffset]))) return false; // The words the lowering compares (heap_token_buffer): word 0 and the three fields, symbol for symbol. constexpr T window_words[] = {T::indexed_descriptor, T::zero_stride_word, T::byte_count, T::byte_oob}; @@ -2001,7 +2007,7 @@ static bool heap_token_eligible(const Program &p, bool buffers, std::vector> 16) != 0xd580 || (word(request.code, 12) >> 16) != 0xd580 || (word(request.code, 24) >> 16) != 0xd580 || (word(request.code, 36) >> 16) != 0xbfa0)) refuse(entry, "unrecognized compute header"); @@ -2147,7 +2153,7 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi const auto &base = program.before[n].at(i.src[0]); if (i.op == 3 && (i.b >> 25) != 125) token_candidate |= base.type == Symbol::Type::table && base.value == compute_resource_heap; - else if (i.op == 2 && heap_view == HeapViewContract::none) + else if (i.op == 2 && heap_view == HeapViewContract::none && buffers_allowed) buffer_candidate |= (base.type == Symbol::Type::table && base.value == compute_resource_heap && (i.b >> 25) != 125) || ((i.b >> 25) == 125 && base.type == Symbol::Type::heap_offset); @@ -2237,7 +2243,17 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi compiler.virtual_waves = static_cast(threads / 64); } } - auto translated = compiler.lower(entry,user,rsrc2,x,y,z); + NativeComputeShader translated; + try { + translated = compiler.lower(entry,user,rsrc2,x,y,z); + } catch (const UnsupportedComputeShader &error) { + // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and root + // constants (the strides are known only while lowering): drop the buffer route and translate again, so the + // buffer loads keep today's path and text. + if (!buffer_consumers.empty() && std::string_view(error.what()).find("heap token words exceed") != std::string_view::npos) + return translate_program(request, entry, direct_dxil, stage, heap_view, false); + throw; + } for (auto &binding : translated.bindings) { if (stage) apply_reflected_table_use(binding, *stage); if (!request.root.empty()) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 2b5bd9bdae..cbbd31ef95 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1162,6 +1162,9 @@ struct DirectCompute { ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; return slot; } + // Words 2 (num_records) and 3 of the title's own V# are not read: the view the token names gives the range, and the shader + // reads that raw view as the byte window (assumption A1). The runtime change (PR 2) must make the raw view's byte range equal + // the range the title's V# describes; nothing here checks it. // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token names a // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a word of // the heap load (the s_load_dwordx4 left the token's byte address in all four words; the byte-window rewrite only diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index 2f70f7ab50..1eed573ff1 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -274,6 +274,29 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, } MASK_WIDE = [0x8711ff10, 0xffffffe0] # s_and_b32 s17, s16, 0xffffffe0 (32-byte aligned, but up to 0xffffffe0) +# More than 32 entry words: the token words (7 with a buffer) and the descriptor strides of table SRVs read as s_bfe_u32 +# stride fields. 25 strides fit next to seven words, 26 do not: the buffer route is dropped and the program keeps today's text. +ROOT_STRIDES = ("RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0, numDescriptors = 32), UAV(u0))") +STRIDE_TABLE_LOADS = [ + 0xf4080304, 0xfa000000, # s_load_dwordx4 s[12:15], s[8:9], 0x0 (t0: the selector) + 0xf4080604, 0xfa000400, # s_load_dwordx4 s[24:27], s[8:9], 0x400 (u0 follows the 32 SRVs) +] + + +def stride_reads(count): + words = [] + for k in range(1, count + 1): + words += [0xf4080c04, 0xfa000000 | (32 * k), # s_load_dwordx4 s[48:51], s[8:9], 32 * k + 0x93b4ff31, 0x000e0010, # s_bfe_u32 s52, s49, 0xe0010 (the stride of table slot k) + 0x85358081] # s_cselect_b32 s53, 1, 0 (reads SCC: the stride is the runtime's) + return words + + +def stride_program(count): + return [*BASES, *STRIDE_TABLE_LOADS, *stride_reads(count), *SELECTOR32, *BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, + *LOAD_X4, *STORE] + + LOOP = "heap byte window loaded inside a loop" # V# uses that make the buffer load not eligible: the refusal text is the one these programs get without the buffer route # (checked against the base of this change). Two of them are refused before the heap load is reached. @@ -315,10 +338,14 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, *REWRITE, *LANE, *WAIT, *LOAD_X4, *STORE], HEAP_REFUSAL), "added_unmasked": (buffer_full(BUFFER_LOAD_ADDED, pre=ADD_HEAP_UNMASKED), HEAP_REFUSAL), "added_immediate": (buffer_full(BUFFER_LOAD_ADDED_IMM, pre=ADD_HEAP), HEAP_REFUSAL), - # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load): eligible, - # refused by the lowering with its own text + # the load and its rewrite inside a one-block loop (s_cmp_eq_u32 s16, 0 ; s_cbranch_scc0 back to the load): the lowering + # would refuse the byte window ("heap byte window loaded inside a loop"), so the analysis drops the candidate "loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *loop_body([*BUFFER_LOAD, *WAIT, *REWRITE, *LANE, *WAIT, *LOAD_X4]), - *STORE], LOOP), + *STORE], HEAP_REFUSAL), + # a texture on the token route next to the same loop: the texture is not taken down with the buffer + "mixed_loop": ([*BASES, *TABLE_LOADS, *SELECTOR32, *TOKEN_LOAD, *SAMPLER, *COORDS_2D, + *loop_body([*MIXED_BUFFER_LOAD, *WAIT, *MIXED_REWRITE, *MIXED_CONSUME]), *WAIT, *SAMPLE_2D, *STORE], + HEAP_REFUSAL), } # The same address with a proven range compiles (controls for the refusals above). BUFFER_ACCEPTED["mask_wide"] = buffer_full(BUFFER_LOAD, selector=[*SELECTOR_HEAD, *MASK_WIDE]) @@ -410,7 +437,7 @@ def request(name, words, root_text=ROOT): counter += 1 folder = base / f"req_{counter}_{name}" folder.mkdir() - user = 6 if root_text == ROOT else 5 # four reserved SGPRs, the table, and the resource heap + user = 6 if "RootFlags" in root_text else 5 # four reserved SGPRs, the table, and the resource heap sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, user << 1) return write_request(folder, words, root(root_text), sa) @@ -532,6 +559,12 @@ def compile_request(marker): for name, (words, text) in BUFFER_ADDRESS_CONTROLS.items(): code, out, err, output = compile_request(request("ba_" + name, words)) require(code != 0 and text in err and not output.exists(), f"buffer {name}: refused with \"{text}\" and no .cso") + # The word budget: 25 strides + 7 token words fit; 26 do not, and the buffer route is dropped (today's text). + code, out, err, output = compile_request(request("strides25", stride_program(25), ROOT_STRIDES)) + require(code == 0 and output.exists(), "25 descriptor strides next to the seven token words compile") + code, out, err, output = compile_request(request("strides26", stride_program(26), ROOT_STRIDES)) + require(code != 0 and HEAP_REFUSAL in err and not output.exists(), + f"26 descriptor strides: the buffer route is dropped, refused with \"{HEAP_REFUSAL}\" and no .cso") # Texture-only programs keep their five words (the same program with a buffer has seven). code, out, err, output = compile_request(request("t_only", PROGRAMS["tex2d"])) require(code == 0, "control: the texture-only program still compiles") From 8353a6fe61e656ba82de51fff05f66d379442ca1 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 13:52:49 +0100 Subject: [PATCH 05/19] native: signal the heap token word budget by exception type, tidy comments - The budget retry in translate_program catches HeapTokenWordBudget (thrown by prepare_heap_tokens with the same text) instead of matching the message. - Exact root signature match for the user SGPR count in the test, comments wrapped to 120 columns, doc line for the seven-word form. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 6 +- src/gfx1013_compute_native.cpp | 67 +++++++++++++------ src/gfx1013_compute_native.h | 3 +- src/gfx1013_direct_compute.inl | 38 +++++++---- src/native_compute_pipeline.h | 3 +- src/startup_stubs/d3d12_compute_dispatch.inl | 3 +- tests/native_heap_token_texture.cpp | 3 +- tests/native_heap_token_texture_check.py | 2 +- 8 files changed, 84 insertions(+), 41 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index 7d7e14c50b..e1631a4754 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -27,12 +27,14 @@ those two words at the guest byte address and maps the id to a host descriptor. - Per image instruction of dimension `d`: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 1 + d`; the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null]` (kind 1, 2 or 7, `nonuniform` false: every lane loads the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`). -- Five more `b0` words follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views +- Five more `b0` words (seven with a raw buffer, see below) follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views (root parameter `compute_heap_token`): the token memory (`heap_token_srv`, a raw SRV), the dimension table (`heap_token_dims_srv`, a raw SRV with one uint per view id: 0 none, else 1 + the image dimension) and the miss counter (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module names the registers while it is lowered. -- Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, `udsrc K heaptok base1d|base2d|base2da|count|null`. +- Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, + `udsrc K heaptok base1d|base2d|base2da|count|null`, and in the seven-word form (raw buffers, below) also + `udsrc K heaptok baseraw|nullraw`. `native_compute_output_revision` is 3 (see Revision below). The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. ## Tests diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 8ac4b1b25e..2d5d159799 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1747,6 +1747,13 @@ struct HeapTokenLoad { struct HeapTokenBufferLoad { unsigned pc, load; }; +// Thrown when the token words of a buffer load do not fit the 32-word entry layout (the descriptor strides are known +// only +// while lowering); translate_program then translates the program again without the buffer route. +class HeapTokenWordBudget : public UnsupportedComputeShader { + public: + using UnsupportedComputeShader::UnsupportedComputeShader; +}; // SGPR ranges {first, count} an instruction may read, widened where the operand width is not known exactly. Anything // that cannot be listed (indexed SGPR moves) reads everything. static std::vector> conservative_sgpr_reads(const Inst &i) { @@ -1805,8 +1812,10 @@ static std::vector instructions_after(const Program &p, size_t l) { return after; } // The texture rules of the heap token route. `loads` are the reached s_load_dwordx8 from the resource heap with an SGPR -// offset (token loads). The program is eligible when every later read of the eight words (until they are overwritten) is -// the T# of an image_load, image_load_mip, image_sample_l, image_sample_lz, image_gather4_lz (2D) or image_get_resinfo of +// offset (token loads). The program is eligible when every later read of the eight words (until they are overwritten) +// is +// the T# of an image_load, image_load_mip, image_sample_l, image_sample_lz, image_gather4_lz (2D) or +// image_get_resinfo of // dimension 1D, 2D or 2D array, without D16; a copy, a numeric read, a store, a comparison, cube or 3D use, a // partial use or a read of the words by an instruction this function cannot place makes it not eligible. `p` is // the analysis with heap_tokens set. @@ -1868,10 +1877,13 @@ static bool heap_token_texture_eligible(const Program &p, const std::vector &consumers) { @@ -1879,7 +1891,8 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector 106) return false; const unsigned immediate = load.b & 0xfffff; - // The address shape the lowering of the load (heap_token_buffer_load site) requires, judged on the state at the load: a + // The address shape the lowering of the load (heap_token_buffer_load site) requires, judged on the state at the + // load: a // candidate that does not have it is not eligible, so that it keeps today's path and text. { const auto &before = p.before[l]; @@ -1911,8 +1924,10 @@ static bool heap_token_buffer_eligible(const Program &p, size_t l, std::vector> 25) == 125 && base.type == Symbol::Type::heap_offset) { - // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own contract. + // A descriptor address formed by s_add_u32 (heap_offset_add) is another way into the heap, with its own + // contract. if (!buffers || !heap_offset_address(p.before[n], i.src[0])) return false; candidates.push_back(n); } else if ((i.b >> 25) != 125 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { @@ -2139,9 +2157,12 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64); // A GPU-selected texture loaded with s_load_dwordx8 from the resource heap: when every such load is only used as the // T# of a supported image instruction, translate the program on the analysis that keeps the byte address. - // A GPU-selected raw buffer (s_load_dwordx4 from the resource heap, with an SGPR offset or through an address formed by - // s_add_u32) takes the same route when no heap view contract covers it: its V# is the byte window of a view token. It is - // judged on an analysis that tracks the byte window rewrite (heap_window); a program with no eligible buffer load is + // A GPU-selected raw buffer (s_load_dwordx4 from the resource heap, with an SGPR offset or through an address + // formed by + // s_add_u32) takes the same route when no heap view contract covers it: its V# is the byte window of a view + // token. It is + // judged on an analysis that tracks the byte window rewrite (heap_window); a program with no eligible buffer load + // is // analysed again exactly as before. std::vector token_consumers; std::vector buffer_consumers; @@ -2162,8 +2183,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi if (token_candidate || buffer_candidate) { // Judged on the analysis that tracks the byte window when there is a buffer candidate (buffer_candidate implies // that no heap contract is set, so heap_window is false here). - auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window || buffer_candidate, - narrow_wave64, true); + auto tokens = parse(request.code, entry, initial, direct_dxil, false, wave64, false, + heap_window || buffer_candidate, narrow_wave64, true); const bool routed = heap_token_eligible(tokens, buffer_candidate, token_consumers, buffer_consumers); if (routed && !buffer_consumers.empty()) { // At least one eligible buffer load: translate on the window analysis. @@ -2177,10 +2198,11 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi heap_tokens = true; } } else if (token_candidate) { - // No buffer load is eligible (dropped candidates keep today's path): judge the textures again on the analysis + // No buffer load is eligible (dropped candidates keep today's path): judge the textures again on the + // analysis // without the byte window, exactly as before this route knew buffers. - auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64, - true); + auto textures = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, + narrow_wave64, true); std::vector none; if (heap_token_eligible(textures, false, token_consumers, none)) { program = std::move(textures); @@ -2246,11 +2268,12 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi NativeComputeShader translated; try { translated = compiler.lower(entry,user,rsrc2,x,y,z); - } catch (const UnsupportedComputeShader &error) { - // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and root + } catch (const HeapTokenWordBudget &) { + // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and + // root // constants (the strides are known only while lowering): drop the buffer route and translate again, so the // buffer loads keep today's path and text. - if (!buffer_consumers.empty() && std::string_view(error.what()).find("heap token words exceed") != std::string_view::npos) + if (!buffer_consumers.empty()) return translate_program(request, entry, direct_dxil, stage, heap_view, false); throw; } diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index c86f6ec4bc..5920e7471d 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -51,7 +51,8 @@ enum class ComputeViewKind { // A raw buffer bound as a root UAV. The guest address is the root pointer plus a VGPR offset. root_buffer_uav, // Runtime-provided bindings of GPU-selected heap textures (view tokens). heap_token_srv: raw view over the title view-heap - // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, 0x20 a raw buffer view, else 1 + image + // memory (32-byte tokens); heap_token_dims_srv: one uint per view id (0 none, 0x20 a raw buffer view, else 1 + + // image // dimension; the runtime that fills the table names the raw buffer views); the miss UAV // is one raw dword counting the waves that read the null slot. heap_token_srv, diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index cbbd31ef95..154f0b124e 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -411,7 +411,8 @@ struct DirectCompute { // picks the path: typed_buffer_srv is typed, every other kind is raw. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); - // A raw buffer that passed the pre-pass of the token route: the contract gate does not apply, the token is checked + // A raw buffer that passed the pre-pass of the token route: the contract gate does not apply, the token is + // checked // on every execution instead (heap_token_buffer). if (!pixel_stage && symbol.type == Symbol::Type::indexed_descriptor && symbol.value == compute_resource_heap && heap_token_buffer_load(symbol.definition)) @@ -767,7 +768,8 @@ struct DirectCompute { return; } if (!pixel_stage && i.op == 2 && heap_token_buffer_load(i.pc)) { - // The V# of a GPU-selected raw buffer: the view token at the guest byte address, kept in all four words (see + // The V# of a GPU-selected raw buffer: the view token at the guest byte address, kept in all four + // words (see // heap_token_buffer). A token is 32 bytes of title heap memory, so the address is a multiple of 32. The // address is the byte offset from heap slot 0, not the slot index. const Word offset = i.b & 0xfffff; @@ -788,9 +790,11 @@ struct DirectCompute { address = ir.binary("add", operand32(i, so), to_string(offset)); } else { // The address formed by s_add_u32. Assumption, no runtime carry check: the model of heap_offset and - // heap_carry is relative to the heap base (slot 0), so the high word is the carry of the byte offset + // heap_carry is relative to the heap base (slot 0), so the high word is the carry of the byte + // offset // alone, which is 0 for offsets below 2^32; the emitter writes it as 0 (see arithmetic()) and the - // existing lshr-5 path of the heap_offset address relies on the same model. The low word is the byte + // existing lshr-5 path of the heap_offset address relies on the same model. The low word is the + // byte // offset. The pre-pass (heap_token_buffer_eligible) already judged these shapes; these refusals are // the safeguard. if (!heap_offset_address(s, i.src[0])) @@ -1124,7 +1128,8 @@ struct DirectCompute { return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); } // The heap slot a view token names. The token is read at the byte address held by SGPR `base` (every lane loads the - // same words, so the slot is dynamically uniform): the slot is first + id when the magic and the id range hold and the + // same words, so the slot is dynamically uniform): the slot is first + id when the magic and the id range hold + // and the // dimension table records `recorded` for the id (texture: 1 + the SQ dimension code; raw buffer: 0x20), and `null` // otherwise, in which case the first lane of the wave counts one miss. string heap_token_slot(unsigned base, unsigned recorded_code, const string &first, const string &null) { @@ -1162,11 +1167,15 @@ struct DirectCompute { ir.body << " br label %tokenMissEnd" << tag << "\ntokenMissEnd" << tag << ":\n"; return slot; } - // Words 2 (num_records) and 3 of the title's own V# are not read: the view the token names gives the range, and the shader - // reads that raw view as the byte window (assumption A1). The runtime change (PR 2) must make the raw view's byte range equal + // Words 2 (num_records) and 3 of the title's own V# are not read: the view the token names gives the range, and + // the shader + // reads that raw view as the byte window (assumption A1). The runtime change (PR 2) must make the raw view's byte + // range equal // the range the title's V# describes; nothing here checks it. - // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token names a - // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a word of + // A GPU-selected raw buffer read through its view token: ResourceDescriptorHeap[baseraw + id] when the token + // names a + // raw buffer view (dimension table entry 0x20), else the null raw view (reads zero) and a miss. `symbol` is a + // word of // the heap load (the s_load_dwordx4 left the token's byte address in all four words; the byte-window rewrite only // changes what the analysis knows about words 1 to 3). string heap_token_buffer(const Inst &i, const State &s, unsigned base, ComputeViewKind kind) { @@ -1183,7 +1192,8 @@ struct DirectCompute { refuse(i.pc, "heap token raw buffer descriptor is not a four-word heap load"); if (symbol.offset % 32 || symbol.type != Symbol::Type::indexed_descriptor) refuse(i.pc, "unaligned heap descriptor"); - // The same precaution as for a heap descriptor without tokens: the words are compared by the pc of their heap load, + // The same precaution as for a heap descriptor without tokens: the words are compared by the pc of their heap + // load, // which a loop around that load executes again for another selection. if (window) for (const auto &inst : analysis.program.code) @@ -1209,8 +1219,12 @@ struct DirectCompute { auto &r = analysis.result; unsigned words = token_word_count() + static_cast(descriptor_strides.size()); for (const auto &block : r.constants) words += block.count; - if (words > 32) - refuse(analysis.program.code.front().pc, "heap token words exceed the 32-word compute entry layout"); + if (words > 32) { + std::ostringstream text; + text << "native compute +0x" << std::hex << analysis.program.code.front().pc + << ": heap token words exceed the 32-word compute entry layout"; + throw HeapTokenWordBudget(text.str()); + } r.heap_token_word_count = token_word_count(); token_srv = analysis.srv++; token_dims_srv = analysis.srv++; diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index 1041af8c1e..a0cdbd8e49 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,7 +17,8 @@ struct NativeComputePipeline { unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; - unsigned token_words = 0; // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) + // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) + unsigned token_words = 0; unsigned instructions = 0; bool cache_hit = false, frontend_cache_hit = false; bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 5f17e02623..b23fd8c252 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -348,7 +348,8 @@ const char* load_compute_translation(ComputeTranslation& tr) }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; - // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this runtime + // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this + // runtime // yet. The reader knows the seven word names (baseraw and nullraw belong to raw buffers); every such line is // refused here until a runtime fills the views and words. const auto token_word = [&] { diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index 807415b629..bfca80bbe6 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -19,7 +19,8 @@ // another dimension, a content token (bit 31), id 0, an empty token. A valid token gives the texel of its view and no // miss; every other case gives the null texel and one miss per wave (the dispatch is three groups of one wave). // The raw modes bind baseraw and nullraw too. The host heap has raw views at baseraw + id: id 1 over a buffer of 64 -// dwords (value 0xA0000000 + index), id 2 over 128 dwords (0xB0000000 + index); id 0 and id 3 are null raw views, and the +// dwords (value 0xA0000000 + index), id 2 over 128 dwords (0xB0000000 + index); id 0 and id 3 are null raw views, and +// the // dimension table names id 3 a 2D texture. Case 8 is a valid token for id 2. Lanes 16 to 31 read past the 64 dwords of // id 1 and get 0. Every other case gives zeros and one miss per wave. // Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index 1eed573ff1..911861d7c0 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -437,7 +437,7 @@ def request(name, words, root_text=ROOT): counter += 1 folder = base / f"req_{counter}_{name}" folder.mkdir() - user = 6 if "RootFlags" in root_text else 5 # four reserved SGPRs, the table, and the resource heap + user = 6 if root_text in (ROOT, ROOT_STRIDES) else 5 # four reserved SGPRs, the table, and the resource heap sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, user << 1) return write_request(folder, words, root(root_text), sa) From a1c1487aee8fe9f7b58b405d825b6bb55677dd27 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 13:53:26 +0100 Subject: [PATCH 06/19] native: rejoin a wrapped comment on the heap token budget retry Co-Authored-By: Claude Opus 5.5 --- src/gfx1013_compute_native.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 2d5d159799..e6e69a81e3 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -2270,9 +2270,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi translated = compiler.lower(entry,user,rsrc2,x,y,z); } catch (const HeapTokenWordBudget &) { // The token words of a buffer load do not fit the 32-word entry layout next to the descriptor strides and - // root - // constants (the strides are known only while lowering): drop the buffer route and translate again, so the - // buffer loads keep today's path and text. + // root constants (the strides are known only while lowering): drop the buffer route and translate again, + // so the buffer loads keep today's path and text. if (!buffer_consumers.empty()) return translate_program(request, entry, direct_dxil, stage, heap_view, false); throw; From 9917aa9cf1f671711f3a484e3fa35a91b3c0f9e0 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 14:07:33 +0100 Subject: [PATCH 07/19] native: address review of heap token textures (EXEC miss count, native-only refusal, SGPR reads) - Count a token miss only when the wave has an active guest lane (ballot of EXEC), not for a wave that reaches the instruction with EXEC = 0. The hardware fixture gains two modes: EXEC limited to the upper 16 lanes (lane 0 inactive) and EXEC = 0. - The native-only route refuses a program with token words with the manifest reader's text ("heap token textures are not bound yet") instead of "view kind N is not bound". Covered by startup_compute_dispatch_native. - conservative_sgpr_reads: encodings without a case now read every SGPR (control flow, LDS, export and interpolation are listed as reading none), and the v_cndmask_b32 lane mask counts as a pair. Control in native_heap_token_texture_controls (mask_pair vs. a mask clear of the T#). - Say why native_compute_output_revision is 2 (header and doc). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 9 +++-- src/gfx1013_compute_native.cpp | 12 ++++++- src/gfx1013_direct_compute.inl | 7 ++-- src/native_compute_output.h | 4 +++ src/startup_stubs/d3d12_compute_dispatch.inl | 3 ++ tests/native_heap_token_texture.cpp | 20 ++++++++--- tests/native_heap_token_texture_check.py | 19 ++++++++-- .../startup_compute_dispatch_native_check.py | 36 +++++++++++++++++++ 8 files changed, 97 insertions(+), 13 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index e554728108..eb9e89c713 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -26,14 +26,19 @@ those two words at the guest byte address and maps the id to a host descriptor. vouch for the view kind of a GPU-selected slot, and this route checks it on every execution. - Per image instruction of dimension `d`: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 1 + d`; the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null]` (kind 1, 2 or 7, `nonuniform` false: every lane loads - the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`). + the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`), but only when the wave has an + active guest lane (`waveActiveBallot` of EXEC is not zero); a wave that reaches the instruction with EXEC = 0 counts nothing. - Five more `b0` words follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views (root parameter `compute_heap_token`): the token memory (`heap_token_srv`, a raw SRV), the dimension table (`heap_token_dims_srv`, a raw SRV with one uint per view id: 0 none, else 1 + the image dimension) and the miss counter (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module names the registers while it is lowered. - Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, `udsrc K heaptok base1d|base2d|base2da|count|null`. - `native_compute_output_revision` is 2. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. + `native_compute_output_revision` is 2: a request with such a load was refused before and is published now, so the + same request changed meaning. Every published manifest of revision 1 then reads as "another compiler revision; rebuild + it", also those without a token load, which differ only in the `native` marker line; they are rebuilt once. The native-only + route (no manifest reader) refuses a program with token words with the same text as the manifest reader, + `heap token textures are not bound yet`. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. ## Tests diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index a3732e5b14..ac8d936073 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1743,7 +1743,7 @@ struct HeapTokenLoad { unsigned pc, dim; }; // SGPR ranges {first, count} an instruction may read, widened where the operand width is not known exactly. Anything -// that cannot be listed (indexed SGPR moves) reads everything. +// that cannot be listed (an encoding without a case here, indexed SGPR moves) reads everything. static std::vector> conservative_sgpr_reads(const Inst &i) { std::vector> out; auto add = [&](unsigned first, unsigned count) { @@ -1769,9 +1769,19 @@ static std::vector> conservative_sgpr_reads(const case Encoding::Image: add(((i.b >> 21) & 31) * 4, 4); break; + case Encoding::Sopp: case Encoding::Lds: case Encoding::Export: case Encoding::Interp: + // Control flow, local data share, export and interpolation read no SGPR below 106 (M0 and EXEC are above it). + break; default: + // An encoding this function does not list (the graphics fetch and fixed-function pseudo encodings) may read + // any SGPR: the program is then not eligible when a token word is live. + out.emplace_back(0, 106); break; } + // The lane mask of v_cndmask_b32 (VOP3 src2) is one SGPR in wave32 and a pair in wave64, and the width is not known + // here: count the pair. + if (i.name == "v_cndmask_b32" && (i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3 || i.enc == Encoding::Mix)) + add(i.src[2], 2); if (i.name.find("movrel") != Name::npos) out.emplace_back(0, 106); return out; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index c3c31b8935..f8bd66f01c 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1082,10 +1082,13 @@ struct DirectCompute { valid = ir.value("and i1 " + valid + ", " + cmp("eq", recorded, to_string(1 + dim))); const auto &first = heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2]; const auto slot = select(valid, ir.binary("add", first, id), heap_token_values[4]); - // One count per wave and execution that reads the null slot. + // One count per wave and execution that reads the null slot, and only when a guest lane is active (EXEC): a + // wave that reaches the instruction with no active lane reads nothing. The first hardware lane counts, active or not. ir.uses_wave = true; const auto first_lane = ir.invoke("i1", "waveIsFirstLane", 110, {}, "nounwind"); - const auto missed = ir.value("and i1 " + ir.value("xor i1 " + valid + ", true") + ", " + first_lane); + const auto any_active = cmp("ne", ballot(active()), "0"); + const auto missed = ir.value("and i1 " + ir.value("and i1 " + ir.value("xor i1 " + valid + ", true") + ", " + + first_lane) + ", " + any_active); const auto tag = to_string(label_number++); ir.body << " br i1 " << missed << ", label %tokenMiss" << tag << ", label %tokenMissEnd" << tag << "\ntokenMiss" << tag << ":\n"; diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 186e4261d8..bcc69392ee 100644 --- a/src/native_compute_output.h +++ b/src/native_compute_output.h @@ -5,6 +5,10 @@ namespace x2w { // Bump whenever a native translation of an unchanged request can change meaning. +// 2: a request that loads a texture from the directly indexed resource heap at a GPU-selected offset was refused before +// and is published now (heap token lines), so the same request changed meaning. The cost is that every manifest of +// revision 1 reads as "another compiler revision; rebuild it" although the ones without such a load differ only in +// this marker line; they are rebuilt once. constexpr unsigned native_compute_output_revision = 2; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index cfa61a3d5f..b5ba2c1ae8 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -513,6 +513,9 @@ bool translate_compute_natively(ComputeTranslation& tr) } if (result == x2w::ComputePackResult::miss) program = x2w::translate_compute(*frozen, 0, true); + // The same refusal text as the manifest reader gives for the token lines, so triage reads one reason on both routes. + if (program.heap_token_words) + throw std::runtime_error("heap token textures are not bound yet"); for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index b54bb4089e..46c36aebba 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -45,9 +45,14 @@ struct Mode { Dim dim; unsigned valid_id, mismatch_id; Texel expected; + unsigned first_active = 0; // lanes below this are inactive in EXEC; `lanes` means no lane is active }; bool make_mode(const std::wstring &name, Mode &mode) { - if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; + // tex2d_exechalf: the guest program sets EXEC to the upper 16 lanes (the first lane is inactive). + // tex2d_execnone: it sets EXEC to 0 and still runs the token load and the sample. + if (name == L"tex2d_exechalf") mode = {Dim::d2, 1, 2, texel_2d(1, 2), 16}; + else if (name == L"tex2d_execnone") mode = {Dim::d2, 1, 2, texel_2d(1, 2), lanes}; + else if (name == L"tex2d") mode = {Dim::d2, 1, 2, texel_2d(1, 2)}; else if (name == L"tex1d") mode = {Dim::d1, 3, 1, texel_1d(1)}; else if (name == L"tex2da") mode = {Dim::d2a, 2, 1, texel_2da(1, 2, 1)}; else return false; @@ -397,8 +402,12 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file std::vector out; std::uint32_t missed = 0; dispatch(c * 32, out, missed); - const Texel expected = c == 0 ? mode.expected : Texel{0, 0, 0, 0}; + Texel sentinel_texel; + std::memcpy(sentinel_texel.data(), std::vector(4, sentinel).data(), sizeof sentinel_texel); for (unsigned lane = 0; lane < lanes; ++lane) { + // An inactive lane does not store: its output keeps the sentinel the dispatch started with. + const Texel expected = lane < mode.first_active ? sentinel_texel + : c == 0 ? mode.expected : Texel{0, 0, 0, 0}; Texel got; std::memcpy(got.data(), &out[lane * 4], sizeof got); if (!same_bits(got, expected)) { @@ -408,10 +417,11 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file return 1; } } - const std::uint32_t expected_misses = c == 0 ? 0 : groups; + // One per wave with an active lane; a wave with EXEC = 0 counts nothing. + const std::uint32_t expected_misses = c == 0 || mode.first_active >= lanes ? 0 : groups; if (missed != expected_misses) { - std::printf("FAIL: %s %s: %u misses, expected %u (one per wave)\n", label.c_str(), cases[c], missed, - expected_misses); + std::printf("FAIL: %s %s: %u misses, expected %u (one per wave with an active lane)\n", label.c_str(), + cases[c], missed, expected_misses); return 1; } std::printf("pass: %s %s: %s in all %u lanes, %u misses (%u waves)\n", label.c_str(), cases[c], diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index cf2651ec12..d906f23b1d 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -114,14 +114,21 @@ ] -def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SELECTOR): - return [*BASES, *TABLE_LOADS, *selector, *load, *sampler, *coords, *WAIT, *op, *store] +EXEC_UPPER_HALF = [0xbefe03ff, 0xffff0000] # s_mov_b32 exec_lo, 0xffff0000 (lane 0 is inactive) +EXEC_NONE = [0xbefe0380] # s_mov_b32 exec_lo, 0 (the load and the sample still execute) + + +def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SELECTOR, exec_mask=()): + return [*BASES, *TABLE_LOADS, *selector, *load, *sampler, *exec_mask, *coords, *WAIT, *op, *store] PROGRAMS = { "tex2d": full(COORDS_2D, SAMPLE_2D), "tex1d": full(COORDS_1D, LOAD_1D), "tex2da": full(COORDS_2DA, LOAD_2DA), + # The same sample with EXEC cut after the token load: a miss counts only in a wave with an active lane. + "tex2d_exechalf": full(COORDS_2D, SAMPLE_2D, exec_mask=EXEC_UPPER_HALF), + "tex2d_execnone": full(COORDS_2D, SAMPLE_2D, exec_mask=EXEC_NONE), "all_ops": full([*COORDS_2D, *FILL_V3], ALL_OPS), # A token load that is never used. "unused": [*BASES, *TABLE_LOADS, *SELECTOR, *TOKEN_LOAD, *END], @@ -147,7 +154,11 @@ def full(coords, op, load=TOKEN_LOAD, sampler=SAMPLER, store=STORE, selector=SEL "join_copy": full(COORDS_2D, [0xbeac0320, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_mov_b32 s44, s32 after the join "numeric_join": full(COORDS_2D, [0x872cff20, 0x000000ff, *SAMPLE_2D], load=[*JOIN, *TOKEN_LOAD]), # s_and_b32 s44, s32, 0xff "field": full(COORDS_2D, [0x93acff21, 0x000e0010, *SAMPLE_2D]), # s_bfe_u32 s44, s33, 0xe0010 (an image field read) + # v_cndmask_b32 v9, v1, v2, s[31:32]: the lane mask is a pair in wave64 and reaches into the T# at s32 + "mask_pair": full(COORDS_2D, [0xd5010009, 0x007e0501, *SAMPLE_2D]), } +# Control for mask_pair: the same instruction with the mask clear of the T# (s[40:41]) keeps the program eligible. +MASK_CLEAR = full(COORDS_2D, [0xd5010009, 0x00a20501, *SAMPLE_2D]) # v_cndmask_b32 v9, v1, v2, s[40:41] # Address shapes. Each program is eligible, so it reaches the load and is refused there. ADDRESS_CONTROLS = { # s_load_dwordx8 s[32:39], s[10:11], s16: the offset register is not masked @@ -244,7 +255,7 @@ def compile_request(marker): return code, out, err, output if adapter != "controls": - for mode in ("tex2d", "tex1d", "tex2da"): + for mode in ("tex2d", "tex1d", "tex2da", "tex2d_exechalf", "tex2d_execnone"): marker = request(mode, PROGRAMS[mode]) cache = base / f"cache_{mode}" cache.mkdir() @@ -300,6 +311,8 @@ def compile_request(marker): code, out, err, output = compile_request(request("c_" + name, words)) require(code != 0 and HEAP_REFUSAL in err and not output.exists(), f"{name}: refused with \"{HEAP_REFUSAL}\" and no .cso") + code, out, err, output = compile_request(request("c_mask_clear", MASK_CLEAR)) + require(code == 0 and output.exists(), "control: a lane mask clear of the token words keeps the program eligible") # 4. Address shapes. for name, (words, text) in ADDRESS_CONTROLS.items(): code, out, err, output = compile_request(request("a_" + name, words)) diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index 5bd50f3539..308f53dbe3 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -45,6 +45,7 @@ import startup_compute_image_store_check as A import startup_compute_image_store_d16_check as D import startup_gfx2hlsl_image_store_3d1d_check as V +import native_heap_token_texture_check as K from startup_compute_dispatch_check import dispatch, lines, prepare_case from startup_compute_translate_check import state_a from startup_stream_check import gfx2hlsl as G @@ -341,8 +342,43 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal): assert not published, published +HEAP_TOKEN_REFUSAL = 'heap token textures are not bound yet' + + +def heap_token_refusal(directory, consumer, dxc_dir, adapter): + """A program that loads a GPU-selected heap texture is refused in process with the manifest reader's text. + + The native-only route has no manifest reader, so without a check of its own the program would translate and then + fail at the first view the runtime cannot bind ("view kind N is not bound for a natively translated program"). + Control: the same program without the token load is not refused for token words.""" + cache, env = prepare_case(directory, adapter) + env.update(X2W_NATIVE_SHADERS=dxc_dir, X2W_NATIVE_SHADERS_ONLY='1') + source, binary = directory / 'root.hlsl', directory / 'root.bin' + source.write_text(f'#define RS "{K.ROOT}"') + subprocess.run([Path(dxc_dir) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', binary, source], + check=True, capture_output=True) + Path(env['X2W_TEST_COMPUTE_ROOT']).write_bytes(binary.read_bytes()) + # Same state words as the token fixture: a 32 x 1 x 1 group, four reserved SGPRs, the table and the heap pointer. + (directory / 'state').write_bytes(struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1, 0, 6 << 1)) + untouched = [C.SENTINEL] * C.WORDS + for name, words, token in (('token', K.PROGRAMS['tex2d'], True), + ('plain', [*K.BASES, *K.TABLE_LOADS, *K.END], False)): + (directory / 'program').write_bytes(struct.pack(f'<{len(words)}I', *words)) + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == untouched, f'{name}: a refused Dispatch wrote the output' + assert not lines(result, 'is not bound for a natively translated program'), result.stderr[-3000:] + if token: + reason = lines(result, 'not translated natively: ') + assert len(reason) == 1 and reason[0].endswith(HEAP_TOKEN_REFUSAL), result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + else: + assert not lines(result, HEAP_TOKEN_REFUSAL), result.stderr[-3000:] + + def main(consumer, dxc_dir, adapter): scalar_window_case(consumer, dxc_dir, adapter) + with tempfile.TemporaryDirectory() as temporary: + heap_token_refusal(Path(temporary), consumer, dxc_dir, adapter) with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) cache, env = prepare_case(directory, adapter) From f4cc6a0ea6ad0678b5afaabfd38bca1405f2f0a0 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 19:17:14 +0100 Subject: [PATCH 08/19] docs: keep the revision 2 note next to revision 3 for heap token loads Co-Authored-By: Claude Opus 5.5 --- docs/experiments/native-heap-token-textures.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index df3e9c526b..a8048727b5 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -99,7 +99,7 @@ path and refusal text. Like the texture route, this translates only where no hea ## Revision -`native_compute_output_revision` is 3. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not +`native_compute_output_revision` is 3. Revision 2 (#3544) published texture token loads that were refused before; every revision-1 manifest then reads as another compiler revision and is rebuilt once, also those without a token load. Revision 3 does the same for raw buffer token loads. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not `native_compute_pipeline.cpp` or `native_compute_output.h`, and the manifest of a program with a token buffer has a new shape, so the marker is bumped by hand. A request the previous translator refused published nothing, so it is translated again by the next run (checked: the previous `compile_dxil` refuses the fixture request and leaves its cache empty, the From d2805e70f70bd83c85c1a65c1f067e84c27f44c9 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 20:47:33 +0100 Subject: [PATCH 09/19] native compute: one null word per dimension for heap token programs The heap token word set becomes base1d, base2d, base2da, count, null1d, null2d, null2da (7 words), plus baseraw, nullraw (9 words) for programs with a raw buffer token load. The null slot of a texture load of dimension index d (1D 0, 2D 1, 2D array 2) is word 4 + d; baseraw and nullraw move to words 7 and 8. A null descriptor read with another dimension is undefined in D3D12, so the runtime has to provide one null view per dimension. native_compute_output_revision 3 -> 4 (the word layout of every token program changed). The cache decoder, the manifest writer, the manifest reader's known names, the documentation and the tests move to 7/9 words; the word budget test now has 23 strides next to nine words. The rig creates three distinct null views (1D, 2D, 2D array). Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 23 ++++----- src/direct_compute_cache.cpp | 9 ++-- src/gfx1013_compute_native.h | 2 +- src/gfx1013_direct_compute.inl | 16 +++--- src/native_compute_output.h | 4 +- src/native_compute_pipeline.h | 2 +- src/startup_stubs/d3d12_compute_dispatch.inl | 4 +- tests/native_compute_manifest_reasons.cpp | 36 +++++++------ tests/native_heap_token_texture.cpp | 23 +++++---- tests/native_heap_token_texture_check.py | 50 ++++++++++--------- .../startup_compute_dispatch_texture_check.py | 7 ++- 11 files changed, 100 insertions(+), 76 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index a8048727b5..7f8df5748e 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -25,18 +25,18 @@ those two words at the guest byte address and maps the id to a host descriptor. writes `so + imm` to the eight words, and bypasses the heap view contract: the contract exists because the runtime cannot vouch for the view kind of a GPU-selected slot, and this route checks it on every execution. - Per image instruction of dimension `d`: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 1 + d`; - the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null]` (kind 1, 2 or 7, `nonuniform` false: every lane loads + the handle is `ResourceDescriptorHeap[valid ? base(d) + id : null(d)]` (kind 1, 2 or 7, `nonuniform` false: every lane loads the same address). When `!valid`, the first lane of the wave adds one to a miss counter (`waveIsFirstLane`, `atomicBinOp`), but only when the wave has an active guest lane (`waveActiveBallot` of EXEC is not zero); a wave that reaches the instruction with EXEC = 0 counts nothing. -- Five more `b0` words (seven with a raw buffer, see below) follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null`. Three runtime-provided views +- Seven more `b0` words (nine with a raw buffer, see below) follow the stride words: `base1d`, `base2d`, `base2da`, `count`, `null1d`, `null2d`, `null2da` (the null slot of an instruction of dimension index `d` is word `4 + d`: 1D 0, 2D 1, 2D array 2). Three runtime-provided views (root parameter `compute_heap_token`): the token memory (`heap_token_srv`, a raw SRV), the dimension table (`heap_token_dims_srv`, a raw SRV with one uint per view id: 0 none, else 1 + the image dimension) and the miss counter (`heap_token_miss_uav`, a raw UAV). They take the first SRV and UAV registers after the stride views, because the module names the registers while it is lowered. - Manifest lines: `srv N heaptok`, `srv N heaptokdims`, `uav N heaptokmiss`, - `udsrc K heaptok base1d|base2d|base2da|count|null`, and in the seven-word form (raw buffers, below) also + `udsrc K heaptok base1d|base2d|base2da|count|null1d|null2d|null2da`, and in the nine-word form (raw buffers, below) also `udsrc K heaptok baseraw|nullraw`. - `native_compute_output_revision` is 3 (see Revision below). The native-only route (no manifest reader) refuses a program + `native_compute_output_revision` is 4 (see Revision below). The native-only route (no manifest reader) refuses a program with token words with the same text as the manifest reader, `heap token textures are not bound yet`. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. @@ -53,9 +53,8 @@ those two words at the guest byte address and maps the id to a host descriptor. ## Open -The null slot has one word; a null view of another dimension than the instruction's is not defined by D3D12 for dynamic -indexing, so the runtime change has to provide a null slot that every dimension may read (the fixture uses a null view of the -dimension under test). +Each dimension has its own null word (null1d, null2d, null2da): a null view read with a dimension other than its own is not defined +by D3D12 for dynamic indexing, so the runtime provides one null view per dimension (the fixture creates three distinct ones). # GPU-selected raw buffers through view tokens (PR 1c) @@ -80,7 +79,7 @@ path and refusal text. Like the texture route, this translates only where no hea - The analysis of a program with a candidate runs with the byte-window tracking (`heap_window`). If no candidate is eligible, the program is analysed again exactly as before, so texture-only programs and every other program translate to the same module and manifest (only the revision line changes). -- The seven token words and the descriptor strides of the program must fit the 32-word entry layout. The strides are known +- The nine token words and the descriptor strides of the program must fit the 32-word entry layout. The strides are known only while lowering, so a program that does not fit is translated again with the buffer route off: its buffer loads keep today's path and text. - The load handler writes the byte address (`so + imm`, or the low word of the added address: the byte offset from heap @@ -92,14 +91,14 @@ path and refusal text. Like the texture route, this translates only where no hea - The consumer reads the token at that address: `valid = word0 == magic && id < count && dims[min(id, count - 1)] == 0x20`, and uses `ResourceDescriptorHeap[valid ? baseraw + id : nullraw]` as a raw buffer. A miss is counted as for textures. No `heap_buffer_srv` binding is created. -- Two more `b0` words follow the five texture words, only in a program with an eligible buffer load: `baseraw`, `nullraw` - (`NativeComputeShader::heap_token_word_count` is 0, 5 or 7). The manifest names them `udsrc K heaptok baseraw|nullraw`. +- Two more `b0` words follow the seven texture words, only in a program with an eligible buffer load: `baseraw`, `nullraw` + (`NativeComputeShader::heap_token_word_count` is 0, 7 or 9). The manifest names them `udsrc K heaptok baseraw|nullraw`. - The dimension table gains the code `0x20`: a raw buffer view (next to 0 none, else 1 + the image dimension). The production writer of that table is the runtime change (PR 2); the fixture writes it for its two raw ids. ## Revision -`native_compute_output_revision` is 3. Revision 2 (#3544) published texture token loads that were refused before; every revision-1 manifest then reads as another compiler revision and is rebuilt once, also those without a token load. Revision 3 does the same for raw buffer token loads. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not +`native_compute_output_revision` is 4. Revision 2 (#3544) published texture token loads that were refused before; every revision-1 manifest then reads as another compiler revision and is rebuilt once, also those without a token load. Revision 3 does the same for raw buffer token loads. Revision 4 changes the word set of every token program (null1d, null2d, null2da replace the single null word; baseraw and nullraw move to words 7 and 8), so a manifest of revision 3 with token lines would be read with the wrong words and is rebuilt. `X2W_NATIVE_SHADER_REVISION` hashes the translator sources but not `native_compute_pipeline.cpp` or `native_compute_output.h`, and the manifest of a program with a token buffer has a new shape, so the marker is bumped by hand. A request the previous translator refused published nothing, so it is translated again by the next run (checked: the previous `compile_dxil` refuses the fixture request and leaves its cache empty, the @@ -133,7 +132,7 @@ new one compiles it from the same cache folder). immediate offset that breaks the descriptor layout), address shapes without a proven range (overflow, a high word that is not the constant 0, an unmasked or misaligned offset, an immediate on an added address; all dropped, today's text), a byte window load in a loop (dropped by the analysis: the lowering would refuse it with `heap byte window loaded inside a loop` - and take the whole program down), the word budget (25 descriptor strides fit next to seven token words, 26 do not and the + and take the whole program down), the word budget (23 descriptor strides fit next to nine token words, 24 do not and the buffer route is dropped), and the mixed cases (a texture on the token route next to a buffer load, an unread load or a loop that keeps today's refusal). - `native_heap_token_texture_warp` and `_hardware`: modes `rawbuf`, `rawbuf_waterfall` and `sbuf` with two raw views (64 and diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 36f337cdb6..e12e22e4e8 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -160,7 +160,7 @@ NativeComputeShader decode(std::string_view bytes) { } shader.sampler_heap = in.count(1) != 0; shader.heap_token_word_count = in.count(7); - if (shader.heap_token_word_count != 0 && shader.heap_token_word_count != 5 && shader.heap_token_word_count != 7) + if (shader.heap_token_word_count != 0 && shader.heap_token_word_count != 7 && shader.heap_token_word_count != 9) throw std::runtime_error("invalid cached heap token word count"); n = in.count(32); for (unsigned j = 0; j < n; ++j) @@ -1217,11 +1217,12 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh out << "udsrc " << ud_index++ << " stride " << srv << '\n'; } if (program.heap_token_word_count) { - if (program.heap_token_word_count != 5 && program.heap_token_word_count != 7) - return refuse("heap token words are five, or seven with a token buffer"); + if (program.heap_token_word_count != 7 && program.heap_token_word_count != 9) + return refuse("heap token words are seven, or nine with a token buffer"); if (token_views[0] != 1 || token_views[1] != 1 || token_views[2] != 1) return refuse("heap token words without the three heap token views"); - const char *const names[]{"base1d", "base2d", "base2da", "count", "null", "baseraw", "nullraw"}; + const char *const names[]{"base1d", "base2d", "base2da", "count", "null1d", "null2d", "null2da", + "baseraw", "nullraw"}; for (unsigned k = 0; k < program.heap_token_word_count; ++k) out << "udsrc " << ud_index++ << " heaptok " << names[k] << '\n'; } diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 7daedece53..b7c3ad9070 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -154,7 +154,7 @@ struct NativeComputeShader { std::vector constants; // Additional b0 words, after root constants, read from these bound SRVs. std::vector stride_srvs; - // More b0 words after the stride words, 0, 5 or 7: base1d, base2d, base2da, count, null (heap token textures), then + // More b0 words after the stride words, 0, 7 or 9: base1d, base2d, base2da, count, null1d, null2d, null2da (heap token textures), then // baseraw, nullraw when a GPU-selected raw buffer is read through its view token. unsigned heap_token_word_count = 0; std::string hlsl, dxil_ir; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 9b9f29eb65..a7167a2e24 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -94,22 +94,24 @@ struct DirectCompute { std::vector scc_live; std::map,string> descriptor_strides; // GPU-selected heap textures through view tokens (the program passed heap_token_eligible). The registers are taken - // before the program is lowered, because the DXIL names them; the five words are base1d, base2d, base2da, count, null. + // before the program is lowered, because the DXIL names them; the seven words are base1d, base2d, base2da, count, + // null1d, null2d, null2da (the null slot of the dimension the instruction reads: word 4 + dimension index, 1D 0, + // 2D 1, 2D array 2; a null descriptor read with another dimension is undefined in D3D12). // A program with an eligible raw buffer load (heap_token_buffer_consumers) has two more, in this order: baseraw // (the first raw view id's slot) and nullraw (a raw buffer view of no bytes, read when the token does not hold a // raw view). bool heap_tokens = false; std::vector heap_token_consumers; std::vector heap_token_buffer_consumers; - std::array heap_token_values; + std::array heap_token_values; unsigned token_srv = 0, token_dims_srv = 0, token_miss_uav = 0; // The views and words exist only when a program uses a token texture or buffer (an unused token load needs none). bool token_bindings() const { return heap_tokens && (!heap_token_consumers.empty() || !heap_token_buffer_consumers.empty()); } - // The number of token words: 5, or 7 with a token buffer. + // The number of token words: 7, or 9 with a token buffer. unsigned token_word_count() const { - return !token_bindings() ? 0u : heap_token_buffer_consumers.empty() ? 5u : 7u; + return !token_bindings() ? 0u : heap_token_buffer_consumers.empty() ? 7u : 9u; } // The load at `pc` is an eligible raw buffer load of the token route. bool heap_token_buffer_load(unsigned pc) const { @@ -1209,8 +1211,8 @@ struct DirectCompute { if (std::none_of(heap_token_consumers.begin(), heap_token_consumers.end(), [&](const auto &c) { return c.pc == i.pc && c.dim == dim; })) refuse(i.pc, "heap token consumer was not listed by the pre-pass"); - const auto slot = heap_token_slot(base, 1 + dim, heap_token_values[dim == 0 ? 0 : dim == 1 ? 1 : 2], - heap_token_values[4]); + const unsigned dim_index = dim == 0 ? 0 : dim == 1 ? 1 : 2; + const auto slot = heap_token_slot(base, 1 + dim, heap_token_values[dim_index], heap_token_values[4 + dim_index]); constexpr unsigned dx_kind[]{1, 2, 0, 0, 0, 7}; return ir.heap_handle(slot, dx_kind[dim], 1033, false, false); } @@ -1300,7 +1302,7 @@ struct DirectCompute { if (!(s.at(base + j) == expected)) refuse(i.pc, "non-contiguous resource descriptor"); } - const auto slot = heap_token_slot(base, 0x20, heap_token_values[5], heap_token_values[6]); + const auto slot = heap_token_slot(base, 0x20, heap_token_values[7], heap_token_values[8]); return ir.heap_handle(slot, 11, 0, false, false); } // The runtime-provided bindings and words of the token route. Taken before lowering because the DXIL names them. diff --git a/src/native_compute_output.h b/src/native_compute_output.h index 2ba6e05f92..32d4473b61 100644 --- a/src/native_compute_output.h +++ b/src/native_compute_output.h @@ -10,7 +10,9 @@ namespace x2w { // revision 1 reads as "another compiler revision; rebuild it" although the ones without such a load differ only in // this marker line; they are rebuilt once. // 3: the same for a raw buffer read through a view token (heap token words baseraw and nullraw). -constexpr unsigned native_compute_output_revision = 3; +// 4: the heap token words are seven (nine with a raw buffer): one null slot per dimension (null1d, null2d, null2da) +// replaces the single null word, and baseraw and nullraw move to words 7 and 8. +constexpr unsigned native_compute_output_revision = 4; enum class NativeComputeOutput { unmarked, current, incompatible }; diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index a0cdbd8e49..6592960b22 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -17,7 +17,7 @@ struct NativeComputePipeline { unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; - // heap token words after the stride words: base1d, base2d, base2da, count, null (5), plus baseraw, nullraw (7) + // heap token words after the stride words: base1d, base2d, base2da, count, null1d, null2d, null2da (7), plus baseraw, nullraw (9) unsigned token_words = 0; unsigned instructions = 0; bool cache_hit = false, frontend_cache_hit = false; diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 1b97709889..cde0f2f7ac 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -379,10 +379,10 @@ const char* load_compute_translation(ComputeTranslation& tr) if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this // runtime - // yet. The reader knows the seven word names (baseraw and nullraw belong to raw buffers); every such line is + // yet. The reader knows the nine word names (baseraw and nullraw belong to raw buffers); every such line is // refused here until a runtime fills the views and words. const auto token_word = [&] { - for (const char *known : {"base1d", "base2d", "base2da", "count", "null", "baseraw", "nullraw"}) + for (const char *known : {"base1d", "base2d", "base2da", "count", "null1d", "null2d", "null2da", "baseraw", "nullraw"}) if (!std::strcmp(name, known)) return true; return false; }; diff --git a/tests/native_compute_manifest_reasons.cpp b/tests/native_compute_manifest_reasons.cpp index a49692b13f..ef99869392 100644 --- a/tests/native_compute_manifest_reasons.cpp +++ b/tests/native_compute_manifest_reasons.cpp @@ -148,30 +148,36 @@ int main() { p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); }}, {"heap token view with another root parameter", [](auto &p) { - p.heap_token_word_count = 5; + p.heap_token_word_count = 7; p.bindings.push_back(view(K::heap_token_srv, 1, 1)); }}, {"heap token view with another root parameter", [](auto &p) { p.bindings.push_back(view(K::buffer_srv, 1, compute_heap_token)); }}, {"heap token words without the three heap token views", [](auto &p) { - p.heap_token_word_count = 5; + p.heap_token_word_count = 7; p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); }}, {"SRV registers not contiguous", [](auto &p) { - p.heap_token_word_count = 5; + p.heap_token_word_count = 7; p.bindings.push_back(view(K::heap_token_srv, 2, compute_heap_token)); }}, {"more than 32 user data words", [](auto &p) { p.constants.assign(3, {0, 0, 8}); p.stride_srvs = {}; - p.heap_token_word_count = 5; + p.heap_token_word_count = 7; p.constants.push_back({0, 0, 4}); p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); p.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); }}, - {"heap token words are five, or seven with a token buffer", [](auto &p) { + {"heap token words are seven, or nine with a token buffer", [](auto &p) { + p.heap_token_word_count = 5; // the count before revision 4 (one null word) is no longer valid + p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); + p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); + p.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); + }}, + {"heap token words are seven, or nine with a token buffer", [](auto &p) { p.heap_token_word_count = 6; p.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); p.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); @@ -267,15 +273,16 @@ int main() { // The views and words of GPU-selected heap textures are published by name, in register order with the other views. { auto program = base(); - program.heap_token_word_count = 5; + program.heap_token_word_count = 7; program.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); program.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); program.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); reason = "unset"; const auto manifest = format_compute_runtime_manifest(program, &reason); - const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 7\nudsrc 0 rootconst 0 0\n" + const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 9\nudsrc 0 rootconst 0 0\n" "udsrc 1 rootconst 0 1\nudsrc 2 heaptok base1d\nudsrc 3 heaptok base2d\n" - "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null\n" + "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null1d\n" + "udsrc 7 heaptok null2d\nudsrc 8 heaptok null2da\n" "srv 0 buf table 1 64\nsrv 1 heaptok\nsrv 2 heaptokdims\nuav 0 table 1 32\n" "uav 1 heaptokmiss\nnative " + std::to_string(native_compute_output_revision) + "\n"; const bool ok = manifest && *manifest == wanted && reason == "unset"; @@ -284,23 +291,24 @@ int main() { std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); failures += !ok; } - // A program with a token buffer has seven words: baseraw and nullraw follow the five of the textures. + // A program with a token buffer has nine words: baseraw and nullraw follow the seven of the textures. { auto program = base(); - program.heap_token_word_count = 7; + program.heap_token_word_count = 9; program.bindings.push_back(view(K::heap_token_srv, 1, compute_heap_token)); program.bindings.push_back(view(K::heap_token_dims_srv, 2, compute_heap_token)); program.bindings.push_back(view(K::heap_token_miss_uav, 1, compute_heap_token)); reason = "unset"; const auto manifest = format_compute_runtime_manifest(program, &reason); - const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 9\nudsrc 0 rootconst 0 0\n" + const std::string wanted = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 11\nudsrc 0 rootconst 0 0\n" "udsrc 1 rootconst 0 1\nudsrc 2 heaptok base1d\nudsrc 3 heaptok base2d\n" - "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null\n" - "udsrc 7 heaptok baseraw\nudsrc 8 heaptok nullraw\n" + "udsrc 4 heaptok base2da\nudsrc 5 heaptok count\nudsrc 6 heaptok null1d\n" + "udsrc 7 heaptok null2d\nudsrc 8 heaptok null2da\n" + "udsrc 9 heaptok baseraw\nudsrc 10 heaptok nullraw\n" "srv 0 buf table 1 64\nsrv 1 heaptok\nsrv 2 heaptokdims\nuav 0 table 1 32\n" "uav 1 heaptokmiss\nnative " + std::to_string(native_compute_output_revision) + "\n"; const bool ok = manifest && *manifest == wanted && reason == "unset"; - std::printf("%s publishes the seven heap token words of a token buffer\n", ok ? "ok " : "FAIL"); + std::printf("%s publishes the nine heap token words of a token buffer\n", ok ? "ok " : "FAIL"); if (!ok) std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); failures += !ok; diff --git a/tests/native_heap_token_texture.cpp b/tests/native_heap_token_texture.cpp index 73078a7109..87e36687a2 100644 --- a/tests/native_heap_token_texture.cpp +++ b/tests/native_heap_token_texture.cpp @@ -12,8 +12,8 @@ // dwords at byte 16 * L with buffer_load_dwordx4 (sbuf: s_buffer_load_dwordx4 of the unrewritten words, the // same four dwords in every lane). The results are compared as dwords. // The rig binds what the manifest names for the runtime-provided views: the token memory (a raw SRV over a buffer of -// eight 32-byte tokens), the dimension table (one uint per view id), the miss counter (a raw UAV) and the five words -// base1d, base2d, base2da, count, null. The shader indexes a host heap with one range per dimension, one slot per view id +// eight 32-byte tokens), the dimension table (one uint per view id), the miss counter (a raw UAV) and the seven words (nine in the raw modes) +// base1d, base2d, base2da, count, null1d, null2d, null2da. The shader indexes a host heap with one range per dimension, one slot per view id // (ids 1 2D, 2 2D array, 3 1D; id 0 and every other slot are null views of the range's dimension). // Cases (token at byte address 32 * case): a valid id, a wrong magic, an id equal to the count, the largest id, an id of // another dimension, a content token (bit 31), id 0, an empty token. A valid token gives the texel of its view and no @@ -42,7 +42,9 @@ using Microsoft::WRL::ComPtr; namespace { constexpr unsigned lanes = 32, groups = 3, count = 4; -constexpr unsigned base_1d = 8, base_2d = 16, base_2da = 24, null_slot = 0, table_start = 32; +constexpr unsigned base_1d = 8, base_2d = 16, base_2da = 24, table_start = 32; +// Three distinct null views, one per dimension (null1d, null2d, null2da); the raw modes use slot 0 as nullraw. +constexpr unsigned null_1d = 0, null_2d = 1, null_2da = 2, null_slot = null_1d; constexpr std::uint32_t magic = 0x56573258u, sentinel = 0x69696969u; using Texel = std::array; @@ -278,7 +280,7 @@ struct Gpu { // What the manifest says about the runtime-provided views and words. struct Layout { int selector = -1, out = -1, tokens = -1, dims = -1, miss = -1; - std::map words; // base1d ... null -> user data index + std::map words; // base1d ... nullraw -> user data index unsigned srv_count = 0; }; bool parse_manifest(const std::string &text, Layout &layout) { @@ -302,7 +304,7 @@ bool parse_manifest(const std::string &text, Layout &layout) { layout.words[w[3]] = static_cast(std::stoul(w[1])); } return layout.selector >= 0 && layout.out >= 0 && layout.tokens >= 0 && layout.dims >= 0 && layout.miss >= 0 && - (layout.words.size() == 5 || layout.words.size() == 7); + (layout.words.size() == 7 || layout.words.size() == 9); } bool same_bits(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } @@ -321,7 +323,7 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file const auto manifest = x2w::format_compute_runtime_manifest(program, &reason); Layout layout; const bool raw = mode.dim == Dim::raw; - if (!manifest || !parse_manifest(*manifest, layout) || layout.words.size() != (raw ? 7u : 5u)) { + if (!manifest || !parse_manifest(*manifest, layout) || layout.words.size() != (raw ? 9u : 7u)) { std::printf("FAIL: the manifest does not name the token views and words (%s)\n%s\n", reason.c_str(), manifest ? manifest->c_str() : "(none)"); return 1; @@ -343,8 +345,6 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file gpu.tex2d = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, [](int x, int y, int) { return texel_2d(x, y); }); gpu.tex2da = gpu.texture(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 2, [](int x, int y, int s) { return texel_2da(x, y, s); }); - const auto dimension = mode.dim == Dim::d1 ? D3D12_SRV_DIMENSION_TEXTURE1D - : mode.dim == Dim::d2 ? D3D12_SRV_DIMENSION_TEXTURE2D : D3D12_SRV_DIMENSION_TEXTURE2DARRAY; std::vector raw_1(raw_words_1), raw_2(raw_words_2); for (unsigned k = 0; k < raw_words_1; ++k) raw_1[k] = raw_word(1, k); for (unsigned k = 0; k < raw_words_2; ++k) raw_2[k] = raw_word(2, k); @@ -358,7 +358,9 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file gpu.raw_srv(raw_base + id, id == 1 ? raw_buffer_1.Get() : id == 2 ? raw_buffer_2.Get() : nullptr, id == 1 ? raw_words_1 : id == 2 ? raw_words_2 : 1); } else { - gpu.srv(null_slot, nullptr, dimension); // the null slot has the dimension of the instruction under test + gpu.srv(null_1d, nullptr, D3D12_SRV_DIMENSION_TEXTURE1D); // the null slot of each dimension has that dimension + gpu.srv(null_2d, nullptr, D3D12_SRV_DIMENSION_TEXTURE2D); + gpu.srv(null_2da, nullptr, D3D12_SRV_DIMENSION_TEXTURE2DARRAY); for (unsigned id = 0; id < count; ++id) { gpu.srv(base_1d + id, id == 3 ? gpu.tex1d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE1D); gpu.srv(base_2d + id, id == 1 ? gpu.tex2d.Get() : nullptr, D3D12_SRV_DIMENSION_TEXTURE2D); @@ -396,7 +398,8 @@ int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::file auto first = gpu.views->GetGPUDescriptorHandleForHeapStart(); first.ptr += UINT64(table_start) * gpu.increment; const std::map values{{"base1d", base_1d}, {"base2d", base_2d}, {"base2da", base_2da}, - {"count", count}, {"null", null_slot}, {"baseraw", raw_base}, + {"count", count}, {"null1d", null_1d}, {"null2d", null_2d}, + {"null2da", null_2da}, {"baseraw", raw_base}, {"nullraw", null_slot}}; auto dispatch = [&](unsigned address, std::vector &out, std::uint32_t &missed) { diff --git a/tests/native_heap_token_texture_check.py b/tests/native_heap_token_texture_check.py index f3c97b5c03..113f314f7c 100644 --- a/tests/native_heap_token_texture_check.py +++ b/tests/native_heap_token_texture_check.py @@ -285,8 +285,8 @@ def mixed(buffer_rewrite, texture_load=TOKEN_LOAD, texture_selector=SELECTOR32, } MASK_WIDE = [0x8711ff10, 0xffffffe0] # s_and_b32 s17, s16, 0xffffffe0 (32-byte aligned, but up to 0xffffffe0) -# More than 32 entry words: the token words (7 with a buffer) and the descriptor strides of table SRVs read as s_bfe_u32 -# stride fields. 25 strides fit next to seven words, 26 do not: the buffer route is dropped and the program keeps today's text. +# More than 32 entry words: the token words (9 with a buffer) and the descriptor strides of table SRVs read as s_bfe_u32 +# stride fields. 23 strides fit next to nine words, 24 do not: the buffer route is dropped and the program keeps today's text. ROOT_STRIDES = ("RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0, numDescriptors = 32), UAV(u0))") STRIDE_TABLE_LOADS = [ 0xf4080304, 0xfa000000, # s_load_dwordx4 s[12:15], s[8:9], 0x0 (t0: the selector) @@ -364,37 +364,41 @@ def stride_program(count): EXPECTED_MANIFEST = """x2w-manifest 2 stage cs group 32 1 1 -ud 5 +ud 7 udsrc 0 heaptok base1d udsrc 1 heaptok base2d udsrc 2 heaptok base2da udsrc 3 heaptok count -udsrc 4 heaptok null +udsrc 4 heaptok null1d +udsrc 5 heaptok null2d +udsrc 6 heaptok null2da srv 0 heaptok srv 1 heaptokdims srv 2 buf table 0 0 uav 0 heaptokmiss uav 1 table 0 32 smpl 0 00000092 00000000 00000000 00000000 -native 3 +native 4 """ EXPECTED_BUFFER_MANIFEST = """x2w-manifest 2 stage cs group 32 1 1 -ud 7 +ud 9 udsrc 0 heaptok base1d udsrc 1 heaptok base2d udsrc 2 heaptok base2da udsrc 3 heaptok count -udsrc 4 heaptok null -udsrc 5 heaptok baseraw -udsrc 6 heaptok nullraw +udsrc 4 heaptok null1d +udsrc 5 heaptok null2d +udsrc 6 heaptok null2da +udsrc 7 heaptok baseraw +udsrc 8 heaptok nullraw srv 0 heaptok srv 1 heaptokdims srv 2 buf table 0 0 uav 0 heaptokmiss uav 1 table 0 32 -native 3 +native 4 """ FIXTURE_CASES = ("valid", "wrong_magic", "id_at_count", "id_max", "dims_mismatch", "content_token", "id_zero", "no_token") @@ -467,7 +471,7 @@ def compile_request(marker): for case in FIXTURE_CASES: require(f"pass: {mode} {case}:" in out, f"{mode}: case {case} held") require(f"pass: {mode} the manifest names the token views and words" in out, - f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and five heaptok words") + f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and seven heaptok words") for mode in BUFFER_PROGRAMS: marker = request(mode, BUFFER_PROGRAMS[mode]) cache = base / f"cache_{mode}" @@ -477,7 +481,7 @@ def compile_request(marker): for case in BUFFER_FIXTURE_CASES: require(f"pass: {mode} {case}:" in out, f"{mode}: case {case} held") require(f"pass: {mode} the manifest names the token views and words" in out, - f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and seven heaptok words") + f"{mode}: the manifest names heaptok, heaptokdims, heaptokmiss and nine heaptok words") print(f"{ok_lines} assertions held") return @@ -510,7 +514,7 @@ def compile_request(marker): marker.parent, out_dir]) manifest = out_dir / (marker.stem[len("req_"):] + ".txt") require(code == 0 and manifest.exists(), "--requests publishes a manifest for a heap token program") - require(manifest.read_text() == EXPECTED_MANIFEST, "the manifest names the token views and the five token words") + require(manifest.read_text() == EXPECTED_MANIFEST, "the manifest names the token views and the seven token words") # Control: a program without a token load publishes no token line. plain = request("plain", [*BASES, *TABLE_LOADS, 0xbf810000]) plain_out = base / "plain_out" @@ -537,7 +541,7 @@ def compile_request(marker): code, out, err, output = compile_request(request("noheap", PROGRAMS["tex2d"], ROOT_NO_HEAP)) require(code != 0 and not output.exists(), "a root without the heap flag does not compile the token program") - # 6. GPU-selected raw buffers. The eligible programs compile and publish seven token words; the module reads the + # 6. GPU-selected raw buffers. The eligible programs compile and publish nine token words; the module reads the # token, checks it and reads the buffer from the heap. for name, words in {**BUFFER_PROGRAMS, **BUFFER_ACCEPTED, **MIXED_PROGRAMS}.items(): marker = request("b_" + name, words) @@ -557,10 +561,10 @@ def compile_request(marker): text = (out_dir / (marker.stem[len("req_"):] + ".txt")).read_text() if name in ("rawbuf", "rawbuf_waterfall", "sbuf", "x1", "x3", "immediate", "sbuf_offset", "mask_wide"): require(code == 0 and text == EXPECTED_BUFFER_MANIFEST, - f"{name}: the manifest names the token views and the seven token words, and no heap buffer view") + f"{name}: the manifest names the token views and the nine token words, and no heap buffer view") else: - require(code == 0 and "udsrc 6 heaptok nullraw\n" in text and "udsrc 4 heaptok null\n" in text and - "ud 7\n" in text, f"{name}: a texture and a buffer publish seven token words") + require(code == 0 and "udsrc 8 heaptok nullraw\n" in text and "udsrc 6 heaptok null2da\n" in text and + "ud 9\n" in text, f"{name}: a texture and a buffer publish nine token words") # Controls: a V# use that is not the byte window of a raw load or a scalar buffer load keeps today's refusal. for name, (words, text) in BUFFER_CONTROLS.items(): code, out, err, output = compile_request(request("bc_" + name, words)) @@ -572,13 +576,13 @@ def compile_request(marker): for name, (words, text) in BUFFER_ADDRESS_CONTROLS.items(): code, out, err, output = compile_request(request("ba_" + name, words)) require(code != 0 and text in err and not output.exists(), f"buffer {name}: refused with \"{text}\" and no .cso") - # The word budget: 25 strides + 7 token words fit; 26 do not, and the buffer route is dropped (today's text). - code, out, err, output = compile_request(request("strides25", stride_program(25), ROOT_STRIDES)) - require(code == 0 and output.exists(), "25 descriptor strides next to the seven token words compile") - code, out, err, output = compile_request(request("strides26", stride_program(26), ROOT_STRIDES)) + # The word budget: 23 strides + 9 token words fit; 24 do not, and the buffer route is dropped (today's text). + code, out, err, output = compile_request(request("strides23", stride_program(23), ROOT_STRIDES)) + require(code == 0 and output.exists(), "23 descriptor strides next to the nine token words compile") + code, out, err, output = compile_request(request("strides24", stride_program(24), ROOT_STRIDES)) require(code != 0 and HEAP_REFUSAL in err and not output.exists(), - f"26 descriptor strides: the buffer route is dropped, refused with \"{HEAP_REFUSAL}\" and no .cso") - # Texture-only programs keep their five words (the same program with a buffer has seven). + f"24 descriptor strides: the buffer route is dropped, refused with \"{HEAP_REFUSAL}\" and no .cso") + # Texture-only programs keep their seven words (the same program with a buffer has nine). code, out, err, output = compile_request(request("t_only", PROGRAMS["tex2d"])) require(code == 0, "control: the texture-only program still compiles") diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 7426b070d1..2997d98d06 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -174,13 +174,18 @@ def check_manifest_refusal(case, variant, reason): 'a sampler that is not a plain static one') # The translator's heap token texture lines (GPU-selected textures read through view tokens) are named, not bound. for case, line in (('heap token view', 'srv 1 heaptok\n'), ('heap token dimension table', 'srv 1 heaptokdims\n'), - ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token word', 'udsrc 3 heaptok null\n'), + ('heap token miss counter', 'uav 1 heaptokmiss\n'), ('heap token null word 1d', 'udsrc 3 heaptok null1d\n'), + ('heap token null word 2d', 'udsrc 3 heaptok null2d\n'), + ('heap token null word 2da', 'udsrc 3 heaptok null2da\n'), ('heap token raw buffer base', 'udsrc 3 heaptok baseraw\n'), ('heap token raw buffer null', 'udsrc 3 heaptok nullraw\n')): check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') # Control: a token word the reader does not know is not taken for one. check_manifest_refusal('unknown heap token word', original + 'udsrc 3 heaptok bogus\n', 'an entry value that is not a root constant or a buffer descriptor word') + # The single null word of revisions 2 and 3 is retired (revision 4 has one null word per dimension). + check_manifest_refusal('retired heap token word null', original + 'udsrc 3 heaptok null\n', + 'an entry value that is not a root constant or a buffer descriptor word') assert original.count('\nud 3\n') == 1, ('entry count mismatch', original) check_manifest_refusal('entry count mismatch', original.replace('\nud 3\n', '\nud 4\n'), 'entry value, input or output count') From a9438e217dfee57d71f6e8f2c2973d2e72a14f74 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 21:02:46 +0100 Subject: [PATCH 10/19] d3d12 runtime: gate heap token programs behind X2W_D3D12_HEAP_TOKENS X2W_D3D12_HEAP_TOKENS=1 (opt-in, read once, next to view_content_tokens) is the switch for binding the heap view tokens of translated compute programs. Binding itself is not implemented yet, so the manifest reader and the native-only route refuse a program with heaptok lines in three cases, with one text shared by both routes (heap_token_refusal): - opt-in unset: "heap token textures are not bound yet" (unchanged); - opt-in together with X2W_D3D12_VIEW_CONTENT_TOKENS: "heap tokens need id tokens"; - opt-in alone: "heap tokens are not bound yet (runtime binding in progress)". Tests cover all three cases on the manifest reader and on the native-only route, plus the content-token-only control. Co-Authored-By: Claude Opus 5.5 --- .../experiments/native-heap-token-textures.md | 5 +++ src/startup_stubs/d3d12_capture.inl | 9 +++++ src/startup_stubs/d3d12_compute_dispatch.inl | 15 ++++++-- .../startup_compute_dispatch_native_check.py | 34 ++++++++++++------- .../startup_compute_dispatch_texture_check.py | 16 +++++++-- 5 files changed, 63 insertions(+), 16 deletions(-) diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index 7f8df5748e..c75d153903 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -39,6 +39,11 @@ those two words at the guest byte address and maps the id to a host descriptor. `native_compute_output_revision` is 4 (see Revision below). The native-only route (no manifest reader) refuses a program with token words with the same text as the manifest reader, `heap token textures are not bound yet`. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. +- The refusal has three texts, the same on both routes (`heap_token_refusal` in `src/startup_stubs/d3d12_compute_dispatch.inl`): + `heap token textures are not bound yet` while the opt-in `X2W_D3D12_HEAP_TOKENS=1` is unset (also when only + `X2W_D3D12_VIEW_CONTENT_TOKENS=1` is set); `heap tokens need id tokens` with both set (the tokens would name content, not + view ids); `heap tokens are not bound yet (runtime binding in progress)` with the opt-in alone, until the runtime binds the + views. Both variables are read once. ## Tests diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index b8b82b1646..0a96f432d6 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -104,6 +104,15 @@ bool view_content_tokens() !GetEnvironmentVariableA("X2W_D3D12_CAPTURE", nullptr, 0); return on; } +// X2W_D3D12_HEAP_TOKENS=1 (opt-in, read once): the runtime may bind the heap view tokens of a translated compute program +// (the heaptok lines). Without it such a program keeps the refusal "heap token textures are not bound yet". It cannot +// be combined with view_content_tokens() (the tokens would name content, not view ids); see heap_token_refusal in +// d3d12_compute_dispatch.inl. +bool heap_tokens() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_HEAP_TOKENS"); + 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; diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index cde0f2f7ac..dc7230218e 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -265,6 +265,17 @@ bool adapter_lacks_directly_indexed_sampler_heap() options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3); } +// Why a translated compute program with heap token words or views (heaptok lines) cannot run. One text for the manifest +// reader and the native-only route, so triage reads the same reason on both. Three cases: the opt-in +// X2W_D3D12_HEAP_TOKENS is off (today's text); it is on together with X2W_D3D12_VIEW_CONTENT_TOKENS (the tokens would +// name content, not view ids); it is on alone (the runtime does not bind the views yet). +const char* heap_token_refusal() +{ + if (!heap_tokens()) return "heap token textures are not bound yet"; + if (view_content_tokens()) return "heap tokens need id tokens"; + return "heap tokens are not bound yet (runtime binding in progress)"; +} + // The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is // unavailable, or null when it is ready. const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, std::size_t bytes) @@ -390,7 +401,7 @@ const char* load_compute_translation(ComputeTranslation& tr) (std::sscanf(line.c_str(), "srv %u heaptokdims%n", &i, &used) == 1 && whole()) || (std::sscanf(line.c_str(), "uav %u heaptokmiss%n", &i, &used) == 1 && whole()) || (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole() && token_word())) - return "heap token textures are not bound yet"; + return heap_token_refusal(); if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) tr.uds.push_back({a, b}); else if (std::sscanf(line.c_str(), "udsrc %u %15s %d%n", &i, name, &a, &used) == 3 && whole() && i == tr.uds.size() && @@ -562,7 +573,7 @@ bool translate_compute_natively(ComputeTranslation& tr) program = x2w::translate_compute(*frozen, 0, true); // The same refusal text as the manifest reader gives for the token lines, so triage reads one reason on both routes. if (program.heap_token_word_count != 0) - throw std::runtime_error("heap token textures are not bound yet"); + throw std::runtime_error(heap_token_refusal()); for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index 2573662bc9..502292aab6 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -377,6 +377,13 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal): HEAP_TOKEN_REFUSAL = 'heap token textures are not bound yet' +# The three refusals of the heap token gate: X2W_D3D12_HEAP_TOKENS unset (also with only the content tokens on), on alone, and +# on together with X2W_D3D12_VIEW_CONTENT_TOKENS. +HEAP_TOKEN_CASES = (({}, HEAP_TOKEN_REFUSAL), + ({'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, HEAP_TOKEN_REFUSAL), + ({'X2W_D3D12_HEAP_TOKENS': '1'}, 'heap tokens are not bound yet (runtime binding in progress)'), + ({'X2W_D3D12_HEAP_TOKENS': '1', 'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, 'heap tokens need id tokens')) +HEAP_TOKEN_TEXTS = tuple(sorted({text for _, text in HEAP_TOKEN_CASES})) def heap_token_refusal(directory, consumer, dxc_dir, adapter): @@ -395,18 +402,21 @@ def heap_token_refusal(directory, consumer, dxc_dir, adapter): # Same state words as the token fixture: a 32 x 1 x 1 group, four reserved SGPRs, the table and the heap pointer. (directory / 'state').write_bytes(struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1, 0, 6 << 1)) untouched = [C.SENTINEL] * C.WORDS - for name, words, token in (('token', K.PROGRAMS['tex2d'], True), - ('plain', [*K.BASES, *K.TABLE_LOADS, *K.END], False)): - (directory / 'program').write_bytes(struct.pack(f'<{len(words)}I', *words)) - got, result = dispatch(directory, consumer, env, 'dispatch') - assert got == untouched, f'{name}: a refused Dispatch wrote the output' - assert not lines(result, 'is not bound for a natively translated program'), result.stderr[-3000:] - if token: - reason = lines(result, 'not translated natively: ') - assert len(reason) == 1 and reason[0].endswith(HEAP_TOKEN_REFUSAL), result.stderr[-3000:] - assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] - else: - assert not lines(result, HEAP_TOKEN_REFUSAL), result.stderr[-3000:] + for extra, expected in HEAP_TOKEN_CASES: + case_env = dict(env, **extra) + for name, words, token in (('token', K.PROGRAMS['tex2d'], True), + ('plain', [*K.BASES, *K.TABLE_LOADS, *K.END], False)): + (directory / 'program').write_bytes(struct.pack(f'<{len(words)}I', *words)) + got, result = dispatch(directory, consumer, case_env, 'dispatch') + assert got == untouched, f'{name} {extra}: a refused Dispatch wrote the output' + assert not lines(result, 'is not bound for a natively translated program'), result.stderr[-3000:] + if token: + reason = lines(result, 'not translated natively: ') + assert len(reason) == 1 and reason[0].endswith(expected), (extra, result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + else: + for text in HEAP_TOKEN_TEXTS: + assert not lines(result, text), (extra, result.stderr[-3000:]) def native_totals(consumer, dxc_dir, adapter, case): diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 2997d98d06..b9ec7ec359 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -145,10 +145,10 @@ def store(directory, consumer, dxc, env): assert got == untouched and len(refused) == 1 and refused[0].endswith('refused: ' + reason), ( mode, reason, refused, result.stderr[-3000:]) - def check_manifest_refusal(case, variant, reason): + def check_manifest_refusal(case, variant, reason, extra_env=None): assert variant != original, (case, original) manifest.write_bytes(variant.encode()) - readback, dispatch_result = run(directory, consumer, env, 'texture-store', layout) + readback, dispatch_result = run(directory, consumer, dict(env, **(extra_env or {})), 'texture-store', layout) refusals = [message for message in lines(dispatch_result, 'Dispatch(') if ' refused: ' in message] suffix = 'Dispatch(2, 1, 1) refused: ' + reason assert len(refusals) == 1 and refusals[0].endswith(suffix), (case, refusals, dispatch_result.stderr[-3000:]) @@ -180,6 +180,18 @@ def check_manifest_refusal(case, variant, reason): ('heap token raw buffer base', 'udsrc 3 heaptok baseraw\n'), ('heap token raw buffer null', 'udsrc 3 heaptok nullraw\n')): check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') + # X2W_D3D12_HEAP_TOKENS (opt-in): on alone the lines are still refused, with their own text while the binding is + # under construction; together with X2W_D3D12_VIEW_CONTENT_TOKENS the refusal names the id tokens. With the opt-in + # unset (the loop above, also with only the content tokens on) the text stays "heap token textures are not bound yet". + for case, line in (('heap token view', 'srv 1 heaptok\n'), ('heap token word', 'udsrc 3 heaptok null2d\n')): + check_manifest_refusal(case + ' under HEAP_TOKENS', original + line, + 'heap tokens are not bound yet (runtime binding in progress)', + {'X2W_D3D12_HEAP_TOKENS': '1'}) + check_manifest_refusal(case + ' under HEAP_TOKENS and VIEW_CONTENT_TOKENS', original + line, + 'heap tokens need id tokens', + {'X2W_D3D12_HEAP_TOKENS': '1', 'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}) + check_manifest_refusal(case + ' under VIEW_CONTENT_TOKENS only', original + line, + 'heap token textures are not bound yet', {'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}) # Control: a token word the reader does not know is not taken for one. check_manifest_refusal('unknown heap token word', original + 'udsrc 3 heaptok bogus\n', 'an entry value that is not a root constant or a buffer descriptor word') From 35278e53faeb6592df8f45bdbfae4a0abcdba382 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Mon, 30 Nov 2026 23:24:31 +0100 Subject: [PATCH 11/19] d3d12 runtime: heap token kinds and pending-id queue (no descriptors yet) Adds heap_token_kinds.h (kinds table codes: texture 1 + SQ dimension, raw buffer 0x20, R32_UINT typed buffer 16 reserved for #3619 and never accepted by the compute route; a pure function from a desktop SRV desc), and heap_token_pending.h (bookkeeping of ids that need a mirror descriptor, with a backfill of existing ids and a generation per reassigned id). note_view only appends ids under note_lock when X2W_D3D12_HEAP_TOKENS is on; nothing creates a descriptor yet. Test hooks: x2w_d3d12_create_srv (real device slot 18 path) and x2w_d3d12_heap_mirror_queue. Tests: heap_token_kinds_check with four mutation controls, and a WARP skeleton startup_compute_heap_token_check.py (records, ids, queue, controls; no dispatch checks yet). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 16 ++ src/startup_stubs/d3d12_capture.inl | 13 ++ src/startup_stubs/d3d12_xs_device.cpp | 24 +++ src/startup_stubs/heap_token_kinds.h | 49 +++++ src/startup_stubs/heap_token_pending.h | 97 +++++++++ tests/heap_token_kinds_check.cpp | 186 ++++++++++++++++ tests/startup_compute_heap_token_check.py | 245 ++++++++++++++++++++++ 7 files changed, 630 insertions(+) create mode 100644 src/startup_stubs/heap_token_kinds.h create mode 100644 src/startup_stubs/heap_token_pending.h create mode 100644 tests/heap_token_kinds_check.cpp create mode 100644 tests/startup_compute_heap_token_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index edcbd1f454..d77c9bb1ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2426,6 +2426,16 @@ endforeach() add_executable(startup_heap_indexed_root_check tests/startup_heap_indexed_root_check.cpp) target_include_directories(startup_heap_indexed_root_check PRIVATE src) target_compile_features(startup_heap_indexed_root_check PRIVATE cxx_std_17) +# Heap token kinds table codes and the mirror's pending-id queue (src/startup_stubs/heap_token_kinds.h and +# heap_token_pending.h), without a device. Each mutated run must fail. +add_executable(heap_token_kinds_check tests/heap_token_kinds_check.cpp) +target_include_directories(heap_token_kinds_check PRIVATE src) +target_compile_features(heap_token_kinds_check PRIVATE cxx_std_17) +add_test(NAME heap_token_kinds COMMAND heap_token_kinds_check) +foreach(mutation IN ITEMS kind-offset typed-any-format backfill-skipped generation-kept) + add_test(NAME heap_token_kinds_${mutation}_control COMMAND heap_token_kinds_check --mutate ${mutation}) + set_tests_properties(heap_token_kinds_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() add_test(NAME startup_heap_indexed_root COMMAND startup_heap_indexed_root_check) foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) @@ -5066,6 +5076,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_heap_word_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_word_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + if(adapter STREQUAL "warp") + # Heap view token runtime, skeleton: x2w_d3d12_create_srv records and queues slot-18 views (WARP only for now). + add_test(NAME startup_compute_heap_token_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_heap_token_check.py" "$") + set_tests_properties(startup_compute_heap_token_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endif() add_test(NAME startup_compute_dispatch_input_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_input_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 0a96f432d6..4b4e386c45 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -113,6 +113,13 @@ bool heap_tokens() static const bool on = x2w_local::env_on("X2W_D3D12_HEAP_TOKENS"); return on; } +// Ids that still need a heap token mirror descriptor (heap_token_pending.h); nothing creates one yet. Only with +// heap_tokens(). Every member: note_lock held. +x2w_startup::HeapMirrorPending& heap_mirror_pending() { static x2w_startup::HeapMirrorPending q; return q; } +bool heap_mirror_eligible(std::uint32_t id) // a materialized shader resource view (note_lock held) +{ + return id < view_records().size() && view_records()[id].slot == 18 && view_materialized()[id]; +} // 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; @@ -728,6 +735,8 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ materialized, content); AcquireSRWLockExclusive(¬e_lock); ++views_noted; + // The first note with the switch on queues every record that exists (heap_token_pending.h, backfill). + if (heap_tokens()) heap_mirror_pending().start(static_cast(view_records().size()), heap_mirror_eligible); const auto found = view_ids().find(hash); if (found != view_ids().end()) { record.id = found->second; @@ -764,6 +773,10 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ return; } ++views_distinct; + if (heap_tokens() && !heap_mirror_pending().note_record(record.id, taken != 0, record.slot == 18 && materialized)) { + static LONG lost; + if (first_calls(lost, 4)) log("x2w-d3d12 note_view: out of memory -> view %u not queued for heap tokens", record.id); + } if (census) { if (record.slot >= 17 && record.slot <= 22) ++view_census.distinct[record.slot - 17]; view_census.missed += !records_full && view_records().capacity() != capacity_before; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 978b86993d..be55c92d58 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -38,6 +38,8 @@ #include "startup_stubs/formatted_buffer.h" #include "startup_stubs/view_content_token.h" #include "startup_stubs/heap_indexed_root.h" +#include "startup_stubs/heap_token_kinds.h" +#include "startup_stubs/heap_token_pending.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" #include "startup_stubs/list_dispatch.h" @@ -7226,6 +7228,28 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_token_texture(const void* token, return TRUE; } +// Fixture export (startup_compute_heap_token): CreateShaderResourceView(resource, desc, destination) through the real +// device slot 18 (view_slot<18, 2>), as a title's call reaches it. `table` is the guest device object (its first word +// is the dispatch table), `slot` the title CPU descriptor handle of the destination, `resource` the guest resource and +// `desc` a D3D12_SHADER_RESOURCE_VIEW_DESC. FALSE when an argument is missing or `table` is no device. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_create_srv(void* table, UINT64 slot, void* resource, const void* desc) +{ + Wrapper* device = as_wrapper(table); + if (!device || device->own().kind != device_kind || !slot || !resource || !desc) return FALSE; + using Create = u64 (*)(Wrapper*, u64, u64, u64, u64); + reinterpret_cast(tables[device_kind][18])(device, reinterpret_cast(resource), reinterpret_cast(desc), slot, 0); + return TRUE; +} +// Fixture export (startup_compute_heap_token): ids waiting for a heap token mirror descriptor, and ids that could not be +// queued (out of memory). Both 0 unless X2W_D3D12_HEAP_TOKENS=1. +extern "C" __declspec(dllexport) void x2w_d3d12_heap_mirror_queue(unsigned long long* queued, unsigned long long* lost) +{ + AcquireSRWLockShared(¬e_lock); + *queued = heap_mirror_pending().queued(); + *lost = heap_mirror_pending().lost(); + 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) { diff --git a/src/startup_stubs/heap_token_kinds.h b/src/startup_stubs/heap_token_kinds.h new file mode 100644 index 0000000000..6d55915e52 --- /dev/null +++ b/src/startup_stubs/heap_token_kinds.h @@ -0,0 +1,49 @@ +#pragma once + +// What a heap view token may name, per record id (the "kinds table" the translated compute programs read as +// heap_token_dims_srv; T/gfx1013_direct_compute.inl heap_token_slot): a program reads ResourceDescriptorHeap[first + id] +// only when the table holds, for that id, the code the program expects, and reads its null view otherwise. The codes +// are the ones the translator compares against: +// texture: 1 + the SQ dimension of the descriptor the program samples (1D 1, 2D 2, 2D array 6), +// raw buffer: 0x20. +// 16 is the code of an R32_UINT typed buffer view, reserved for the typed buffer token route (#3619). The compute +// token route here never accepts it: compute_token_accepts(16) is false. Any other view is 0 (no entry). + +#include + +#include + +namespace x2w_startup { + +constexpr std::uint32_t heap_kind_none = 0; +constexpr std::uint32_t heap_kind_texture_1d = 1; +constexpr std::uint32_t heap_kind_texture_2d = 2; +constexpr std::uint32_t heap_kind_texture_2d_array = 6; +constexpr std::uint32_t heap_kind_typed_r32_uint = 16; +constexpr std::uint32_t heap_kind_raw_buffer = 0x20; + +// The kind of a desktop shader resource view description, 0 for every view a heap token cannot name. Raw buffer views +// need the RAW flag and R32_TYPELESS (the only format D3D12 allows with it); a typed buffer view counts only as +// R32_UINT without the RAW flag. +inline std::uint32_t heap_token_kind(const D3D12_SHADER_RESOURCE_VIEW_DESC& desc) +{ + switch (desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: return heap_kind_texture_1d; + case D3D12_SRV_DIMENSION_TEXTURE2D: return heap_kind_texture_2d; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: return heap_kind_texture_2d_array; + case D3D12_SRV_DIMENSION_BUFFER: + if (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) + return desc.Format == DXGI_FORMAT_R32_TYPELESS ? heap_kind_raw_buffer : heap_kind_none; + return desc.Format == DXGI_FORMAT_R32_UINT ? heap_kind_typed_r32_uint : heap_kind_none; + default: return heap_kind_none; + } +} + +// Whether a translated compute program can be given the kind: every kind but 0 and the typed buffer code. +inline bool compute_token_accepts(std::uint32_t kind) +{ + return kind == heap_kind_texture_1d || kind == heap_kind_texture_2d || kind == heap_kind_texture_2d_array || + kind == heap_kind_raw_buffer; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/heap_token_pending.h b/src/startup_stubs/heap_token_pending.h new file mode 100644 index 0000000000..a372becd90 --- /dev/null +++ b/src/startup_stubs/heap_token_pending.h @@ -0,0 +1,97 @@ +#pragma once + +// Bookkeeping for the heap token mirror (X2W_D3D12_HEAP_TOKENS): which view record ids still need a descriptor, and the +// generation of each id. No D3D12 call. note_view only appends ids here (under note_lock); the dispatch path later takes +// the ids and creates the descriptors outside that lock. +// +// start(existing, eligible): once, queues every id that exists already (backfill), so a record created before the +// queue was started is not lost. Later calls do nothing. +// note_record(id, reassigned, eligible): a record was stored under `id`. `reassigned` is true when the id held another +// record before (a parked record was taken again); that bumps the id's generation, so an entry written for the old +// record can be told from one for the new. Only an eligible record (a materialized shader resource view) is queued, +// and an id already queued is not queued twice. +// take(): the queued ids in the order they were queued, each with its current generation; empties the queue. +// +// Every member: the caller holds the lock that guards it (note_lock). Not thread safe by itself. + +#include +#include +#include + +namespace x2w_startup { + +class HeapMirrorPending { +public: + struct Entry { + std::uint32_t id, generation; + }; + + bool started() const { return started_; } + std::uint32_t generation(std::uint32_t id) const { return id < generation_.size() ? generation_[id] : 0; } + std::size_t queued() const { return queue_.size(); } + // Ids that could not be queued for lack of memory since the start; each is a view the mirror will not know. + std::uint64_t lost() const { return lost_; } + + template + void start(std::uint32_t existing, Eligible&& eligible) + { + if (started_) return; + started_ = true; + for (std::uint32_t id = 0; id < existing; ++id) + if (eligible(id)) enqueue(id); + } + + // False when the id was eligible and could not be queued (out of memory); it is counted in lost(). + bool note_record(std::uint32_t id, bool reassigned, bool eligible) + { + if (!started_) return true; // start() queues it with the backfill + if (reassigned && !bump(id)) return false; + return !eligible || enqueue(id); + } + + std::vector take() + { + std::vector out; + out.reserve(queue_.size()); + for (const std::uint32_t id : queue_) { + out.push_back({id, generation(id)}); + queued_[id] = 0; + } + queue_.clear(); + return out; + } + +private: + bool bump(std::uint32_t id) + { + try { + if (id >= generation_.size()) generation_.resize(std::size_t{id} + 1, 0); + } catch (const std::bad_alloc&) { + ++lost_; + return false; + } + ++generation_[id]; + return true; + } + bool enqueue(std::uint32_t id) + { + try { + if (id >= queued_.size()) queued_.resize(std::size_t{id} + 1, 0); + if (queued_[id]) return true; + queue_.push_back(id); + queued_[id] = 1; + return true; + } catch (const std::bad_alloc&) { + ++lost_; + return false; + } + } + + bool started_ = false; + std::vector queue_; // ids in queueing order + std::vector queued_; // per id: 1 while it is in queue_ + std::vector generation_; // per id: how often the id was reassigned + std::uint64_t lost_ = 0; +}; + +} // namespace x2w_startup diff --git a/tests/heap_token_kinds_check.cpp b/tests/heap_token_kinds_check.cpp new file mode 100644 index 0000000000..b5faad1219 --- /dev/null +++ b/tests/heap_token_kinds_check.cpp @@ -0,0 +1,186 @@ +// Checks src/startup_stubs/heap_token_kinds.h (the kind a shader resource view gets in the heap token kinds table) and +// src/startup_stubs/heap_token_pending.h (the queue of ids that need a mirror descriptor, with a generation per id), +// without a device. +// +// heap_token_kinds_check [--mutate kind-offset|typed-any-format|backfill-skipped|generation-kept] +// +// Each mutation changes an expectation to what a wrong implementation would give; every one must make the check fail. +#include "startup_stubs/heap_token_kinds.h" +#include "startup_stubs/heap_token_pending.h" + +#include +#include +#include + +namespace { +using namespace x2w_startup; +int failures, cases; +bool mutate_kind_offset, mutate_typed_any_format, mutate_backfill_skipped, mutate_generation_kept; + +void expect(bool ok, const char* what) +{ + ++cases; + if (ok) return; + ++failures; + std::printf("FAIL: %s\n", what); +} + +void expect_kind(const char* label, const D3D12_SHADER_RESOURCE_VIEW_DESC& desc, std::uint32_t expected) +{ + const std::uint32_t got = heap_token_kind(desc); + ++cases; + if (got == expected) return; + ++failures; + std::printf("FAIL %s: kind %u, expected %u\n", label, got, expected); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC view(D3D12_SRV_DIMENSION dimension, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_BUFFER_SRV_FLAGS flags = D3D12_BUFFER_SRV_FLAG_NONE) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc; + std::memset(&desc, 0, sizeof(desc)); + desc.ViewDimension = dimension; + desc.Format = format; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (dimension == D3D12_SRV_DIMENSION_BUFFER) { + desc.Buffer.NumElements = 16; + desc.Buffer.Flags = flags; + } + return desc; +} + +void kinds() +{ + const std::uint32_t off = mutate_kind_offset ? 1 : 0; // a table that stores the SQ dimension without the +1 + expect_kind("1d", view(D3D12_SRV_DIMENSION_TEXTURE1D), 1 - off); + expect_kind("2d", view(D3D12_SRV_DIMENSION_TEXTURE2D), 2 - off); + expect_kind("2d array", view(D3D12_SRV_DIMENSION_TEXTURE2DARRAY), 6 - off); + expect_kind("raw buffer", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_TYPELESS, D3D12_BUFFER_SRV_FLAG_RAW), 0x20); + expect_kind("typed r32_uint buffer", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_UINT), 16); + + // Not nameable by a token: every other dimension, and the buffers that are neither raw nor R32_UINT. + expect_kind("unknown dimension", view(D3D12_SRV_DIMENSION_UNKNOWN), 0); + expect_kind("1d array", view(D3D12_SRV_DIMENSION_TEXTURE1DARRAY), 0); + expect_kind("2d multisampled", view(D3D12_SRV_DIMENSION_TEXTURE2DMS), 0); + expect_kind("2d multisampled array", view(D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY), 0); + expect_kind("3d", view(D3D12_SRV_DIMENSION_TEXTURE3D), 0); + expect_kind("cube", view(D3D12_SRV_DIMENSION_TEXTURECUBE), 0); + expect_kind("cube array", view(D3D12_SRV_DIMENSION_TEXTURECUBEARRAY), 0); + expect_kind("acceleration structure", view(D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE), 0); + expect_kind("typed buffer, float", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_FLOAT), 0); + expect_kind("typed buffer, rgba8", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R8G8B8A8_UNORM), 0); + expect_kind("typed buffer, unknown format", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_UNKNOWN), 0); + expect_kind("typed buffer, r32_typeless without the raw flag", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_TYPELESS), 0); + expect_kind("raw flag with a typed format", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_UINT, D3D12_BUFFER_SRV_FLAG_RAW), 0); + expect_kind("raw flag with the wrong width", view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R16_TYPELESS, D3D12_BUFFER_SRV_FLAG_RAW), 0); + // A texture format makes no difference to a texture's kind. + expect_kind("2d, depth format", view(D3D12_SRV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R32_FLOAT), 2); + + if (mutate_typed_any_format) { + // A wrong rule would give every typed buffer 16: the float buffer above must not be one. + expect(heap_token_kind(view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_FLOAT)) == 16, "mutation: typed buffer of any format"); + } + + // The compute token route accepts the texture codes and the raw buffer code, never 16 (typed buffers, #3619) or 0. + expect(compute_token_accepts(1) && compute_token_accepts(2) && compute_token_accepts(6) && compute_token_accepts(0x20), + "the compute route accepts the texture and raw buffer kinds"); + expect(!compute_token_accepts(16), "the compute route accepts the typed buffer kind"); + expect(!compute_token_accepts(0), "the compute route accepts kind 0"); + expect(!compute_token_accepts(3) && !compute_token_accepts(0x21) && !compute_token_accepts(0xffffffffu), + "the compute route accepts an unknown kind"); +} + +std::vector ids_of(const std::vector& entries) +{ + std::vector out; + for (const auto& e : entries) out.push_back(e.id); + return out; +} +using Ids = std::vector; + +void pending() +{ + const auto all = [](std::uint32_t) { return true; }; + { + // Backfill: a started queue holds every id that existed, in id order, and later ids follow in note order. + HeapMirrorPending q; + expect(!q.started() && q.queued() == 0, "a new queue is started or not empty"); + expect(q.note_record(0, false, true) && q.queued() == 0, "a record noted before start() was queued (start() backfills it)"); + q.start(mutate_backfill_skipped ? 0 : 3, all); + expect(q.started() && q.queued() == 3, "start(3) did not queue the three existing ids"); + q.start(10, all); + expect(q.queued() == 3, "a second start() queued more ids"); + q.note_record(3, false, true); + q.note_record(4, false, true); + expect(q.queued() == 5, "two new ids after the backfill were not queued"); + const auto entries = q.take(); + expect(ids_of(entries) == Ids({0, 1, 2, 3, 4}), "ids are not in backfill, then note order"); + bool zero = true; + for (const auto& e : entries) zero = zero && e.generation == 0; + expect(zero, "a first assignment has a generation other than 0"); + expect(q.queued() == 0 && q.take().empty(), "take() leaves ids queued"); + q.note_record(5, false, true); + expect(ids_of(q.take()) == Ids({5}), "an id after a take() is lost"); + } + { + // Eligibility: only eligible ids are queued, in the backfill and afterwards. + HeapMirrorPending q; + q.start(6, [](std::uint32_t id) { return id % 2 == 1; }); + expect(ids_of(q.take()) == Ids({1, 3, 5}), "the backfill queued ids the predicate refused"); + q.note_record(6, false, false); + q.note_record(7, false, true); + expect(ids_of(q.take()) == Ids({7}), "an ineligible new record was queued"); + } + { + // An id is queued once, however often it is noted before the flush. + HeapMirrorPending q; + q.start(0, all); + q.note_record(2, false, true); + q.note_record(2, false, true); + q.note_record(1, false, true); + q.note_record(2, false, true); + expect(ids_of(q.take()) == Ids({2, 1}), "an id queued twice appears twice, or the order changed"); + } + { + // Generation: a reassigned id gets the next one, other ids keep theirs, and a take() reports the current value. + HeapMirrorPending q; + q.start(2, all); + q.take(); + expect(q.generation(0) == 0 && q.generation(1) == 0 && q.generation(9) == 0, "a generation is not 0 at first"); + q.note_record(1, !mutate_generation_kept, true); // id 1 taken again by another record + expect(q.generation(1) == 1 && q.generation(0) == 0, "reassigning id 1 did not change exactly its generation"); + auto entries = q.take(); + expect(entries.size() == 1 && entries[0].id == 1 && entries[0].generation == 1, "the entry lacks the new generation"); + // Reassigned twice while still queued: queued once, with the latest generation. + q.note_record(1, true, true); + q.note_record(1, true, true); + entries = q.take(); + expect(entries.size() == 1 && entries[0].generation == 3, "two reassignments queued the id twice or lost one"); + // A reassigned id whose new record is not eligible gets the generation (the old entry must be released) but no entry. + q.note_record(1, true, false); + expect(q.generation(1) == 4 && q.queued() == 0, "an ineligible reassignment queued the id or kept the generation"); + // A fresh id far above the known ones. + q.note_record(1000, true, true); + expect(q.generation(1000) == 1 && q.generation(999) == 0, "a high id has a wrong generation"); + expect(q.lost() == 0, "ids were lost without an allocation failure"); + } +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { + mutate_kind_offset = !std::strcmp(argv[2], "kind-offset"); + mutate_typed_any_format = !std::strcmp(argv[2], "typed-any-format"); + mutate_backfill_skipped = !std::strcmp(argv[2], "backfill-skipped"); + mutate_generation_kept = !std::strcmp(argv[2], "generation-kept"); + if (!(mutate_kind_offset || mutate_typed_any_format || mutate_backfill_skipped || mutate_generation_kept)) return 2; + } else if (argc != 1) { + return 2; + } + kinds(); + pending(); + std::printf("%d of %d checks failed\n", failures, cases); + return failures ? 1 : 0; +} diff --git a/tests/startup_compute_heap_token_check.py b/tests/startup_compute_heap_token_check.py new file mode 100644 index 0000000000..7e75f24fc4 --- /dev/null +++ b/tests/startup_compute_heap_token_check.py @@ -0,0 +1,245 @@ +"""Skeleton of the heap view token runtime test (X2W_D3D12_HEAP_TOKENS): the fixture side that later checks grow from. + +usage: startup_compute_heap_token_check.py (WARP only; exit 77 when WARP is not available) + +What this checks, and nothing else: + +1. x2w_d3d12_create_srv reaches the real device slot 18 path: a texture shader resource view and a raw buffer shader + resource view, created through it into a descriptor heap over title memory, leave materialized slot-18 records + (x2w_d3d12_resolve_view by descriptor handle): the resource, the 40 description bytes, and the view token the stand-in + wrote into the title descriptor (the id in word 1) all name the record. +2. The same view written to a second descriptor shares the record (same id); another view gets another id. +3. With X2W_D3D12_HEAP_TOKENS=1 the ids of those records are queued once each for a mirror descriptor + (x2w_d3d12_heap_mirror_queue: 2 for 3 writes of 2 distinct views); with the switch off nothing is queued although the + records exist (the control). +4. Controls: a descriptor nothing was written to resolves to no record; the export refuses a missing device, resource + or description. + +Not checked here (later commits): descriptors in the draw heap, the kinds table, any dispatch, texels or raw words read +through a token, the miss counter, lifetime and states, hardware adapters. +""" +import ctypes +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +TOKEN_MAGIC = 0x56573258 # "X2WV" +SLOT_SRV = 18 + +BUDGET_ENV = {'X2W_D3D12_BUDGET': '1', 'X2W_D3D12_PERMISSIVE': '1', 'X2W_D3D12_RENDER': '1', 'X2W_D3D12_DEBUG': '0'} + + +def guid(text): + import uuid + return (ctypes.c_ubyte * 16).from_buffer_copy(uuid.UUID(text).bytes_le) + + +# SDK 10.0.26100 d3d12.h, dxgi.h, dxgi1_4.h. +IID_FACTORY4 = '1bc6ea02-ef36-464f-bf0c-21ca39e5168a' +IID_ADAPTER = '2411e7e1-12ac-4ccf-bd14-9798e8534dc0' +IID_DEVICE = '189819f1-1db6-4b57-be54-1821339b85f7' +IID_HEAP = '8efb471d-616c-4f49-90f7-127bb763fa51' +IID_RESOURCE = '696442be-a72e-4059-bc79-5b5c98040fad' + + +def vcall(obj, slot, restype, argtypes, *args): + table = ctypes.cast(obj, ctypes.POINTER(ctypes.c_void_p))[0] + function = ctypes.cast(table, ctypes.POINTER(ctypes.c_void_p))[slot] + return ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *argtypes)(function)(obj, *args) + + +class HeapDesc(ctypes.Structure): # D3D12_DESCRIPTOR_HEAP_DESC, then the title memory behind it (stand-in extension) + _fields_ = [('Type', ctypes.c_uint), ('NumDescriptors', ctypes.c_uint), ('Flags', ctypes.c_uint), + ('NodeMask', ctypes.c_uint), ('backing', ctypes.c_ulonglong), ('bytes', ctypes.c_ulonglong)] + + +class HeapProperties(ctypes.Structure): + _fields_ = [('Type', ctypes.c_uint), ('CPUPageProperty', ctypes.c_uint), ('MemoryPoolPreference', ctypes.c_uint), + ('CreationNodeMask', ctypes.c_uint), ('VisibleNodeMask', ctypes.c_uint)] + + +class ResourceDesc(ctypes.Structure): + _fields_ = [('Dimension', ctypes.c_uint), ('Alignment', ctypes.c_ulonglong), ('Width', ctypes.c_ulonglong), + ('Height', ctypes.c_uint), ('DepthOrArraySize', ctypes.c_ushort), ('MipLevels', ctypes.c_ushort), + ('Format', ctypes.c_uint), ('SampleCount', ctypes.c_uint), ('SampleQuality', ctypes.c_uint), + ('Layout', ctypes.c_uint), ('Flags', ctypes.c_uint)] + + +class ResolvedViewProbe(ctypes.Structure): + _fields_ = [('known', ctypes.c_uint), ('slot', ctypes.c_uint), ('desc_bytes', ctypes.c_uint), + ('materialized', ctypes.c_uint), ('resource', ctypes.c_ulonglong), ('desc', ctypes.c_ubyte * 64)] + + +def srv_desc(dimension, fmt, union): + """D3D12_SHADER_RESOURCE_VIEW_DESC: Format, ViewDimension, Shader4ComponentMapping, 4 bytes padding, 24-byte union.""" + return struct.pack('= 0, 'CreateDescriptorHeap') + + def handle(index): + return memory + stride * index + + def committed(dimension, width, height, fmt, layout): + props = HeapProperties(1, 0, 0, 1, 1) # DEFAULT + desc = ResourceDesc(dimension, 0, width, height, 1, 1, fmt, 1, 0, layout, 0) + out = ctypes.c_void_p() + hr = vcall(device, 27, ctypes.c_long, + [ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, + ctypes.c_void_p], + ctypes.byref(props), 0, ctypes.byref(desc), 0, None, ctypes.byref(guid(IID_RESOURCE)), ctypes.byref(out)) + fails.expect(hr >= 0, 'CreateCommittedResource') + return out + + texture = committed(3, 16, 16, 28, 0) # TEXTURE2D, R8G8B8A8_UNORM + buffer = committed(1, 0x1000, 1, 0, 1) # BUFFER, row major + if fails.count: + return 3 + + queued_before = queue() + texture_view = ctypes.create_string_buffer(TEXTURE_VIEW, len(TEXTURE_VIEW)) + buffer_view = ctypes.create_string_buffer(RAW_BUFFER_VIEW, len(RAW_BUFFER_VIEW)) + fails.expect(xs.x2w_d3d12_create_srv(device, handle(0), texture, texture_view) == 1, 'create_srv texture') + fails.expect(xs.x2w_d3d12_create_srv(device, handle(1), buffer, buffer_view) == 1, 'create_srv raw buffer') + fails.expect(xs.x2w_d3d12_create_srv(device, handle(2), texture, texture_view) == 1, 'create_srv texture again') + + # 1. Each descriptor names a materialized slot-18 record that holds what was passed. + ids = [] + for index, resource, view, label in ((0, texture, TEXTURE_VIEW, 'texture'), (1, buffer, RAW_BUFFER_VIEW, 'raw buffer'), + (2, texture, TEXTURE_VIEW, 'texture again')): + shadow = resolve(None, handle(index)) + fails.expect(shadow.known == 1 and shadow.slot == SLOT_SRV and shadow.materialized == 1, + label + ': the descriptor does not name a materialized slot-18 record') + fails.expect(shadow.resource == resource.value, label + ': the record names another resource') + fails.expect(shadow.desc_bytes == 40 and bytes(shadow.desc[:40]) == view, label + ': the record holds other description bytes') + words = struct.unpack('<8I', ctypes.string_at(handle(index), 32)) + fails.expect(words[0] == TOKEN_MAGIC and words[2] == SLOT_SRV, label + ': the title descriptor holds no slot-18 view token') + token = ctypes.create_string_buffer(ctypes.string_at(handle(index), 32), 32) + by_token = resolve(token) + fails.expect(by_token.known == 1 and by_token.slot == SLOT_SRV and by_token.resource == resource.value and + bytes(by_token.desc[:40]) == view, label + ': the token and the descriptor name different views') + ids.append(words[1]) + + # 2. Same view, same record; another view, another record. + fails.expect(ids[0] == ids[2], 'the same view got two ids') + fails.expect(ids[0] != ids[1], 'two different views share an id') + + # 3. Queue: once per distinct record with the switch on; nothing with it off. + queued = queue() - queued_before + if switch == 'on': + fails.expect(queued == 2, 'queued %d ids for 2 distinct views, expected 2' % queued) + else: + fails.expect(queued == 0, 'queued %d ids with X2W_D3D12_HEAP_TOKENS off' % queued) + + # 4. Controls. + never = resolve(None, handle(5)) + fails.expect(never.known == 0, 'a descriptor nothing was written to names a record') + fails.expect(xs.x2w_d3d12_create_srv(None, handle(3), texture, texture_view) == 0, 'create_srv accepted no device') + fails.expect(xs.x2w_d3d12_create_srv(device, handle(3), None, texture_view) == 0, 'create_srv accepted no resource') + fails.expect(xs.x2w_d3d12_create_srv(device, handle(3), texture, None) == 0, 'create_srv accepted no description') + fails.expect(xs.x2w_d3d12_create_srv(texture, handle(3), texture, texture_view) == 0, 'create_srv accepted a resource as device') + fails.expect(resolve(None, handle(3)).known == 0, 'a refused create_srv left a record') + fails.expect(queue() - queued_before == queued, 'a refused create_srv queued an id') + + print('child %s: %s' % (switch, 'PASS' if not fails.count else '%d failures' % fails.count), flush=True) + return 1 if fails.count else 0 + + +def main(): + if len(sys.argv) == 4 and sys.argv[1] == '--child': + return child(sys.argv[2], sys.argv[3]) + if len(sys.argv) != 2 or sys.platform != 'win32': + print(__doc__) + return 2 + dll = str(Path(sys.argv[1]).resolve()) + if not Path(dll).exists(): + print('FAIL: no such file: ' + dll) + return 2 + status = 0 + with tempfile.TemporaryDirectory() as scratch: + for switch in ('on', 'off'): + env = dict(os.environ, **BUDGET_ENV, X2W_TRAP_LOG=str(Path(scratch) / ('trap_' + switch + '.log'))) + env.pop('X2W_D3D12_VIEW_CONTENT_TOKENS', None) + env['X2W_D3D12_HEAP_TOKENS'] = '1' if switch == 'on' else '0' + result = subprocess.run([sys.executable, '-I', '-B', os.path.abspath(__file__), '--child', dll, switch], + env=env, capture_output=True, text=True, timeout=120) + sys.stdout.write(result.stdout) + if result.returncode == 77: + print('SKIP: no WARP adapter') + return 77 + if result.returncode: + sys.stderr.write(result.stderr) + print('FAIL: child %s exited with %d' % (switch, result.returncode)) + status = 1 + if not status: + print('PASS: heap token skeleton (records, ids, queue, controls)') + return status + + +if __name__ == '__main__': + sys.exit(main()) From 0730d80350a646244e05dec45c88e1ae765270d3 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 00:27:07 +0100 Subject: [PATCH 12/19] d3d12 runtime: heap token queue survives failed reassignment and allocation A reassigned id whose generation could not be stored (bad_alloc) kept its old generation, so an entry for the old record looked current. The generation is now epoch + per-id count; a failed count grows the epoch (allocation-free), which changes every generation. note_view calls invalidate(id) when store_view fails after take_parked_record emptied the record. take() accepts an eligibility predicate so the consumer drops ids that are no longer materialized SRVs, and returns nothing (queue intact) if its result cannot be allocated. The lost-queue log moves after note_lock is released. compute_token_accepts is a helper for the mirror flush in a later commit; the runtime does not call it yet (the earlier message said otherwise). Tests: failure injection compiled only with X2W_HEAP_TOKEN_PENDING_TEST_HOOKS (test target only, no cost in the runtime), cases for generation, queue, backfill and take failures, and the mutation generation-kept-on-alloc-failure. Mutation controls now pass only on the "mutation : caught" line instead of WILL_FAIL, so a crash or unknown name no longer passes. Note: the Python skeleton startup_compute_heap_token_check.py does not check the backfill. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 8 +- src/startup_stubs/d3d12_capture.inl | 14 +++- src/startup_stubs/heap_token_kinds.h | 8 +- src/startup_stubs/heap_token_pending.h | 88 +++++++++++++++++--- tests/heap_token_kinds_check.cpp | 110 ++++++++++++++++++++++++- 5 files changed, 204 insertions(+), 24 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d77c9bb1ba..71ff151572 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2432,9 +2432,13 @@ add_executable(heap_token_kinds_check tests/heap_token_kinds_check.cpp) target_include_directories(heap_token_kinds_check PRIVATE src) target_compile_features(heap_token_kinds_check PRIVATE cxx_std_17) add_test(NAME heap_token_kinds COMMAND heap_token_kinds_check) -foreach(mutation IN ITEMS kind-offset typed-any-format backfill-skipped generation-kept) +target_compile_definitions(heap_token_kinds_check PRIVATE X2W_HEAP_TOKEN_PENDING_TEST_HOOKS) +# A control passes only when the check ran to the end and printed "mutation : caught" (a mutation that made it +# fail with FAIL lines); a crash, an unknown mutation name or a mutation that is not caught prints no such line. +foreach(mutation IN ITEMS kind-offset typed-any-format backfill-skipped generation-kept generation-kept-on-alloc-failure) add_test(NAME heap_token_kinds_${mutation}_control COMMAND heap_token_kinds_check --mutate ${mutation}) - set_tests_properties(heap_token_kinds_${mutation}_control PROPERTIES WILL_FAIL TRUE) + set_tests_properties(heap_token_kinds_${mutation}_control PROPERTIES + PASS_REGULAR_EXPRESSION "mutation ${mutation}: caught") endforeach() add_test(NAME startup_heap_indexed_root COMMAND startup_heap_indexed_root_check) foreach(mutation IN ITEMS sampler-alone bind-unrestorable) diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 4b4e386c45..24cc0b5f20 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -734,6 +734,7 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ x2w_startup::encode_view_content(view_token_magic, record.slot, resource, counter, record.desc, record.desc_bytes, materialized, content); AcquireSRWLockExclusive(¬e_lock); + bool queue_lost = false; // the id could not be queued for heap tokens; logged after note_lock is released ++views_noted; // The first note with the switch on queues every record that exists (heap_token_pending.h, backfill). if (heap_tokens()) heap_mirror_pending().start(static_cast(view_records().size()), heap_mirror_eligible); @@ -769,14 +770,15 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } 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 + // The old record is gone and no new one stands in its place: an entry queued or handed out for the old + // record must not stay current (the record is empty, so the consumer's eligibility check also refuses it). + if (taken && heap_tokens()) heap_mirror_pending().invalidate(record.id); drop_unrecorded_view(record, materialized, container); return; } ++views_distinct; - if (heap_tokens() && !heap_mirror_pending().note_record(record.id, taken != 0, record.slot == 18 && materialized)) { - static LONG lost; - if (first_calls(lost, 4)) log("x2w-d3d12 note_view: out of memory -> view %u not queued for heap tokens", record.id); - } + if (heap_tokens() && !heap_mirror_pending().note_record(record.id, taken != 0, record.slot == 18 && materialized)) + queue_lost = true; if (census) { if (record.slot >= 17 && record.slot <= 22) ++view_census.distinct[record.slot - 17]; view_census.missed += !records_full && view_records().capacity() != capacity_before; @@ -806,6 +808,10 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ park_view_record(record.id); if (freeable) ++content_tokens_written; ReleaseSRWLockExclusive(¬e_lock); + if (queue_lost) { // logged outside note_lock + static LONG lost; + if (first_calls(lost, 4)) log("x2w-d3d12 note_view: out of memory -> view %u not queued for heap tokens", record.id); + } 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)) { diff --git a/src/startup_stubs/heap_token_kinds.h b/src/startup_stubs/heap_token_kinds.h index 6d55915e52..1f251e6fb1 100644 --- a/src/startup_stubs/heap_token_kinds.h +++ b/src/startup_stubs/heap_token_kinds.h @@ -6,8 +6,9 @@ // are the ones the translator compares against: // texture: 1 + the SQ dimension of the descriptor the program samples (1D 1, 2D 2, 2D array 6), // raw buffer: 0x20. -// 16 is the code of an R32_UINT typed buffer view, reserved for the typed buffer token route (#3619). The compute -// token route here never accepts it: compute_token_accepts(16) is false. Any other view is 0 (no entry). +// 16 is the code of an R32_UINT typed buffer view, reserved for the typed buffer token route (#3619). Any other view is +// 0 (no entry). compute_token_accepts is the rule the compute route will apply when the mirror writes the table +// (16 and 0 are refused); nothing calls it yet, only heap_token_kinds_check exercises it. #include @@ -39,7 +40,8 @@ inline std::uint32_t heap_token_kind(const D3D12_SHADER_RESOURCE_VIEW_DESC& desc } } -// Whether a translated compute program can be given the kind: every kind but 0 and the typed buffer code. +// Whether a translated compute program can be given the kind: the three texture codes and the raw buffer code, never 0 +// or the typed buffer code. Not called by the runtime yet (a helper for the mirror flush). inline bool compute_token_accepts(std::uint32_t kind) { return kind == heap_kind_texture_1d || kind == heap_kind_texture_2d || kind == heap_kind_texture_2d_array || diff --git a/src/startup_stubs/heap_token_pending.h b/src/startup_stubs/heap_token_pending.h index a372becd90..590a039367 100644 --- a/src/startup_stubs/heap_token_pending.h +++ b/src/startup_stubs/heap_token_pending.h @@ -10,14 +10,28 @@ // record before (a parked record was taken again); that bumps the id's generation, so an entry written for the old // record can be told from one for the new. Only an eligible record (a materialized shader resource view) is queued, // and an id already queued is not queued twice. -// take(): the queued ids in the order they were queued, each with its current generation; empties the queue. +// invalidate(id): the id's old record is gone but no new one was stored (a reassignment that failed after the old +// record was cleared); bumps the generation like a reassignment, so no entry written for the old record stays valid. +// take(eligible): the queued ids in the order they were queued, each with its current generation; empties the queue. +// An id for which eligible(id) is false now (its record was cleared or replaced after it was queued) is dropped, so +// the consumer never gets an entry for a record that is no longer a materialized shader resource view. take() with +// no predicate keeps every id. If the result cannot be allocated, take() returns nothing and leaves the queue as it +// was (take_failures() counts it); the caller tries again at its next flush. +// generation(id): the epoch plus the id's own count. When a count cannot be stored for lack of memory the epoch grows +// instead, which changes the generation of every id: an entry older than that is stale for all ids and never looks +// current by accident. That path allocates nothing, so a reassignment cannot leave an old entry looking current. // // Every member: the caller holds the lock that guards it (note_lock). Not thread safe by itself. +#include #include #include #include +// Test only: X2W_HEAP_TOKEN_PENDING_TEST_HOOKS (defined by tests/heap_token_kinds_check.cpp and nowhere else) adds a +// failure injection to each place that allocates, and one deliberately wrong behaviour (a mutation). Without it, +// inject() is an empty inline function and the class has no extra member: the runtime pays nothing. + namespace x2w_startup { class HeapMirrorPending { @@ -27,10 +41,24 @@ class HeapMirrorPending { }; bool started() const { return started_; } - std::uint32_t generation(std::uint32_t id) const { return id < generation_.size() ? generation_[id] : 0; } + std::uint32_t generation(std::uint32_t id) const + { + return epoch_ + (id < generation_.size() ? generation_[id] : 0); + } std::size_t queued() const { return queue_.size(); } // Ids that could not be queued for lack of memory since the start; each is a view the mirror will not know. std::uint64_t lost() const { return lost_; } + // Generations answered by the epoch for lack of memory, and takes that returned nothing for the same reason. + std::uint32_t epoch_bumps() const { return epoch_; } + std::uint64_t take_failures() const { return take_failures_; } + +#ifdef X2W_HEAP_TOKEN_PENDING_TEST_HOOKS + enum Site { site_generation = 0, site_queue = 1, site_take = 2 }; + // The n-th (1-based) allocation at `site` from now on throws std::bad_alloc; 0 switches the injection off. + void test_fail_nth(Site site, unsigned n) { fail_in_[site] = n; } + // Mutation: a failed generation allocation leaves the generation as it was (the defect this class must not have). + void test_keep_generation_on_failure() { keep_on_failure_ = true; } +#endif template void start(std::uint32_t existing, Eligible&& eligible) @@ -45,37 +73,73 @@ class HeapMirrorPending { bool note_record(std::uint32_t id, bool reassigned, bool eligible) { if (!started_) return true; // start() queues it with the backfill - if (reassigned && !bump(id)) return false; + if (reassigned) bump(id); return !eligible || enqueue(id); } - std::vector take() + void invalidate(std::uint32_t id) + { + if (started_) bump(id); + } + + template + std::vector take(Eligible&& eligible) { std::vector out; - out.reserve(queue_.size()); + try { + inject(site_take); + out.reserve(queue_.size()); + } catch (const std::bad_alloc&) { + ++take_failures_; + return {}; + } for (const std::uint32_t id : queue_) { - out.push_back({id, generation(id)}); + if (eligible(id)) out.push_back({id, generation(id)}); // reserved above: cannot allocate queued_[id] = 0; } queue_.clear(); return out; } + std::vector take() + { + return take([](std::uint32_t) { return true; }); + } private: - bool bump(std::uint32_t id) +#ifdef X2W_HEAP_TOKEN_PENDING_TEST_HOOKS + enum { sites = 3 }; + void inject(int site) + { + if (fail_in_[site] && --fail_in_[site] == 0) throw std::bad_alloc(); + } + unsigned fail_in_[sites] = {0, 0, 0}; + bool keep_on_failure_ = false; +#else + enum { site_generation, site_queue, site_take }; + static void inject(int) {} +#endif + + // Never fails: when the id's own count cannot be stored, the epoch grows and every generation changes. + void bump(std::uint32_t id) { try { - if (id >= generation_.size()) generation_.resize(std::size_t{id} + 1, 0); + if (id >= generation_.size()) { + inject(site_generation); + generation_.resize(std::size_t{id} + 1, 0); + } } catch (const std::bad_alloc&) { - ++lost_; - return false; +#ifdef X2W_HEAP_TOKEN_PENDING_TEST_HOOKS + if (keep_on_failure_) return; +#endif + ++epoch_; + return; } ++generation_[id]; - return true; } bool enqueue(std::uint32_t id) { try { + inject(site_queue); if (id >= queued_.size()) queued_.resize(std::size_t{id} + 1, 0); if (queued_[id]) return true; queue_.push_back(id); @@ -91,7 +155,9 @@ class HeapMirrorPending { std::vector queue_; // ids in queueing order std::vector queued_; // per id: 1 while it is in queue_ std::vector generation_; // per id: how often the id was reassigned + std::uint32_t epoch_ = 0; // added to every generation; grows when a count could not be stored std::uint64_t lost_ = 0; + std::uint64_t take_failures_ = 0; }; } // namespace x2w_startup diff --git a/tests/heap_token_kinds_check.cpp b/tests/heap_token_kinds_check.cpp index b5faad1219..cb9f57b1cc 100644 --- a/tests/heap_token_kinds_check.cpp +++ b/tests/heap_token_kinds_check.cpp @@ -2,9 +2,13 @@ // src/startup_stubs/heap_token_pending.h (the queue of ids that need a mirror descriptor, with a generation per id), // without a device. // -// heap_token_kinds_check [--mutate kind-offset|typed-any-format|backfill-skipped|generation-kept] +// heap_token_kinds_check [--mutate kind-offset|typed-any-format|backfill-skipped|generation-kept| +// generation-kept-on-alloc-failure] // -// Each mutation changes an expectation to what a wrong implementation would give; every one must make the check fail. +// Each mutation changes an expectation (or, for the last one, the queue itself) to what a wrong implementation would +// give; every one must make the check fail. A mutated run that fails prints "mutation : caught" as its last line; +// an unknown name, a crash, or a mutation that is not caught prints no such line. +#define X2W_HEAP_TOKEN_PENDING_TEST_HOOKS // allocation failure injection in heap_token_pending.h (the CMake target sets it too) #include "startup_stubs/heap_token_kinds.h" #include "startup_stubs/heap_token_pending.h" @@ -15,7 +19,7 @@ namespace { using namespace x2w_startup; int failures, cases; -bool mutate_kind_offset, mutate_typed_any_format, mutate_backfill_skipped, mutate_generation_kept; +bool mutate_kind_offset, mutate_typed_any_format, mutate_backfill_skipped, mutate_generation_kept, mutate_keep_on_failure; void expect(bool ok, const char* what) { @@ -163,6 +167,94 @@ void pending() q.note_record(1000, true, true); expect(q.generation(1000) == 1 && q.generation(999) == 0, "a high id has a wrong generation"); expect(q.lost() == 0, "ids were lost without an allocation failure"); + expect(q.epoch_bumps() == 0 && q.take_failures() == 0, "an allocation failure was counted without one"); + } +} + +// Allocation failures (std::bad_alloc injected through the test hooks of heap_token_pending.h). +void pending_alloc_failures() +{ + using Q = HeapMirrorPending; + const auto all = [](std::uint32_t) { return true; }; + { + // S1: the generation of a reassigned id cannot be stored. The entry written for the old record must not look + // like the new record's: the generation has to change anyway, and the id is still queued for the new record. + Q q; + if (mutate_keep_on_failure) q.test_keep_generation_on_failure(); + q.start(0, all); + q.note_record(5, false, true); + const auto first = q.take(); + expect(first.size() == 1 && first[0].id == 5, "setup: id 5 was not queued"); + const std::uint32_t old_generation = first.empty() ? 0 : first[0].generation; + q.test_fail_nth(Q::site_generation, 1); + const bool queued = q.note_record(5, true, true); // id 5 taken again by another record; its count cannot grow + expect(queued && q.queued() == 1, "a failed generation allocation also lost the new record's queue entry"); + expect(q.generation(5) != old_generation, "a failed generation allocation left the old generation current"); + const auto second = q.take(); + expect(second.size() == 1 && second[0].generation != old_generation, + "the entry for the new record carries the generation of the old one"); + // Every other id's old entries are stale too (the epoch moved), which is safe: they are only rebuilt. + expect(q.epoch_bumps() == 1 && q.lost() == 0, "the failure was not answered by the epoch alone"); + } + { + // S1, second route: a reassignment that fails after the old record was cleared (note_view -> invalidate). + Q q; + q.start(0, all); + q.note_record(7, false, true); + q.note_record(8, false, true); + const auto handed_out = q.take(); + expect(handed_out.size() == 2, "setup: ids 7 and 8 were not queued"); + const std::uint32_t old7 = q.generation(7), old8 = q.generation(8); + q.invalidate(7); // no allocation failure: the count grows + expect(q.generation(7) != old7 && q.generation(8) == old8, "invalidate did not change exactly the id's generation"); + q.test_fail_nth(Q::site_generation, 1); + q.invalidate(900); // fails to store: the epoch answers for every id + expect(q.generation(7) != old7 && q.generation(8) != old8 && q.epoch_bumps() == 1, + "a failed invalidate left an old generation current"); + Q idle; // not started: nothing was queued, nothing to invalidate + idle.invalidate(3); + expect(idle.generation(3) == 0, "invalidate on a queue that was not started changed a generation"); + } + { + // take(eligible): an id whose record is no longer eligible is dropped, the others keep their order. + Q q; + q.start(0, all); + q.note_record(1, false, true); + q.note_record(2, false, true); + q.note_record(3, false, true); + const auto entries = q.take([](std::uint32_t id) { return id != 2; }); + expect(ids_of(entries) == Ids({1, 3}), "take(eligible) kept an id the predicate refused"); + expect(q.queued() == 0, "take(eligible) left an id queued"); + q.note_record(2, false, true); // dropped ids can be queued again + expect(ids_of(q.take()) == Ids({2}), "an id dropped by take(eligible) cannot be queued again"); + } + { + // A queue entry that cannot be allocated is counted and reported, and the id can be queued later. + Q q; + q.start(0, all); + q.test_fail_nth(Q::site_queue, 1); + expect(!q.note_record(3, false, true), "a failed queue allocation was reported as queued"); + expect(q.lost() == 1 && q.queued() == 0, "a failed queue allocation was not counted or left an entry"); + expect(q.note_record(3, false, true) && q.queued() == 1, "an id lost once cannot be queued again"); + q.test_fail_nth(Q::site_queue, 1); + expect(q.note_record(4, false, false) && q.lost() == 1, "an ineligible record reached the queue allocation"); + } + { + // Backfill: the second id cannot be queued; the first and third still are. + Q q; + q.test_fail_nth(Q::site_queue, 2); + q.start(3, all); + expect(ids_of(q.take()) == Ids({0, 2}) && q.lost() == 1, "a failed backfill entry lost more than that id"); + } + { + // take() cannot allocate its result: nothing is returned and nothing is lost; the next take() gets it all. + Q q; + q.start(0, all); + q.note_record(1, false, true); + q.note_record(2, false, true); + q.test_fail_nth(Q::site_take, 1); + expect(q.take().empty() && q.take_failures() == 1 && q.queued() == 2, "a failed take() lost queued ids"); + expect(ids_of(q.take()) == Ids({1, 2}), "the take() after a failed one did not return the ids in order"); } } @@ -175,12 +267,22 @@ int main(int argc, char** argv) mutate_typed_any_format = !std::strcmp(argv[2], "typed-any-format"); mutate_backfill_skipped = !std::strcmp(argv[2], "backfill-skipped"); mutate_generation_kept = !std::strcmp(argv[2], "generation-kept"); - if (!(mutate_kind_offset || mutate_typed_any_format || mutate_backfill_skipped || mutate_generation_kept)) return 2; + mutate_keep_on_failure = !std::strcmp(argv[2], "generation-kept-on-alloc-failure"); + if (!(mutate_kind_offset || mutate_typed_any_format || mutate_backfill_skipped || mutate_generation_kept || + mutate_keep_on_failure)) { + std::printf("unknown mutation %s\n", argv[2]); + return 2; + } } else if (argc != 1) { return 2; } kinds(); pending(); + pending_alloc_failures(); std::printf("%d of %d checks failed\n", failures, cases); + if (argc == 3) { + if (failures) std::printf("mutation %s: caught\n", argv[2]); + else std::printf("mutation %s: NOT caught\n", argv[2]); + } return failures ? 1 : 0; } From 0f61075025e483a20026f42d3ac4f0fd44686d1d Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 01:38:44 +0100 Subject: [PATCH 13/19] d3d12 runtime: heap token region, view heap alias and root flag (no descriptors yet) Draw heap: the top of the heap becomes a fixed region for heap view tokens, 65,536 mirror slots plus 5 typed nulls (1D, 2D, 2D array, raw, R32_UINT typed; written once at heap creation, only with X2W_D3D12_HEAP_TOKENS). The heap keeps 1 << 18 slots; the ring of per-draw and per-dispatch tables shrinks from 262,144 to 196,603 slots (draw_ring_size = draw_heap_size - 65,536 - 5), also without the opt-in. Both ring sites go through one reservation (modulus and wrap check), so the ring never writes a region slot. Alias: with the opt-in, every shader-visible CBV/SRV/UAV descriptor heap gets a heap from OpenExistingHeapFromAddress on its memory (era_gpu_alias, never the existing-heap cache of unplaced_memory_buffer) with a buffer placed over it; the raw SRV is FirstElement 0, NumElements = entries * 8, checked against the allocation. Memory that is not an allocation base, or a refused alias, gives no alias and heap token programs keep a named refusal ("heap tokens need a GPU-visible view heap"). No upload fallback. Root: adapter_lacks_directly_indexed_resource_heap (shader model 6.6, tier 3) with its own refusal texts; compute_root_flags ORs CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with the sampler flag for a program that reads heap tokens. Nothing sets that yet: the reader still refuses heaptok lines. Tests: heap_token_binding_check (ring, layout, nulls, alias view, root flags, refusal text; six mutation controls), resource-heap rows and a control in startup_translated_sampler_bindings, and the WARP fixture startup_compute_heap_token_check.py (layout, nulls, ring reservations, alias on VirtualAlloc memory and refusal for an interior pointer, refusal text). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 18 +- src/startup_stubs/d3d12_capture.inl | 2 + src/startup_stubs/d3d12_compute_dispatch.inl | 43 ++-- src/startup_stubs/d3d12_draw.inl | 28 ++- src/startup_stubs/d3d12_xs_device.cpp | 67 ++++++ src/startup_stubs/heap_token_alias.h | 110 ++++++++++ src/startup_stubs/heap_token_binding.h | 127 +++++++++++ .../translated_sampler_bindings.h | 13 +- tests/cmake/startup_present_log.cmake | 2 + tests/heap_token_binding_check.cpp | 197 ++++++++++++++++++ tests/startup_compute_heap_token_check.py | 110 +++++++++- ...rtup_translated_sampler_bindings_check.cpp | 34 ++- tools/startup/triage_run.py | 1 + 13 files changed, 708 insertions(+), 44 deletions(-) create mode 100644 src/startup_stubs/heap_token_alias.h create mode 100644 src/startup_stubs/heap_token_binding.h create mode 100644 tests/heap_token_binding_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 71ff151572..b49ca00909 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,7 +426,7 @@ target_compile_options(x2w_build_rev PRIVATE /Zl) # Desktop d3d12_xs.dll for the package DLLs' two named d3d12_xs root-signature imports. add_library(d3d12_xs_shim SHARED src/d3d12_xs_shim.cpp src/d3d12x_device_slots.cpp - src/d3d12_xs_iids.cpp src/d3d12_xs_shim.def src/startup_stubs/d3d12_xs_device.cpp) + src/d3d12_xs_iids.cpp src/d3d12_xs_shim.def src/startup_stubs/d3d12_xs_device.cpp src/era_gpu_alias.cpp) set_target_properties(d3d12_xs_shim PROPERTIES OUTPUT_NAME d3d12_xs) target_include_directories(d3d12_xs_shim PRIVATE src) target_compile_features(d3d12_xs_shim PRIVATE cxx_std_17) @@ -2399,6 +2399,9 @@ add_test(NAME startup_translated_sampler_bindings COMMAND startup_translated_sam add_test(NAME startup_translated_sampler_bindings_shared_axis_control COMMAND startup_translated_sampler_bindings_check --mutate shared-axis) set_tests_properties(startup_translated_sampler_bindings_shared_axis_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_translated_sampler_bindings_resource_text_control + COMMAND startup_translated_sampler_bindings_check --mutate resource-text) +set_tests_properties(startup_translated_sampler_bindings_resource_text_control PROPERTIES WILL_FAIL TRUE) # Real-draw decision for title root signatures that index descriptor heaps directly # (src/startup_stubs/heap_indexed_root.h), without a device. The mutated runs are the negative controls. # Limits of the slot 70 refusal and "token" null census (src/startup_stubs/memory_srv_census.h), without a device. @@ -2440,6 +2443,17 @@ foreach(mutation IN ITEMS kind-offset typed-any-format backfill-skipped generati set_tests_properties(heap_token_kinds_${mutation}_control PROPERTIES PASS_REGULAR_EXPRESSION "mutation ${mutation}: caught") endforeach() +# The draw heap's heap token region and ring, the typed nulls, the raw view over a title view heap, the root flags and the +# refusal text (src/startup_stubs/heap_token_binding.h), without a device. Each mutated run must fail. +add_executable(heap_token_binding_check tests/heap_token_binding_check.cpp) +target_include_directories(heap_token_binding_check PRIVATE src) +target_compile_features(heap_token_binding_check PRIVATE cxx_std_17) +add_test(NAME heap_token_binding COMMAND heap_token_binding_check) +foreach(mutation IN ITEMS ring-full-heap null-2da-as-2d alias-unchecked root-flag-dropped gate-alias-ignored region-overlap) + add_test(NAME heap_token_binding_${mutation}_control COMMAND heap_token_binding_check --mutate ${mutation}) + set_tests_properties(heap_token_binding_${mutation}_control PROPERTIES + PASS_REGULAR_EXPRESSION "mutation ${mutation}: caught") +endforeach() add_test(NAME startup_heap_indexed_root COMMAND startup_heap_indexed_root_check) foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) @@ -9596,7 +9610,7 @@ if(EXISTS "${INTAKE_PYTHON}") DEPENDS cpu_shim_startup tests/cpu/translate_shim_startup.py tools/cpu_switch_aot.py tools/cpu_call_aot.py tools/cpu_leaf_aot.py tools/cpu_ranges.py VERBATIM) add_library(cpu_placed_dxr_provider SHARED tests/cpu/placed_dxr_provider.cpp tests/dxr_check.cpp - tests/desktop_gpu.cpp src/era_title_va.cpp + tests/desktop_gpu.cpp src/era_title_va.cpp src/era_gpu_alias.cpp "${ray_header}" "${ray_table_header}" "${ray_pipeline_header}" "${candidates_header}" "${candidates_pipeline_header}") if(TARGET d3d12_xs_device_obj) target_sources(cpu_placed_dxr_provider PRIVATE $) diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 24cc0b5f20..38a62fb0ee 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -116,6 +116,8 @@ bool heap_tokens() // Ids that still need a heap token mirror descriptor (heap_token_pending.h); nothing creates one yet. Only with // heap_tokens(). Every member: note_lock held. x2w_startup::HeapMirrorPending& heap_mirror_pending() { static x2w_startup::HeapMirrorPending q; return q; } +// The GPU view of each shader-visible title view heap's memory (heap_token_alias.h); empty without heap_tokens(). +x2w_startup::HeapTokenAliases& heap_token_aliases() { static x2w_startup::HeapTokenAliases a; return a; } bool heap_mirror_eligible(std::uint32_t id) // a materialized shader resource view (note_lock held) { return id < view_records().size() && view_records()[id].slot == 18 && view_materialized()[id]; diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index dc7230218e..39e31e4e23 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -61,6 +61,7 @@ struct ComputeTranslation { std::vector uds, srvs, uavs; UINT heap_srvs = 0; UINT sampler_heap_bytes = 0; // `smpidx`: the program reads the title's sampler heap (directly indexed) up to this byte + bool heap_token_views = false; // heaptok lines: the program reads the view heap directly indexed (set by a later commit) x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; @@ -265,15 +266,25 @@ bool adapter_lacks_directly_indexed_sampler_heap() options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3); } +// The directly indexed resource heap (D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, which a heap token +// program takes) has the same requirement as the sampler heap: shader model 6.6 and resource binding tier 3. It is its own +// check because it has its own refusal text, and a device with no startup device yet is not taken for lacking it. +bool adapter_lacks_directly_indexed_resource_heap() +{ + return the_device && adapter_lacks_directly_indexed_sampler_heap(); +} + // Why a translated compute program with heap token words or views (heaptok lines) cannot run. One text for the manifest -// reader and the native-only route, so triage reads the same reason on both. Three cases: the opt-in -// X2W_D3D12_HEAP_TOKENS is off (today's text); it is on together with X2W_D3D12_VIEW_CONTENT_TOKENS (the tokens would -// name content, not view ids); it is on alone (the runtime does not bind the views yet). +// reader and the native-only route, so triage reads the same reason on both (heap_token_gate_text, in the order the +// causes are checked): the opt-in X2W_D3D12_HEAP_TOKENS is off (today's text); it is on together with +// X2W_D3D12_VIEW_CONTENT_TOKENS (the tokens would name content, not view ids); the adapter lacks the directly indexed +// resource heap; no shader-visible view heap has a GPU alias of its memory (heap_token_alias.h); or all hold and the +// runtime does not bind the views yet. const char* heap_token_refusal() { - if (!heap_tokens()) return "heap token textures are not bound yet"; - if (view_content_tokens()) return "heap tokens need id tokens"; - return "heap tokens are not bound yet (runtime binding in progress)"; + return x2w_startup::heap_token_gate_text(heap_tokens(), view_content_tokens(), + heap_tokens() && !view_content_tokens() && adapter_lacks_directly_indexed_resource_heap(), + heap_token_aliases().any()); } // The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is @@ -286,14 +297,18 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st for (UINT i = 0; i < tr.uavs.size(); ++i) if (tr.uavs[i].atomic) atomic_registers.push_back(i); bool serialized = false; + // A program that reads heap tokens indexes the list's view heap directly (the region of the draw heap). No translation + // sets heap_token_views yet: the reader still refuses the heaptok lines. + const bool token_views = tr.heap_token_views && heap_tokens(); if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), false, tr.heap_srvs, static_cast(atomic_registers.size()), atomic_registers.data(), - tr.sampler_heap_bytes ? D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE, - &serialized))) - return x2w_startup::compute_root_refusal(tr.sampler_heap_bytes != 0, serialized, - tr.sampler_heap_bytes != 0 && serialized && - adapter_lacks_directly_indexed_sampler_heap()); + x2w_startup::compute_root_flags(tr.sampler_heap_bytes != 0, token_views), &serialized))) { + const bool lacks = serialized && (tr.sampler_heap_bytes != 0 || token_views) && + (tr.sampler_heap_bytes != 0 ? adapter_lacks_directly_indexed_sampler_heap() + : adapter_lacks_directly_indexed_resource_heap()); + return x2w_startup::compute_root_refusal(tr.sampler_heap_bytes != 0, token_views, serialized, lacks); + } D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root.Get(); desc.CS = {code, bytes}; @@ -1423,11 +1438,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& return reason; } const UINT n = static_cast(count + tr->heap_srvs); - UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; - if (first + n > draw_heap_size) { - first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast(n)); - } + const UINT first = draw_ring_reserve(n); D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 00c04492d5..bc53c1422a 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1703,12 +1703,20 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P return pipeline; } -// Private shader-visible heap for the translated draws' tables, used as a ring. +// Private shader-visible heap for the translated draws' tables, used as a ring. The top of the heap is a fixed region for +// heap view tokens (heap_token_binding.h): the mirror slots and five typed nulls. The ring is the rest, draw_ring_size +// slots, and never writes the region; the heap itself keeps draw_heap_size. Without X2W_D3D12_HEAP_TOKENS the region +// stays unwritten (only the ring is smaller than the heap, by heap_token_region_slots). constexpr UINT draw_heap_size = 1u << 18; +constexpr UINT draw_ring_size = x2w_startup::heap_token_ring_size(draw_heap_size); ID3D12DescriptorHeap* draw_heap; Wrapper* draw_heap_device; UINT draw_heap_increment; volatile LONG draw_heap_cursor; +UINT draw_region_nulls_written; // the typed nulls written into the region when the heap was created (fixture probe) + +// The first of n consecutive ring slots, for the table of a draw or a dispatch. Both users go through here. +UINT draw_ring_reserve(UINT n) { return x2w_startup::heap_token_ring_reserve(&draw_heap_cursor, n, draw_ring_size); } bool ensure_draw_heap(Wrapper* device) { @@ -1720,6 +1728,18 @@ bool ensure_draw_heap(Wrapper* device) if (FAILED(device_of(the_device)->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&draw_heap)))) return false; draw_heap_device = device; draw_heap_increment = device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (heap_tokens()) { + // Written once; the ring never touches them. A heap token program reads the null of the dimension it declares for an + // id that names no view of that dimension. + for (UINT which = 0; which < x2w_startup::heap_token_null_slots; ++which) { + const auto null = static_cast(which); + const D3D12_SHADER_RESOURCE_VIEW_DESC null_desc = x2w_startup::heap_token_null_desc(null); + device_of(the_device)->CreateShaderResourceView(nullptr, &null_desc, + D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + + std::size_t{x2w_startup::heap_token_null_slot(draw_heap_size, null)} * draw_heap_increment}); + ++draw_region_nulls_written; + } + } return true; } @@ -3519,11 +3539,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } const UINT n = static_cast(tr->srvs.size()); const UINT views = n + static_cast(tr->uavs.size()); // the SRVs, then the UAVs, in one table - UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(views))) % draw_heap_size; - if (first + views > draw_heap_size) { - first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast(views)); - } + const UINT first = draw_ring_reserve(views); std::uint32_t strides[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index be55c92d58..a68efcc3d2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -40,6 +40,8 @@ #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/heap_token_kinds.h" #include "startup_stubs/heap_token_pending.h" +#include "startup_stubs/heap_token_binding.h" +#include "startup_stubs/heap_token_alias.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" #include "startup_stubs/list_dispatch.h" @@ -5696,8 +5698,22 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR heap->Release(); return E_OUTOFMEMORY; } + // Heap tokens (X2W_D3D12_HEAP_TOKENS): the GPU reads the 32-byte records of a shader-visible view heap through an alias + // of its memory (heap_token_alias.h). A heap that cannot be aliased is not an error for the title; heap token programs + // are refused by name while no view heap has an alias (heap_token_refusal). + const bool token_alias = heap_tokens() && title_memory && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && + (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + if (token_alias) { + const HRESULT alias_hr = heap_token_aliases().open(device_of(self), title_memory, bytes, desc->NumDescriptors); + static LONG alias_logs; + if (first_calls(alias_logs, 8)) + log("x2w-d3d12 Device::CreateDescriptorHeap: heap token alias of 0x%llx (%llu bytes) -> 0x%08lx", title_memory, bytes, + static_cast(alias_hr)); + } Wrapper* w = wrap(heap, descriptor_heap_kind); if (!w) { + // The alias holds the heap and buffer over the memory: release both before the memory is freed. + if (token_alias) heap_token_aliases().release(title_memory); if (title_memory != supplied_memory) VirtualFree(reinterpret_cast(title_memory), 0, MEM_RELEASE); heap->Release(); return E_OUTOFMEMORY; @@ -7250,6 +7266,57 @@ extern "C" __declspec(dllexport) void x2w_d3d12_heap_mirror_queue(unsigned long ReleaseSRWLockShared(¬e_lock); } +// Fixture exports (startup_compute_heap_token): the heap token region of the translated draw heap and its ring, and the +// GPU alias of a title view heap's memory. +// Layout: draw heap slots, ring slots, mirror capacity, null slots. +extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_layout(UINT* out) +{ + out[0] = draw_heap_size; + out[1] = draw_ring_size; + out[2] = x2w_startup::heap_token_mirror_capacity; + out[3] = x2w_startup::heap_token_null_slots; +} +// Creates the draw heap of `table` (a device) when it does not exist yet; the number of typed nulls the region holds, or +// ~0u when the heap cannot be created. +extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_token_draw_heap(void* table) +{ + return ensure_draw_heap(as_wrapper(table)) ? draw_region_nulls_written : ~0u; +} +// The first slot of the next n-slot reservation of the ring, the one the draws and dispatches take; the cursor is first +// set to `cursor` when `set` is nonzero. +extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_token_ring(UINT n, int set, LONG cursor) +{ + if (set) InterlockedExchange(&draw_heap_cursor, cursor); + return draw_ring_reserve(n); +} +struct HeapTokenAliasProbe { + unsigned found, entries, num_elements, alias_any, alias_failed, lacks_resource_heap, pad; + unsigned long long bytes, buffer_bytes, heap_bytes; +}; +// The alias of the title view heap memory at `memory`: whether there is one, what it covers, and the global state the +// reader's refusal text depends on. +extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_alias(UINT64 memory, HeapTokenAliasProbe* out) +{ + *out = {}; + x2w_startup::HeapTokenAlias alias; + if (heap_token_aliases().find(memory, alias)) { + out->found = 1; + out->entries = alias.entries; + out->num_elements = alias.num_elements; + out->bytes = alias.bytes; + out->buffer_bytes = alias.alias.buffer ? alias.alias.buffer->GetDesc().Width : 0; + out->heap_bytes = alias.alias.heap ? alias.alias.heap->GetDesc().SizeInBytes : 0; + } + out->alias_any = heap_token_aliases().any(); + out->alias_failed = heap_token_aliases().failed(); + out->lacks_resource_heap = adapter_lacks_directly_indexed_resource_heap(); +} +// The reason a program with heaptok lines is refused now (heap_token_refusal, the text the manifest reader gives). +extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_refusal(char* out, UINT size) +{ + if (size) std::snprintf(out, size, "%s", heap_token_refusal()); +} + // 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) { diff --git a/src/startup_stubs/heap_token_alias.h b/src/startup_stubs/heap_token_alias.h new file mode 100644 index 0000000000..e5d0424bab --- /dev/null +++ b/src/startup_stubs/heap_token_alias.h @@ -0,0 +1,110 @@ +// The GPU view of a title view heap's memory for heap tokens (X2W_D3D12_HEAP_TOKENS): one heap per shader-visible +// CBV/SRV/UAV descriptor heap from OpenExistingHeapFromAddress on the allocation base (era_gpu_alias), with a buffer +// placed over it. A raw SRV of that buffer (heap_token_alias_srv_desc, written by a later commit) lets a shader read +// the 32-byte records the title memory holds, with no copy. Never the existing-heap cache of unplaced_memory_buffer, never +// an upload fallback: memory that is not an allocation base, or a device that refuses, gives no alias and the heap +// token programs are refused ("heap tokens need a GPU-visible view heap"). +#pragma once + +#include "era_gpu_alias.h" +#include "startup_stubs/heap_token_binding.h" + +#include +#include +#include + +namespace x2w_startup { + +struct HeapTokenAlias { + std::uint64_t memory = 0; // the title memory (allocation base) + std::uint64_t bytes = 0; // the span the alias covers + UINT entries = 0; // title descriptors the heap holds + UINT num_elements = 0; // entries * 8: the NumElements of the raw SRV + era_gpu_alias::Alias alias; +}; + +class HeapTokenAliases { +public: + // Opens the alias of [memory, memory + bytes) for a heap of `entries` descriptors. S_OK, or why not: E_INVALIDARG for + // a span that does not hold the records or memory that is not an allocation base, E_NOTIMPL when the device has no + // existing heaps, E_OUTOFMEMORY, or the failing D3D12 result. A failure is counted. + HRESULT open(ID3D12Device* device, std::uint64_t memory, std::uint64_t bytes, UINT entries) + { + HRESULT hr = open_unlocked(device, memory, bytes, entries); + AcquireSRWLockExclusive(&lock_); + if (FAILED(hr)) ++failed_; + ReleaseSRWLockExclusive(&lock_); + return hr; + } + // Drops the alias of `memory` (the buffer, then the heap). Callers do this before the memory is freed. + void release(std::uint64_t memory) + { + era_gpu_alias::Alias dropped; // released outside the lock + AcquireSRWLockExclusive(&lock_); + for (std::size_t i = 0; i < aliases_.size(); ++i) + if (aliases_[i].memory == memory) { + dropped = std::move(aliases_[i].alias); + aliases_.erase(aliases_.begin() + static_cast(i)); + break; + } + ReleaseSRWLockExclusive(&lock_); + dropped.buffer.Reset(); + dropped.heap.Reset(); + } + bool any() const + { + AcquireSRWLockShared(&lock_); + const bool result = !aliases_.empty(); + ReleaseSRWLockShared(&lock_); + return result; + } + unsigned failed() const + { + AcquireSRWLockShared(&lock_); + const unsigned result = failed_; + ReleaseSRWLockShared(&lock_); + return result; + } + // Copy of the entry for `memory`; false when there is none. + bool find(std::uint64_t memory, HeapTokenAlias& out) const + { + bool found = false; + AcquireSRWLockShared(&lock_); + for (const HeapTokenAlias& a : aliases_) + if (a.memory == memory) { + out = a; + found = true; + break; + } + ReleaseSRWLockShared(&lock_); + return found; + } + +private: + HRESULT open_unlocked(ID3D12Device* device, std::uint64_t memory, std::uint64_t bytes, UINT entries) + { + if (!device || !memory || !heap_token_alias_fits(entries, bytes)) return E_INVALIDARG; + HeapTokenAlias entry; + entry.memory = memory; + entry.bytes = bytes; + entry.entries = entries; + entry.num_elements = entries * heap_token_record_dwords; + const HRESULT hr = era_gpu_alias::open(device, reinterpret_cast(static_cast(memory)), bytes, entry.alias); + if (FAILED(hr)) return hr; + bool stored = true; + AcquireSRWLockExclusive(&lock_); + try { + aliases_.push_back(std::move(entry)); + } catch (const std::bad_alloc&) { + stored = false; + } + ReleaseSRWLockExclusive(&lock_); + return stored ? S_OK : E_OUTOFMEMORY; // a failed push leaves the entry (and its alias) to be released here + } + + mutable SRWLOCK lock_ = SRWLOCK_INIT; + std::vector aliases_; + unsigned failed_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/heap_token_binding.h b/src/startup_stubs/heap_token_binding.h new file mode 100644 index 0000000000..12df7e66da --- /dev/null +++ b/src/startup_stubs/heap_token_binding.h @@ -0,0 +1,127 @@ +// What the runtime binding of heap view tokens (X2W_D3D12_HEAP_TOKENS) fixes without a device: the region at the top of the +// translated draw heap, the ring below it, the raw view over a title view heap, the root flag, and the refusal text. +// Checked by tests/heap_token_binding_check.cpp. +// +// Draw heap layout (draw_heap_size slots, shader visible, one ring of per-dispatch tables plus the fixed region): +// +// [0, ring) the ring: per-draw and per-dispatch view tables, written by the draws and dispatches +// [ring, ring + capacity) the mirror: one slot per view record id (written by a later commit) +// [ring + capacity, heap) five typed null descriptors, written once when the heap is created +// +// The ring never writes the region: its modulus and its wrap check both use ring_size(heap), and a reservation that +// would leave the ring starts at slot 0. +#pragma once + +#include + +#include + +namespace x2w_startup { + +constexpr UINT heap_token_mirror_capacity = 65536; // view record ids the mirror can name +constexpr UINT heap_token_null_slots = 5; +constexpr UINT heap_token_region_slots = heap_token_mirror_capacity + heap_token_null_slots; + +// The five nulls, in the order of the translator's per-dimension null words (null1d, null2d, null2da), then the raw buffer +// and the R32_UINT typed buffer (reserved for #3619). +enum HeapTokenNull : UINT { null_1d, null_2d, null_2da, null_raw, null_typed_uint }; + +constexpr UINT heap_token_ring_size(UINT heap_slots) { return heap_slots - heap_token_region_slots; } +constexpr UINT heap_token_mirror_slot(UINT heap_slots, UINT id) { return heap_token_ring_size(heap_slots) + id; } +constexpr UINT heap_token_null_slot(UINT heap_slots, HeapTokenNull which) +{ + return heap_token_ring_size(heap_slots) + heap_token_mirror_capacity + which; +} + +// Reserves n consecutive ring slots and returns the first. `cursor` only grows (it wraps through 32 bits, which the +// modulus survives); a reservation that does not fit before the end of the ring starts again at 0. +inline UINT heap_token_ring_reserve(volatile LONG* cursor, UINT n, UINT ring_size) +{ + UINT first = static_cast(InterlockedExchangeAdd(cursor, static_cast(n))) % ring_size; + if (first + n > ring_size) { + first = 0; + InterlockedExchange(cursor, static_cast(n)); + } + return first; +} + +// The typed null of a kind: a null resource reads no more of the description than its format and dimension. +inline D3D12_SHADER_RESOURCE_VIEW_DESC heap_token_null_desc(HeapTokenNull which) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + switch (which) { + case null_1d: + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + desc.Texture1D.MipLevels = 1; + break; + case null_2d: + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipLevels = 1; + break; + case null_2da: + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + desc.Texture2DArray.MipLevels = 1; + desc.Texture2DArray.ArraySize = 1; + break; + case null_raw: + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Buffer.NumElements = 1; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + break; + case null_typed_uint: + desc.Format = DXGI_FORMAT_R32_UINT; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Buffer.NumElements = 1; + break; + } + return desc; +} + +// The title view heap is read as raw dwords: one 32-byte record (8 dwords) per entry, from the allocation base. +constexpr UINT heap_token_record_dwords = 8; +constexpr std::uint64_t heap_token_record_bytes = heap_token_record_dwords * 4; + +// Whether `entries` records fit in an allocation of `bytes` (NumElements * 4 <= bytes, without overflow). +inline bool heap_token_alias_fits(std::uint64_t entries, std::uint64_t bytes) +{ + return entries != 0 && entries <= 0xffffffffull / heap_token_record_dwords && + entries * heap_token_record_bytes <= bytes; +} + +// The raw SRV over the alias buffer: FirstElement 0 (the alias starts at the allocation base), NumElements = entries * 8. +inline D3D12_SHADER_RESOURCE_VIEW_DESC heap_token_alias_srv_desc(UINT entries) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = 0; + desc.Buffer.NumElements = entries * heap_token_record_dwords; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return desc; +} + +// Root signature flags of a compute program: the directly indexed sampler heap, and the directly indexed resource heap +// of a program that reads heap tokens (when the runtime may bind them). +inline D3D12_ROOT_SIGNATURE_FLAGS compute_root_flags(bool sampler_heap, bool heap_tokens_bound) +{ + return static_cast( + (sampler_heap ? D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE) | + (heap_tokens_bound ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE)); +} + +// Why a translated compute program with heap token lines cannot run, in the order the causes are checked. One text for +// the manifest reader and the native-only route. +inline const char* heap_token_gate_text(bool opt_in, bool content_tokens, bool lacks_resource_heap, bool view_heap_alias) +{ + if (!opt_in) return "heap token textures are not bound yet"; + if (content_tokens) return "heap tokens need id tokens"; + if (lacks_resource_heap) return "heap tokens need a directly indexed resource heap"; + if (!view_heap_alias) return "heap tokens need a GPU-visible view heap"; + return "heap tokens are not bound yet (runtime binding in progress)"; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 66df064f68..0ac933af36 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -179,12 +179,15 @@ inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT // device refused a root that serialized and takes SAMPLER_HEAP_DIRECTLY_INDEXED, on an adapter that lacks what the // flag needs (shader model 6.6 and resource binding tier 3, as tests/native_sampler_heap.cpp requires). That is an // inference from the adapter's reported capabilities, not proof of the driver's reason: CreateRootSignature gives no -// finer cause. Both texts are fixed triage reasons. -inline const char* compute_root_refusal(bool directly_indexed_sampler_heap, bool serialized, bool adapter_lacks_capability) +// finer cause. A root that takes CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED (a heap token program) gets its own text on the same +// terms; a root with both flags names the sampler heap. All texts are fixed triage reasons. +inline const char* compute_root_refusal(bool directly_indexed_sampler_heap, bool directly_indexed_resource_heap, + bool serialized, bool adapter_lacks_capability) { - return directly_indexed_sampler_heap && serialized && adapter_lacks_capability - ? "the device does not take a directly indexed sampler heap" - : "root signature creation failed"; + if (!serialized || !adapter_lacks_capability) return "root signature creation failed"; + if (directly_indexed_sampler_heap) return "the device does not take a directly indexed sampler heap"; + if (directly_indexed_resource_heap) return "the device does not take a directly indexed resource heap"; + return "root signature creation failed"; } struct SamplerSource { diff --git a/tests/cmake/startup_present_log.cmake b/tests/cmake/startup_present_log.cmake index 7c50643534..56fc31ebe1 100644 --- a/tests/cmake/startup_present_log.cmake +++ b/tests/cmake/startup_present_log.cmake @@ -9,6 +9,8 @@ if(NOT OFFSCREEN_AGILITY_620_DIR) else() target_sources(startup_present_log PRIVATE src/startup_stubs/d3d12_xs_device.cpp) endif() +# d3d12_xs_device.cpp opens the GPU alias of a title view heap (heap tokens) through era_gpu_alias. +target_sources(startup_present_log PRIVATE src/era_gpu_alias.cpp) target_link_libraries(startup_present_log PRIVATE d3d12 dxgi dxguid d3dcompiler user32 gdi32 x2w_build_rev) add_test(NAME startup_present_log COMMAND startup_present_log) # The control reads a five-line budget, one more than the code produces, and must print FAIL. diff --git a/tests/heap_token_binding_check.cpp b/tests/heap_token_binding_check.cpp new file mode 100644 index 0000000000..5c95fdf48c --- /dev/null +++ b/tests/heap_token_binding_check.cpp @@ -0,0 +1,197 @@ +// Checks src/startup_stubs/heap_token_binding.h without a device: the region at the top of the translated draw heap and the +// ring below it, the typed nulls, the raw view over a title view heap, the root flags and the refusal text of a heap token +// program. +// +// heap_token_binding_check [--mutate ring-full-heap|null-2da-as-2d|alias-unchecked|root-flag-dropped|gate-alias-ignored| +// region-overlap] +// +// Each mutation makes the check compute with what a wrong implementation would use (the ring over the whole heap, a 2D +// null for the 2D array, no size check, the root flag left out, the missing alias ignored, a mirror that starts inside +// the ring); every one must make the check fail. A mutated run that fails prints "mutation : caught" as its last +// line; an unknown name, a crash, or a mutation that is not caught prints no such line. +#include "startup_stubs/heap_token_binding.h" + +#include +#include +#include + +namespace { +using namespace x2w_startup; +int failures, cases; +bool m_ring_full_heap, m_null_2da_as_2d, m_alias_unchecked, m_root_flag_dropped, m_gate_alias_ignored, m_region_overlap; + +constexpr UINT heap = 1u << 18; // draw_heap_size + +void expect(bool ok, const char* what) +{ + ++cases; + if (ok) return; + ++failures; + std::printf("FAIL: %s\n", what); +} + +// The ring: no reservation reaches the region, whatever the sizes and wherever the cursor starts (including a cursor that +// has wrapped through 32 bits). +void ring() +{ + constexpr UINT expected_ring = (1u << 18) - 65536 - 5; + expect(heap_token_region_slots == 65541 && heap_token_mirror_capacity == 65536 && heap_token_null_slots == 5, + "the region is not 65,536 mirror slots plus 5 nulls"); + expect(heap_token_ring_size(heap) == expected_ring && expected_ring == 196603, "the ring is not 196,603 slots"); + const UINT ring_size = m_ring_full_heap ? heap : heap_token_ring_size(heap); + const UINT region_start = heap_token_ring_size(heap); + + const UINT sizes[] = {1, 2, 5, 7, 64, 1000, 1024, 1100, 4096}; + for (const LONG start : {LONG{0}, LONG{196000}, LONG{0x7fffff00}, LONG{-300}, static_cast(0x80000000u)}) { + volatile LONG cursor = start; + UINT highest = 0, wraps = 0, previous_first = 0; + bool inside = true, touched_region = false; + for (int i = 0; i < 20000; ++i) { + const UINT n = sizes[(i * 7 + i / 3) % (sizeof(sizes) / sizeof(sizes[0]))]; + const UINT first = heap_token_ring_reserve(&cursor, n, ring_size); + inside = inside && first + n <= ring_size; + touched_region = touched_region || first + n > region_start; // a slot at or above the region's first + if (first + n > highest) highest = first + n; + if (i && first < previous_first) ++wraps; + previous_first = first; + } + expect(inside, "a reservation left the ring"); + expect(!touched_region, "a ring reservation reached the region"); + expect(highest <= region_start, "the highest ring slot is inside the region"); + expect(wraps > 5, "the ring never wrapped in the test run"); + expect(highest > region_start - 4096, "the ring does not use its top (the check may be too weak)"); + } +} + +// Region slots: after the ring, the mirror then the nulls, nothing outside the heap, nothing twice. +void layout() +{ + const UINT ring_size = heap_token_ring_size(heap); + const UINT mirror_first = heap_token_mirror_slot(heap, 0) - (m_region_overlap ? 1 : 0); + expect(mirror_first == ring_size, "the mirror does not start where the ring ends"); + expect(heap_token_mirror_slot(heap, heap_token_mirror_capacity - 1) + 1 == heap_token_null_slot(heap, null_1d), + "the nulls do not follow the last mirror slot"); + UINT previous = 0; + for (UINT which = 0; which < heap_token_null_slots; ++which) { + const UINT slot = heap_token_null_slot(heap, static_cast(which)); + expect(which == 0 || slot == previous + 1, "the nulls are not consecutive"); + expect(slot < heap, "a null is outside the heap"); + previous = slot; + } + expect(previous == heap - 1, "the last null is not the last slot of the heap"); + expect(heap_token_mirror_slot(heap, heap_token_mirror_capacity - 1) < heap, "the last mirror slot is outside the heap"); +} + +void nulls() +{ + const auto d1 = heap_token_null_desc(null_1d); + const auto d2 = heap_token_null_desc(null_2d); + const auto da = heap_token_null_desc(m_null_2da_as_2d ? null_2d : null_2da); // a table that has no 2D array null + const auto raw = heap_token_null_desc(null_raw); + const auto typed = heap_token_null_desc(null_typed_uint); + expect(d1.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D && d1.Texture1D.MipLevels == 1, "the 1D null is not a 1D texture view"); + expect(d2.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && d2.Texture2D.MipLevels == 1, "the 2D null is not a 2D texture view"); + expect(da.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY, "the 2D array null is not a 2D array texture view"); + expect(da.Texture2DArray.ArraySize == 1 && da.Texture2DArray.MipLevels == 1, "the 2D array null has no array size"); + expect(raw.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && raw.Format == DXGI_FORMAT_R32_TYPELESS && + (raw.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) && raw.Buffer.NumElements == 1, + "the raw null is not a raw buffer view"); + expect(typed.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && typed.Format == DXGI_FORMAT_R32_UINT && + !(typed.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW), + "the typed null is not an R32_UINT buffer view"); + for (const auto& d : {d1, d2, da, raw, typed}) + expect(d.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, "a null has a component mapping other than the default"); +} + +// The raw view over the title view heap: 8 dwords per entry, checked against the allocation. +void alias() +{ + expect(heap_token_record_bytes == 32, "a record is not 32 bytes"); + const auto srv = heap_token_alias_srv_desc(256); + expect(srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && srv.Format == DXGI_FORMAT_R32_TYPELESS && + srv.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW && srv.Buffer.FirstElement == 0 && srv.Buffer.NumElements == 256 * 8 && + srv.Buffer.StructureByteStride == 0, + "the alias view is not a raw buffer view of entries * 8 dwords from element 0"); + // NumElements * 4 <= bytes. + expect(heap_token_alias_fits(256, 256 * 32), "an exactly fitting heap is refused"); + expect(heap_token_alias_fits(256, 256 * 32 + 4096), "a heap with room to spare is refused"); + // --mutate alias-unchecked: an implementation that does not compare NumElements * 4 with the allocation. + const auto fits = [](std::uint64_t entries, std::uint64_t bytes) { return m_alias_unchecked ? entries != 0 : heap_token_alias_fits(entries, bytes); }; + expect(!fits(256, 256 * 32 - 1), "a heap one byte short is taken"); + expect(!fits(256, 256 * 16), "a 16-byte stride heap is taken for 32-byte records"); + expect(!heap_token_alias_fits(0, 4096), "a heap of no entries is taken"); + expect(!heap_token_alias_fits(0x20000000ull, ~0ull), "entries whose dword count overflows 32 bits are taken"); +} + +void root_flags() +{ + constexpr UINT sampler = D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, view = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + expect(sampler == 0x800 && view == 0x400, "the flag values changed"); + const bool tokens = !m_root_flag_dropped; + expect(compute_root_flags(false, false) == 0, "a root with neither heap has flags"); + expect(compute_root_flags(true, false) == sampler, "the sampler flag alone is not the sampler flag"); + expect(compute_root_flags(false, tokens) == view, "a heap token program's root lacks the view heap flag"); + expect(compute_root_flags(true, tokens) == (sampler | view), "the two flags are not ORed"); +} + +void gate() +{ + const char* off = "heap token textures are not bound yet"; + const char* content = "heap tokens need id tokens"; + const char* capability = "heap tokens need a directly indexed resource heap"; + const char* no_heap = "heap tokens need a GPU-visible view heap"; + const char* in_progress = "heap tokens are not bound yet (runtime binding in progress)"; + struct Row { const char* name; bool opt_in, content, lacks, alias; const char* want; }; + const Row rows[] = { + {"opt-in off", false, false, false, false, off}, + {"opt-in off, everything else wrong", false, true, true, false, off}, + {"content tokens", true, true, false, true, content}, + {"content tokens beat the capability", true, true, true, false, content}, + {"adapter lacks the resource heap", true, false, true, true, capability}, + {"capability is checked before the alias", true, false, true, false, capability}, + {"no GPU-visible view heap", true, false, false, false, no_heap}, + {"everything holds", true, false, false, true, in_progress}, + }; + for (const Row& r : rows) { + const bool alias = m_gate_alias_ignored ? true : r.alias; + const char* got = heap_token_gate_text(r.opt_in, r.content, r.lacks, alias); + ++cases; + if (std::strcmp(got, r.want)) { + ++failures; + std::printf("FAIL gate %s: \"%s\", expected \"%s\"\n", r.name, got, r.want); + } + } +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { + m_ring_full_heap = !std::strcmp(argv[2], "ring-full-heap"); + m_null_2da_as_2d = !std::strcmp(argv[2], "null-2da-as-2d"); + m_alias_unchecked = !std::strcmp(argv[2], "alias-unchecked"); + m_root_flag_dropped = !std::strcmp(argv[2], "root-flag-dropped"); + m_gate_alias_ignored = !std::strcmp(argv[2], "gate-alias-ignored"); + m_region_overlap = !std::strcmp(argv[2], "region-overlap"); + if (!(m_ring_full_heap || m_null_2da_as_2d || m_alias_unchecked || m_root_flag_dropped || m_gate_alias_ignored || + m_region_overlap)) { + std::printf("unknown mutation %s\n", argv[2]); + return 2; + } + } else if (argc != 1) { + return 2; + } + ring(); + layout(); + nulls(); + alias(); + root_flags(); + gate(); + std::printf("%d of %d checks failed\n", failures, cases); + if (argc == 3) { + if (failures) std::printf("mutation %s: caught\n", argv[2]); + else std::printf("mutation %s: NOT caught\n", argv[2]); + } + return failures ? 1 : 0; +} diff --git a/tests/startup_compute_heap_token_check.py b/tests/startup_compute_heap_token_check.py index 7e75f24fc4..2faeebe308 100644 --- a/tests/startup_compute_heap_token_check.py +++ b/tests/startup_compute_heap_token_check.py @@ -14,9 +14,18 @@ records exist (the control). 4. Controls: a descriptor nothing was written to resolves to no record; the export refuses a missing device, resource or description. - -Not checked here (later commits): descriptors in the draw heap, the kinds table, any dispatch, texels or raw words read -through a token, the miss counter, lifetime and states, hardware adapters. +5. The draw heap region (x2w_d3d12_heap_token_layout, _draw_heap, _ring): the heap keeps 1 << 18 slots, the ring is + 196,603 of them (65,536 mirror slots and 5 nulls above), the five typed nulls are written when the heap is created + (with the switch on only), and no reservation of the ring, wherever its cursor starts, reaches the region. +6. The GPU alias of a title view heap (x2w_d3d12_heap_token_alias): a shader-visible view heap over a VirtualAlloc + allocation gets an alias heap and buffer over all its memory (NumElements = entries * 8 raw dwords); title memory + that is not an allocation base gets none and is counted as a failure; a heap that is not shader visible gets none. + The refusal a heap token program gets (x2w_d3d12_heap_token_refusal) follows: "heap tokens need a GPU-visible view + heap" while no view heap has an alias, then the transitional text once one has (or the capability text when the + adapter lacks the directly indexed resource heap). With the switch off no alias is made and the text is the old one. + +Not checked here (later commits): descriptors per record in the draw heap, the kinds table, any dispatch, texels or raw +words read through a token, the miss counter, lifetime and states, hardware adapters. """ import ctypes import os @@ -206,6 +215,99 @@ def committed(dimension, width, height, fmt, layout): fails.expect(resolve(None, handle(3)).known == 0, 'a refused create_srv left a record') fails.expect(queue() - queued_before == queued, 'a refused create_srv queued an id') + on = switch == 'on' + # 5. The draw heap region and its ring. + layout = (ctypes.c_uint * 4)() + xs.x2w_d3d12_heap_token_layout(layout) + fails.expect(list(layout) == [1 << 18, (1 << 18) - 65536 - 5, 65536, 5], + 'layout (heap, ring, mirror, nulls) is %s' % list(layout)) + ring_size = (1 << 18) - 65536 - 5 # not read back from the export: the reservations below must keep to it + xs.x2w_d3d12_heap_token_draw_heap.restype = ctypes.c_uint + xs.x2w_d3d12_heap_token_draw_heap.argtypes = [ctypes.c_void_p] + nulls = xs.x2w_d3d12_heap_token_draw_heap(device) + fails.expect(nulls == (5 if on else 0), 'the draw heap holds %d typed nulls, expected %d' % (nulls, 5 if on else 0)) + fails.expect(xs.x2w_d3d12_heap_token_draw_heap(device) == nulls, 'a second call changed the number of nulls (written twice?)') + xs.x2w_d3d12_heap_token_ring.restype = ctypes.c_uint + xs.x2w_d3d12_heap_token_ring.argtypes = [ctypes.c_uint, ctypes.c_int, ctypes.c_long] + # A reservation that does not fit before the end of the ring starts again at slot 0 (the old modulus, the whole + # heap, gave 196600 here and reached the region). + first = xs.x2w_d3d12_heap_token_ring(5, 1, ring_size - 3) + fails.expect(first == 0, 'a reservation of 5 slots 3 below the end of the ring starts at %d, not 0' % first) + top = 0 + for start in (0, ring_size - 7, 0x7fffff00, -300, -0x80000000): + first = xs.x2w_d3d12_heap_token_ring(1, 1, start) + for step in range(30000): + n = (1, 2, 5, 7, 64, 1000, 1100)[(step * 7 + step // 3) % 7] + first = xs.x2w_d3d12_heap_token_ring(n, 0, 0) + top = max(top, first + n) + if first + n > ring_size: + fails.expect(False, 'ring reservation [%d, %d) leaves the ring (%d slots)' % (first, first + n, ring_size)) + break + fails.expect(top > ring_size - 4096, 'the ring never came near its top (%d of %d): the check is too weak' % (top, ring_size)) + + # 6. The GPU alias of title view heap memory, and the refusal that follows. + xs.x2w_d3d12_heap_token_alias.argtypes = [ctypes.c_ulonglong, ctypes.c_void_p] + xs.x2w_d3d12_heap_token_refusal.argtypes = [ctypes.c_char_p, ctypes.c_uint] + + def alias(memory): + class Probe(ctypes.Structure): + _fields_ = [('found', ctypes.c_uint), ('entries', ctypes.c_uint), ('num_elements', ctypes.c_uint), + ('alias_any', ctypes.c_uint), ('alias_failed', ctypes.c_uint), ('lacks', ctypes.c_uint), + ('pad', ctypes.c_uint), ('bytes', ctypes.c_ulonglong), ('buffer_bytes', ctypes.c_ulonglong), + ('heap_bytes', ctypes.c_ulonglong)] + probe = Probe() + xs.x2w_d3d12_heap_token_alias(memory, ctypes.byref(probe)) + return probe + + def refusal(): + text = ctypes.create_string_buffer(256) + xs.x2w_d3d12_heap_token_refusal(text, 256) + return text.value.decode() + + def view_heap(flags, backing): + desc = HeapDesc(0, count, flags, 0, backing, stride * count) + out = ctypes.c_void_p() + fails.expect(vcall(device, 14, ctypes.c_long, [ctypes.c_void_p] * 3, ctypes.byref(desc), + ctypes.byref(guid(IID_HEAP)), ctypes.byref(out)) >= 0, 'CreateDescriptorHeap (alias case)') + return out + + OLD = 'heap token textures are not bound yet' + NEED_HEAP = 'heap tokens need a GPU-visible view heap' + PROGRESS = 'heap tokens are not bound yet (runtime binding in progress)' + NEED_ROOT = 'heap tokens need a directly indexed resource heap' + SHADER_VISIBLE = 1 + state = alias(0) + lacks = bool(state.lacks) + fails.expect(state.alias_any == 0 and state.alias_failed == 0, 'an alias or a failure before any shader-visible view heap') + # The heaps created above are not shader visible: no alias even with the switch on. + fails.expect(alias(memory).found == 0, 'a heap that is not shader visible got an alias') + fails.expect(refusal() == (NEED_ROOT if on and lacks else NEED_HEAP if on else OLD), + 'refusal before any alias: "%s"' % refusal()) + + base = kernel.VirtualAlloc(None, 0x3000, 0x3000, 0x04) + interior = base + 0x1000 # not the start of an allocation + view_heap(SHADER_VISIBLE, interior) + state = alias(interior) + fails.expect(state.found == 0 and state.alias_any == 0, 'title memory that is not an allocation base got an alias') + fails.expect(state.alias_failed == (1 if on else 0), 'alias failures %d after the interior heap' % state.alias_failed) + fails.expect(refusal() == (NEED_ROOT if on and lacks else NEED_HEAP if on else OLD), + 'refusal with only an interior heap: "%s"' % refusal()) + + good = kernel.VirtualAlloc(None, 0x1000, 0x3000, 0x04) + view_heap(SHADER_VISIBLE, good) + state = alias(good) + if on: + fails.expect(state.found == 1 and state.alias_any == 1, 'a shader-visible view heap over a VirtualAlloc allocation got no alias') + fails.expect(state.entries == count and state.num_elements == count * 8, 'alias covers %d entries / %d elements' % (state.entries, state.num_elements)) + fails.expect(state.bytes == stride * count and state.buffer_bytes == state.bytes and state.heap_bytes >= state.bytes, + 'alias spans %d bytes (buffer %d, heap %d) of %d' % (state.bytes, state.buffer_bytes, state.heap_bytes, stride * count)) + fails.expect(state.num_elements * 4 <= state.buffer_bytes, 'NumElements * 4 exceeds the alias buffer') + fails.expect(state.alias_failed == 1, 'alias failures %d after the good heap' % state.alias_failed) + fails.expect(refusal() == (NEED_ROOT if lacks else PROGRESS), 'refusal with an alias: "%s"' % refusal()) + else: + fails.expect(state.found == 0 and state.alias_any == 0 and state.alias_failed == 0, 'an alias was made with the switch off') + fails.expect(refusal() == OLD, 'refusal with the switch off: "%s"' % refusal()) + print('child %s: %s' % (switch, 'PASS' if not fails.count else '%d failures' % fails.count), flush=True) return 1 if fails.count else 0 @@ -237,7 +339,7 @@ def main(): print('FAIL: child %s exited with %d' % (switch, result.returncode)) status = 1 if not status: - print('PASS: heap token skeleton (records, ids, queue, controls)') + print('PASS: heap token skeleton (records, ids, queue, controls) and runtime binding (region, ring, alias, refusal)') return status diff --git a/tests/startup_translated_sampler_bindings_check.cpp b/tests/startup_translated_sampler_bindings_check.cpp index 9e38abe307..4907057b7a 100644 --- a/tests/startup_translated_sampler_bindings_check.cpp +++ b/tests/startup_translated_sampler_bindings_check.cpp @@ -14,6 +14,7 @@ namespace { using namespace x2w_startup; int failures, cases; bool shared_axis; // --mutate shared-axis +bool resource_text; // --mutate resource-text void fail(const char* name, const char* what, unsigned got, unsigned expected) { @@ -165,7 +166,8 @@ int main(int argc, char** argv) // --mutate shared-axis: the expectations of a decoder that applies the U field to all three axes // (a negative control: the check must then fail on every case with distinct axes). shared_axis = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "shared-axis") == 0; - if (argc > 1 && !shared_axis) { + resource_text = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "resource-text") == 0; + if (argc > 1 && !shared_axis && !resource_text) { std::printf("unknown mutation\n"); return 2; } @@ -343,19 +345,29 @@ int main(int argc, char** argv) ++cases; const char* capability = "the device does not take a directly indexed sampler heap"; const char* plain = "root signature creation failed"; - struct Row { const char* name; bool flag, serialized, lacks; const char* want; }; + // A heap token program's root takes CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED instead (or with it): its own text, on the + // same terms. --mutate resource-text: the expectation of a runtime that gave the plain text for it. + const char* resource = resource_text ? plain : "the device does not take a directly indexed resource heap"; + struct Row { const char* name; bool flag, resource_flag, serialized, lacks; const char* want; }; const Row rows[] = { - {"CreateRootSignature refused, flag, lacks capability", true, true, true, capability}, - {"CreateRootSignature refused, flag, has capability", true, true, false, plain}, - {"serialisation failed, flag, lacks capability", true, false, true, plain}, - {"serialisation failed, flag, has capability", true, false, false, plain}, - {"CreateRootSignature refused, no flag, lacks capability", false, true, true, plain}, - {"CreateRootSignature refused, no flag, has capability", false, true, false, plain}, - {"serialisation failed, no flag, lacks capability", false, false, true, plain}, - {"serialisation failed, no flag, has capability", false, false, false, plain}, + {"CreateRootSignature refused, flag, lacks capability", true, false, true, true, capability}, + {"CreateRootSignature refused, flag, has capability", true, false, true, false, plain}, + {"serialisation failed, flag, lacks capability", true, false, false, true, plain}, + {"serialisation failed, flag, has capability", true, false, false, false, plain}, + {"CreateRootSignature refused, no flag, lacks capability", false, false, true, true, plain}, + {"CreateRootSignature refused, no flag, has capability", false, false, true, false, plain}, + {"serialisation failed, no flag, lacks capability", false, false, false, true, plain}, + {"serialisation failed, no flag, has capability", false, false, false, false, plain}, + {"resource heap flag, CreateRootSignature refused, lacks capability", false, true, true, true, resource}, + {"resource heap flag, CreateRootSignature refused, has capability", false, true, true, false, plain}, + {"resource heap flag, serialisation failed, lacks capability", false, true, false, true, plain}, + {"resource heap flag, serialisation failed, has capability", false, true, false, false, plain}, + {"both flags, CreateRootSignature refused, lacks capability", true, true, true, true, capability}, + {"both flags, CreateRootSignature refused, has capability", true, true, true, false, plain}, }; for (const Row& r : rows) - if (std::strcmp(compute_root_refusal(r.flag, r.serialized, r.lacks), r.want)) fail("root refusal", r.name, 0, 1); + if (std::strcmp(compute_root_refusal(r.flag, r.resource_flag, r.serialized, r.lacks), r.want)) + fail("root refusal", r.name, 0, 1); } if (failures) { diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 1bc5ea3367..34230cf978 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -247,6 +247,7 @@ 'the adapter has no 32-lane waves', 'the adapter reports shader model below 6.6', 'the compute root set is not the one the pipeline was created with', + 'the device does not take a directly indexed resource heap', 'the device does not take a directly indexed sampler heap', 'the indirect argument buffer is also a bound shader resource', 'the list type has no Dispatch', From eb9b1bfc83a0a11d518ca029ec34f3f8459e767d Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 03:01:18 +0100 Subject: [PATCH 14/19] d3d12 runtime: heap token review fixes (alias lifetime, opt-in-only ring carve-out, ring guards) Alias lifetime (blocker): the GPU alias of a view heap is released when its descriptor heap is finally released (before anything of its memory can be freed), not only on the creation failure path. HeapTokenAliases keeps at most one entry per address: open() drops an existing entry first, and a duplicate found at store time replaces the old one. Only memory the runtime allocated itself is aliased; a shader-visible view heap over memory the title supplied (extra[0]) gets no alias, is counted, and heap token programs keep the refusal "heap tokens need a GPU-visible view heap". The title descriptor stride must be 32 bytes (one record), else the same refusal. Ring: the 65,536 + 5 region is carved out only with X2W_D3D12_HEAP_TOKENS=1. Without the opt-in the ring is the whole 262,144-slot heap, as on main. A reservation larger than the ring is refused (draw: refusal reason, dispatch: "the descriptor table is larger than the ring") and never writes the region. The translated draw sets the descriptor heaps before its root signature, as a translated Dispatch does. Tests: heap_token_binding_check (opt-in ring, oversize, stride) with ten mutation controls that now build the unchanged check against a copy of heap_token_binding.h with one real source edit; startup_compute_heap_token (own-memory alias, supplied memory, drop to 0 live, duplicate and reopen at one address, stride and size refusals, oversize reservations, ring with the switch off); startup_compute_dispatch_ring and startup_draw_depth_target_ring (production Dispatch and draw sites reserve through the ring function with the cursor past the ring, opt-in on and off); triage allowlist and scanner for the heap token gate texts and the new ring reason. Not covered by a device: the successful alias through CreateDescriptorHeap on WARP (its descriptor stride is 64; the stride-32 path is covered by the direct open and by the hardware dispatch run), the note_view invalidate path (class test only), the draw heap-before-root-signature order (no program takes the directly indexed flag yet). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 61 ++++++- src/startup_stubs/d3d12_compute_dispatch.inl | 5 + src/startup_stubs/d3d12_draw.inl | 35 +++- src/startup_stubs/d3d12_xs_device.cpp | 83 +++++++-- src/startup_stubs/heap_token_alias.h | 79 ++++++-- src/startup_stubs/heap_token_binding.h | 22 ++- tests/heap_token_binding_check.cpp | 86 +++++---- .../startup_compute_dispatch_native_check.py | 13 +- tests/startup_compute_dispatch_ring_check.py | 95 ++++++++++ .../startup_compute_dispatch_texture_check.py | 7 + tests/startup_compute_heap_token_check.py | 172 +++++++++++++++--- tests/startup_draw_depth_target.cpp | 15 ++ tests/startup_draw_depth_target_check.py | 51 +++++- tests/startup_stream_consumer.cpp | 18 ++ tests/startup_triage_run_check.py | 11 +- tools/startup/triage_run.py | 5 + 16 files changed, 631 insertions(+), 127 deletions(-) create mode 100644 tests/startup_compute_dispatch_ring_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b49ca00909..5e4ac43422 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2443,17 +2443,54 @@ foreach(mutation IN ITEMS kind-offset typed-any-format backfill-skipped generati set_tests_properties(heap_token_kinds_${mutation}_control PROPERTIES PASS_REGULAR_EXPRESSION "mutation ${mutation}: caught") endforeach() -# The draw heap's heap token region and ring, the typed nulls, the raw view over a title view heap, the root flags and the -# refusal text (src/startup_stubs/heap_token_binding.h), without a device. Each mutated run must fail. +# The draw heap's heap token region and ring, the typed nulls, the raw view over a title view heap and its stride rule, the +# root flags and the refusal text (src/startup_stubs/heap_token_binding.h), without a device. add_executable(heap_token_binding_check tests/heap_token_binding_check.cpp) target_include_directories(heap_token_binding_check PRIVATE src) target_compile_features(heap_token_binding_check PRIVATE cxx_std_17) add_test(NAME heap_token_binding COMMAND heap_token_binding_check) -foreach(mutation IN ITEMS ring-full-heap null-2da-as-2d alias-unchecked root-flag-dropped gate-alias-ignored region-overlap) - add_test(NAME heap_token_binding_${mutation}_control COMMAND heap_token_binding_check --mutate ${mutation}) - set_tests_properties(heap_token_binding_${mutation}_control PROPERTIES - PASS_REGULAR_EXPRESSION "mutation ${mutation}: caught") -endforeach() +# Mutation controls: the same check, built against a copy of heap_token_binding.h with one real edit of the production code +# (the anchor is replaced; configure fails when the header no longer holds it). The check must print FAIL lines. +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/heap_token_binding.h) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/heap_token_binding.h" heap_token_binding_text) +function(heap_token_binding_mutant name anchor replacement) + string(FIND "${heap_token_binding_text}" "${anchor}" position) + if(position LESS 0) + message(FATAL_ERROR "heap_token_binding.h lost the anchor of heap_token_binding_${name}_control: ${anchor}") + endif() + string(REPLACE "${anchor}" "${replacement}" mutated "${heap_token_binding_text}") + if(mutated STREQUAL heap_token_binding_text) + message(FATAL_ERROR "heap_token_binding_${name}_control does not change the header") + endif() + set(directory "${CMAKE_CURRENT_BINARY_DIR}/heap_token_binding_mutants/${name}") + file(WRITE "${directory}/startup_stubs/heap_token_binding.h" "${mutated}") + add_executable(heap_token_binding_${name}_check tests/heap_token_binding_check.cpp) + target_include_directories(heap_token_binding_${name}_check PRIVATE "${directory}" src) + target_compile_features(heap_token_binding_${name}_check PRIVATE cxx_std_17) + add_test(NAME heap_token_binding_${name}_control COMMAND heap_token_binding_${name}_check) + set_tests_properties(heap_token_binding_${name}_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL") +endfunction() +heap_token_binding_mutant(ring-full-heap + "return opt_in ? heap_token_ring_size(heap_slots) : heap_slots;" "return heap_slots;") +heap_token_binding_mutant(ring-always-reduced + "return opt_in ? heap_token_ring_size(heap_slots) : heap_slots;" "return heap_token_ring_size(heap_slots);") +heap_token_binding_mutant(region-overlap + "return heap_token_ring_size(heap_slots) + id; }" "return heap_token_ring_size(heap_slots) + id - 1; }") +heap_token_binding_mutant(ring-wrap-dropped + "if (first + n > ring_size) {" "if (false) {") +heap_token_binding_mutant(ring-oversize-taken + "if (n > ring_size || n > 0x7fffffffu) return heap_token_ring_refused;" "") +heap_token_binding_mutant(null-2da-as-2d + "desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;" "desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;") +heap_token_binding_mutant(alias-unchecked + "entries * heap_token_record_bytes <= bytes;" "true;") +heap_token_binding_mutant(alias-stride-unchecked + "return title_stride == heap_token_record_bytes;" "return title_stride != 0;") +heap_token_binding_mutant(root-flag-dropped + "(heap_tokens_bound ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE)" + "D3D12_ROOT_SIGNATURE_FLAG_NONE") +heap_token_binding_mutant(gate-alias-ignored + "if (!view_heap_alias) return \"heap tokens need a GPU-visible view heap\";" "") add_test(NAME startup_heap_indexed_root COMMAND startup_heap_indexed_root_check) foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) @@ -5103,6 +5140,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_input_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_input_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_ring_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_ring_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) add_test(NAME startup_compute_live_retry_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_live_retry_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) @@ -5116,6 +5156,7 @@ if(EXISTS "${INTAKE_PYTHON}") startup_compute_dispatch_heap_${adapter} startup_compute_dispatch_heap_word_${adapter} startup_compute_live_retry_${adapter} startup_compute_dispatch_entry_${adapter} startup_compute_dispatch_input_${adapter} startup_compute_dispatch_two_mips_${adapter} + startup_compute_dispatch_ring_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B @@ -5170,8 +5211,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_draw_depth_target_debug_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_depth_target_check.py" "$" "${backend}" debug) + add_test(NAME startup_draw_depth_target_ring_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_depth_target_check.py" + "$" "${backend}" ring) set_tests_properties(startup_draw_depth_target_${backend} startup_draw_depth_target_drop_control_${backend} - startup_draw_depth_target_debug_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + startup_draw_depth_target_debug_${backend} startup_draw_depth_target_ring_${backend} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(compiler IN ITEMS fxc dxc) add_test(NAME startup_joined_table_pointer_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_joined_table_pointer_check.py" diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 39e31e4e23..710fbed88f 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1439,6 +1439,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } const UINT n = static_cast(count + tr->heap_srvs); const UINT first = draw_ring_reserve(n); + if (first == x2w_startup::heap_token_ring_refused) { // a table larger than the ring would reach the heap token region + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(counter); + return "the descriptor table is larger than the ring"; + } D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index bc53c1422a..7755a773ce 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1703,20 +1703,31 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P return pipeline; } -// Private shader-visible heap for the translated draws' tables, used as a ring. The top of the heap is a fixed region for -// heap view tokens (heap_token_binding.h): the mirror slots and five typed nulls. The ring is the rest, draw_ring_size -// slots, and never writes the region; the heap itself keeps draw_heap_size. Without X2W_D3D12_HEAP_TOKENS the region -// stays unwritten (only the ring is smaller than the heap, by heap_token_region_slots). +// Private shader-visible heap for the translated draws' tables, used as a ring. With X2W_D3D12_HEAP_TOKENS the top of the +// heap is a fixed region for heap view tokens (heap_token_binding.h): the mirror slots and five typed nulls. The ring is +// the rest, draw_ring_size() slots, and never writes the region; the heap itself keeps draw_heap_size. Without the opt-in +// the region does not exist and the ring is the whole heap, as it was before the region. constexpr UINT draw_heap_size = 1u << 18; -constexpr UINT draw_ring_size = x2w_startup::heap_token_ring_size(draw_heap_size); +UINT draw_ring_size() { return x2w_startup::heap_token_ring_slots(draw_heap_size, heap_tokens()); } ID3D12DescriptorHeap* draw_heap; Wrapper* draw_heap_device; UINT draw_heap_increment; volatile LONG draw_heap_cursor; UINT draw_region_nulls_written; // the typed nulls written into the region when the heap was created (fixture probe) +// What the ring reserved since the fixture's last mark (x2w_d3d12_heap_token_ring_probe). +volatile LONG draw_ring_reserves, draw_ring_refused; +UINT draw_ring_first_since_mark = ~0u, draw_ring_highest_end; -// The first of n consecutive ring slots, for the table of a draw or a dispatch. Both users go through here. -UINT draw_ring_reserve(UINT n) { return x2w_startup::heap_token_ring_reserve(&draw_heap_cursor, n, draw_ring_size); } +// The first of n consecutive ring slots, for the table of a draw or a dispatch; heap_token_ring_refused when the table is +// larger than the ring (the caller refuses the draw or dispatch; nothing is written). Both users go through here. +UINT draw_ring_reserve(UINT n) +{ + const UINT first = x2w_startup::heap_token_ring_reserve(&draw_heap_cursor, n, draw_ring_size()); + if (InterlockedIncrement(&draw_ring_reserves) == 1) draw_ring_first_since_mark = first; + if (first == x2w_startup::heap_token_ring_refused) InterlockedIncrement(&draw_ring_refused); + else if (first + n > draw_ring_highest_end) draw_ring_highest_end = first + n; + return first; +} bool ensure_draw_heap(Wrapper* device) { @@ -3540,6 +3551,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI const UINT n = static_cast(tr->srvs.size()); const UINT views = n + static_cast(tr->uavs.size()); // the SRVs, then the UAVs, in one table const UINT first = draw_ring_reserve(views); + if (first == x2w_startup::heap_token_ring_refused) { // a table larger than the ring would reach the heap token region + log("x2w-draw %016llx table of %u views is larger than the descriptor ring (%u slots)", tr->key, views, draw_ring_size()); + note_draw_refusal(tr->key, "descriptor_ring_too_small", "descriptor table larger than the ring"); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } std::uint32_t strides[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by @@ -4022,13 +4039,15 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass_dsv_format(*bound, pass) != DXGI_FORMAT_UNKNOWN && bound->stencil_ref != pass.stencil_reference; if (scoped_stencil_ref) list->OMSetStencilRef(bound->stencil_ref); - list->SetGraphicsRootSignature(tr->root); + // The heaps come before the root signature, as in a translated Dispatch: a root signature with a directly indexed heap + // (the heap token programs' CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) needs its heap set before it is set on the list. ID3D12DescriptorHeap* samplers = tr->samplers.heap ? pass.sampler_heap.Get() : nullptr; if (!pass.heap_set || pass.bound_sampler_heap != samplers) { x2w_startup::bind_translated_heaps(list, draw_heap, samplers); pass.heap_set = true; pass.bound_sampler_heap = samplers; } + list->SetGraphicsRootSignature(tr->root); list->SetGraphicsRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); if (views) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(views), samplers->GetGPUDescriptorHandleForHeapStart()); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index a68efcc3d2..e204a76c25 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1208,6 +1208,7 @@ void retire_leave_class(const void* object, RetireLeft why); void retire_add_view_ref(const void* object); void retire_release_view_ref(const void* object); void retire_drop_heap_views(Wrapper* heap); +void release_heap_token_alias(Wrapper* heap); void retire_note_title_release(Wrapper* w); bool retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); @@ -1234,7 +1235,10 @@ ULONG __stdcall release(Wrapper* self) if (!refs) { if (self->own().budget) self->own().budget->end_use(); if (self->own().backing_budget) self->own().backing_budget->end_use(); - if (self->own().kind == descriptor_heap_kind) retire_drop_heap_views(self); + if (self->own().kind == descriptor_heap_kind) { + release_heap_token_alias(self); // before anything of the heap's memory can be freed + retire_drop_heap_views(self); + } if (self->own().kind == resource_kind && self->own().title_memory) { drop_mesh_lease_owner(self); retire_placement(self); @@ -5699,12 +5703,22 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR return E_OUTOFMEMORY; } // Heap tokens (X2W_D3D12_HEAP_TOKENS): the GPU reads the 32-byte records of a shader-visible view heap through an alias - // of its memory (heap_token_alias.h). A heap that cannot be aliased is not an error for the title; heap token programs - // are refused by name while no view heap has an alias (heap_token_refusal). - const bool token_alias = heap_tokens() && title_memory && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && - (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + // of its memory (heap_token_alias.h). Only memory of ours is aliased: the runtime cannot see when the title frees memory + // it supplied, so such a heap (counted) gets no alias. A heap that cannot be aliased is not an error for the title; + // heap token programs are refused by name while no view heap has an alias (heap_token_refusal). The alias is released + // when the descriptor heap is finally released (release_heap_token_alias). + const bool token_view_heap = heap_tokens() && title_memory && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && + (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + const bool token_alias = token_view_heap && title_memory != supplied_memory; + if (token_view_heap && !token_alias) { + heap_token_aliases().note_title_supplied(); + static LONG supplied_logs; + if (first_calls(supplied_logs, 8)) + log("x2w-d3d12 Device::CreateDescriptorHeap: no heap token alias of title-supplied memory 0x%llx (%llu bytes)", + title_memory, bytes); + } if (token_alias) { - const HRESULT alias_hr = heap_token_aliases().open(device_of(self), title_memory, bytes, desc->NumDescriptors); + const HRESULT alias_hr = heap_token_aliases().open(device_of(self), title_memory, bytes, desc->NumDescriptors, title_stride); static LONG alias_logs; if (first_calls(alias_logs, 8)) log("x2w-d3d12 Device::CreateDescriptorHeap: heap token alias of 0x%llx (%llu bytes) -> 0x%08lx", title_memory, bytes, @@ -6592,6 +6606,13 @@ void retire_release_view_ref(const void* object) InterlockedDecrement(&w->own().retire_view_refs); } +// The heap token alias over the memory of a descriptor heap that is finally released (heap_token_alias.h); none when +// the heap has none (the switch is off, the memory is the title's, or the alias was refused). +void release_heap_token_alias(Wrapper* heap) +{ + if (heap && heap_tokens() && heap->own().title_cpu) heap_token_aliases().release(heap->own().title_cpu); +} + void retire_drop_heap_views(Wrapper* heap) { if (!release_retired_enabled() || !heap) return; @@ -7272,7 +7293,7 @@ extern "C" __declspec(dllexport) void x2w_d3d12_heap_mirror_queue(unsigned long extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_layout(UINT* out) { out[0] = draw_heap_size; - out[1] = draw_ring_size; + out[1] = draw_ring_size(); out[2] = x2w_startup::heap_token_mirror_capacity; out[3] = x2w_startup::heap_token_null_slots; } @@ -7289,12 +7310,32 @@ extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_token_ring(UINT n, int set, if (set) InterlockedExchange(&draw_heap_cursor, cursor); return draw_ring_reserve(n); } +// The ring's record of the reservations the draws and dispatches (and this fixture) made since the last mark: how many, +// the first slot of the first one, the end of the highest one, how many were refused as larger than the ring. +struct HeapTokenRingProbe { + unsigned reserves, first_since_mark, highest_end, refused, ring_slots, pad; +}; +// Starts a new record and sets the ring cursor (no reservation is made). +extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_ring_mark(LONG cursor) +{ + InterlockedExchange(&draw_heap_cursor, cursor); + draw_ring_reserves = 0; + draw_ring_first_since_mark = ~0u; + draw_ring_highest_end = 0; + draw_ring_refused = 0; +} +extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_ring_probe(HeapTokenRingProbe* out) +{ + *out = {static_cast(draw_ring_reserves), draw_ring_first_since_mark, draw_ring_highest_end, + static_cast(draw_ring_refused), draw_ring_size(), 0}; +} struct HeapTokenAliasProbe { - unsigned found, entries, num_elements, alias_any, alias_failed, lacks_resource_heap, pad; - unsigned long long bytes, buffer_bytes, heap_bytes; + unsigned found, entries, num_elements, alias_any, alias_failed, lacks_resource_heap, count, title_supplied; + unsigned long long bytes, buffer_bytes, heap_bytes, generation; }; -// The alias of the title view heap memory at `memory`: whether there is one, what it covers, and the global state the -// reader's refusal text depends on. +// The alias of the view heap memory at `memory`: whether there is one, what it covers, which open made it, and the global +// state the reader's refusal text depends on (how many aliases live, how many opens failed, how many heaps had memory +// the title supplied). extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_alias(UINT64 memory, HeapTokenAliasProbe* out) { *out = {}; @@ -7304,13 +7345,33 @@ extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_alias(UINT64 memory, out->entries = alias.entries; out->num_elements = alias.num_elements; out->bytes = alias.bytes; + out->generation = alias.generation; out->buffer_bytes = alias.alias.buffer ? alias.alias.buffer->GetDesc().Width : 0; out->heap_bytes = alias.alias.heap ? alias.alias.heap->GetDesc().SizeInBytes : 0; } out->alias_any = heap_token_aliases().any(); out->alias_failed = heap_token_aliases().failed(); + out->count = static_cast(heap_token_aliases().count()); + out->title_supplied = heap_token_aliases().title_supplied(); out->lacks_resource_heap = adapter_lacks_directly_indexed_resource_heap(); } +// Opens the alias of [memory, memory + bytes) the way CreateDescriptorHeap does for a view heap of `entries` descriptors +// of `title_stride` bytes (the production HeapTokenAliases::open); the HRESULT. The memory is the caller's. +extern "C" __declspec(dllexport) LONG x2w_d3d12_heap_token_alias_open(void* table, UINT64 memory, UINT64 bytes, UINT entries, + UINT64 title_stride) +{ + return heap_token_aliases().open(device_of(as_wrapper(table)), memory, bytes, entries, title_stride); +} +// Drops the alias of `memory` the way the final release of its descriptor heap does; whether there was one. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_heap_token_alias_release(UINT64 memory) +{ + return heap_token_aliases().release(memory); +} +// The descriptor stride the device gives a CBV/SRV/UAV heap (what CreateDescriptorHeap takes as the title stride). +extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_token_view_stride(void* table) +{ + return device_of(as_wrapper(table))->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); +} // The reason a program with heaptok lines is refused now (heap_token_refusal, the text the manifest reader gives). extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_refusal(char* out, UINT size) { diff --git a/src/startup_stubs/heap_token_alias.h b/src/startup_stubs/heap_token_alias.h index e5d0424bab..5c7bae9fb9 100644 --- a/src/startup_stubs/heap_token_alias.h +++ b/src/startup_stubs/heap_token_alias.h @@ -1,9 +1,15 @@ -// The GPU view of a title view heap's memory for heap tokens (X2W_D3D12_HEAP_TOKENS): one heap per shader-visible -// CBV/SRV/UAV descriptor heap from OpenExistingHeapFromAddress on the allocation base (era_gpu_alias), with a buffer -// placed over it. A raw SRV of that buffer (heap_token_alias_srv_desc, written by a later commit) lets a shader read -// the 32-byte records the title memory holds, with no copy. Never the existing-heap cache of unplaced_memory_buffer, never -// an upload fallback: memory that is not an allocation base, or a device that refuses, gives no alias and the heap +// The GPU view of a view heap's memory for heap tokens (X2W_D3D12_HEAP_TOKENS): one heap per shader-visible CBV/SRV/UAV +// descriptor heap from OpenExistingHeapFromAddress on the allocation base (era_gpu_alias), with a buffer placed over it. +// A raw SRV of that buffer (heap_token_alias_srv_desc, written by a later commit) lets a shader read the 32-byte records +// the heap memory holds, with no copy. Never the existing-heap cache of unplaced_memory_buffer, never an upload fallback. +// +// Only memory the runtime allocated itself is aliased (a view heap the title gave no memory for): the runtime cannot see +// when the title frees memory it supplied. The title descriptor stride must be one record (32 bytes). Memory that is +// not an allocation base, a device that refuses, memory the title supplied or another stride give no alias and the heap // token programs are refused ("heap tokens need a GPU-visible view heap"). +// +// Lifetime: at most one entry per address. open() drops an existing entry of the address first (its memory was freed and +// reused), and release() is called when the descriptor heap is finally released, before its memory can be freed. #pragma once #include "era_gpu_alias.h" @@ -16,45 +22,67 @@ namespace x2w_startup { struct HeapTokenAlias { - std::uint64_t memory = 0; // the title memory (allocation base) + std::uint64_t memory = 0; // the heap memory (allocation base) std::uint64_t bytes = 0; // the span the alias covers - UINT entries = 0; // title descriptors the heap holds + UINT entries = 0; // descriptors the heap holds UINT num_elements = 0; // entries * 8: the NumElements of the raw SRV + std::uint64_t generation = 0; // which open made it (grows with every open) era_gpu_alias::Alias alias; }; class HeapTokenAliases { public: - // Opens the alias of [memory, memory + bytes) for a heap of `entries` descriptors. S_OK, or why not: E_INVALIDARG for - // a span that does not hold the records or memory that is not an allocation base, E_NOTIMPL when the device has no - // existing heaps, E_OUTOFMEMORY, or the failing D3D12 result. A failure is counted. - HRESULT open(ID3D12Device* device, std::uint64_t memory, std::uint64_t bytes, UINT entries) + // Opens the alias of [memory, memory + bytes) for a heap of `entries` descriptors of `title_stride` bytes. S_OK, or + // why not: E_INVALIDARG for a stride other than one record, a span that does not hold the records or memory that is + // not an allocation base, E_NOTIMPL when the device has no existing heaps, E_OUTOFMEMORY, or the failing D3D12 + // result. A failure is counted. An entry of the same address is dropped first, so there is never more than one. + HRESULT open(ID3D12Device* device, std::uint64_t memory, std::uint64_t bytes, UINT entries, std::uint64_t title_stride) { - HRESULT hr = open_unlocked(device, memory, bytes, entries); + HRESULT hr = heap_token_alias_stride_ok(title_stride) ? open_unlocked(device, memory, bytes, entries) : E_INVALIDARG; AcquireSRWLockExclusive(&lock_); if (FAILED(hr)) ++failed_; ReleaseSRWLockExclusive(&lock_); return hr; } - // Drops the alias of `memory` (the buffer, then the heap). Callers do this before the memory is freed. - void release(std::uint64_t memory) + // Drops the alias of `memory` (the buffer, then the heap); false when there is none. Callers do this before the memory + // is freed. + bool release(std::uint64_t memory) { era_gpu_alias::Alias dropped; // released outside the lock + bool found = false; AcquireSRWLockExclusive(&lock_); for (std::size_t i = 0; i < aliases_.size(); ++i) if (aliases_[i].memory == memory) { dropped = std::move(aliases_[i].alias); aliases_.erase(aliases_.begin() + static_cast(i)); + found = true; break; } ReleaseSRWLockExclusive(&lock_); dropped.buffer.Reset(); dropped.heap.Reset(); + return found; + } + bool any() const { return count() != 0; } + // A view heap whose memory the title supplied got no alias (counted for the launcher's measurement). + void note_title_supplied() + { + AcquireSRWLockExclusive(&lock_); + ++title_supplied_; + ReleaseSRWLockExclusive(&lock_); + } + unsigned title_supplied() const + { + AcquireSRWLockShared(&lock_); + const unsigned result = title_supplied_; + ReleaseSRWLockShared(&lock_); + return result; } - bool any() const + // How many aliases are alive. + std::size_t count() const { AcquireSRWLockShared(&lock_); - const bool result = !aliases_.empty(); + const std::size_t result = aliases_.size(); ReleaseSRWLockShared(&lock_); return result; } @@ -84,6 +112,9 @@ class HeapTokenAliases { HRESULT open_unlocked(ID3D12Device* device, std::uint64_t memory, std::uint64_t bytes, UINT entries) { if (!device || !memory || !heap_token_alias_fits(entries, bytes)) return E_INVALIDARG; + // The address is being opened again: the entry there belongs to memory that was freed. Its heap must be gone + // before a new one is opened over the same pages. + release(memory); HeapTokenAlias entry; entry.memory = memory; entry.bytes = bytes; @@ -91,20 +122,34 @@ class HeapTokenAliases { entry.num_elements = entries * heap_token_record_dwords; const HRESULT hr = era_gpu_alias::open(device, reinterpret_cast(static_cast(memory)), bytes, entry.alias); if (FAILED(hr)) return hr; + era_gpu_alias::Alias replaced; // an entry another thread stored for the address meanwhile, released outside the lock bool stored = true; AcquireSRWLockExclusive(&lock_); + entry.generation = ++generation_; try { - aliases_.push_back(std::move(entry)); + bool took_place = false; + for (HeapTokenAlias& existing : aliases_) + if (existing.memory == memory) { + replaced = std::move(existing.alias); + existing = std::move(entry); + took_place = true; + break; + } + if (!took_place) aliases_.push_back(std::move(entry)); } catch (const std::bad_alloc&) { stored = false; } ReleaseSRWLockExclusive(&lock_); + replaced.buffer.Reset(); + replaced.heap.Reset(); return stored ? S_OK : E_OUTOFMEMORY; // a failed push leaves the entry (and its alias) to be released here } mutable SRWLOCK lock_ = SRWLOCK_INIT; std::vector aliases_; unsigned failed_ = 0; + unsigned title_supplied_ = 0; + std::uint64_t generation_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/heap_token_binding.h b/src/startup_stubs/heap_token_binding.h index 12df7e66da..47cbcb97ce 100644 --- a/src/startup_stubs/heap_token_binding.h +++ b/src/startup_stubs/heap_token_binding.h @@ -8,8 +8,9 @@ // [ring, ring + capacity) the mirror: one slot per view record id (written by a later commit) // [ring + capacity, heap) five typed null descriptors, written once when the heap is created // -// The ring never writes the region: its modulus and its wrap check both use ring_size(heap), and a reservation that -// would leave the ring starts at slot 0. +// The ring never writes the region: its modulus and its wrap check both use the ring size, a reservation that would +// leave the ring starts at slot 0, and a reservation larger than the ring is refused. The region is reserved only with +// the opt-in X2W_D3D12_HEAP_TOKENS; without it the ring is the whole heap, as before the region existed. #pragma once #include @@ -27,16 +28,27 @@ constexpr UINT heap_token_region_slots = heap_token_mirror_capacity + heap_token enum HeapTokenNull : UINT { null_1d, null_2d, null_2da, null_raw, null_typed_uint }; constexpr UINT heap_token_ring_size(UINT heap_slots) { return heap_slots - heap_token_region_slots; } +// The slots the ring of per-draw and per-dispatch tables uses: below the region with the opt-in, the whole heap without. +constexpr UINT heap_token_ring_slots(UINT heap_slots, bool opt_in) +{ + return opt_in ? heap_token_ring_size(heap_slots) : heap_slots; +} constexpr UINT heap_token_mirror_slot(UINT heap_slots, UINT id) { return heap_token_ring_size(heap_slots) + id; } constexpr UINT heap_token_null_slot(UINT heap_slots, HeapTokenNull which) { return heap_token_ring_size(heap_slots) + heap_token_mirror_capacity + which; } +// What heap_token_ring_reserve returns for a reservation larger than the ring. +constexpr UINT heap_token_ring_refused = ~0u; + // Reserves n consecutive ring slots and returns the first. `cursor` only grows (it wraps through 32 bits, which the -// modulus survives); a reservation that does not fit before the end of the ring starts again at 0. +// modulus survives); a reservation that does not fit before the end of the ring starts again at 0. A reservation larger +// than the whole ring fits nowhere without reaching the region: it is refused with heap_token_ring_refused and the +// cursor is left alone. inline UINT heap_token_ring_reserve(volatile LONG* cursor, UINT n, UINT ring_size) { + if (n > ring_size || n > 0x7fffffffu) return heap_token_ring_refused; UINT first = static_cast(InterlockedExchangeAdd(cursor, static_cast(n))) % ring_size; if (first + n > ring_size) { first = 0; @@ -84,6 +96,10 @@ inline D3D12_SHADER_RESOURCE_VIEW_DESC heap_token_null_desc(HeapTokenNull which) constexpr UINT heap_token_record_dwords = 8; constexpr std::uint64_t heap_token_record_bytes = heap_token_record_dwords * 4; +// Only a title descriptor stride of one record (32 bytes) lets the raw view address the descriptors: entry i is dwords +// [8 * i, 8 * i + 8). Another stride (the desktop's 64 bytes on some adapters) is the same refusal as no alias. +inline bool heap_token_alias_stride_ok(std::uint64_t title_stride) { return title_stride == heap_token_record_bytes; } + // Whether `entries` records fit in an allocation of `bytes` (NumElements * 4 <= bytes, without overflow). inline bool heap_token_alias_fits(std::uint64_t entries, std::uint64_t bytes) { diff --git a/tests/heap_token_binding_check.cpp b/tests/heap_token_binding_check.cpp index 5c95fdf48c..ac123d992e 100644 --- a/tests/heap_token_binding_check.cpp +++ b/tests/heap_token_binding_check.cpp @@ -1,14 +1,12 @@ // Checks src/startup_stubs/heap_token_binding.h without a device: the region at the top of the translated draw heap and the -// ring below it, the typed nulls, the raw view over a title view heap, the root flags and the refusal text of a heap token -// program. +// ring below it (with and without the opt-in), the typed nulls, the raw view over a title view heap and its stride rule, +// the root flags and the refusal text of a heap token program. // -// heap_token_binding_check [--mutate ring-full-heap|null-2da-as-2d|alias-unchecked|root-flag-dropped|gate-alias-ignored| -// region-overlap] +// heap_token_binding_check // -// Each mutation makes the check compute with what a wrong implementation would use (the ring over the whole heap, a 2D -// null for the 2D array, no size check, the root flag left out, the missing alias ignored, a mirror that starts inside -// the ring); every one must make the check fail. A mutated run that fails prints "mutation : caught" as its last -// line; an unknown name, a crash, or a mutation that is not caught prints no such line. +// The mutation controls (CMakeLists.txt, heap_token_binding__control) do not change this file: each builds it against +// a copy of heap_token_binding.h with one real edit of the production code (a replaced anchor, checked at configure time), +// and the check must print FAIL lines. #include "startup_stubs/heap_token_binding.h" #include @@ -18,7 +16,6 @@ namespace { using namespace x2w_startup; int failures, cases; -bool m_ring_full_heap, m_null_2da_as_2d, m_alias_unchecked, m_root_flag_dropped, m_gate_alias_ignored, m_region_overlap; constexpr UINT heap = 1u << 18; // draw_heap_size @@ -38,7 +35,10 @@ void ring() expect(heap_token_region_slots == 65541 && heap_token_mirror_capacity == 65536 && heap_token_null_slots == 5, "the region is not 65,536 mirror slots plus 5 nulls"); expect(heap_token_ring_size(heap) == expected_ring && expected_ring == 196603, "the ring is not 196,603 slots"); - const UINT ring_size = m_ring_full_heap ? heap : heap_token_ring_size(heap); + // The opt-in decides: the region is reserved with it, the whole heap is the ring without it (as on main, 262,144). + expect(heap_token_ring_slots(heap, true) == 196603, "the ring with the opt-in is not 196,603 slots"); + expect(heap_token_ring_slots(heap, false) == 262144, "the ring without the opt-in is not the whole 262,144-slot heap"); + const UINT ring_size = heap_token_ring_slots(heap, true); const UINT region_start = heap_token_ring_size(heap); const UINT sizes[] = {1, 2, 5, 7, 64, 1000, 1024, 1100, 4096}; @@ -49,7 +49,7 @@ void ring() for (int i = 0; i < 20000; ++i) { const UINT n = sizes[(i * 7 + i / 3) % (sizeof(sizes) / sizeof(sizes[0]))]; const UINT first = heap_token_ring_reserve(&cursor, n, ring_size); - inside = inside && first + n <= ring_size; + inside = inside && first != heap_token_ring_refused && first + n <= ring_size; touched_region = touched_region || first + n > region_start; // a slot at or above the region's first if (first + n > highest) highest = first + n; if (i && first < previous_first) ++wraps; @@ -61,14 +61,29 @@ void ring() expect(wraps > 5, "the ring never wrapped in the test run"); expect(highest > region_start - 4096, "the ring does not use its top (the check may be too weak)"); } + // A table that does not fit before the end of the ring starts at slot 0; the old whole-heap modulus put it in the region. + { + volatile LONG cursor = static_cast(ring_size - 3); + expect(heap_token_ring_reserve(&cursor, 5, ring_size) == 0, "a reservation of 5 slots 3 below the end of the ring does not start at 0"); + } + // A reservation larger than the ring never writes the region: it is refused and the cursor stays where it was. + for (const UINT n : {ring_size + 1, ring_size + 5, ring_size + heap_token_region_slots, heap, 0x80000000u, ~0u - 1}) { + volatile LONG cursor = 1234; + const UINT first = heap_token_ring_reserve(&cursor, n, ring_size); + expect(first == heap_token_ring_refused, "a reservation larger than the ring is not refused"); + expect(cursor == 1234, "a refused reservation moved the cursor"); + } + { + volatile LONG cursor = 0; + expect(heap_token_ring_reserve(&cursor, ring_size, ring_size) == 0, "a reservation of exactly the whole ring is refused"); + } } // Region slots: after the ring, the mirror then the nulls, nothing outside the heap, nothing twice. void layout() { const UINT ring_size = heap_token_ring_size(heap); - const UINT mirror_first = heap_token_mirror_slot(heap, 0) - (m_region_overlap ? 1 : 0); - expect(mirror_first == ring_size, "the mirror does not start where the ring ends"); + expect(heap_token_mirror_slot(heap, 0) == ring_size, "the mirror does not start where the ring ends"); expect(heap_token_mirror_slot(heap, heap_token_mirror_capacity - 1) + 1 == heap_token_null_slot(heap, null_1d), "the nulls do not follow the last mirror slot"); UINT previous = 0; @@ -86,7 +101,7 @@ void nulls() { const auto d1 = heap_token_null_desc(null_1d); const auto d2 = heap_token_null_desc(null_2d); - const auto da = heap_token_null_desc(m_null_2da_as_2d ? null_2d : null_2da); // a table that has no 2D array null + const auto da = heap_token_null_desc(null_2da); const auto raw = heap_token_null_desc(null_raw); const auto typed = heap_token_null_desc(null_typed_uint); expect(d1.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D && d1.Texture1D.MipLevels == 1, "the 1D null is not a 1D texture view"); @@ -103,7 +118,7 @@ void nulls() expect(d.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, "a null has a component mapping other than the default"); } -// The raw view over the title view heap: 8 dwords per entry, checked against the allocation. +// The raw view over the title view heap: 8 dwords per entry, checked against the allocation, 32-byte stride only. void alias() { expect(heap_token_record_bytes == 32, "a record is not 32 bytes"); @@ -115,23 +130,25 @@ void alias() // NumElements * 4 <= bytes. expect(heap_token_alias_fits(256, 256 * 32), "an exactly fitting heap is refused"); expect(heap_token_alias_fits(256, 256 * 32 + 4096), "a heap with room to spare is refused"); - // --mutate alias-unchecked: an implementation that does not compare NumElements * 4 with the allocation. - const auto fits = [](std::uint64_t entries, std::uint64_t bytes) { return m_alias_unchecked ? entries != 0 : heap_token_alias_fits(entries, bytes); }; - expect(!fits(256, 256 * 32 - 1), "a heap one byte short is taken"); - expect(!fits(256, 256 * 16), "a 16-byte stride heap is taken for 32-byte records"); + expect(!heap_token_alias_fits(256, 256 * 32 - 1), "a heap one byte short is taken"); + expect(!heap_token_alias_fits(256, 256 * 16), "a 16-byte stride heap is taken for 32-byte records"); expect(!heap_token_alias_fits(0, 4096), "a heap of no entries is taken"); expect(!heap_token_alias_fits(0x20000000ull, ~0ull), "entries whose dword count overflows 32 bits are taken"); + // The title stride is one record. A 64-byte stride would put entry i at dwords 16 * i, not 8 * i. + expect(heap_token_alias_stride_ok(32), "a 32-byte stride is refused"); + expect(!heap_token_alias_stride_ok(64), "a 64-byte stride is taken"); + expect(!heap_token_alias_stride_ok(16), "a 16-byte stride is taken"); + expect(!heap_token_alias_stride_ok(0), "a stride of 0 is taken"); } void root_flags() { constexpr UINT sampler = D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, view = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; expect(sampler == 0x800 && view == 0x400, "the flag values changed"); - const bool tokens = !m_root_flag_dropped; expect(compute_root_flags(false, false) == 0, "a root with neither heap has flags"); expect(compute_root_flags(true, false) == sampler, "the sampler flag alone is not the sampler flag"); - expect(compute_root_flags(false, tokens) == view, "a heap token program's root lacks the view heap flag"); - expect(compute_root_flags(true, tokens) == (sampler | view), "the two flags are not ORed"); + expect(compute_root_flags(false, true) == view, "a heap token program's root lacks the view heap flag"); + expect(compute_root_flags(true, true) == (sampler | view), "the two flags are not ORed"); } void gate() @@ -153,8 +170,7 @@ void gate() {"everything holds", true, false, false, true, in_progress}, }; for (const Row& r : rows) { - const bool alias = m_gate_alias_ignored ? true : r.alias; - const char* got = heap_token_gate_text(r.opt_in, r.content, r.lacks, alias); + const char* got = heap_token_gate_text(r.opt_in, r.content, r.lacks, r.alias); ++cases; if (std::strcmp(got, r.want)) { ++failures; @@ -165,23 +181,9 @@ void gate() } // namespace -int main(int argc, char** argv) +int main(int argc, char**) { - if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { - m_ring_full_heap = !std::strcmp(argv[2], "ring-full-heap"); - m_null_2da_as_2d = !std::strcmp(argv[2], "null-2da-as-2d"); - m_alias_unchecked = !std::strcmp(argv[2], "alias-unchecked"); - m_root_flag_dropped = !std::strcmp(argv[2], "root-flag-dropped"); - m_gate_alias_ignored = !std::strcmp(argv[2], "gate-alias-ignored"); - m_region_overlap = !std::strcmp(argv[2], "region-overlap"); - if (!(m_ring_full_heap || m_null_2da_as_2d || m_alias_unchecked || m_root_flag_dropped || m_gate_alias_ignored || - m_region_overlap)) { - std::printf("unknown mutation %s\n", argv[2]); - return 2; - } - } else if (argc != 1) { - return 2; - } + if (argc != 1) return 2; ring(); layout(); nulls(); @@ -189,9 +191,5 @@ int main(int argc, char** argv) root_flags(); gate(); std::printf("%d of %d checks failed\n", failures, cases); - if (argc == 3) { - if (failures) std::printf("mutation %s: caught\n", argv[2]); - else std::printf("mutation %s: NOT caught\n", argv[2]); - } return failures ? 1 : 0; } diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index 502292aab6..d1ac56d00a 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -383,7 +383,8 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal): ({'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, HEAP_TOKEN_REFUSAL), ({'X2W_D3D12_HEAP_TOKENS': '1'}, 'heap tokens are not bound yet (runtime binding in progress)'), ({'X2W_D3D12_HEAP_TOKENS': '1', 'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, 'heap tokens need id tokens')) -HEAP_TOKEN_TEXTS = tuple(sorted({text for _, text in HEAP_TOKEN_CASES})) +NEED_VIEW_HEAP = 'heap tokens need a GPU-visible view heap' # the opt-in alone, when the view heap got no GPU alias +HEAP_TOKEN_TEXTS = tuple(sorted({text for _, text in HEAP_TOKEN_CASES} | {NEED_VIEW_HEAP})) def heap_token_refusal(directory, consumer, dxc_dir, adapter): @@ -412,7 +413,15 @@ def heap_token_refusal(directory, consumer, dxc_dir, adapter): assert not lines(result, 'is not bound for a natively translated program'), result.stderr[-3000:] if token: reason = lines(result, 'not translated natively: ') - assert len(reason) == 1 and reason[0].endswith(expected), (extra, result.stderr[-3000:]) + want = expected + if expected == 'heap tokens are not bound yet (runtime binding in progress)': + # With the opt-in alone the text depends on whether the consumer's view heap got a GPU alias: only a + # 32-byte descriptor stride does (WARP's is 64 bytes), and then the refusal is the named one for it. + aliases = lines(result, 'heap token alias of ') + assert len(aliases) == 1, (extra, aliases) + if not aliases[0].endswith('-> 0x00000000'): + want = NEED_VIEW_HEAP + assert len(reason) == 1 and reason[0].endswith(want), (extra, result.stderr[-3000:]) assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] else: for text in HEAP_TOKEN_TEXTS: diff --git a/tests/startup_compute_dispatch_ring_check.py b/tests/startup_compute_dispatch_ring_check.py new file mode 100644 index 0000000000..4709077b0e --- /dev/null +++ b/tests/startup_compute_dispatch_ring_check.py @@ -0,0 +1,95 @@ +"""The ring of descriptor tables of a translated Dispatch stays out of the heap token region (X2W_D3D12_HEAP_TOKENS). + +usage: startup_compute_dispatch_ring_check.py + +The consumer records case A of startup_gfx2hlsl_compute_check.py as startup_compute_dispatch_check.py does. After +gfx2hlsl.py --pending with DXC, the Dispatch runs with the ring cursor set to the last slot of the ring (X2W_TEST_RING_CURSOR) +and the consumer prints what the Dispatch reserved (the production ring function, src/startup_stubs/d3d12_draw.inl): + +- X2W_D3D12_HEAP_TOKENS=1: the ring is 196,603 slots, the table (2 slots) does not fit before the end of the ring, so it + starts at slot 0 and never reaches the region above (65,536 mirror slots and 5 nulls). A Dispatch site that went back to + the old modulus (the whole 262,144-slot heap) makes no reservation through the ring function (reserves 0) or takes slot + 196,602 and ends in the region; either fails here. +- opt-in off: the ring is the whole heap (262,144 slots, as before the region existed) and the same cursor gives the table + at slot 196,602. + +All 320 output words match in both runs. Exit 77 when the adapter is not available. +""" +from pathlib import Path +import os +import re +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +HEAP = 1 << 18 +REGION = 65536 + 5 +RING_ON = HEAP - REGION # 196,603 +PROBE = re.compile(r'descriptor ring: reserves (\d+) first (\d+) highest end (\d+) refused (\d+) ring slots (\d+)') + + +def ring_line(result): + found = PROBE.findall(result.stdout) + assert len(found) == 1, 'no descriptor ring line (exit %d, stdout %r):\n' % (result.returncode, result.stdout[-1500:]) + result.stderr[-1500:] + return tuple(int(v) for v in found[0]) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + for name in ('X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT', 'X2W_D3D12_RING_RELEASE_AT_SUBMIT', 'X2W_D3D12_HEAP_TOKENS', + 'X2W_D3D12_VIEW_CONTENT_TOKENS', 'X2W_TEST_RING_CURSOR'): + env.pop(name, None) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == untouched and len(lines(result, 'refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + on_env = dict(env, X2W_D3D12_HEAP_TOKENS='1', X2W_TEST_RING_CURSOR=str(RING_ON - 1)) + got, result = dispatch(directory, consumer, on_env, 'dispatch') + assert got == expected and not lines(result, 'refused'), result.stderr[-3000:] + reserves, first, highest, refused, ring = ring_line(result) + assert ring == RING_ON, 'opt-in ring is %d slots, expected %d' % (ring, RING_ON) + assert reserves == 1, 'the Dispatch made %d reservations through the ring function, expected 1' % reserves + assert first == 0, 'a table that does not fit before the end of the ring starts at %d, not 0' % first + assert 2 <= highest <= RING_ON and refused == 0, (highest, refused) + table = highest - first + print(f'{adapter}: opt-in: ring {ring} slots, a {table}-slot table at the last ring slot starts at slot 0, ends at {highest}') + + off_env = dict(env, X2W_D3D12_HEAP_TOKENS='0', X2W_TEST_RING_CURSOR=str(RING_ON - 1)) + got, result = dispatch(directory, consumer, off_env, 'dispatch') + assert got == expected and not lines(result, 'refused'), result.stderr[-3000:] + reserves, first, highest, refused, ring = ring_line(result) + assert ring == HEAP, 'the ring without the opt-in is %d slots, expected %d' % (ring, HEAP) + assert reserves == 1 and first == RING_ON - 1 and highest == first + table and refused == 0, (reserves, first, highest, refused) + print(f'{adapter}: opt-in off: ring {ring} slots (the whole heap), the same cursor gives slot {first}') + print(f'startup_compute_dispatch_ring: PASS on {adapter}') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index b9ec7ec359..4b4d459cc7 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -150,6 +150,13 @@ def check_manifest_refusal(case, variant, reason, extra_env=None): manifest.write_bytes(variant.encode()) readback, dispatch_result = run(directory, consumer, dict(env, **(extra_env or {})), 'texture-store', layout) refusals = [message for message in lines(dispatch_result, 'Dispatch(') if ' refused: ' in message] + if reason == 'heap tokens are not bound yet (runtime binding in progress)': + # With the opt-in alone the text depends on whether the consumer's view heap got a GPU alias: only a 32-byte + # descriptor stride does (WARP's is 64 bytes), and then the refusal is the named one for the missing alias. + aliases = lines(dispatch_result, 'heap token alias of ') + assert len(aliases) == 1, (case, aliases) + if not aliases[0].endswith('-> 0x00000000'): + reason = 'heap tokens need a GPU-visible view heap' suffix = 'Dispatch(2, 1, 1) refused: ' + reason assert len(refusals) == 1 and refusals[0].endswith(suffix), (case, refusals, dispatch_result.stderr[-3000:]) assert readback == untouched, f'{case}: a refused Dispatch wrote the texture' diff --git a/tests/startup_compute_heap_token_check.py b/tests/startup_compute_heap_token_check.py index 2faeebe308..0e60f4658f 100644 --- a/tests/startup_compute_heap_token_check.py +++ b/tests/startup_compute_heap_token_check.py @@ -14,15 +14,22 @@ records exist (the control). 4. Controls: a descriptor nothing was written to resolves to no record; the export refuses a missing device, resource or description. -5. The draw heap region (x2w_d3d12_heap_token_layout, _draw_heap, _ring): the heap keeps 1 << 18 slots, the ring is - 196,603 of them (65,536 mirror slots and 5 nulls above), the five typed nulls are written when the heap is created - (with the switch on only), and no reservation of the ring, wherever its cursor starts, reaches the region. -6. The GPU alias of a title view heap (x2w_d3d12_heap_token_alias): a shader-visible view heap over a VirtualAlloc - allocation gets an alias heap and buffer over all its memory (NumElements = entries * 8 raw dwords); title memory - that is not an allocation base gets none and is counted as a failure; a heap that is not shader visible gets none. - The refusal a heap token program gets (x2w_d3d12_heap_token_refusal) follows: "heap tokens need a GPU-visible view - heap" while no view heap has an alias, then the transitional text once one has (or the capability text when the - adapter lacks the directly indexed resource heap). With the switch off no alias is made and the text is the old one. +5. The draw heap region (x2w_d3d12_heap_token_layout, _draw_heap, _ring): the heap keeps 1 << 18 slots. With the switch + on the ring is 196,603 of them (65,536 mirror slots and 5 nulls above) and the five typed nulls are written when the + heap is created; with it off the ring is the whole heap (262,144, as before the region) and nothing is written. No + reservation of the ring, wherever its cursor starts, leaves it; a reservation larger than the ring is refused and + counted (x2w_d3d12_heap_token_ring_mark / _ring_probe). +6. The GPU alias of a view heap's memory (x2w_d3d12_heap_token_alias): only memory the runtime allocated itself (a + shader-visible view heap the title gave no memory for) and only with the 32-byte descriptor stride the raw view + needs. Memory the title supplied gets none (counted, never aliased), nor does a heap that is not shader visible. + Releasing the descriptor heap drops its alias (0 live afterwards). The production HeapTokenAliases::open is also + driven directly (x2w_d3d12_heap_token_alias_open): an address opened twice, or reopened after its release, keeps one + entry and the entry is the fresh one (generation); a 64-byte stride, a span too small for the records and an + interior pointer are refused and counted. The refusal a heap token program gets (x2w_d3d12_heap_token_refusal) + follows: "heap tokens need a GPU-visible view heap" while no view heap has an alias, then the transitional text once + one has (or the capability text when the adapter lacks the directly indexed resource heap). With the switch off no + alias is made and the text is the old one. WARP's CBV/SRV/UAV stride may be 64 bytes: the heap created through + CreateDescriptorHeap is then the refusal case, and the success case is covered by the direct open only. Not checked here (later commits): descriptors per record in the draw heap, the kinds table, any dispatch, texels or raw words read through a token, the miss counter, lifetime and states, hardware adapters. @@ -219,9 +226,10 @@ def committed(dimension, width, height, fmt, layout): # 5. The draw heap region and its ring. layout = (ctypes.c_uint * 4)() xs.x2w_d3d12_heap_token_layout(layout) - fails.expect(list(layout) == [1 << 18, (1 << 18) - 65536 - 5, 65536, 5], + # With the switch on the region is reserved and the ring is below it; with it off the ring is the whole heap, as on main. + ring_size = (1 << 18) - 65536 - 5 if on else 1 << 18 # not read back from the export: the reservations must keep to it + fails.expect(list(layout) == [1 << 18, ring_size, 65536, 5], 'layout (heap, ring, mirror, nulls) is %s' % list(layout)) - ring_size = (1 << 18) - 65536 - 5 # not read back from the export: the reservations below must keep to it xs.x2w_d3d12_heap_token_draw_heap.restype = ctypes.c_uint xs.x2w_d3d12_heap_token_draw_heap.argtypes = [ctypes.c_void_p] nulls = xs.x2w_d3d12_heap_token_draw_heap(device) @@ -244,17 +252,42 @@ def committed(dimension, width, height, fmt, layout): fails.expect(False, 'ring reservation [%d, %d) leaves the ring (%d slots)' % (first, first + n, ring_size)) break fails.expect(top > ring_size - 4096, 'the ring never came near its top (%d of %d): the check is too weak' % (top, ring_size)) + # A reservation larger than the ring never writes the region: it is refused (and counted), the cursor stays. + class RingProbe(ctypes.Structure): + _fields_ = [('reserves', ctypes.c_uint), ('first', ctypes.c_uint), ('highest_end', ctypes.c_uint), + ('refused', ctypes.c_uint), ('ring_slots', ctypes.c_uint), ('pad', ctypes.c_uint)] + xs.x2w_d3d12_heap_token_ring_mark.argtypes = [ctypes.c_long] + xs.x2w_d3d12_heap_token_ring_probe.argtypes = [ctypes.c_void_p] + xs.x2w_d3d12_heap_token_ring_mark(1000) + for n in (ring_size + 1, ring_size + 5, ring_size + 65541, 1 << 19, 0x80000000): + fails.expect(xs.x2w_d3d12_heap_token_ring(n, 0, 0) == 0xffffffff, 'a reservation of %d slots (ring %d) was not refused' % (n, ring_size)) + probe = RingProbe() + xs.x2w_d3d12_heap_token_ring_probe(ctypes.byref(probe)) + fails.expect(probe.refused == 5 and probe.reserves == 5 and probe.highest_end == 0 and probe.ring_slots == ring_size, + 'ring probe after 5 oversize reservations: reserves %d refused %d highest end %d ring %d' % + (probe.reserves, probe.refused, probe.highest_end, probe.ring_slots)) + first = xs.x2w_d3d12_heap_token_ring(1, 0, 0) + fails.expect(first == 1000, 'a refused reservation moved the cursor: the next one starts at %d, not 1000' % first) + first = xs.x2w_d3d12_heap_token_ring(ring_size, 0, 0) + fails.expect(first == 0, 'a reservation of exactly the whole ring starts at %d, not 0' % first) # 6. The GPU alias of title view heap memory, and the refusal that follows. xs.x2w_d3d12_heap_token_alias.argtypes = [ctypes.c_ulonglong, ctypes.c_void_p] xs.x2w_d3d12_heap_token_refusal.argtypes = [ctypes.c_char_p, ctypes.c_uint] + xs.x2w_d3d12_heap_token_alias_open.restype = ctypes.c_long + xs.x2w_d3d12_heap_token_alias_open.argtypes = [ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong, ctypes.c_uint, + ctypes.c_ulonglong] + xs.x2w_d3d12_heap_token_alias_release.restype = ctypes.c_int + xs.x2w_d3d12_heap_token_alias_release.argtypes = [ctypes.c_ulonglong] + + class Probe(ctypes.Structure): + _fields_ = [('found', ctypes.c_uint), ('entries', ctypes.c_uint), ('num_elements', ctypes.c_uint), + ('alias_any', ctypes.c_uint), ('alias_failed', ctypes.c_uint), ('lacks', ctypes.c_uint), + ('count', ctypes.c_uint), ('title_supplied', ctypes.c_uint), ('bytes', ctypes.c_ulonglong), + ('buffer_bytes', ctypes.c_ulonglong), ('heap_bytes', ctypes.c_ulonglong), + ('generation', ctypes.c_ulonglong)] def alias(memory): - class Probe(ctypes.Structure): - _fields_ = [('found', ctypes.c_uint), ('entries', ctypes.c_uint), ('num_elements', ctypes.c_uint), - ('alias_any', ctypes.c_uint), ('alias_failed', ctypes.c_uint), ('lacks', ctypes.c_uint), - ('pad', ctypes.c_uint), ('bytes', ctypes.c_ulonglong), ('buffer_bytes', ctypes.c_ulonglong), - ('heap_bytes', ctypes.c_ulonglong)] probe = Probe() xs.x2w_d3d12_heap_token_alias(memory, ctypes.byref(probe)) return probe @@ -284,29 +317,108 @@ def view_heap(flags, backing): fails.expect(refusal() == (NEED_ROOT if on and lacks else NEED_HEAP if on else OLD), 'refusal before any alias: "%s"' % refusal()) + def cpu_start(heap): + # ID3D12DescriptorHeap::GetCPUDescriptorHandleForHeapStart, slot 9: the title memory of a view heap. + return vcall(heap, 9, ctypes.c_ulonglong, []) + + def release_heap(heap): + vcall(heap, 2, ctypes.c_ulong, []) + + unsupported_stride = stride != 32 # WARP may give 64: the heaps below are then the refusal case + MIN_REFUSAL = NEED_ROOT if on and lacks else NEED_HEAP if on else OLD + + # Memory the title supplied is never aliased (the runtime cannot see when the title frees it), whether it is an + # allocation base or an interior pointer; it is counted for the measurement. base = kernel.VirtualAlloc(None, 0x3000, 0x3000, 0x04) - interior = base + 0x1000 # not the start of an allocation - view_heap(SHADER_VISIBLE, interior) + interior = base + 0x1000 + supplied_heap = view_heap(SHADER_VISIBLE, interior) state = alias(interior) - fails.expect(state.found == 0 and state.alias_any == 0, 'title memory that is not an allocation base got an alias') - fails.expect(state.alias_failed == (1 if on else 0), 'alias failures %d after the interior heap' % state.alias_failed) - fails.expect(refusal() == (NEED_ROOT if on and lacks else NEED_HEAP if on else OLD), - 'refusal with only an interior heap: "%s"' % refusal()) - + fails.expect(state.found == 0 and state.count == 0 and state.alias_failed == 0, + 'a view heap over title-supplied interior memory got an alias or a failure') + fails.expect(state.title_supplied == (1 if on else 0), 'title-supplied view heaps counted: %d' % state.title_supplied) good = kernel.VirtualAlloc(None, 0x1000, 0x3000, 0x04) - view_heap(SHADER_VISIBLE, good) + supplied_base_heap = view_heap(SHADER_VISIBLE, good) state = alias(good) - if on: - fails.expect(state.found == 1 and state.alias_any == 1, 'a shader-visible view heap over a VirtualAlloc allocation got no alias') + fails.expect(state.found == 0 and state.count == 0 and state.alias_failed == 0, + 'a view heap over title-supplied memory (an allocation base) got an alias') + fails.expect(state.title_supplied == (2 if on else 0), 'title-supplied view heaps counted: %d' % state.title_supplied) + fails.expect(refusal() == MIN_REFUSAL, 'refusal with only title-supplied view heaps: "%s"' % refusal()) + + # A shader-visible view heap with memory of the runtime's own (no backing given) is aliased when the stride is 32. + own_heap = view_heap(SHADER_VISIBLE, 0) + own = cpu_start(own_heap) + fails.expect(own != 0, 'a view heap without title memory has no CPU start') + state = alias(own) + if not on: + fails.expect(state.found == 0 and state.count == 0 and state.alias_failed == 0, 'an alias was made with the switch off') + fails.expect(refusal() == OLD, 'refusal with the switch off: "%s"' % refusal()) + elif unsupported_stride: + print('note: the descriptor stride here is %d, not 32: CreateDescriptorHeap gives the refusal case' % stride, flush=True) + fails.expect(state.found == 0 and state.count == 0, 'a view heap with a %d-byte descriptor stride got an alias' % stride) + fails.expect(state.alias_failed == 1, 'alias failures %d after the %d-byte stride heap' % (state.alias_failed, stride)) + fails.expect(refusal() == MIN_REFUSAL, 'refusal with a %d-byte stride heap: "%s"' % (stride, refusal())) + else: + fails.expect(state.found == 1 and state.count == 1, 'a shader-visible view heap of our own memory got no alias') fails.expect(state.entries == count and state.num_elements == count * 8, 'alias covers %d entries / %d elements' % (state.entries, state.num_elements)) fails.expect(state.bytes == stride * count and state.buffer_bytes == state.bytes and state.heap_bytes >= state.bytes, 'alias spans %d bytes (buffer %d, heap %d) of %d' % (state.bytes, state.buffer_bytes, state.heap_bytes, stride * count)) fails.expect(state.num_elements * 4 <= state.buffer_bytes, 'NumElements * 4 exceeds the alias buffer') - fails.expect(state.alias_failed == 1, 'alias failures %d after the good heap' % state.alias_failed) + fails.expect(state.alias_failed == 0, 'alias failures %d after the good heap' % state.alias_failed) fails.expect(refusal() == (NEED_ROOT if lacks else PROGRESS), 'refusal with an alias: "%s"' % refusal()) - else: - fails.expect(state.found == 0 and state.alias_any == 0 and state.alias_failed == 0, 'an alias was made with the switch off') - fails.expect(refusal() == OLD, 'refusal with the switch off: "%s"' % refusal()) + # The final release of the descriptor heap drops its alias: none live afterwards, and the refusal is back. + release_heap(own_heap) + state = alias(own) + fails.expect(state.found == 0 and state.count == 0, 'the alias survived the release of its descriptor heap (%d live)' % state.count) + fails.expect(refusal() == MIN_REFUSAL, 'refusal after the release: "%s"' % refusal()) + + if not on: + print('child %s: %s' % (switch, 'PASS' if not fails.count else '%d failures' % fails.count), flush=True) + return 1 if fails.count else 0 + + # The production open, driven directly (any descriptor stride): memory the test owns, so it can be opened again. + before = alias(0).count + mem = kernel.VirtualAlloc(None, 0x2000, 0x3000, 0x04) + S_OK, E_INVALIDARG = 0, -2147024809 + + def open_alias(memory, bytes_, entries, title_stride): + return xs.x2w_d3d12_heap_token_alias_open(device, memory, bytes_, entries, title_stride) + + failed_before = alias(0).alias_failed + fails.expect(open_alias(mem, 256 * 32, 256, 32) == S_OK, 'a direct open of an allocation base with a 32-byte stride failed') + first_alias = alias(mem) + fails.expect(first_alias.found == 1 and first_alias.count == before + 1 and first_alias.num_elements == 256 * 8, + 'the direct open left %d aliases (before %d), num_elements %d' % (first_alias.count, before, first_alias.num_elements)) + # The same address again, as when freed memory comes back: one entry, and it is the fresh one. + fails.expect(open_alias(mem, 128 * 32, 128, 32) == S_OK, 'opening the same address again failed') + second_alias = alias(mem) + fails.expect(second_alias.count == before + 1, 'two opens of one address left %d entries (one expected)' % (second_alias.count - before)) + fails.expect(second_alias.found == 1 and second_alias.entries == 128 and second_alias.generation > first_alias.generation, + 'the entry at a reopened address is stale (entries %d, generation %d after %d)' % + (second_alias.entries, second_alias.generation, first_alias.generation)) + fails.expect(xs.x2w_d3d12_heap_token_alias_release(mem) == 1, 'release found no alias of the address') + fails.expect(alias(mem).found == 0 and alias(0).count == before, 'an alias is left after its release') + fails.expect(xs.x2w_d3d12_heap_token_alias_release(mem) == 0, 'a second release found an alias') + fails.expect(open_alias(mem, 64 * 32, 64, 32) == S_OK, 'an open after the release failed') + third_alias = alias(mem) + fails.expect(third_alias.found == 1 and third_alias.entries == 64 and third_alias.generation > second_alias.generation and + third_alias.count == before + 1, 'the alias after release and reopen is not fresh') + # Refusals, each counted: the 64-byte stride (S4), too few bytes for the records, an interior pointer. + fails.expect(open_alias(mem + 0x1000, 8 * 32, 8, 64) == E_INVALIDARG, 'a 64-byte stride was taken') + fails.expect(open_alias(mem + 0x1000, 8 * 32, 8, 16) == E_INVALIDARG, 'a 16-byte stride was taken') + fails.expect(open_alias(mem + 0x1000, 7 * 32, 8, 32) == E_INVALIDARG, 'a span too small for its records was taken') + fails.expect(open_alias(mem + 0x1000, 8 * 32, 8, 32) < 0, 'an interior pointer was taken') + fails.expect(alias(mem + 0x1000).found == 0, 'a refused open left an entry') + fails.expect(alias(0).alias_failed == failed_before + 4, 'the four refused opens counted %d failures' % (alias(0).alias_failed - failed_before)) + fails.expect(alias(0).count == before + 1, 'refused opens changed the number of aliases') + + # The drop path of the real descriptor heap, whatever the stride: the final release of a descriptor heap whose title + # memory is that of a live alias drops it. (A heap the title gave memory for gets no alias of its own, so the alias + # of `mem` here is the one opened above; this is the same hook a runtime-owned heap goes through.) + drop_heap = view_heap(SHADER_VISIBLE, mem) + fails.expect(alias(mem).found == 1, 'creating a heap over supplied memory dropped an alias') + release_heap(drop_heap) + state = alias(mem) + fails.expect(state.found == 0 and state.count == before, 'releasing the descriptor heap left %d alias(es)' % (state.count - before)) print('child %s: %s' % (switch, 'PASS' if not fails.count else '%d failures' % fails.count), flush=True) return 1 if fails.count else 0 diff --git a/tests/startup_draw_depth_target.cpp b/tests/startup_draw_depth_target.cpp index a2a8bf1a85..e37d030215 100644 --- a/tests/startup_draw_depth_target.cpp +++ b/tests/startup_draw_depth_target.cpp @@ -33,6 +33,13 @@ using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) void x2w_d3d12_render_target_stats(unsigned* binds, unsigned* unresolved); +// The ring of the translated draws' descriptor tables: X2W_TEST_RING_CURSOR= sets its cursor before the two draws and the +// reservations the draws made are printed after them (startup_draw_depth_target_check.py ring). +struct HeapTokenRingProbe { + unsigned reserves, first_since_mark, highest_end, refused, ring_slots, pad; +}; +extern "C" __declspec(dllimport) void x2w_d3d12_heap_token_ring_mark(LONG cursor); +extern "C" __declspec(dllimport) void x2w_d3d12_heap_token_ring_probe(HeapTokenRingProbe* out); namespace { @@ -285,10 +292,18 @@ int main(int argc, char** argv) invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); const D3D12_CPU_DESCRIPTOR_HANDLE* depth_handle = which == "bound" ? &dsv : which == "unknown" ? &unknown_handle : &null_handle; invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(depth_handle)); + const char* const ring_cursor = std::getenv("X2W_TEST_RING_CURSOR"); + if (ring_cursor) x2w_d3d12_heap_token_ring_mark(std::strtol(ring_cursor, nullptr, 10)); invoke(state.list, 25, ptr_arg(green)); invoke(state.list, 12, 3, 1); invoke(state.list, 25, ptr_arg(red)); invoke(state.list, 12, 3, 1); + if (ring_cursor) { + HeapTokenRingProbe ring{}; + x2w_d3d12_heap_token_ring_probe(&ring); + std::printf("descriptor ring: reserves %u first %u highest end %u refused %u ring slots %u\n", ring.reserves, + ring.first_since_mark, ring.highest_end, ring.refused, ring.ring_slots); + } if (const int rc = execute_guest_list(state.queue, state.list, state.fence, 1)) return rc; x2w_d3d12_render_target_stats(&binds_after, &unresolved_after); if (const int rc = read_stream_target(desktop.Get(), state, (prefix + ".rgba").c_str())) return rc; diff --git a/tests/startup_draw_depth_target_check.py b/tests/startup_draw_depth_target_check.py index a93a93e9bf..26bd025f7d 100644 --- a/tests/startup_draw_depth_target_check.py +++ b/tests/startup_draw_depth_target_check.py @@ -22,6 +22,13 @@ "debug" runs the bound case with the D3D12 debug layer (X2W_D3D12_DEBUG=1) and requires the bound picture and no debug-layer message of any severity after the fence. Without an installed debug layer the message check cannot run, so this mode exits 77 (a capability skip that CTest reports as such) instead of passing. + +"ring" runs the bound case twice with the ring cursor of the translated draws' descriptor tables set past the ring +(X2W_TEST_RING_CURSOR = ring + 7) and reads back what the two draws reserved through the production ring function +(src/startup_stubs/d3d12_draw.inl): with X2W_D3D12_HEAP_TOKENS=1 the ring is 196,603 slots and the first table starts at +slot 7, and nothing reaches the region above the ring; without the opt-in the ring is the whole 262,144-slot heap and the +same cursor gives slot 196,610. A draw site that went back to the old modulus makes no reservation through the ring +function (reserves 0 instead of 2) and fails. The picture is the bound one in both runs. """ import os from pathlib import Path @@ -102,9 +109,41 @@ def run_case(directory, args, env, case): "refused": REFUSED_LOG in run.stderr, "debug": debug, "debug_layer": "x2w-d3d12 debug layer: 0x00000000 enabled" in run.stderr, + "ring": re.findall(r"descriptor ring: reserves (\d+) first (\d+) highest end (\d+) refused (\d+) ring slots (\d+)", + run.stdout), } +HEAP_SLOTS = 1 << 18 +RING_ON = HEAP_SLOTS - 65536 - 5 # 196,603 + + +def check_ring(directory, args, env): + """The two bound draws' reservations with the cursor past the ring, opt-in on and off. Returns the failures.""" + failed = [] + for opt_in, ring_slots, first in (("1", RING_ON, 7), ("0", HEAP_SLOTS, RING_ON + 7)): + case_env = dict(env, X2W_D3D12_HEAP_TOKENS=opt_in, X2W_TEST_RING_CURSOR=str(RING_ON + 7)) + case_env.pop("X2W_D3D12_VIEW_CONTENT_TOKENS", None) + result = run_case(directory, args, case_env, "bound") + label = "ring opt-in " + ("on" if opt_in == "1" else "off") + if (result["colour"], result["depth"]) != BOUND: + failed.append(f"{label}: {describe(result)}") + if len(result["ring"]) != 1: + failed.append(f"{label}: no descriptor ring line") + continue + reserves, got_first, highest, refused, slots = map(int, result["ring"][0]) + print(f"{label}: reserves {reserves}, first {got_first}, highest end {highest}, refused {refused}, ring {slots} slots") + if slots != ring_slots: + failed.append(f"{label}: the ring is {slots} slots, expected {ring_slots}") + if reserves != 2: + failed.append(f"{label}: the two draws made {reserves} reservations through the ring function, expected 2") + if got_first != first: + failed.append(f"{label}: the first table starts at slot {got_first}, expected {first}") + if highest > slots or refused: + failed.append(f"{label}: highest end {highest} of a {slots}-slot ring, {refused} refused") + return failed + + def describe(result): values = struct.unpack("<32f", result["depth"]) return f"colour {result['colour'][:16].hex()}..., depth row 0 {values[:8]}" @@ -113,7 +152,7 @@ def describe(result): def main(): program, backend = sys.argv[1], sys.argv[2] mode = sys.argv[3] if len(sys.argv) > 3 else "check" - if mode not in ("check", "drop", "debug"): + if mode not in ("check", "drop", "debug", "ring"): print(__doc__) return 64 try: @@ -133,8 +172,16 @@ def main(): print(f"control drop: {describe(result)} -> " + ("failed for the stated reason" if stated else "did NOT fail for the stated reason")) return 0 if stated else 1 + if mode == "ring": + failures = check_ring(directory, args, env) + for line in failures: + print("FAIL", line) + if not failures: + print(f"{backend}: the draw ring is 196,603 slots with the opt-in and 262,144 without; the two draws " + "reserved through it and stayed below the region") + return 1 if failures else 0 if mode == "debug": - bound = run_case(directory, args, env, "bound") + bound =run_case(directory, args, env, "bound") if not bound["debug_layer"]: print("the D3D12 debug layer is not installed: the debug-message check cannot run (skip)") return 77 diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index b52a50a839..75888d5a3a 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -29,6 +29,13 @@ using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) void x2w_d3d12_compute_census(); extern "C" __declspec(dllimport) UINT64 x2w_d3d12_snapshot_pool_used(); +// The ring of per-dispatch descriptor tables (startup_compute_dispatch_ring_check.py): set its cursor, read back what the +// reservations since did. +struct HeapTokenRingProbe { + unsigned reserves, first_since_mark, highest_end, refused, ring_slots, pad; +}; +extern "C" __declspec(dllimport) void x2w_d3d12_heap_token_ring_mark(LONG cursor); +extern "C" __declspec(dllimport) void x2w_d3d12_heap_token_ring_probe(HeapTokenRingProbe* out); extern "C" __declspec(dllimport) BOOL x2w_d3d12_record_uncreated_buffer_srv(void* resource, const void* desc, UINT desc_bytes, UINT64 title_cpu); @@ -916,6 +923,10 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin invoke(list, 14, 3, 2, 2); std::memcpy(reinterpret_cast(between), input, sizeof(input)); } + // X2W_TEST_RING_CURSOR=: the ring cursor of the translated tables is set to n just before the Dispatch, and what the + // Dispatch reserved is printed after it. + const char* const ring_cursor = std::getenv("X2W_TEST_RING_CURSOR"); + if (ring_cursor) x2w_d3d12_heap_token_ring_mark(std::strtol(ring_cursor, nullptr, 10)); const bool measure_snapshot_pool = snapshot_input || mode == "dispatch-input-null"; const UINT64 snapshot_used_before = measure_snapshot_pool ? x2w_d3d12_snapshot_pool_used() : 0; if (pixel) record.capture_before_consumer(adapter, device, list); @@ -933,6 +944,13 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin invoke(list, 14, 3, full_wave ? 3 : 2, full_wave ? 1 : 2); if (measure_snapshot_pool) std::printf("snapshot pool used bytes: %llu -> %llu\n", snapshot_used_before, x2w_d3d12_snapshot_pool_used()); + if (ring_cursor) { + HeapTokenRingProbe ring{}; + x2w_d3d12_heap_token_ring_probe(&ring); + std::printf("descriptor ring: reserves %u first %u highest end %u refused %u ring slots %u\n", ring.reserves, + ring.first_since_mark, ring.highest_end, ring.refused, ring.ring_slots); + std::fflush(stdout); + } if (copied_token_output) { // An attempted read of the very placement whose UAV could not be made guest-visible. invoke(list, 15, word(placed[1]), 16, word(copied_token_output), 16, 16); diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index c9ab0ff510..00b9bb8465 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -386,7 +386,7 @@ def check_allowlist_covers_source_reasons(failures: list[str]) -> None: quote = chr(34) reason_start = re.compile( "^(?:a|an|the|no|not|zeros|formatted|translated indirect|manifest|native|root|pipeline|entry|" - "more than|resource|view above|stride words)\\b", + "more than|resource|view above|stride words|heap tokens?)\\b", re.I, ) # Source labels printed beside a reason, not refusal reasons themselves. @@ -433,13 +433,20 @@ def function_body(text: str, name: str) -> str: draw_path = REPO_ROOT / "src" / "startup_stubs" / "d3d12_draw.inl" token_path = REPO_ROOT / "src" / "startup_stubs" / "input_view_token.h" root_path = REPO_ROOT / "src" / "startup_stubs" / "translated_sampler_bindings.h" - if not dispatch_path.exists() or not draw_path.exists() or not token_path.exists() or not root_path.exists(): + gate_path = REPO_ROOT / "src" / "startup_stubs" / "heap_token_binding.h" + if (not dispatch_path.exists() or not draw_path.exists() or not token_path.exists() or not root_path.exists() or + not gate_path.exists()): failures.append("compute Dispatch source files not found") return found = literals(dispatch_path.read_text(encoding="utf-8")) found |= literals(function_body(draw_path.read_text(encoding="utf-8"), "indirect_table_buffer")) found |= literals(function_body(token_path.read_text(encoding="utf-8"), "input_view_token_refusal")) found |= literals(function_body(root_path.read_text(encoding="utf-8"), "compute_root_refusal")) + # The heap token gate (heap_token_refusal gives its text to the manifest reader and the native route). + gate = literals(function_body(gate_path.read_text(encoding="utf-8"), "heap_token_gate_text")) + if len(gate) != 5: + failures.append(f"heap_token_gate_text should carry 5 refusal texts, the scan found {len(gate)}") + found |= gate missing = sorted(s for s in found if s not in triage_run.COMPUTE_DISPATCH_REASONS) if missing: failures.append("source reasons missing from COMPUTE_DISPATCH_REASONS: " + ", ".join(repr(s) for s in missing)) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 34230cf978..30c2a841da 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -231,6 +231,10 @@ 'formatted D16 write has an incompatible typed buffer UAV', 'formatted D16 write needs the original typed buffer view', 'heap token textures are not bound yet', + 'heap tokens are not bound yet (runtime binding in progress)', + 'heap tokens need a GPU-visible view heap', + 'heap tokens need a directly indexed resource heap', + 'heap tokens need id tokens', 'manifest version', 'native translation from another compiler revision; rebuild it', 'native translation without a revision; rebuild it', @@ -247,6 +251,7 @@ 'the adapter has no 32-lane waves', 'the adapter reports shader model below 6.6', 'the compute root set is not the one the pipeline was created with', + 'the descriptor table is larger than the ring', 'the device does not take a directly indexed resource heap', 'the device does not take a directly indexed sampler heap', 'the indirect argument buffer is also a bound shader resource', From 716139be25ef9b0fdff16471718ad04b2e49d4fc Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 04:13:33 +0100 Subject: [PATCH 15/19] d3d12 runtime: heap token review fixes 2 (stride-derived test expectations, pinned mutant controls, refusal path) - Dispatch native/texture checks derive the expected refusal from the adapter's view descriptor stride (now logged by the alias open): stride != 32 expects the view heap refusal, stride 32 requires the alias to have succeeded. - Each heap_token_binding mutant control pins its own FAIL line. - Draw ring refusal text is in the triage allowlist; the scanner also scans draw_translated. Dispatch oversize refusal now goes through the reason path (checked before reserving). - Fix a misleading label in heap_token_binding_check. Sites without a header mutant are caught by device tests (mutation-checked by hand): alias release on final heap release and duplicate replace by startup_compute_heap_token; draw/dispatch oversize have no device test (unreachable in production). AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 36 ++++++++++++------- src/startup_stubs/d3d12_compute_dispatch.inl | 11 +++--- src/startup_stubs/d3d12_xs_device.cpp | 4 +-- tests/heap_token_binding_check.cpp | 2 +- .../startup_compute_dispatch_native_check.py | 11 ++++-- .../startup_compute_dispatch_texture_check.py | 12 +++++-- tests/startup_triage_run_check.py | 12 +++++-- tools/startup/triage_run.py | 1 + 8 files changed, 59 insertions(+), 30 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5e4ac43422..62236a4fb1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2450,10 +2450,10 @@ target_include_directories(heap_token_binding_check PRIVATE src) target_compile_features(heap_token_binding_check PRIVATE cxx_std_17) add_test(NAME heap_token_binding COMMAND heap_token_binding_check) # Mutation controls: the same check, built against a copy of heap_token_binding.h with one real edit of the production code -# (the anchor is replaced; configure fails when the header no longer holds it). The check must print FAIL lines. +# (the anchor is replaced; configure fails when the header no longer holds it). The check must print the FAIL line named for the mutant (the last argument), not just any. set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/heap_token_binding.h) file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/heap_token_binding.h" heap_token_binding_text) -function(heap_token_binding_mutant name anchor replacement) +function(heap_token_binding_mutant name anchor replacement caught) string(FIND "${heap_token_binding_text}" "${anchor}" position) if(position LESS 0) message(FATAL_ERROR "heap_token_binding.h lost the anchor of heap_token_binding_${name}_control: ${anchor}") @@ -2468,29 +2468,39 @@ function(heap_token_binding_mutant name anchor replacement) target_include_directories(heap_token_binding_${name}_check PRIVATE "${directory}" src) target_compile_features(heap_token_binding_${name}_check PRIVATE cxx_std_17) add_test(NAME heap_token_binding_${name}_control COMMAND heap_token_binding_${name}_check) - set_tests_properties(heap_token_binding_${name}_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL") + set_tests_properties(heap_token_binding_${name}_control PROPERTIES PASS_REGULAR_EXPRESSION "${caught}") endfunction() heap_token_binding_mutant(ring-full-heap - "return opt_in ? heap_token_ring_size(heap_slots) : heap_slots;" "return heap_slots;") + "return opt_in ? heap_token_ring_size(heap_slots) : heap_slots;" "return heap_slots;" + "FAIL: the ring with the opt-in is not 196,603 slots") heap_token_binding_mutant(ring-always-reduced - "return opt_in ? heap_token_ring_size(heap_slots) : heap_slots;" "return heap_token_ring_size(heap_slots);") + "return opt_in ? heap_token_ring_size(heap_slots) : heap_slots;" "return heap_token_ring_size(heap_slots);" + "FAIL: the ring without the opt-in is not the whole 262,144-slot heap") heap_token_binding_mutant(region-overlap - "return heap_token_ring_size(heap_slots) + id; }" "return heap_token_ring_size(heap_slots) + id - 1; }") + "return heap_token_ring_size(heap_slots) + id; }" "return heap_token_ring_size(heap_slots) + id - 1; }" + "FAIL: the mirror does not start where the ring ends") heap_token_binding_mutant(ring-wrap-dropped - "if (first + n > ring_size) {" "if (false) {") + "if (first + n > ring_size) {" "if (false) {" + "FAIL: a reservation of 5 slots 3 below the end of the ring does not start at 0") heap_token_binding_mutant(ring-oversize-taken - "if (n > ring_size || n > 0x7fffffffu) return heap_token_ring_refused;" "") + "if (n > ring_size || n > 0x7fffffffu) return heap_token_ring_refused;" "" + "FAIL: a reservation larger than the ring is not refused") heap_token_binding_mutant(null-2da-as-2d - "desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;" "desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;") + "desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;" "desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;" + "FAIL: the 2D array null is not a 2D array texture view") heap_token_binding_mutant(alias-unchecked - "entries * heap_token_record_bytes <= bytes;" "true;") + "entries * heap_token_record_bytes <= bytes;" "true;" + "FAIL: a heap one byte short is taken") heap_token_binding_mutant(alias-stride-unchecked - "return title_stride == heap_token_record_bytes;" "return title_stride != 0;") + "return title_stride == heap_token_record_bytes;" "return title_stride != 0;" + "FAIL: a 64-byte stride is taken") heap_token_binding_mutant(root-flag-dropped "(heap_tokens_bound ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE)" - "D3D12_ROOT_SIGNATURE_FLAG_NONE") + "D3D12_ROOT_SIGNATURE_FLAG_NONE" + "FAIL: a heap token program's root lacks the view heap flag") heap_token_binding_mutant(gate-alias-ignored - "if (!view_heap_alias) return \"heap tokens need a GPU-visible view heap\";" "") + "if (!view_heap_alias) return \"heap tokens need a GPU-visible view heap\";" "" + "FAIL gate no GPU-visible view heap:") add_test(NAME startup_heap_indexed_root COMMAND startup_heap_indexed_root_check) foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 710fbed88f..e927b4785c 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1424,6 +1424,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& else if (u64{pass.sampler_snapshot->count} * x2w_startup::title_sampler_stride < tr->sampler_heap_bytes) reason = "the sampler heap is smaller than the program reads"; } + const UINT n = static_cast(count + tr->heap_srvs); + // A table larger than the ring would reach the heap token region: refused here, before anything is reserved, through + // the same reason path as the other refusals (draw_ring_reserve refuses exactly the tables larger than the ring). + if (!reason && n > draw_ring_size()) + reason = "the descriptor table is larger than the ring"; if (reason) { if (!tr->first_refusal) { tr->first_refusal = reason; @@ -1437,13 +1442,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); return reason; } - const UINT n = static_cast(count + tr->heap_srvs); const UINT first = draw_ring_reserve(n); - if (first == x2w_startup::heap_token_ring_refused) { // a table larger than the ring would reach the heap token region - ReleaseSRWLockExclusive(&draw_lock); - InterlockedIncrement(counter); - return "the descriptor table is larger than the ring"; - } D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index e204a76c25..ccef43c87d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5721,8 +5721,8 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR const HRESULT alias_hr = heap_token_aliases().open(device_of(self), title_memory, bytes, desc->NumDescriptors, title_stride); static LONG alias_logs; if (first_calls(alias_logs, 8)) - log("x2w-d3d12 Device::CreateDescriptorHeap: heap token alias of 0x%llx (%llu bytes) -> 0x%08lx", title_memory, bytes, - static_cast(alias_hr)); + log("x2w-d3d12 Device::CreateDescriptorHeap: heap token alias of 0x%llx (%llu bytes, view stride %u) -> 0x%08lx", + title_memory, bytes, title_stride, static_cast(alias_hr)); } Wrapper* w = wrap(heap, descriptor_heap_kind); if (!w) { diff --git a/tests/heap_token_binding_check.cpp b/tests/heap_token_binding_check.cpp index ac123d992e..77ed501213 100644 --- a/tests/heap_token_binding_check.cpp +++ b/tests/heap_token_binding_check.cpp @@ -75,7 +75,7 @@ void ring() } { volatile LONG cursor = 0; - expect(heap_token_ring_reserve(&cursor, ring_size, ring_size) == 0, "a reservation of exactly the whole ring is refused"); + expect(heap_token_ring_reserve(&cursor, ring_size, ring_size) == 0, "a reservation of exactly the whole ring is not accepted at slot 0"); } } diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index d1ac56d00a..8d703ec45a 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -415,12 +415,17 @@ def heap_token_refusal(directory, consumer, dxc_dir, adapter): reason = lines(result, 'not translated natively: ') want = expected if expected == 'heap tokens are not bound yet (runtime binding in progress)': - # With the opt-in alone the text depends on whether the consumer's view heap got a GPU alias: only a - # 32-byte descriptor stride does (WARP's is 64 bytes), and then the refusal is the named one for it. + # With the opt-in alone the text follows the adapter's CBV/SRV/UAV descriptor stride, which the open + # logs from the device (not from its result): only a 32-byte stride gets an alias (WARP's is 64 + # bytes). Another stride expects the named refusal; 32 needs the alias to have succeeded. aliases = lines(result, 'heap token alias of ') assert len(aliases) == 1, (extra, aliases) - if not aliases[0].endswith('-> 0x00000000'): + stride = re.search(r'view stride (\d+)\) -> (0x[0-9a-f]{8})$', aliases[0]) + assert stride, aliases + if int(stride.group(1)) != 32: want = NEED_VIEW_HEAP + else: + assert stride.group(2) == '0x00000000', f'the alias failed on a 32-byte stride adapter: {aliases[0]}' assert len(reason) == 1 and reason[0].endswith(want), (extra, result.stderr[-3000:]) assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] else: diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 4b4d459cc7..f486edc2a3 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -37,6 +37,7 @@ """ import os from pathlib import Path +import re import struct import subprocess import sys @@ -151,12 +152,17 @@ def check_manifest_refusal(case, variant, reason, extra_env=None): readback, dispatch_result = run(directory, consumer, dict(env, **(extra_env or {})), 'texture-store', layout) refusals = [message for message in lines(dispatch_result, 'Dispatch(') if ' refused: ' in message] if reason == 'heap tokens are not bound yet (runtime binding in progress)': - # With the opt-in alone the text depends on whether the consumer's view heap got a GPU alias: only a 32-byte - # descriptor stride does (WARP's is 64 bytes), and then the refusal is the named one for the missing alias. + # With the opt-in alone the text follows the adapter's CBV/SRV/UAV descriptor stride, which the open logs from + # the device (not from its result): only a 32-byte stride gets an alias (WARP's is 64 bytes). Another stride + # expects the named refusal; 32 needs the alias to have succeeded. aliases = lines(dispatch_result, 'heap token alias of ') assert len(aliases) == 1, (case, aliases) - if not aliases[0].endswith('-> 0x00000000'): + stride = re.search(r'view stride (\d+)\) -> (0x[0-9a-f]{8})$', aliases[0]) + assert stride, aliases + if int(stride.group(1)) != 32: reason = 'heap tokens need a GPU-visible view heap' + else: + assert stride.group(2) == '0x00000000', f'the alias failed on a 32-byte stride adapter: {aliases[0]}' suffix = 'Dispatch(2, 1, 1) refused: ' + reason assert len(refusals) == 1 and refusals[0].endswith(suffix), (case, refusals, dispatch_result.stderr[-3000:]) assert readback == untouched, f'{case}: a refused Dispatch wrote the texture' diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 00b9bb8465..f9d6af3d68 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -395,11 +395,15 @@ def check_allowlist_covers_source_reasons(failures: list[str]) -> None: "native", "native ", "no token", } - def literals(text: str) -> set[str]: + # draw_translated's other refusal notes (draw census codes such as "resource binding refused ...") are not Dispatch + # reasons; the one sentence about the descriptor table is, so only those are taken from it. + table_start = re.compile(r"^descriptor table\b", re.I) + + def literals(text: str, start=reason_start) -> set[str]: # The * matters: L"" pairs must stay aligned or every later string is mispaired. return { s for s in re.findall(quote + "([^" + quote + "]*)" + quote, text) - if reason_start.match(s) and s not in labels + if start.match(s) and s not in labels } def function_body(text: str, name: str) -> str: @@ -440,6 +444,10 @@ def function_body(text: str, name: str) -> str: return found = literals(dispatch_path.read_text(encoding="utf-8")) found |= literals(function_body(draw_path.read_text(encoding="utf-8"), "indirect_table_buffer")) + ring = literals(function_body(draw_path.read_text(encoding="utf-8"), "draw_translated"), table_start) + if ring != {"descriptor table larger than the ring"}: + failures.append(f"draw_translated should carry the descriptor table refusal text, the scan found {sorted(ring)}") + found |= ring found |= literals(function_body(token_path.read_text(encoding="utf-8"), "input_view_token_refusal")) found |= literals(function_body(root_path.read_text(encoding="utf-8"), "compute_root_refusal")) # The heap token gate (heap_token_refusal gives its text to the manifest reader and the native route). diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 30c2a841da..e6d444e401 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -227,6 +227,7 @@ 'an output typed buffer range is over 16 MiB', 'an unknown manifest line', 'an unsupported compute output view', + 'descriptor table larger than the ring', 'entry value, input or output count', 'formatted D16 write has an incompatible typed buffer UAV', 'formatted D16 write needs the original typed buffer view', From b0cdcdca97c1a9494781c71eadea4b1156c3e957 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 05:50:32 +0100 Subject: [PATCH 16/19] d3d12 runtime: bind heap view tokens for translated compute (opt-in) With X2W_D3D12_HEAP_TOKENS=1 a translated compute program with heaptok lines (manifest or in-process native route) now runs with the views its tokens name instead of being refused, when the runtime can bind them: - heap_token_mirror.inl: at a heap token Dispatch the ids queued by note_view get one desktop SRV each in the mirror region of the draw heap (slot ring + id), made from the title's own description through the new translate_srv_desc/check_view helpers that view_slot<18> shares. Only 1D, 2D, 2D array textures and raw buffer views are named; anything else gets kind 0. The mirror holds its own COM reference on each desktop resource. - The kinds table (heaptokdims) is a default-heap buffer; the span of it that changed is copied from the upload ring in the same command list before the Dispatch, after the descriptor was written. - The token SRV is a raw view over the GPU alias of the list's view heap, the miss UAV a persistent counter (read back and logged every 4096 heap token Dispatches); the three take table registers, no new root parameter, and the root takes the directly indexed resource heap flag. - Entry words (base/count/null per dimension) are computed per Dispatch (heap_token_word_value); count follows the current record count. - The gate text "heap tokens are not bound yet (runtime binding in progress)" is gone. A manifest whose token lines are not the translator's complete set is refused as such; no alias for the bound view heap keeps "heap tokens need a GPU-visible view heap". - Tests: startup_compute_heap_token_dispatch (hardware: texels of 1D, 2D, 2D array views, raw words, misses per wave, debug layer, published manifest, 4096-dispatch readback; WARP: the named refusal), mirror, kinds, refs and words in startup_compute_heap_token, unit checks and mutant controls in heap_token_binding. Known limits, left to the next commit: a mirror entry is never released (the resource stays alive, nothing is written to the slot again); resources a list tracks in a write state are not transitioned for a token read; the kinds copy is recorded in the first Dispatch list that sees the change. Default behaviour without the opt-in is unchanged. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 13 + docs/experiments.md | 2 +- .../experiments/native-heap-token-textures.md | 37 +- src/startup_stubs/d3d12_capture.inl | 2 +- src/startup_stubs/d3d12_compute_dispatch.inl | 134 ++++++-- src/startup_stubs/d3d12_xs_device.cpp | 325 +++++++++++++++--- src/startup_stubs/heap_token_binding.h | 94 ++++- src/startup_stubs/heap_token_kinds.h | 4 +- src/startup_stubs/heap_token_mirror.inl | 295 ++++++++++++++++ .../startup_compute_dispatch_native.cmake | 8 +- tests/heap_token_binding_check.cpp | 67 +++- tests/heap_token_kinds_check.cpp | 4 +- .../startup_compute_dispatch_native_check.py | 26 +- .../startup_compute_dispatch_texture_check.py | 18 +- tests/startup_compute_heap_token_check.py | 86 ++++- ...artup_compute_heap_token_dispatch_check.py | 280 +++++++++++++++ tests/startup_stream_consumer.cpp | 104 +++++- tests/startup_triage_run_check.py | 16 +- tools/startup/triage_run.py | 6 +- 19 files changed, 1385 insertions(+), 136 deletions(-) create mode 100644 src/startup_stubs/heap_token_mirror.inl create mode 100644 tests/startup_compute_heap_token_dispatch_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 62236a4fb1..dcef013601 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2501,6 +2501,19 @@ heap_token_binding_mutant(root-flag-dropped heap_token_binding_mutant(gate-alias-ignored "if (!view_heap_alias) return \"heap tokens need a GPU-visible view heap\";" "" "FAIL gate no GPU-visible view heap:") +heap_token_binding_mutant(null-2d-word-wrong + "case 5: return heap_token_null_slot(heap_slots, null_2d);" "case 5: return heap_token_null_slot(heap_slots, null_1d);" + "FAIL: null2d is not the 2D null slot") +heap_token_binding_mutant(null-2da-word-wrong + "case 6: return heap_token_null_slot(heap_slots, null_2da);" "case 6: return heap_token_null_slot(heap_slots, null_2d);" + "FAIL: null2da is not the 2D array null slot") +heap_token_binding_mutant(count-unbounded + "const UINT bounded = records < heap_token_mirror_capacity ? records : heap_token_mirror_capacity;" + "const UINT bounded = records;" + "FAIL: count is not bounded by the mirror capacity") +heap_token_binding_mutant(kind-unchanged-dirty + "if (kinds_[id] != kind) {" "if (true) {" + "FAIL: storing the same kind again is dirty") add_test(NAME startup_heap_indexed_root COMMAND startup_heap_indexed_root_check) foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) diff --git a/docs/experiments.md b/docs/experiments.md index 7a646a4afa..7a4496b8e7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18188,4 +18188,4 @@ ctest --preset dev --no-tests=error -j1 -R '^native_pixel_atomic_(warp|hardware) Repeat with the release preset. The source-built fixture verifies 13 actual draws and four refusal controls per adapter/configuration, including contention, guard words, active out-of-view, odd raster edges and real WQM quad-neighbor reads with and without GLC. WQM+GLC records returned old values through a second exact atomic in a private lane slot and checks a valid serialization of the varying addends. Local RX 7900 XT/WARP Debug/Release integration over main 4b0350e passed 52 draws, 3328 DWORD and 1664 pixel comparisons, and 16 refusal controls. The debug layer was unavailable; actual title rendering is not established. -See [GPU-selected heap textures through view tokens in native compute](experiments/native-heap-token-textures.md) (#3023 stage 3, translator only) for the `heaptok` manifest lines the runtime still refuses. The same page covers GPU-selected raw buffers read through view tokens (`baseraw` and `nullraw` words). +See [GPU-selected heap textures through view tokens in native compute](experiments/native-heap-token-textures.md) (#3023 stage 3) for the `heaptok` manifest lines (refused without `X2W_D3D12_HEAP_TOKENS=1`, bound by the runtime with it). The same page covers GPU-selected raw buffers read through view tokens (`baseraw` and `nullraw` words). diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index c75d153903..4876b15362 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -2,9 +2,10 @@ Issue #3023. The native compute translator accepts a texture that the program loads with `s_load_dwordx8` from the directly indexed resource heap at a byte offset chosen by GPU data (a "heap token texture"). This change is the translator, the -manifest writer, the reader refusal and the fixtures. The runtime still refuses the new manifest lines by name ("heap token -textures are not bound yet"), so no dispatch behaviour changes. The runtime side (binding the token memory, the dimension -table and the host descriptor ranges) is a later change. +manifest writer, the reader refusal and the fixtures. Without the opt-in `X2W_D3D12_HEAP_TOKENS=1` the runtime still refuses the +new manifest lines by name ("heap token textures are not bound yet"), so no dispatch behaviour changes. With it the runtime +binds the token memory, the dimension table and the miss counter and fills the host descriptor ranges (see "Runtime binding" +below). ## Why a token @@ -39,11 +40,12 @@ those two words at the guest byte address and maps the id to a host descriptor. `native_compute_output_revision` is 4 (see Revision below). The native-only route (no manifest reader) refuses a program with token words with the same text as the manifest reader, `heap token textures are not bound yet`. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. -- The refusal has three texts, the same on both routes (`heap_token_refusal` in `src/startup_stubs/d3d12_compute_dispatch.inl`): +- The refusal has four texts, the same on both routes (`heap_token_refusal` in `src/startup_stubs/d3d12_compute_dispatch.inl`): `heap token textures are not bound yet` while the opt-in `X2W_D3D12_HEAP_TOKENS=1` is unset (also when only `X2W_D3D12_VIEW_CONTENT_TOKENS=1` is set); `heap tokens need id tokens` with both set (the tokens would name content, not - view ids); `heap tokens are not bound yet (runtime binding in progress)` with the opt-in alone, until the runtime binds the - views. Both variables are read once. + view ids); `heap tokens need a directly indexed resource heap` when the adapter lacks it; `heap tokens need a GPU-visible + view heap` when no shader-visible view heap has an alias of its memory (and at the dispatch, when the heap the list bound + has none). With none of them the runtime binds the program. Both variables are read once. ## Tests @@ -126,8 +128,27 @@ new one compiles it from the same cache folder). once PR 2 defines it). - A2: an out-of-bounds raw buffer read returns 0 (the D3D12 raw buffer bounds rule, an external specification not verified in this repository; the fixture checks it for lanes past the end of the first raw view on one adapter). -- The runtime reader still refuses every `heaptok` line ("heap token textures are not bound yet"), including `baseraw` and - `nullraw`; programs of this change stay refused at dispatch until PR 2. +- Without `X2W_D3D12_HEAP_TOKENS=1` the runtime reader refuses every `heaptok` line ("heap token textures are not bound yet"), + including `baseraw` and `nullraw`. + +## Runtime binding (X2W_D3D12_HEAP_TOKENS=1) + +- The mirror: `src/startup_stubs/heap_token_mirror.inl`. At a heap token dispatch the runtime takes the view record ids queued since + the last one and writes one desktop shader resource view per accepted id into the mirror region at the top of the translated + draw heap (slot `ring + id`; `heap_token_binding.h`), from the description the title's own `CreateShaderResourceView` + used (`translate_srv_desc`, shared with that call). The mirror holds its own COM reference on each desktop resource. A view that is + not a 1D, 2D or 2D array texture or a raw buffer view gets no descriptor and kind 0. +- The kinds table (`heap_token_dims_srv`) is a default-heap buffer of 65,536 uints, copied from the CPU table in the dispatch's own + list before the dispatch (only the span that changed); the kind of an id is set after its descriptor is written. The token + memory (`heap_token_srv`) is a raw view over the GPU alias of the list's view heap memory (`heap_token_alias.h`); the miss + counter (`heap_token_miss_uav`) is a persistent default-heap UAV, read back every 4096 heap token dispatches into the log. + The three take table registers like the other views (no new root parameter); the root takes the directly indexed resource heap flag. +- The entry words: base1d, base2d, base2da and baseraw are the heap slot of id 0 of the mirror, count the number of view records + (at least 1, at most 65,536), and each null word the slot of the typed null of its dimension (`heap_token_word_value`). +- Known limits of this change: a mirror entry is never released; a resource a list tracks in a write state is not transitioned + for a token read; a texture the title filled in memory only (never by a GPU copy) is not uploaded for a token read; the kinds copy is + recorded in the list of the first dispatch that sees the change, so ids of a list that is recorded but never submitted read as + misses; the kinds table is read on the direct queue the list runs on only. ## Tests diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 38a62fb0ee..e9881440df 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -113,7 +113,7 @@ bool heap_tokens() static const bool on = x2w_local::env_on("X2W_D3D12_HEAP_TOKENS"); return on; } -// Ids that still need a heap token mirror descriptor (heap_token_pending.h); nothing creates one yet. Only with +// Ids that still need a heap token mirror descriptor (heap_token_pending.h); a heap token dispatch writes them (heap_mirror_flush). Only with // heap_tokens(). Every member: note_lock held. x2w_startup::HeapMirrorPending& heap_mirror_pending() { static x2w_startup::HeapMirrorPending q; return q; } // The GPU view of each shader-visible title view heap's memory (heap_token_alias.h); empty without heap_tokens(). diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e927b4785c..34110c6426 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -32,7 +32,8 @@ struct ComputeTranslation { // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param // set, the table buffer (word_param, word_byte) whose word at byte at + root constant (a, b) * times (a < 0: // at alone) is the index. An entry value that is not a root constant names input or output a by its source. - enum Source { root_constant, input_stride, input_word3, output_word3, output_stride, output_records }; + // heaptok_word (`udsrc K heaptok `, a heap token program) is last: `a` is the word index (heap_token_word_name), not a view. + enum Source { root_constant, input_stride, input_word3, output_word3, output_stride, output_records, heaptok_word }; struct Slot { int a, b; bool texture, heap; @@ -52,6 +53,7 @@ struct ComputeTranslation { D3D12_SRV_DIMENSION srv_dimension = D3D12_SRV_DIMENSION_UNKNOWN; unsigned half_buffer_bytes = 0; unsigned typed_bytes = 0; // `srv typed`: the widest formatted load, 4 bytes per component + int token = 0; // a runtime-provided heap token view: 1 the token memory (`srv heaptok`), 2 the kinds table (`heaptokdims`), 3 the miss counter (`uav heaptokmiss`) }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable @@ -61,7 +63,7 @@ struct ComputeTranslation { std::vector uds, srvs, uavs; UINT heap_srvs = 0; UINT sampler_heap_bytes = 0; // `smpidx`: the program reads the title's sampler heap (directly indexed) up to this byte - bool heap_token_views = false; // heaptok lines: the program reads the view heap directly indexed (set by a later commit) + bool heap_token_views = false; // heaptok lines: the program reads the view heap directly indexed (the root takes the flag) x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; @@ -278,8 +280,9 @@ bool adapter_lacks_directly_indexed_resource_heap() // reader and the native-only route, so triage reads the same reason on both (heap_token_gate_text, in the order the // causes are checked): the opt-in X2W_D3D12_HEAP_TOKENS is off (today's text); it is on together with // X2W_D3D12_VIEW_CONTENT_TOKENS (the tokens would name content, not view ids); the adapter lacks the directly indexed -// resource heap; no shader-visible view heap has a GPU alias of its memory (heap_token_alias.h); or all hold and the -// runtime does not bind the views yet. +// resource heap; or no shader-visible view heap has a GPU alias of its memory (heap_token_alias.h). Null when none of them +// holds: the program is bound at its dispatch (heap_mirror_prepare, which refuses by name when the heap the list has bound +// has no alias). const char* heap_token_refusal() { return x2w_startup::heap_token_gate_text(heap_tokens(), view_content_tokens(), @@ -297,8 +300,7 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st for (UINT i = 0; i < tr.uavs.size(); ++i) if (tr.uavs[i].atomic) atomic_registers.push_back(i); bool serialized = false; - // A program that reads heap tokens indexes the list's view heap directly (the region of the draw heap). No translation - // sets heap_token_views yet: the reader still refuses the heaptok lines. + // A program that reads heap tokens indexes the list's view heap directly (the region of the draw heap). const bool token_views = tr.heap_token_views && heap_tokens(); if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), false, tr.heap_srvs, @@ -359,6 +361,7 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.manifest_retry.found(); tr.manifest_mark = 0; unsigned declared_uds = 0, line_number = 0; + unsigned token_views[3] = {0, 0, 0}, token_words = 0; // heap token lines seen: the three views, the entry words for (std::size_t at = 0; at < manifest.size(); ++line_number) { std::size_t end = manifest.find('\n', at); if (end == std::string::npos) end = manifest.size(); @@ -403,20 +406,41 @@ const char* load_compute_translation(ComputeTranslation& tr) }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; - // GPU-selected heap textures and raw buffers (view tokens): published by the translator, not bound by this - // runtime - // yet. The reader knows the nine word names (baseraw and nullraw belong to raw buffers); every such line is - // refused here until a runtime fills the views and words. - const auto token_word = [&] { - for (const char *known : {"base1d", "base2d", "base2da", "count", "null1d", "null2d", "null2da", "baseraw", "nullraw"}) - if (!std::strcmp(name, known)) return true; - return false; - }; - if ((std::sscanf(line.c_str(), "srv %u heaptok%n", &i, &used) == 1 && whole()) || - (std::sscanf(line.c_str(), "srv %u heaptokdims%n", &i, &used) == 1 && whole()) || - (std::sscanf(line.c_str(), "uav %u heaptokmiss%n", &i, &used) == 1 && whole()) || - (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole() && token_word())) - return heap_token_refusal(); + // GPU-selected heap textures and raw buffers (view tokens): the translator publishes three runtime-provided views + // (the token memory, the kinds table, the miss counter) and seven words (nine with raw buffers: baseraw, nullraw), + // in this order. With X2W_D3D12_HEAP_TOKENS the runtime binds them (heap_mirror_prepare) when the gate allows; + // every such line is refused by heap_token_refusal() otherwise, and a set that is not complete is refused as such. + int token_view = 0; // 1 token memory, 2 kinds table, 3 miss counter, 4 an entry word + UINT token_word = x2w_startup::heap_token_word_count_max; + if (std::sscanf(line.c_str(), "srv %u heaptok%n", &i, &used) == 1 && whole()) token_view = 1; + else if (std::sscanf(line.c_str(), "srv %u heaptokdims%n", &i, &used) == 1 && whole()) token_view = 2; + else if (std::sscanf(line.c_str(), "uav %u heaptokmiss%n", &i, &used) == 1 && whole()) token_view = 3; + else if (std::sscanf(line.c_str(), "udsrc %u heaptok %15s%n", &i, name, &used) == 2 && whole() && + (token_word = x2w_startup::heap_token_word_index(name)) < x2w_startup::heap_token_word_count_max) + token_view = 4; + if (token_view) { + if (const char* refusal = heap_token_refusal()) return refusal; + static const char* const incomplete = "heap token lines that are not the translator's complete set"; + if (token_view == 4) { + // The words come in the translator's order, one after the other, among the entry values. + if (i != tr.uds.size() || token_word != token_words) return incomplete; + ComputeTranslation::Slot slot{}; + slot.a = static_cast(token_word); + slot.source = ComputeTranslation::heaptok_word; + tr.uds.push_back(slot); + ++token_words; + } else { + auto& slots = token_view == 3 ? tr.uavs : tr.srvs; + if (i != slots.size() || token_views[token_view - 1]) return incomplete; + ComputeTranslation::Slot slot{}; + slot.a = slot.b = -1; + slot.token = token_view; + slots.push_back(slot); + ++token_views[token_view - 1]; + } + tr.heap_token_views = true; + continue; + } if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) tr.uds.push_back({a, b}); else if (std::sscanf(line.c_str(), "udsrc %u %15s %d%n", &i, name, &a, &used) == 3 && whole() && i == tr.uds.size() && @@ -517,7 +541,12 @@ const char* load_compute_translation(ComputeTranslation& tr) } if (tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) return "entry value, input or output count"; + // Heap token lines come as a whole: the three views once each and seven words (nine with raw buffers), or none. + if (tr.heap_token_views && (token_views[0] != 1 || token_views[1] != 1 || token_views[2] != 1 || + (token_words != 7 && token_words != 9))) + return "heap token lines that are not the translator's complete set"; for (const ComputeTranslation::Slot& ud : tr.uds) { + if (ud.source == ComputeTranslation::heaptok_word) continue; // `a` is a word index, not a view const auto& slots = ud.source >= ComputeTranslation::output_word3 ? tr.uavs : tr.srvs; if (ud.source != ComputeTranslation::root_constant && (ud.a < 0 || static_cast(ud.a) >= slots.size() || slots[ud.a].texture || slots[ud.a].root)) @@ -558,6 +587,7 @@ bool translate_compute_natively(ComputeTranslation& tr) tr.uds.clear(); tr.srvs.clear(); tr.uavs.clear(); + tr.heap_token_views = false; tr.samplers = {}; // a published manifest read next numbers its sampler lines from 0 tr.root.Reset(); tr.pipeline.Reset(); @@ -588,7 +618,7 @@ bool translate_compute_natively(ComputeTranslation& tr) program = x2w::translate_compute(*frozen, 0, true); // The same refusal text as the manifest reader gives for the token lines, so triage reads one reason on both routes. if (program.heap_token_word_count != 0) - throw std::runtime_error(heap_token_refusal()); + if (const char* refusal = heap_token_refusal()) throw std::runtime_error(refusal); for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); @@ -602,6 +632,14 @@ bool translate_compute_natively(ComputeTranslation& tr) slot.source = ComputeTranslation::input_stride; tr.uds.push_back(slot); } + // The heap token words follow the entry values and the stride words, in the translator's order (the manifest's udsrc + // lines): base1d, base2d, base2da, count, null1d, null2d, null2da, and with raw buffers baseraw, nullraw. + for (unsigned word = 0; word < program.heap_token_word_count; ++word) { + ComputeTranslation::Slot slot{}; + slot.a = static_cast(word); + slot.source = ComputeTranslation::heaptok_word; + tr.uds.push_back(slot); + } std::sort(program.bindings.begin(), program.bindings.end(), [](const auto& a, const auto& b) { return a.shader_register < b.shader_register; }); for (const auto& view : program.bindings) { @@ -618,8 +656,12 @@ bool translate_compute_natively(ComputeTranslation& tr) // buffer_load_format_* / buffer_store_format_*: a UINT view of 32-bit components, as `srv/uav typed`. const bool typed = (view.kind == Kind::typed_buffer_srv || view.kind == Kind::typed_buffer_uav) && x2w::typed_dword_view_bytes(view.required_bytes); + // The runtime-provided views of a heap token program (the token memory, the kinds table, the miss counter): the + // runtime fills them at the dispatch (heap_mirror_prepare), they name no title descriptor. + const int token = view.kind == Kind::heap_token_srv ? 1 : view.kind == Kind::heap_token_dims_srv ? 2 + : view.kind == Kind::heap_token_miss_uav ? 3 : 0; const bool output = texture_output || view.kind == Kind::raw_buffer_uav || half_typed || atomic || - view.kind == Kind::typed_buffer_uav; + view.kind == Kind::typed_buffer_uav || token == 3; auto dimension = D3D12_UAV_DIMENSION_UNKNOWN; if (texture_output) { switch (view.image_dimension) { @@ -631,12 +673,20 @@ bool translate_compute_natively(ComputeTranslation& tr) } auto& slots = output ? tr.uavs : tr.srvs; const bool supported = view.kind == Kind::raw_buffer_uav || half_typed || view.kind == Kind::raw_vector_srv || - x2w::accepts_cbv_window(view.kind) || texture_input || atomic || typed || + x2w::accepts_cbv_window(view.kind) || texture_input || atomic || typed || token || dimension != D3D12_UAV_DIMENSION_UNKNOWN; - if (!supported || view.array_count != 1 || - view.root_parameter >= 16 || view.shader_register != slots.size()) + if (!supported || view.array_count != 1 || (token && !program.heap_token_word_count) || + (view.root_parameter >= 16 && !token) || view.shader_register != slots.size()) throw std::runtime_error("view kind " + std::to_string(static_cast(view.kind)) + " is not bound for a natively translated program"); + if (token) { + ComputeTranslation::Slot slot{}; + slot.a = slot.b = -1; + slot.token = token; + slots.push_back(slot); + tr.heap_token_views = true; + continue; + } slots.push_back({static_cast(view.root_parameter), static_cast(view.byte_offset), texture_input || texture_output}); auto& slot = slots.back(); @@ -660,6 +710,14 @@ bool translate_compute_natively(ComputeTranslation& tr) tr.samplers.comparison.push_back(sampler.comparison); tr.samplers.lod_limits.push_back(sampler.explicit_lod && !sampler.comparison); } + if (program.heap_token_word_count) { // the translator publishes the three views with the words; a program without them is not bound + unsigned views[3] = {0, 0, 0}; + for (const auto* group : {&tr.srvs, &tr.uavs}) + for (const auto& slot : *group) + if (slot.token) ++views[slot.token - 1]; + if (views[0] != 1 || views[1] != 1 || views[2] != 1) + throw std::runtime_error("heap token words without the three heap token views"); + } if (tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) throw std::runtime_error("more entry values, inputs or outputs than the dispatch path binds"); // Direct modules use shader model 6.6 with WaveSize(32). @@ -886,6 +944,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& UINT atomic_stride = 0, atomic_count = 0; bool atomic = false; int input_source = 0; + int token = 0; // a heap token runtime view: 1 token memory, 2 kinds table, 3 miss counter (ComputeTranslation::Slot::token) u64 snapshot_address = 0, input_entry = 0; }; static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) >= ViewRecord::srv_desc_bytes); @@ -933,6 +992,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& reason = "translated indirect Dispatch requires fixed-table raw buffers"; break; } + if (slot.token) { // a heap token runtime view: nothing of the title's, filled at the dispatch (heap_mirror_prepare) + views[i] = View{}; + views[i].token = slot.token; + continue; + } std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); if (!output && slot.root) { @@ -1191,7 +1255,8 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& pass.compute_constants.word(ud.a, ud.b)); } for (const auto& ud : tr->uds) - if (ud.source >= ComputeTranslation::output_word3 && ud.a == static_cast(i - inputs) && !reason) + if (ud.source >= ComputeTranslation::output_word3 && ud.source != ComputeTranslation::heaptok_word && + ud.a == static_cast(i - inputs) && !reason) reason = "an output token has no original ISA descriptor words for entry constants"; for (std::size_t input = 0; input < inputs && !reason; ++input) if (views[input].resource == token.resource) reason = "an output buffer is also an input"; @@ -1384,6 +1449,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& std::uint32_t values[32] = {}; for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) { const ComputeTranslation::Slot& ud = tr->uds[i]; + if (ud.source == ComputeTranslation::heaptok_word) continue; // filled below, once the runtime views are prepared const View& view = views[ud.source >= ComputeTranslation::output_word3 ? inputs + ud.a : ud.a]; std::uint32_t format = 0, word[8]; switch (ud.source) { @@ -1429,6 +1495,17 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& // the same reason path as the other refusals (draw_ring_reserve refuses exactly the tables larger than the ring). if (!reason && n > draw_ring_size()) reason = "the descriptor table is larger than the ring"; + // A heap token program (X2W_D3D12_HEAP_TOKENS): the mirror's descriptors and kinds for the ids this dispatch can read, the + // alias of the list's view heap, and the entry words. A refusal here goes through the same exit as the others. + HeapMirrorBinding mirror; + if (!reason && tr->heap_token_views) reason = heap_mirror_prepare(self, list, pass, mirror); + if (!reason && mirror.active) { + for (std::size_t i = 0; i < tr->uds.size(); ++i) + if (tr->uds[i].source == ComputeTranslation::heaptok_word) + values[i] = x2w_startup::heap_token_word_value(static_cast(tr->uds[i].a), draw_heap_size, mirror.records); + for (std::size_t i = inputs; i < count; ++i) + if (views[i].token == 3) views[i].resource = mirror.miss; // the barrier after the dispatch names it + } if (reason) { if (!tr->first_refusal) { tr->first_refusal = reason; @@ -1446,6 +1523,10 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; + if (view.token) { // a heap token runtime view + heap_mirror_write_view(self, mirror, view.token, dest); + continue; + } if (i < inputs && view.texture) { // A compute list accepts no pixel-shader or depth state in a transition. require_state(self, view.resource, type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE @@ -1518,6 +1599,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& barrier.UAV.pResource = views[i].resource; list->ResourceBarrier(1, &barrier); } + heap_mirror_after_dispatch(self, list, mirror); // The translated root replaced the desktop compute root of the title and its arguments. if (pass.desktop_compute_root) { list->SetComputeRootSignature(pass.desktop_compute_root.Get()); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ccef43c87d..6526aa6104 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5241,6 +5241,20 @@ struct TextureWrite { std::unordered_map& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); +// What a translated compute Dispatch with heap token views (X2W_D3D12_HEAP_TOKENS) writes into its table: the alias of the +// title view heap's memory, the kinds table, the miss counter, and the number of view records. The functions are defined in +// heap_token_mirror.inl, below translate_srv_desc, which they use. +struct HeapMirrorBinding { + bool active = false; + ID3D12Resource* tokens = nullptr; // the alias of the title view heap's memory + UINT token_elements = 0; // raw (dword) elements of the token view: entries * 8 + ID3D12Resource* dims = nullptr; + ID3D12Resource* miss = nullptr; + UINT records = 0; // view records at this dispatch (the program's count word) +}; +const char* heap_mirror_prepare(Wrapper* self, ID3D12GraphicsCommandList* list, Pass& pass, HeapMirrorBinding& out); +void heap_mirror_write_view(Wrapper* self, const HeapMirrorBinding& binding, int token, D3D12_CPU_DESCRIPTOR_HANDLE dest); +void heap_mirror_after_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, const HeapMirrorBinding& binding); #include "startup_stubs/d3d12_draw.inl" #include "startup_stubs/d3d12_compute_dispatch.inl" #include "startup_stubs/mesh86_cache.inl" @@ -5782,6 +5796,118 @@ x2w_view_dimension::DefaultViews view_defaults_mode() return mode; } +// What the checks before a desktop view call (device slots 18-21) decide about a view: why none can be made (the desktop +// removes the device on a view call it rejects), whether the resource's default view stands in for an unknown dimension, +// and what the first_calls logs of view_slot report. No log, no note_view, no desktop call. +struct ViewCheck { + const char* skip = nullptr; + bool default_view = false; + bool record_refused_uav = false; + unsigned note = 0; // 1: unknown view dimension (default view or skipped), 2: dimension does not suit the resource + UINT view_format = 0, view_dimension = 0, needed_dimension = 0; + unsigned resource_dimension = 0; + DXGI_FORMAT resource_format = DXGI_FORMAT_UNKNOWN; +}; + +// `slot` is the device slot (18 SRV, 19 UAV, 20 RTV, 21 DSV), `resource` the desktop resource (null: no check), `described` +// the address of the view description (0: none; every description starts with a DXGI_FORMAT, then the ViewDimension). +ViewCheck check_view(int slot, ID3D12Resource* resource, u64 described) +{ + ViewCheck check; + if (!(slot >= 18 && slot <= 21) || !resource) return check; + const UINT flags = resource->GetDesc().Flags; + if (slot == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) check.skip = "resource denies shader resource views"; + if (slot == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + check.skip = "resource lacks unordered access"; + check.record_refused_uav = true; + } + if (slot == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) check.skip = "resource lacks render target"; + if (slot == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) check.skip = "resource lacks depth stencil"; + if (check.skip || !described || !x2w_local::readable(reinterpret_cast(described), 8)) return check; + UINT view_dimension = 0; + std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); + const D3D12_RESOURCE_DESC resource_desc = resource->GetDesc(); + const auto dimension = static_cast(resource_desc.Dimension); + if (view_dimension == 0) { + // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. By default only + // SRVs (slot 18) get one; UAV, RTV and DSV need X2W_D3D12_VIEW_DEFAULTS=all (view_dimension.h). + const auto mode = view_defaults_mode(); + if (x2w_view_dimension::default_view_allowed(slot, dimension, static_cast(resource_desc.Format), mode)) + check.default_view = true; + else if (x2w_view_dimension::default_view_allowed(slot, dimension, static_cast(resource_desc.Format), + x2w_view_dimension::DefaultViews::all)) + check.skip = mode == x2w_view_dimension::DefaultViews::off + ? "unknown view dimension, and default views are off (X2W_D3D12_VIEW_DEFAULTS=off)" + : "unknown view dimension; a default view of this type needs X2W_D3D12_VIEW_DEFAULTS=all"; + else + check.skip = "unknown view dimension, and the resource has no default view"; + check.note = 1; + std::memcpy(&check.view_format, reinterpret_cast(described), sizeof(check.view_format)); + check.resource_dimension = dimension; + check.resource_format = resource_desc.Format; + } else if (!x2w_view_dimension::fits(slot, view_dimension, dimension)) { + check.skip = "view dimension does not suit the resource"; + check.note = 2; + check.view_dimension = view_dimension; + check.needed_dimension = x2w_view_dimension::needed(slot, view_dimension); + check.resource_dimension = dimension; + } else if (slot == 19) { + if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast(described), sizeof(view)); + check.skip = volume_uav_range_error(resource_desc, view.Texture3D); + check.record_refused_uav = check.skip != nullptr; + } else if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast(described), sizeof(view)); + if (view.Texture1D.MipSlice >= resource_desc.MipLevels) check.skip = "an output 1D texture mip is outside the resource"; + check.record_refused_uav = check.skip != nullptr; + } + } + return check; +} + +// The desktop shader resource view description of a title's (slot 18): the checks above, then the title's description with +// its format mapped (a packed format follows a stand-in texture, or is refused). Shared by the title's +// CreateShaderResourceView (view_slot<18, 2>) and the heap token mirror, which creates its descriptors from the record's +// description bytes. `title_desc` is read for sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) bytes when it is readable. +struct SrvTranslation { + ViewCheck check; + bool packed_refused = false; // a packed format on a texture that does not stand in for it + DXGI_FORMAT packed_mapped = DXGI_FORMAT_UNKNOWN, packed_actual = DXGI_FORMAT_UNKNOWN; + bool has_desc = false; // `desc` is the title's description with the mapped format + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; +}; + +SrvTranslation translate_srv_desc(ID3D12Resource* resource, const void* title_desc) +{ + SrvTranslation result; + result.check = check_view(18, resource, reinterpret_cast(title_desc)); + if (result.check.skip) return result; + if (!title_desc || !x2w_local::readable(title_desc, sizeof(result.desc))) return result; + std::memcpy(&result.desc, title_desc, sizeof(result.desc)); + result.has_desc = true; + DXGI_FORMAT mapped = desktop_format(result.desc.Format); + if (resource && x2w_startup::packed_target_format(mapped)) { + // A packed view follows a stand-in texture and is refused on any other texture of another format. + const auto actual = resource->GetDesc().Format; + const auto verdict = x2w_startup::packed_view(mapped, actual, x2w_startup::packed_stand_in_of(resource)); + if (verdict == x2w_startup::PackedView::refused) { + result.packed_refused = true; + result.packed_mapped = mapped; + result.packed_actual = actual; + return result; + } + if (verdict == x2w_startup::PackedView::stand_in) mapped = actual; + } + result.desc.Format = mapped; + return result; +} + +#include "startup_stubs/heap_token_mirror.inl" + // Device view slots: forwarded with the destination CPU handle (argument D, 0-based after the // object) translated from title to desktop. // Desktop removes the device (DXGI_ERROR_INVALID_CALL) on view calls it rejects, so they are checked @@ -5828,61 +5954,26 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) bool default_view = false; bool record_refused_uav = false; if (N == 17) skip = "constant buffer view (title GPU address)"; - if (N >= 18 && N <= 21 && args[0]) { - const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; - if (N == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) skip = "resource denies shader resource views"; - if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { - skip = "resource lacks unordered access"; - record_refused_uav = true; - } - if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; - if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; - // Every view description of slots 18-21 starts with Format, then ViewDimension. - const u64 described = N == 19 ? args[2] : args[1]; - UINT view_dimension = 0; - if (!skip && described && x2w_local::readable(reinterpret_cast(described), 8)) { - std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); - const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast(args[0])->GetDesc(); - const auto dimension = static_cast(resource_desc.Dimension); - if (view_dimension == 0) { - // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. By default only - // SRVs (slot 18) get one; UAV, RTV and DSV need X2W_D3D12_VIEW_DEFAULTS=all (view_dimension.h). - const auto mode = view_defaults_mode(); - if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), mode)) - default_view = true; - else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), - x2w_view_dimension::DefaultViews::all)) - skip = mode == x2w_view_dimension::DefaultViews::off - ? "unknown view dimension, and default views are off (X2W_D3D12_VIEW_DEFAULTS=off)" - : "unknown view dimension; a default view of this type needs X2W_D3D12_VIEW_DEFAULTS=all"; - else - skip = "unknown view dimension, and the resource has no default view"; - static LONG unknown_dimension; - if (first_calls(unknown_dimension, 6)) - log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, - *reinterpret_cast(described), dimension, resource_desc.Format, - default_view ? "default view" : "skipped"); - } else if (!x2w_view_dimension::fits(N, view_dimension, dimension)) { - skip = "view dimension does not suit the resource"; - static LONG mismatched; - if (first_calls(mismatched, 6)) - log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, - x2w_view_dimension::needed(N, view_dimension), dimension); - } else if constexpr (N == 19) { - if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && - x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { - D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; - std::memcpy(&view, reinterpret_cast(described), sizeof(view)); - skip = volume_uav_range_error(resource_desc, view.Texture3D); - record_refused_uav = skip != nullptr; - } else if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && - x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { - D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; - std::memcpy(&view, reinterpret_cast(described), sizeof(view)); - if (view.Texture1D.MipSlice >= resource_desc.MipLevels) skip = "an output 1D texture mip is outside the resource"; - record_refused_uav = skip != nullptr; - } - } + // Slots 18-21: the checks the desktop's view calls need (check_view, shared with the heap token mirror through + // translate_srv_desc for slot 18). Every view description of slots 18-21 starts with Format, then ViewDimension. + [[maybe_unused]] SrvTranslation srv; + if constexpr (N == 18) srv = translate_srv_desc(reinterpret_cast(args[0]), reinterpret_cast(args[1])); + if constexpr (N >= 18 && N <= 21) { + const ViewCheck check = N == 18 ? srv.check + : check_view(N, reinterpret_cast(args[0]), N == 19 ? args[2] : args[1]); + skip = check.skip; + default_view = check.default_view; + record_refused_uav = check.record_refused_uav; + if (check.note == 1) { + static LONG unknown_dimension; + if (first_calls(unknown_dimension, 6)) + log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, + check.view_format, check.resource_dimension, check.resource_format, default_view ? "default view" : "skipped"); + } else if (check.note == 2) { + static LONG mismatched; + if (first_calls(mismatched, 6)) + log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, + check.view_dimension, check.needed_dimension, check.resource_dimension); } } // Replace a refused SRV in both the desktop heap and the descriptor record. A skipped UAV, RTV or DSV @@ -5915,7 +6006,18 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) constexpr std::size_t view_bytes = N == 18 ? sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) : N == 19 ? sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) : N == 20 ? sizeof(D3D12_RENDER_TARGET_VIEW_DESC) : sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC); - if (N >= 18 && N <= 21 && args[desc_index] && x2w_local::readable(reinterpret_cast(args[desc_index]), view_bytes)) { + if constexpr (N == 18) { + // translate_srv_desc made the desktop description (the title's with its format mapped). + if (srv.packed_refused) { + refuse_view(); + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 Device::slot%d view skipped: packed format %d on a texture of format %d that does not stand in for it", + N, srv.packed_mapped, srv.packed_actual); + return 0; + } + if (srv.has_desc) args[desc_index] = reinterpret_cast(&srv.desc); + } else if (N >= 19 && N <= 21 && args[desc_index] && x2w_local::readable(reinterpret_cast(args[desc_index]), view_bytes)) { std::memcpy(desc_copy, reinterpret_cast(args[desc_index]), view_bytes); DXGI_FORMAT format; std::memcpy(&format, desc_copy, sizeof(format)); @@ -7287,6 +7389,114 @@ extern "C" __declspec(dllexport) void x2w_d3d12_heap_mirror_queue(unsigned long ReleaseSRWLockShared(¬e_lock); } +// Fixture exports (startup_compute_heap_token, startup_compute_heap_token_dispatch): the heap token mirror. A real dispatch +// runs the same flush; this one runs it without a list, for the descriptors and kinds only (the kinds are not copied to the +// GPU). Returns the number of descriptors written so far, or -1 when the mirror cannot run (no device or draw heap, the +// opt-in off, or the queue could not be taken). +extern "C" __declspec(dllexport) long long x2w_d3d12_heap_mirror_flush() +{ + if (!heap_tokens() || !the_device) return -1; + AcquireSRWLockExclusive(&draw_lock); + long long result = -1; + if (ensure_draw_heap(the_device) && !heap_mirror_flush(heap_mirror())) result = static_cast(heap_mirror().descriptors); + ReleaseSRWLockExclusive(&draw_lock); + return result; +} +// The kind the mirror holds for a view record id (heap_token_kinds.h; 0: no descriptor). +extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_mirror_kind(UINT id) +{ + AcquireSRWLockExclusive(&draw_lock); + const UINT kind = heap_mirror().kinds.kind(id); + ReleaseSRWLockExclusive(&draw_lock); + return kind; +} +// The COM reference count of the desktop resource the mirror holds for `id` (0: none), and of the desktop resource of a title +// resource wrapper (0: none), each read by an AddRef and the Release that follows it. The mirror's own reference makes the +// first one larger than the second was before the id was flushed. +extern "C" __declspec(dllexport) ULONG x2w_d3d12_heap_mirror_refs(UINT id) +{ + AcquireSRWLockExclusive(&draw_lock); + auto& mirror = heap_mirror(); + ID3D12Resource* const resource = id < mirror.entries.size() ? mirror.entries[id].resource.Get() : nullptr; + ULONG refs = 0; + if (resource) { + resource->AddRef(); + refs = resource->Release(); + } + ReleaseSRWLockExclusive(&draw_lock); + return refs; +} +extern "C" __declspec(dllexport) ULONG x2w_d3d12_desktop_resource_refs(void* title_resource) +{ + Wrapper* const wrapper = as_wrapper(title_resource); + auto* const resource = wrapper && wrapper->own().kind == resource_kind ? static_cast(wrapper->own().real) : nullptr; + if (!resource) return 0; + resource->AddRef(); + return resource->Release(); +} +// The nine entry words a heap token program gets (heap_token_word_name order) with the current record count. +extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_words(UINT* out) +{ + AcquireSRWLockShared(¬e_lock); + const UINT records = static_cast(view_records().size()); + ReleaseSRWLockShared(¬e_lock); + for (UINT i = 0; i < x2w_startup::heap_token_word_count_max; ++i) + out[i] = x2w_startup::heap_token_word_value(i, draw_heap_size, records); +} +// The miss counter of the heap token programs (persistent, never reset), read back on a private queue and waited for; +// ~0u when the counter does not exist or the readback failed. Call it when no list that uses the counter is executing. +extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_token_misses() +{ + AcquireSRWLockExclusive(&draw_lock); + ID3D12Resource* const miss = heap_mirror().miss.Get(); + UINT result = ~0u; + if (miss && the_device) { + ID3D12Device* const device = device_of(the_device); + x2w_startup::ComPtr queue; + x2w_startup::ComPtr allocator; + x2w_startup::ComPtr list; + x2w_startup::ComPtr fence; + x2w_startup::ComPtr readback; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(queue.GetAddressOf()))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf()))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(list.GetAddressOf()))) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.GetAddressOf()))) && + SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(readback.GetAddressOf())))) { + // The counter rests in COMMON between lists (the list that uses it returns it at Close). + transition(list.Get(), miss, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback.Get(), 0, miss, 0, 4); + transition(list.Get(), miss, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + ID3D12CommandList* const lists[] = {list.Get()}; + if (SUCCEEDED(list->Close())) { + queue->ExecuteCommandLists(1, lists); + if (SUCCEEDED(queue->Signal(fence.Get(), 1))) { + const ULONGLONG deadline = GetTickCount64() + 10000; + while (fence->GetCompletedValue() < 1 && GetTickCount64() < deadline) Sleep(1); + void* mapped = nullptr; + const D3D12_RANGE range{0, 4}; + if (fence->GetCompletedValue() >= 1 && SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped) { + std::memcpy(&result, mapped, sizeof(result)); + const D3D12_RANGE none{}; + readback->Unmap(0, &none); + } + } + } + } + } + ReleaseSRWLockExclusive(&draw_lock); + return result; +} + // Fixture exports (startup_compute_heap_token): the heap token region of the translated draw heap and its ring, and the // GPU alias of a title view heap's memory. // Layout: draw heap slots, ring slots, mirror capacity, null slots. @@ -7375,7 +7585,8 @@ extern "C" __declspec(dllexport) UINT x2w_d3d12_heap_token_view_stride(void* tab // The reason a program with heaptok lines is refused now (heap_token_refusal, the text the manifest reader gives). extern "C" __declspec(dllexport) void x2w_d3d12_heap_token_refusal(char* out, UINT size) { - if (size) std::snprintf(out, size, "%s", heap_token_refusal()); + const char* const reason = heap_token_refusal(); // null: nothing static stops a heap token program + if (size) std::snprintf(out, size, "%s", reason ? reason : ""); } // Fixture-only: the next `count` wrapper allocations fail as an exhausted heap would (#2653). diff --git a/src/startup_stubs/heap_token_binding.h b/src/startup_stubs/heap_token_binding.h index 47cbcb97ce..1e798aede0 100644 --- a/src/startup_stubs/heap_token_binding.h +++ b/src/startup_stubs/heap_token_binding.h @@ -16,6 +16,7 @@ #include #include +#include namespace x2w_startup { @@ -129,15 +130,102 @@ inline D3D12_ROOT_SIGNATURE_FLAGS compute_root_flags(bool sampler_heap, bool hea (heap_tokens_bound ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE)); } -// Why a translated compute program with heap token lines cannot run, in the order the causes are checked. One text for -// the manifest reader and the native-only route. +// Why a translated compute program with heap token lines cannot run, in the order the causes are checked: null when nothing +// static stops it (the runtime then binds the views, or refuses by name at the dispatch). One text for the manifest reader +// and the native-only route. inline const char* heap_token_gate_text(bool opt_in, bool content_tokens, bool lacks_resource_heap, bool view_heap_alias) { if (!opt_in) return "heap token textures are not bound yet"; if (content_tokens) return "heap tokens need id tokens"; if (lacks_resource_heap) return "heap tokens need a directly indexed resource heap"; if (!view_heap_alias) return "heap tokens need a GPU-visible view heap"; - return "heap tokens are not bound yet (runtime binding in progress)"; + return nullptr; } +// The words a heap token program reads as entry values, in the translator's order (the manifest's `udsrc K heaptok `): +// base1d, base2d, base2da, count, null1d, null2d, null2da, and with raw buffers baseraw, nullraw. A base is the heap slot of +// id 0 of the mirror (the slot of id n is base + n, whatever the dimension: one slot per view record), a null the slot of +// the typed null of that dimension, and count the number of ids the kinds table names (at least 1: with no records the +// program still reads dims[0], which is 0, so every read misses). +constexpr UINT heap_token_word_count_max = 9; +inline const char* heap_token_word_name(UINT index) +{ + static const char* const names[heap_token_word_count_max] = {"base1d", "base2d", "base2da", "count", "null1d", + "null2d", "null2da", "baseraw", "nullraw"}; + return index < heap_token_word_count_max ? names[index] : nullptr; +} +// The index of a word name, heap_token_word_count_max for a name that is none of them. +inline UINT heap_token_word_index(const char* name) +{ + for (UINT i = 0; i < heap_token_word_count_max; ++i) { + const char* known = heap_token_word_name(i); + UINT k = 0; + while (known[k] && name[k] == known[k]) ++k; + if (!known[k] && !name[k]) return i; + } + return heap_token_word_count_max; +} +inline UINT heap_token_count_word(UINT records) +{ + const UINT bounded = records < heap_token_mirror_capacity ? records : heap_token_mirror_capacity; + return bounded ? bounded : 1; +} +inline UINT heap_token_word_value(UINT index, UINT heap_slots, UINT records) +{ + switch (index) { + case 0: case 1: case 2: case 7: return heap_token_mirror_slot(heap_slots, 0); + case 3: return heap_token_count_word(records); + case 4: return heap_token_null_slot(heap_slots, null_1d); + case 5: return heap_token_null_slot(heap_slots, null_2d); + case 6: return heap_token_null_slot(heap_slots, null_2da); + case 8: return heap_token_null_slot(heap_slots, null_raw); + default: return 0; + } +} + +// The kinds table (heap_token_kinds.h) as the CPU keeps it, and the span of it the GPU copy has not seen. set() records the +// kind of an id and widens the span when the value changes; take_dirty() hands the span out and clears it. An id at or past +// the capacity is not stored (a program reads it as a miss). +class HeapTokenKindShadow { +public: + HeapTokenKindShadow() : kinds_(heap_token_mirror_capacity, 0) {} + bool set(UINT id, std::uint32_t kind) + { + if (id >= heap_token_mirror_capacity) return false; + if (kinds_[id] != kind) { + kinds_[id] = kind; + widen(id, 1); + } + return true; + } + std::uint32_t kind(UINT id) const { return id < heap_token_mirror_capacity ? kinds_[id] : 0; } + bool dirty() const { return dirty_; } + // The dirty span [first, first + count) in ids; false when there is none. Clears it. + bool take_dirty(UINT& first, UINT& count) + { + if (!dirty_) return false; + first = lo_; + count = hi_ - lo_ + 1; + dirty_ = false; + return true; + } + // Marks a span dirty again (its copy was not recorded). + void restore_dirty(UINT first, UINT count) + { + if (count) widen(first, count); + } + const std::uint32_t* data() const { return kinds_.data(); } + +private: + void widen(UINT first, UINT count) + { + if (!dirty_ || first < lo_) lo_ = first; + if (!dirty_ || first + count - 1 > hi_) hi_ = first + count - 1; + dirty_ = true; + } + std::vector kinds_; + bool dirty_ = false; + UINT lo_ = 0, hi_ = 0; +}; + } // namespace x2w_startup diff --git a/src/startup_stubs/heap_token_kinds.h b/src/startup_stubs/heap_token_kinds.h index 1f251e6fb1..351ef60d28 100644 --- a/src/startup_stubs/heap_token_kinds.h +++ b/src/startup_stubs/heap_token_kinds.h @@ -8,7 +8,7 @@ // raw buffer: 0x20. // 16 is the code of an R32_UINT typed buffer view, reserved for the typed buffer token route (#3619). Any other view is // 0 (no entry). compute_token_accepts is the rule the compute route will apply when the mirror writes the table -// (16 and 0 are refused); nothing calls it yet, only heap_token_kinds_check exercises it. +// (16 and 0 are refused); heap_mirror_flush (heap_token_mirror.inl) applies it. #include @@ -41,7 +41,7 @@ inline std::uint32_t heap_token_kind(const D3D12_SHADER_RESOURCE_VIEW_DESC& desc } // Whether a translated compute program can be given the kind: the three texture codes and the raw buffer code, never 0 -// or the typed buffer code. Not called by the runtime yet (a helper for the mirror flush). +// or the typed buffer code. The mirror flush applies it. inline bool compute_token_accepts(std::uint32_t kind) { return kind == heap_kind_texture_1d || kind == heap_kind_texture_2d || kind == heap_kind_texture_2d_array || diff --git a/src/startup_stubs/heap_token_mirror.inl b/src/startup_stubs/heap_token_mirror.inl new file mode 100644 index 0000000000..b1856656e0 --- /dev/null +++ b/src/startup_stubs/heap_token_mirror.inl @@ -0,0 +1,295 @@ +// The heap token mirror (X2W_D3D12_HEAP_TOKENS): what a translated compute program that reads GPU-selected heap views +// (the heaptok lines) is bound to. Included from d3d12_xs_device.cpp after translate_srv_desc and before the view slots. +// +// heap_mirror_flush takes the view record ids note_view queued (heap_token_pending.h) and writes one desktop shader +// resource view per id into the mirror region of the translated draw heap (heap_token_binding.h), +// at slot ring + id. The description is the one the title's own CreateShaderResourceView used +// (translate_srv_desc). The mirror takes its own COM reference on the desktop resource, so nothing a +// descriptor names can be destroyed while the mirror holds it. A view a compute token route cannot +// name (not a 1D/2D/2D-array texture or a raw buffer view) gets no descriptor and kind 0. +// heap_mirror_upload_dims records the span of the kinds table that changed since the last upload as a copy into the +// kinds buffer (a default-heap buffer, heap_token_dims_srv of the program) in the dispatch's own list, +// before the dispatch; the kind of an id is set only after its descriptor was written. +// heap_mirror_prepare both of the above plus the states the three runtime views need and the count of ids; the dispatch +// then writes the token SRV (a raw view of the title view heap's alias), the kinds SRV and the miss +// UAV into its table (no new root parameter). +// heap_mirror_after_dispatch the miss counter's periodic readback (logged every 4096 dispatches). +// +// Known limits until the release path exists (a later commit): a mirror entry is never released (the resource stays alive, the +// descriptor stays written, its kind stays); an id whose record was reassigned keeps its first entry and reads kind 0; a +// resource the title has not made on the desktop when the id is flushed is never retried; resources a list tracks in a write +// state are not transitioned for a token read (the title's barriers are the only states they get); the kinds copy is +// recorded in the list of the first dispatch that sees the change, so a list that is recorded but never submitted loses it +// (its ids read kind 0, a miss, never a wrong view). Every member of the mirror: draw_lock held. + +struct HeapMirrorEntry { + x2w_startup::ComPtr resource; // the mirror's own reference on the desktop resource + std::uint32_t generation = 0, kind = 0; + bool written = false; +}; + +struct HeapMirror { + std::vector entries; // by id + x2w_startup::HeapTokenKindShadow kinds; + x2w_startup::ComPtr dims, miss, readback; + bool create_failed = false; + std::uint64_t dispatches = 0; // heap token dispatches prepared + std::uint64_t descriptors = 0, skipped = 0, unresolved = 0, unaccepted = 0, overflow = 0, reassigned = 0; + std::uint64_t uploads = 0, upload_bytes = 0, flush_failures = 0; + UINT readback_slot = 0; + bool readback_pending = false; + std::uint32_t logged_misses = 0; +}; + +// Never released: a static destructor would release the buffers after the device's module may have detached. +HeapMirror& heap_mirror() +{ + static HeapMirror* const mirror = new HeapMirror; + return *mirror; +} + +constexpr UINT heap_mirror_readback_slots = 4, heap_mirror_readback_stride = 256; + +bool heap_mirror_create_buffers(HeapMirror& m) +{ + if (m.dims && m.miss && m.readback) return true; + if (m.create_failed) return false; + ID3D12Device* const device = device_of(the_device); + const auto buffer = [](UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; + }; + D3D12_HEAP_PROPERTIES defaults{}; + defaults.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_HEAP_PROPERTIES readback{}; + readback.Type = D3D12_HEAP_TYPE_READBACK; + // Committed resources start zeroed: every id reads kind 0 until its kind is copied in. + const D3D12_RESOURCE_DESC dims_desc = buffer(UINT64{x2w_startup::heap_token_mirror_capacity} * 4, D3D12_RESOURCE_FLAG_NONE); + const D3D12_RESOURCE_DESC miss_desc = buffer(256, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const D3D12_RESOURCE_DESC readback_desc = buffer(UINT64{heap_mirror_readback_slots} * heap_mirror_readback_stride, D3D12_RESOURCE_FLAG_NONE); + if (FAILED(device->CreateCommittedResource(&defaults, D3D12_HEAP_FLAG_NONE, &dims_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(m.dims.ReleaseAndGetAddressOf()))) || + FAILED(device->CreateCommittedResource(&defaults, D3D12_HEAP_FLAG_NONE, &miss_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(m.miss.ReleaseAndGetAddressOf()))) || + FAILED(device->CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &readback_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(m.readback.ReleaseAndGetAddressOf())))) { + m.dims.Reset(); + m.miss.Reset(); + m.readback.Reset(); + m.create_failed = true; + log("x2w-draw heap token buffers could not be created"); + return false; + } + return true; +} + +// The kind of the view the desktop makes of a resource when the title gave no description (the resource's default view). +std::uint32_t heap_mirror_default_view_kind(const D3D12_RESOURCE_DESC& resource) +{ + if (resource.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && resource.DepthOrArraySize == 1) + return x2w_startup::heap_kind_texture_1d; + if (resource.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && resource.SampleDesc.Count == 1) + return resource.DepthOrArraySize == 1 ? x2w_startup::heap_kind_texture_2d : x2w_startup::heap_kind_texture_2d_array; + return x2w_startup::heap_kind_none; +} + +// Writes the mirror descriptors of the ids queued since the last flush. Returns why the queue could not be taken (the +// dispatch is then refused and the ids stay queued), or null; an id that gets no descriptor is counted in the mirror's totals. +const char* heap_mirror_flush(HeapMirror& m) +{ + std::vector taken; + std::vector records; + AcquireSRWLockExclusive(¬e_lock); + auto& pending = heap_mirror_pending(); + const std::uint64_t failures = pending.take_failures(); + taken = pending.take(heap_mirror_eligible); + const bool take_failed = pending.take_failures() != failures; + ReleaseSRWLockExclusive(¬e_lock); + if (take_failed) { + ++m.flush_failures; + static LONG logged; + if (first_calls(logged, 4)) log("x2w-draw heap token mirror could not take its queue (out of memory); retried at the next dispatch"); + return "the heap token queue could not be taken"; + } + if (taken.empty()) return nullptr; + // The records are copied under the lock; the descriptors are created without it. + std::vector still_current(taken.size(), 0); + AcquireSRWLockShared(¬e_lock); + for (std::size_t i = 0; i < taken.size(); ++i) { + const std::uint32_t id = taken[i].id; + if (id < view_records().size() && heap_mirror_pending().generation(id) == taken[i].generation) { + records.push_back(view_records()[id]); + still_current[i] = 1; + } else { + records.push_back({}); + } + } + ReleaseSRWLockShared(¬e_lock); + ID3D12Device* const device = device_of(the_device); + const D3D12_CPU_DESCRIPTOR_HANDLE start = draw_heap->GetCPUDescriptorHandleForHeapStart(); + for (std::size_t i = 0; i < taken.size(); ++i) { + const std::uint32_t id = taken[i].id; + if (!still_current[i]) continue; // reassigned since it was queued: its own entry is queued behind this one + if (id >= x2w_startup::heap_token_mirror_capacity) { + if (!m.overflow++) log("x2w-draw heap token mirror: view id %u is past the capacity %u; such ids read as misses", id, + x2w_startup::heap_token_mirror_capacity); + continue; + } + if (m.entries.size() <= id) m.entries.resize(std::size_t{id} + 1); + HeapMirrorEntry& entry = m.entries[id]; + if (entry.written) { // the id holds another record now: entries are not released yet, so it keeps the first one + if (entry.generation != taken[i].generation) { + ++m.reassigned; + m.kinds.set(id, 0); + } + continue; + } + const ViewRecord& record = records[i]; + Wrapper* const wrapper = as_wrapper(reinterpret_cast(record.resource)); + ID3D12Resource* const resource = wrapper && wrapper->own().kind == resource_kind && + InterlockedCompareExchange(&wrapper->own().refs, 0, 0) + ? static_cast(wrapper->own().real) : nullptr; + if (!resource || record.slot != 18 || record.desc_bytes < ViewRecord::srv_desc_bytes) { + ++m.unresolved; + continue; + } + if (wrapper->own().tiled_address_srv) { // a texture by title address: what it samples is another object (sampled_address_texture) + ++m.skipped; + continue; + } + // The title's description bytes, padded to the desktop structure (the desktop's may be wider than the record's). + alignas(D3D12_SHADER_RESOURCE_VIEW_DESC) unsigned char title_desc[sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)] = {}; + std::memcpy(title_desc, record.desc, ViewRecord::srv_desc_bytes); + const SrvTranslation srv = translate_srv_desc(resource, title_desc); + if (srv.check.skip || srv.packed_refused) { + ++m.skipped; + continue; + } + const std::uint32_t kind = srv.check.default_view ? heap_mirror_default_view_kind(resource->GetDesc()) + : srv.has_desc ? x2w_startup::heap_token_kind(srv.desc) : 0; + if (!x2w_startup::compute_token_accepts(kind)) { + ++m.unaccepted; + continue; + } + const D3D12_CPU_DESCRIPTOR_HANDLE slot{start.ptr + std::size_t{x2w_startup::heap_token_mirror_slot(draw_heap_size, id)} * + draw_heap_increment}; + device->CreateShaderResourceView(resource, srv.check.default_view ? nullptr : &srv.desc, slot); + entry.resource = resource; // the mirror's own reference + entry.generation = taken[i].generation; + entry.kind = kind; + entry.written = true; + ++m.descriptors; + // The descriptor exists before its kind is set; the kind reaches the GPU in the dispatch's list. + m.kinds.set(id, kind); + } + return nullptr; +} + +// Records the copy of the kinds table's changed span into the list. The kinds buffer is in COMMON between lists (the list +// that uses it returns it at Close, like every tracked resource), so one list's copy is ordered before this list's reads by +// the single direct queue they run on. +const char* heap_mirror_upload_dims(Wrapper* self, ID3D12GraphicsCommandList* list, HeapMirror& m) +{ + UINT first = 0, count = 0; + if (m.kinds.take_dirty(first, count)) { + const std::size_t bytes = std::size_t{count} * 4; + u64 offset = 0; + ID3D12Resource* upload = nullptr; + unsigned char* const mapped = reserve_upload_ring(self, bytes, &offset, &upload); + if (!mapped || !upload) { + m.kinds.restore_dirty(first, count); + return "the heap token kinds could not be uploaded"; + } + std::memcpy(mapped, m.kinds.data() + first, bytes); + require_state(self, m.dims.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(m.dims.Get(), std::size_t{first} * 4, upload, offset, bytes); + ++m.uploads; + m.upload_bytes += bytes; + } + return nullptr; +} + +// Everything a heap token dispatch needs before it writes its table (HeapMirrorBinding, declared above the dispatch): the +// alias of its view heap, the buffers, and the ids of this dispatch. Returns why it cannot run, or null. +const char* heap_mirror_prepare(Wrapper* self, ID3D12GraphicsCommandList* list, Pass& pass, HeapMirrorBinding& out) +{ + HeapMirror& m = heap_mirror(); + x2w_startup::HeapTokenAlias alias; + if (!pass.title_view_heap.address || !heap_token_aliases().find(pass.title_view_heap.address, alias) || !alias.alias.buffer) + return "heap tokens need a GPU-visible view heap"; + if (!heap_mirror_create_buffers(m)) return "the heap token buffers could not be created"; + if (const char* why = heap_mirror_flush(m)) return why; + if (const char* why = heap_mirror_upload_dims(self, list, m)) return why; + AcquireSRWLockShared(¬e_lock); + out.records = static_cast((std::min)(view_records().size(), x2w_startup::heap_token_mirror_capacity)); + ReleaseSRWLockShared(¬e_lock); + out.active = true; + out.tokens = alias.alias.buffer.Get(); + out.token_elements = alias.num_elements; + out.dims = m.dims.Get(); + out.miss = m.miss.Get(); + ++m.dispatches; + return nullptr; +} + +// The three runtime views of the program's table: the token memory (a raw view over the alias), the kinds table and the +// miss counter. Each is also moved to the state the dispatch reads or writes it in. +void heap_mirror_write_view(Wrapper* self, const HeapMirrorBinding& binding, int token, D3D12_CPU_DESCRIPTOR_HANDLE dest) +{ + ID3D12Device* const device = device_of(the_device); + if (token == 1 || token == 2) { + ID3D12Resource* const resource = token == 1 ? binding.tokens : binding.dims; + require_state(self, resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.NumElements = token == 1 ? binding.token_elements : x2w_startup::heap_token_mirror_capacity; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(resource, &desc, dest); + return; + } + require_state(self, binding.miss, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.NumElements = 1; + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(binding.miss, nullptr, &desc, dest); +} + +// Every 4096th heap token dispatch copies the miss counter into a small readback ring; the delta since the previous copy is +// logged when the next copy is recorded (4096 dispatches later, so the earlier copy has long been executed; the value is read +// without a fence and may lag, never lead). The counter itself is persistent and never reset. +void heap_mirror_after_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, const HeapMirrorBinding& binding) +{ + HeapMirror& m = heap_mirror(); + if (!binding.active || (m.dispatches & 4095) != 0) return; + if (m.readback_pending) { + const UINT previous = (m.readback_slot + heap_mirror_readback_slots - 1) % heap_mirror_readback_slots; + const D3D12_RANGE range{std::size_t{previous} * heap_mirror_readback_stride, std::size_t{previous} * heap_mirror_readback_stride + 4}; + void* mapped = nullptr; + if (SUCCEEDED(m.readback->Map(0, &range, &mapped)) && mapped) { + std::uint32_t total = 0; + std::memcpy(&total, static_cast(mapped) + range.Begin, sizeof(total)); + const D3D12_RANGE none{}; + m.readback->Unmap(0, &none); + log("x2w-draw heap token misses: %u in total, %u since the last readback (%llu heap token dispatches)", total, + total - m.logged_misses, static_cast(m.dispatches)); + m.logged_misses = total; + } + } + require_state(self, binding.miss, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(m.readback.Get(), std::size_t{m.readback_slot} * heap_mirror_readback_stride, binding.miss, 0, 4); + m.readback_slot = (m.readback_slot + 1) % heap_mirror_readback_slots; + m.readback_pending = true; +} diff --git a/tests/cmake/startup_compute_dispatch_native.cmake b/tests/cmake/startup_compute_dispatch_native.cmake index 197d13ea72..271e720e11 100644 --- a/tests/cmake/startup_compute_dispatch_native.cmake +++ b/tests/cmake/startup_compute_dispatch_native.cmake @@ -1,12 +1,18 @@ # A slot 67 request translated in-process by the C++ compiler (X2W_NATIVE_SHADERS) and dispatched through the # stand-in. Without 32-lane waves the check verifies its refusals and exits 77. -if(TARGET x2w_shader_compiler AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" +if(TARGET x2w_shader_compiler AND TARGET compile_dxil AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_compute_dispatch_native_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py" "$" "${DXC_BIN_DIR}" ${adapter}) set_tests_properties(startup_compute_dispatch_native_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # Heap token programs bound by the runtime (X2W_D3D12_HEAP_TOKENS): texels, raw words and misses on hardware (a view + # heap with a 32-byte descriptor stride), the named refusal on WARP, in process and through a published manifest. + add_test(NAME startup_compute_heap_token_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_heap_token_dispatch_check.py" + "$" "${DXC_BIN_DIR}" ${adapter} "$") + set_tests_properties(startup_compute_heap_token_dispatch_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) add_test(NAME startup_native_shader_totals_compile_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py" "$" "${DXC_BIN_DIR}" ${adapter} compile) diff --git a/tests/heap_token_binding_check.cpp b/tests/heap_token_binding_check.cpp index 77ed501213..fd516300d6 100644 --- a/tests/heap_token_binding_check.cpp +++ b/tests/heap_token_binding_check.cpp @@ -8,6 +8,7 @@ // a copy of heap_token_binding.h with one real edit of the production code (a replaced anchor, checked at configure time), // and the check must print FAIL lines. #include "startup_stubs/heap_token_binding.h" +#include "startup_stubs/heap_token_kinds.h" #include #include @@ -157,7 +158,7 @@ void gate() const char* content = "heap tokens need id tokens"; const char* capability = "heap tokens need a directly indexed resource heap"; const char* no_heap = "heap tokens need a GPU-visible view heap"; - const char* in_progress = "heap tokens are not bound yet (runtime binding in progress)"; + const char* const none = nullptr; // nothing static stops the program: the runtime binds the views struct Row { const char* name; bool opt_in, content, lacks, alias; const char* want; }; const Row rows[] = { {"opt-in off", false, false, false, false, off}, @@ -167,18 +168,74 @@ void gate() {"adapter lacks the resource heap", true, false, true, true, capability}, {"capability is checked before the alias", true, false, true, false, capability}, {"no GPU-visible view heap", true, false, false, false, no_heap}, - {"everything holds", true, false, false, true, in_progress}, + {"everything holds", true, false, false, true, none}, }; for (const Row& r : rows) { const char* got = heap_token_gate_text(r.opt_in, r.content, r.lacks, r.alias); ++cases; - if (std::strcmp(got, r.want)) { + if (got != r.want && (!got || !r.want || std::strcmp(got, r.want))) { ++failures; - std::printf("FAIL gate %s: \"%s\", expected \"%s\"\n", r.name, got, r.want); + std::printf("FAIL gate %s: \"%s\", expected \"%s\"\n", r.name, got ? got : "(none)", r.want ? r.want : "(none)"); } } } +// The nine entry words the runtime gives a heap token program, by the translator's names and order. +void words() +{ + const UINT mirror = heap_token_mirror_slot(heap, 0); + expect(heap_token_word_name(0) && !std::strcmp(heap_token_word_name(0), "base1d") && !std::strcmp(heap_token_word_name(3), "count") && + !std::strcmp(heap_token_word_name(6), "null2da") && !std::strcmp(heap_token_word_name(8), "nullraw") && + !heap_token_word_name(9), + "the word names are not the translator's, in its order"); + for (UINT i = 0; i < heap_token_word_count_max; ++i) + expect(heap_token_word_index(heap_token_word_name(i)) == i, "a word name does not give its own index"); + expect(heap_token_word_index("null") == heap_token_word_count_max && heap_token_word_index("") == heap_token_word_count_max && + heap_token_word_index("base1dx") == heap_token_word_count_max && heap_token_word_index("bogus") == heap_token_word_count_max, + "a name that is not a token word has an index"); + // The bases are the slot of id 0 whatever the dimension; one null per dimension, each its own slot (a null of another + // dimension read through a view of this one is undefined in D3D12). + for (const UINT base : {0u, 1u, 2u, 7u}) expect(heap_token_word_value(base, heap, 5) == mirror, "a base word is not the mirror's first slot"); + expect(heap_token_word_value(4, heap, 5) == heap_token_null_slot(heap, null_1d), "null1d is not the 1D null slot"); + expect(heap_token_word_value(5, heap, 5) == heap_token_null_slot(heap, null_2d), "null2d is not the 2D null slot"); + expect(heap_token_word_value(6, heap, 5) == heap_token_null_slot(heap, null_2da), "null2da is not the 2D array null slot"); + expect(heap_token_word_value(8, heap, 5) == heap_token_null_slot(heap, null_raw), "nullraw is not the raw buffer null slot"); + expect(heap_token_word_value(4, heap, 5) != heap_token_word_value(5, heap, 5) && + heap_token_word_value(5, heap, 5) != heap_token_word_value(6, heap, 5) && + heap_token_word_value(6, heap, 5) != heap_token_word_value(8, heap, 5) && + heap_token_word_value(4, heap, 5) != heap_token_word_value(8, heap, 5), + "two dimensions share a null slot"); + // count: the record count, at least 1, at most the capacity. + expect(heap_token_word_value(3, heap, 0) == 1, "count is not at least 1 with no records"); + expect(heap_token_word_value(3, heap, 1) == 1 && heap_token_word_value(3, heap, 5) == 5, "count is not the record count"); + expect(heap_token_word_value(3, heap, 65536) == 65536 && heap_token_word_value(3, heap, 65537) == 65536 && + heap_token_word_value(3, heap, ~0u) == 65536, + "count is not bounded by the mirror capacity"); +} + +// The CPU copy of the kinds table and the span the GPU has not seen. +void shadow() +{ + HeapTokenKindShadow table; + UINT first = 99, count = 99; + expect(!table.dirty() && !table.take_dirty(first, count) && first == 99, "a new table is dirty"); + expect(table.set(7, heap_kind_texture_2d) && table.kind(7) == heap_kind_texture_2d && table.dirty(), "a stored kind is not kept"); + expect(table.set(3, heap_kind_raw_buffer) && table.set(9, heap_kind_texture_2d_array), "a kind below the capacity is refused"); + expect(table.take_dirty(first, count) && first == 3 && count == 7, "the dirty span is not [3, 9]"); + expect(!table.dirty() && !table.take_dirty(first, count), "taking the span did not clear it"); + expect(table.set(7, heap_kind_texture_2d) && !table.dirty(), "storing the same kind again is dirty"); + expect(table.set(7, heap_kind_none) && table.take_dirty(first, count) && first == 7 && count == 1, "clearing a kind is not a one-id span"); + table.restore_dirty(10, 4); + table.restore_dirty(2, 1); + expect(table.take_dirty(first, count) && first == 2 && count == 12, "a restored span is not [2, 13]"); + expect(!table.set(heap_token_mirror_capacity, heap_kind_texture_2d) && table.kind(heap_token_mirror_capacity) == 0 && !table.dirty(), + "an id at the capacity is stored"); + expect(table.set(heap_token_mirror_capacity - 1, heap_kind_texture_1d) && table.take_dirty(first, count) && + first == heap_token_mirror_capacity - 1 && count == 1, + "the last id is refused"); + expect(table.data()[heap_token_mirror_capacity - 1] == heap_kind_texture_1d && table.data()[0] == 0, "the table data is not the stored kinds"); +} + } // namespace int main(int argc, char**) @@ -190,6 +247,8 @@ int main(int argc, char**) alias(); root_flags(); gate(); + words(); + shadow(); std::printf("%d of %d checks failed\n", failures, cases); return failures ? 1 : 0; } diff --git a/tests/heap_token_kinds_check.cpp b/tests/heap_token_kinds_check.cpp index cb9f57b1cc..8030fe2c31 100644 --- a/tests/heap_token_kinds_check.cpp +++ b/tests/heap_token_kinds_check.cpp @@ -8,7 +8,9 @@ // Each mutation changes an expectation (or, for the last one, the queue itself) to what a wrong implementation would // give; every one must make the check fail. A mutated run that fails prints "mutation : caught" as its last line; // an unknown name, a crash, or a mutation that is not caught prints no such line. -#define X2W_HEAP_TOKEN_PENDING_TEST_HOOKS // allocation failure injection in heap_token_pending.h (the CMake target sets it too) +#ifndef X2W_HEAP_TOKEN_PENDING_TEST_HOOKS // the CMake target defines it too (a second definition is a macro redefinition warning) +#define X2W_HEAP_TOKEN_PENDING_TEST_HOOKS // allocation failure injection in heap_token_pending.h +#endif #include "startup_stubs/heap_token_kinds.h" #include "startup_stubs/heap_token_pending.h" diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index 8d703ec45a..b2bc403aec 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -377,18 +377,20 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal): HEAP_TOKEN_REFUSAL = 'heap token textures are not bound yet' -# The three refusals of the heap token gate: X2W_D3D12_HEAP_TOKENS unset (also with only the content tokens on), on alone, and +# The refusals of the heap token gate: X2W_D3D12_HEAP_TOKENS unset (also with only the content tokens on), on alone (bound, or the +# named refusal of a view heap without an alias; startup_compute_heap_token_dispatch checks what a bound program reads), and # on together with X2W_D3D12_VIEW_CONTENT_TOKENS. HEAP_TOKEN_CASES = (({}, HEAP_TOKEN_REFUSAL), ({'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, HEAP_TOKEN_REFUSAL), - ({'X2W_D3D12_HEAP_TOKENS': '1'}, 'heap tokens are not bound yet (runtime binding in progress)'), + ({'X2W_D3D12_HEAP_TOKENS': '1'}, None), # bound when the view heap has a GPU alias, else NEED_VIEW_HEAP ({'X2W_D3D12_HEAP_TOKENS': '1', 'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, 'heap tokens need id tokens')) NEED_VIEW_HEAP = 'heap tokens need a GPU-visible view heap' # the opt-in alone, when the view heap got no GPU alias -HEAP_TOKEN_TEXTS = tuple(sorted({text for _, text in HEAP_TOKEN_CASES} | {NEED_VIEW_HEAP})) +HEAP_TOKEN_TEXTS = tuple(sorted({text for _, text in HEAP_TOKEN_CASES if text} | {NEED_VIEW_HEAP})) def heap_token_refusal(directory, consumer, dxc_dir, adapter): - """A program that loads a GPU-selected heap texture is refused in process with the manifest reader's text. + """A program that loads a GPU-selected heap texture is refused in process with the manifest reader's text (the opt-in off, + with the content tokens, or with no GPU alias of the view heap) and bound with the opt-in on a 32-byte stride heap. The native-only route has no manifest reader, so without a check of its own the program would translate and then fail at the first view the runtime cannot bind ("view kind N is not bound for a natively translated program"). @@ -414,7 +416,7 @@ def heap_token_refusal(directory, consumer, dxc_dir, adapter): if token: reason = lines(result, 'not translated natively: ') want = expected - if expected == 'heap tokens are not bound yet (runtime binding in progress)': + if expected is None: # With the opt-in alone the text follows the adapter's CBV/SRV/UAV descriptor stride, which the open # logs from the device (not from its result): only a 32-byte stride gets an alias (WARP's is 64 # bytes). Another stride expects the named refusal; 32 needs the alias to have succeeded. @@ -426,8 +428,18 @@ def heap_token_refusal(directory, consumer, dxc_dir, adapter): want = NEED_VIEW_HEAP else: assert stride.group(2) == '0x00000000', f'the alias failed on a 32-byte stride adapter: {aliases[0]}' - assert len(reason) == 1 and reason[0].endswith(want), (extra, result.stderr[-3000:]) - assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + want = None # the runtime binds the program + if want is None: + # Bound: the program translates natively and takes the runtime's views. This rig puts the table at root + # parameter 1 and the token root's table is parameter 0, so its Dispatch is refused for the table; + # startup_compute_heap_token_dispatch binds a table at parameter 0 and checks what the program reads. + assert not reason, (extra, reason) + assert len(lines(result, 'translated natively: 7 entry values, 3 inputs, 2 outputs')) == 1, result.stderr[-3000:] + for text in HEAP_TOKEN_TEXTS: + assert not lines(result, 'refused: ' + text), (extra, result.stderr[-3000:]) + else: + assert len(reason) == 1 and reason[0].endswith(want), (extra, result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] else: for text in HEAP_TOKEN_TEXTS: assert not lines(result, text), (extra, result.stderr[-3000:]) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index f486edc2a3..6d7c3fa600 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -52,6 +52,9 @@ from startup_stream_check import gfx2hlsl as G +INCOMPLETE_SET = "heap token lines that are not the translator's complete set" + + def run(directory, consumer, env, mode, layout): out = directory / 'out.bin' out.unlink(missing_ok=True) @@ -151,10 +154,12 @@ def check_manifest_refusal(case, variant, reason, extra_env=None): manifest.write_bytes(variant.encode()) readback, dispatch_result = run(directory, consumer, dict(env, **(extra_env or {})), 'texture-store', layout) refusals = [message for message in lines(dispatch_result, 'Dispatch(') if ' refused: ' in message] - if reason == 'heap tokens are not bound yet (runtime binding in progress)': - # With the opt-in alone the text follows the adapter's CBV/SRV/UAV descriptor stride, which the open logs from + if reason == INCOMPLETE_SET: + # With the opt-in alone the lines are read when the gate lets them through, which follows the adapter's CBV/SRV/UAV + # descriptor stride, which the open logs from # the device (not from its result): only a 32-byte stride gets an alias (WARP's is 64 bytes). Another stride - # expects the named refusal; 32 needs the alias to have succeeded. + # expects the named refusal; 32 needs the alias to have succeeded and the lines (one view or one word of a + # program that has no complete set) are refused as an incomplete set. aliases = lines(dispatch_result, 'heap token alias of ') assert len(aliases) == 1, (case, aliases) stride = re.search(r'view stride (\d+)\) -> (0x[0-9a-f]{8})$', aliases[0]) @@ -193,12 +198,13 @@ def check_manifest_refusal(case, variant, reason, extra_env=None): ('heap token raw buffer base', 'udsrc 3 heaptok baseraw\n'), ('heap token raw buffer null', 'udsrc 3 heaptok nullraw\n')): check_manifest_refusal(case, original + line, 'heap token textures are not bound yet') - # X2W_D3D12_HEAP_TOKENS (opt-in): on alone the lines are still refused, with their own text while the binding is - # under construction; together with X2W_D3D12_VIEW_CONTENT_TOKENS the refusal names the id tokens. With the opt-in + # X2W_D3D12_HEAP_TOKENS (opt-in): on alone, one token line is not the translator's set of views and words, which is the + # refusal of the reader (a program with the whole set is bound: startup_compute_heap_token_dispatch); together with + # X2W_D3D12_VIEW_CONTENT_TOKENS the refusal names the id tokens. With the opt-in # unset (the loop above, also with only the content tokens on) the text stays "heap token textures are not bound yet". for case, line in (('heap token view', 'srv 1 heaptok\n'), ('heap token word', 'udsrc 3 heaptok null2d\n')): check_manifest_refusal(case + ' under HEAP_TOKENS', original + line, - 'heap tokens are not bound yet (runtime binding in progress)', + INCOMPLETE_SET, {'X2W_D3D12_HEAP_TOKENS': '1'}) check_manifest_refusal(case + ' under HEAP_TOKENS and VIEW_CONTENT_TOKENS', original + line, 'heap tokens need id tokens', diff --git a/tests/startup_compute_heap_token_check.py b/tests/startup_compute_heap_token_check.py index 0e60f4658f..7388be61cf 100644 --- a/tests/startup_compute_heap_token_check.py +++ b/tests/startup_compute_heap_token_check.py @@ -26,13 +26,22 @@ driven directly (x2w_d3d12_heap_token_alias_open): an address opened twice, or reopened after its release, keeps one entry and the entry is the fresh one (generation); a 64-byte stride, a span too small for the records and an interior pointer are refused and counted. The refusal a heap token program gets (x2w_d3d12_heap_token_refusal) - follows: "heap tokens need a GPU-visible view heap" while no view heap has an alias, then the transitional text once - one has (or the capability text when the adapter lacks the directly indexed resource heap). With the switch off no + follows: "heap tokens need a GPU-visible view heap" while no view heap has an alias, then no refusal at all once one has + (or the capability text when the adapter lacks the directly indexed resource heap). With the switch off no alias is made and the text is the old one. WARP's CBV/SRV/UAV stride may be 64 bytes: the heap created through CreateDescriptorHeap is then the refusal case, and the success case is covered by the direct open only. -Not checked here (later commits): descriptors per record in the draw heap, the kinds table, any dispatch, texels or raw -words read through a token, the miss counter, lifetime and states, hardware adapters. +7. The mirror (x2w_d3d12_heap_mirror_flush, the flush a dispatch runs, here without a list): a 2D texture, a raw buffer, a + 1D texture and a 2D array texture get a descriptor each in the mirror region and the kinds 2, 0x20, 1 and 6 + (x2w_d3d12_heap_mirror_kind); a 3D texture and a typed R32_UINT buffer view get none and kind 0. The mirror holds a COM + reference of its own on each resource (x2w_d3d12_heap_mirror_refs is one more than the resource had before the + flush; 0 for an id without a descriptor), a second flush writes nothing again, and the nine entry words + (x2w_d3d12_heap_token_words) are the mirror's first slot (three bases and baseraw), the record count, and the five + slots of the 1D, 2D, 2D array and raw typed nulls (the translator's order). No miss counter exists before a dispatch ran, and none with the switch + off (where the flush refuses to run, no kind is set and no reference is held). + +Not checked here: a dispatch (startup_compute_heap_token_dispatch on hardware: texels, raw words, misses), lifetime and +states (a later commit). """ import ctypes import os @@ -161,9 +170,9 @@ def resolve(token=None, handle=0): def handle(index): return memory + stride * index - def committed(dimension, width, height, fmt, layout): + def committed(dimension, width, height, fmt, layout, depth=1): props = HeapProperties(1, 0, 0, 1, 1) # DEFAULT - desc = ResourceDesc(dimension, 0, width, height, 1, 1, fmt, 1, 0, layout, 0) + desc = ResourceDesc(dimension, 0, width, height, depth, 1, fmt, 1, 0, layout, 0) out = ctypes.c_void_p() hr = vcall(device, 27, ctypes.c_long, [ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, @@ -306,7 +315,6 @@ def view_heap(flags, backing): OLD = 'heap token textures are not bound yet' NEED_HEAP = 'heap tokens need a GPU-visible view heap' - PROGRESS = 'heap tokens are not bound yet (runtime binding in progress)' NEED_ROOT = 'heap tokens need a directly indexed resource heap' SHADER_VISIBLE = 1 state = alias(0) @@ -364,13 +372,73 @@ def release_heap(heap): 'alias spans %d bytes (buffer %d, heap %d) of %d' % (state.bytes, state.buffer_bytes, state.heap_bytes, stride * count)) fails.expect(state.num_elements * 4 <= state.buffer_bytes, 'NumElements * 4 exceeds the alias buffer') fails.expect(state.alias_failed == 0, 'alias failures %d after the good heap' % state.alias_failed) - fails.expect(refusal() == (NEED_ROOT if lacks else PROGRESS), 'refusal with an alias: "%s"' % refusal()) + fails.expect(refusal() == (NEED_ROOT if lacks else ''), 'refusal with an alias: "%s"' % refusal()) # The final release of the descriptor heap drops its alias: none live afterwards, and the refusal is back. release_heap(own_heap) state = alias(own) fails.expect(state.found == 0 and state.count == 0, 'the alias survived the release of its descriptor heap (%d live)' % state.count) fails.expect(refusal() == MIN_REFUSAL, 'refusal after the release: "%s"' % refusal()) + # 7. The mirror (heap_mirror_flush, outside a dispatch): one desktop descriptor per accepted view record in the mirror + # region and its kind in the table the programs read (heap_token_kinds.h), 0 for a view a heap token cannot name. The + # mirror holds a COM reference of its own on each resource. With the switch off nothing exists: no mirror, no counter. + xs.x2w_d3d12_heap_mirror_flush.restype = ctypes.c_longlong + xs.x2w_d3d12_heap_mirror_kind.restype = ctypes.c_uint + xs.x2w_d3d12_heap_mirror_kind.argtypes = [ctypes.c_uint] + xs.x2w_d3d12_heap_mirror_refs.restype = ctypes.c_ulong + xs.x2w_d3d12_heap_mirror_refs.argtypes = [ctypes.c_uint] + xs.x2w_d3d12_desktop_resource_refs.restype = ctypes.c_ulong + xs.x2w_d3d12_desktop_resource_refs.argtypes = [ctypes.c_void_p] + xs.x2w_d3d12_heap_token_words.argtypes = [ctypes.c_void_p] + xs.x2w_d3d12_heap_token_misses.restype = ctypes.c_uint + if not on: + fails.expect(xs.x2w_d3d12_heap_mirror_flush() == -1, 'the mirror ran with the switch off') + fails.expect(xs.x2w_d3d12_heap_mirror_kind(ids[0]) == 0, 'a kind is set with the switch off') + fails.expect(xs.x2w_d3d12_heap_token_misses() == 0xffffffff, 'a miss counter exists with the switch off') + fails.expect(xs.x2w_d3d12_heap_mirror_refs(ids[0]) == 0, 'the mirror holds a reference with the switch off') + else: + extra_views = [] # (label, handle index, resource, description, expected kind) + for label, dimension, depth, view_dimension, union, kind in ( + ('1D texture', 2, 1, 2, struct.pack(' + +The programs are the token fixtures of native_heap_token_texture_check.py (a selector buffer names the byte address of a +view token in the title's view heap; the program loads the 32-byte token with s_load_dwordx8 or s_load_dwordx4 and reads +the view it names). X2W_NATIVE_SHADERS makes the stand-in translate them in process; the consumer's dispatch-viewtok mode +creates, in a view heap the runtime allocated, the tokens of + entry 2 a 1D texture texel x = 10 + x + entry 3 a 2D texture texel (x, y) = 100 + 4 y + x + entry 4 a 2D array texture texel (x, y, slice) = 200 + 16 slice + 4 y + x + entry 5 a raw buffer view FirstElement 4, NumElements 100 of an upload buffer holding 0x1000 + j at word j + entry 6 another 2D texture texel (x, y) = 500 + 4 y + x +and leaves entries 7 and up empty. Entry 0 holds the selector's own buffer descriptor (not a token). + +Hardware (a 32-byte view descriptor stride, 32-lane waves, shader model 6.6, resource binding tier 3): +1. Valid tokens: every lane reads the texel (or the raw words) of the view the token names, the 1D, 2D and 2D array programs + and the raw buffer program each from their own entry, two 2D textures apart, and the miss counter does not move. +2. A token of another dimension or kind (a 1D token for the 2D program, a 2D token for the 1D, 2D array and raw programs, + an array token for the 2D program), an empty entry and a table descriptor that is no token read the null view of the + program's dimension (all zeros), and the counter rises by exactly one per wave that ran. +3. The miss counter is persistent: 1 + 2 x 4096 dispatches of a missing token add up to 12 misses each, and the copy the runtime + takes at the 4096th heap token dispatch is logged ("x2w-draw heap token misses") when the 8192nd is recorded. +4. The same program through a published manifest and bytecode (compile_dxil) gives the same texel and misses; edits that make + the token lines something other than the translator's set (a word or the counter missing, words out of order, a view + twice, an unknown word) are refused, each by name, with nothing bound. +5. The debug layer reports no error. +6. Opt-in off (the control): the program is refused with the old text, the output is untouched and no miss counter exists + (the consumer prints 4294967295). +WARP (a 64-byte descriptor stride, so no GPU alias of the view heap): the same program is refused by name, the output is +untouched and no miss counter exists. Exit 77 when the adapter is not available. +""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +import native_heap_token_texture_check as K +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case + +UNTOUCHED = [C.SENTINEL] * C.WORDS +NEED_VIEW_HEAP = 'heap tokens need a GPU-visible view heap' +CAPABILITY = 'heap tokens need a directly indexed resource heap' +OFF = 'heap token textures are not bound yet' +LANES = 32 +NO_COUNTER = 4294967295 # what x2w_d3d12_heap_token_misses returns when no counter exists + + +def bits(value): + return struct.unpack('.txt and .cs.cso).""" + cache = directory / 'published-cache' # a cache of its own: the in-process runs above left their request files in the first + cache.mkdir() + env = {k: v for k, v in base_env.items() if k not in ('X2W_NATIVE_SHADERS', 'X2W_NATIVE_SHADERS_ONLY')} + env['X2W_SHADER_CACHE'] = str(cache) + on = dict(env, X2W_D3D12_HEAP_TOKENS='1') + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3) + assert got == UNTOUCHED and len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + compiled = subprocess.run([compiler, dxc_dir, directory / 'frontend', 'gfx1013-direct-cs@0', '--requests', cache, cache], + capture_output=True, text=True) + assert compiled.returncode == 0 and 'requests=1 compiled=1 refused=0' in compiled.stdout, (compiled.stdout, compiled.stderr) + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + rows = original.splitlines() + assert 'srv 0 heaptok' in rows or 'srv 1 heaptok' in rows, original # the translator published the token lines + assert ('srv 1 heaptokdims' in rows and 'uav 0 heaptokmiss' in rows and 'udsrc 6 heaptok null2da' in rows + and 'udsrc 0 heaptok base1d' in rows), original + wanted = None + if adapter == 'hardware' and stride == 32: + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3) + assert not lines(result, 'refused'), result.stderr[-3000:] + assert got == texture_words(109.0), 'the published manifest did not read the 2D texture' + assert misses == 0 and not debug_errors(result), (misses, debug_errors(result)) + assert lines(result, 'translated: 7 entry values, 3 inputs, 2 outputs'), result.stderr[-3000:] + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 2) + assert got == null_words() and misses == 12, 'a 1D token read through the 2D program was not a miss per wave' + wanted = 'the same texel and the same misses' + else: + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3) + reason = lines(result, 'Dispatch(3, 2, 2) refused: ') + assert got == UNTOUCHED and len(reason) == 1 and (reason[0].endswith(NEED_VIEW_HEAP) or reason[0].endswith(CAPABILITY)), ( + reason, result.stderr[-3000:]) + assert misses == NO_COUNTER + wanted = f'refused as "{reason[0].split(": ")[-1]}"' + # The opt-in off: the old text for the same manifest. + got, result, stride, misses = run(directory, consumer, env, K.PROGRAMS['tex2d'], 3) + reason = lines(result, 'Dispatch(3, 2, 2) refused: ') + assert got == UNTOUCHED and len(reason) == 1 and reason[0].endswith(OFF) and misses == NO_COUNTER, (reason, misses) + # A set of lines that is not the translator's is refused as such (with the gate open) and nothing is bound. + if adapter == 'hardware' and stride == 32: + for label, edit, expected in MANIFEST_CONTROLS: + edited = edit(rows) + assert edited != rows, label + manifest.write_bytes(('\n'.join(edited) + '\n').encode()) + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3) + reason = lines(result, 'Dispatch(3, 2, 2) refused: ') + assert got == UNTOUCHED and len(reason) == 1 and reason[0].endswith(expected), (label, reason, result.stderr[-2000:]) + assert misses == NO_COUNTER, (label, 'a refused manifest created a miss counter') + manifest.write_bytes(original.encode()) + return wanted + + +if __name__ == '__main__': + if len(sys.argv) != 5 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 75888d5a3a..f96470bfef 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -29,6 +29,7 @@ using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) void x2w_d3d12_compute_census(); extern "C" __declspec(dllimport) UINT64 x2w_d3d12_snapshot_pool_used(); +extern "C" __declspec(dllimport) UINT x2w_d3d12_heap_token_misses(); // The ring of per-dispatch descriptor tables (startup_compute_dispatch_ring_check.py): set its cursor, read back what the // reservations since did. struct HeapTokenRingProbe { @@ -396,7 +397,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; - } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_waterfall ? (heap_short ? 3u : 5u) : 4u, + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_waterfall ? (heap_short ? 3u : 5u) : mode == "dispatch-viewtok" ? 16u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; // dispatch-sampled-compute records the same calls on a compute list and queue. @@ -447,7 +448,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin // X2W_TEST_RECORDS32=1 moves the output descriptor to byte 32 for programs whose descriptor loads are // split into aligned dwordx4 loads (the D16 sample tests). const char* records32 = std::getenv("X2W_TEST_RECORDS32"); - if (mode == "dispatch-records32" || native_totals || typed_output_offset || input_offset || shared_uav || + if (mode == "dispatch-records32" || mode == "dispatch-viewtok" || native_totals || typed_output_offset || input_offset || shared_uav || mode == "dispatch-srv-token-typed" || mode == "dispatch-records32-input-null" || mode.rfind("dispatch-cube", 0) == 0 || (records32 && std::strcmp(records32, "1") == 0)) { // output at byte 32, none at byte 16 @@ -592,6 +593,76 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (!record.check_record(groups, write_zero)) return 80; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; } + if (mode == "dispatch-viewtok") { + // Heap token views (X2W_D3D12_HEAP_TOKENS=1, startup_compute_heap_token_dispatch_check.py): the heap holds, after the + // two table records (selector at byte 0, output at byte 32), the tokens of four textures and a raw buffer view: + // entry 2 1D R32_FLOAT, 8 texels, texel x = 10 + x entry 3 2D 4x4, texel (x, y) = 100 + 4 y + x + // entry 4 2D array 4x4x2, (x, y, slice) = 200 + 16 slice + 4 y + x + // entry 5 raw buffer view of an upload buffer of 128 words (word j = 0x1000 + j): FirstElement 4, NumElements 100 + // entry 6 another 2D 4x4, texel (x, y) = 500 + 4 y + x entries 7 and up: untouched (all zero) + // The textures are filled by a list of their own that is submitted and completed first, so the dispatch's list finds + // them in COMMON; the views are created after it. The selector's first word names the byte address of the token. + struct Texture { D3D12_RESOURCE_DIMENSION dimension; UINT width, height, slices; float base; UINT entry; D3D12_SRV_DIMENSION view; }; + const Texture textures[] = { + {D3D12_RESOURCE_DIMENSION_TEXTURE1D, 8, 1, 1, 10.0f, 2, D3D12_SRV_DIMENSION_TEXTURE1D}, + {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, 100.0f, 3, D3D12_SRV_DIMENSION_TEXTURE2D}, + {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 2, 200.0f, 4, D3D12_SRV_DIMENSION_TEXTURE2DARRAY}, + {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, 500.0f, 6, D3D12_SRV_DIMENSION_TEXTURE2D}}; + constexpr DXGI_FORMAT format = DXGI_FORMAT_R32_FLOAT; + constexpr UINT pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT, slice_bytes = 1024; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 4096, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* resources[4]{}; + for (int t = 0; t < 4; ++t) { + const Texture& texture = textures[t]; + const D3D12_RESOURCE_DESC texture_desc{texture.dimension, 0, texture.width, texture.height, static_cast(texture.slices), 1, + format, {1, 0}}; + resources[t] = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!resources[t] || !upload || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + std::memset(texel, 0, upload_desc.Width); + for (UINT slice = 0; slice < texture.slices; ++slice) + for (UINT y = 0; y < texture.height; ++y) + for (UINT x = 0; x < texture.width; ++x) { + const float value = texture.base + 16.0f * slice + 4.0f * y + x; + std::memcpy(static_cast(texel) + slice * slice_bytes + y * pitch + x * 4, &value, sizeof(value)); + } + invoke(upload, 9, 0, 0); + for (UINT slice = 0; slice < texture.slices; ++slice) { + D3D12_TEXTURE_COPY_LOCATION image{static_cast(resources[t]), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + image.SubresourceIndex = slice; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {UINT64{slice} * slice_bytes, {format, texture.width, texture.height, 1, pitch}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + } + } + const D3D12_RESOURCE_DESC raw_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 512, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const raw_buffer = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, raw_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* raw_words = nullptr; + if (!raw_buffer || FAILED(static_cast(invoke(raw_buffer, 8, 0, 0, word(&raw_words)))) || !raw_words) return 80; + for (UINT j = 0; j < 128; ++j) static_cast(raw_words)[j] = 0x1000 + j; + invoke(raw_buffer, 9, 0, 0); + if (const int rc = submit(1)) return rc; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + const StreamWord stride = invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::printf("view stride %llu\n", static_cast(stride)); + std::fflush(stdout); + for (int t = 0; t < 4; ++t) { + const Texture& texture = textures[t]; + D3D12_SHADER_RESOURCE_VIEW_DESC view{format, texture.view, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + if (texture.view == D3D12_SRV_DIMENSION_TEXTURE1D) view.Texture1D = {0, 1, 0.0f}; + else if (texture.view == D3D12_SRV_DIMENSION_TEXTURE2D) view.Texture2D.MipLevels = 1; + else view.Texture2DArray = {0, 1, 0, texture.slices, 0, 0.0f}; + invoke(device, 18, word(resources[t]), word(&view), cpu + stride * texture.entry); + } + D3D12_SHADER_RESOURCE_VIEW_DESC raw_view{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + raw_view.Buffer.FirstElement = 4; + raw_view.Buffer.NumElements = 100; + raw_view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + invoke(device, 18, word(raw_buffer), word(&raw_view), cpu + stride * 5); + } bind(); if (mode.rfind("dispatch-sampled", 0) == 0 || mode == "dispatch-input-token" || mode == "dispatch-output-texture-token") { const bool depth = mode == "dispatch-sampled-depth"; @@ -881,9 +952,11 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; bind(); } - if (mode != "dispatch-missing-word") invoke(list, 37, 0, constants[0], 0); - invoke(list, 40, 0, 2, word(graphics), 0); - invoke(list, 39, 0, 1, word(&constants[1]), 1); + // dispatch-viewtok has no root constants: its guest root is one descriptor table, parameter 0. + const bool viewtok = mode == "dispatch-viewtok"; + if (mode != "dispatch-missing-word" && !viewtok) invoke(list, 37, 0, constants[0], 0); + if (!viewtok) invoke(list, 40, 0, 2, word(graphics), 0); + if (!viewtok) invoke(list, 39, 0, 1, word(&constants[1]), 1); if (mode == "dispatch-root-changed") invoke(list, 33, word(slot67_other_root)); if (mode == "dispatch-root-changed" || mode == "dispatch-same-root") invoke(list, 33, word(slot67_root)); if (mode == "dispatch-reset") { @@ -905,7 +978,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); } - invoke(list, 35, 1, table_gpu + (heap_waterfall && !heap_short ? 128u : 0u)); + invoke(list, 35, viewtok ? 0 : 1, table_gpu + (heap_waterfall && !heap_short ? 128u : 0u)); if (change_table_root) { invoke(list, 33, word(slot67_other_root)); invoke(list, 33, word(slot67_root)); @@ -955,7 +1028,24 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin // An attempted read of the very placement whose UAV could not be made guest-visible. invoke(list, 15, word(placed[1]), 16, word(copied_token_output), 16, 16); } - if (const int rc = submit(pixel ? 2 : 1)) return rc; + if (const int rc = submit(pixel || mode == "dispatch-viewtok" ? 2 : 1)) return rc; + if (mode == "dispatch-viewtok") { + // X2W_TEST_VIEWTOK_REPEAT=: two more lists of n Dispatches each, every list submitted and completed before the next + // (the miss counter's periodic readback: a copy is recorded at every 4096th heap token Dispatch and logged when the + // next one is recorded, so n = 4096 logs the first copy in the second list). + char repeat_text[16]{}; + const DWORD repeat_chars = GetEnvironmentVariableA("X2W_TEST_VIEWTOK_REPEAT", repeat_text, sizeof(repeat_text)); + const UINT repeat = repeat_chars && repeat_chars < sizeof(repeat_text) ? static_cast(std::strtoul(repeat_text, nullptr, 10)) : 0; + for (UINT round = 0; round < (repeat ? 2u : 0u); ++round) { + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + invoke(list, 35, 0, table_gpu); + for (UINT i = 0; i < repeat; ++i) invoke(list, 14, 3, 2, 2); + if (const int rc = submit(3 + round)) return rc; + } + std::printf("heap token misses: %u\n", x2w_d3d12_heap_token_misses()); + std::fflush(stdout); + } if (pixel) { std::printf("guest queue=%p consumer fence=2 completed\n", queue); if (!record.check_record(groups, write_zero, true)) return 80; diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index f9d6af3d68..30b223cfa4 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -452,9 +452,21 @@ def function_body(text: str, name: str) -> str: found |= literals(function_body(root_path.read_text(encoding="utf-8"), "compute_root_refusal")) # The heap token gate (heap_token_refusal gives its text to the manifest reader and the native route). gate = literals(function_body(gate_path.read_text(encoding="utf-8"), "heap_token_gate_text")) - if len(gate) != 5: - failures.append(f"heap_token_gate_text should carry 5 refusal texts, the scan found {len(gate)}") + if len(gate) != 4: + failures.append(f"heap_token_gate_text should carry 4 refusal texts, the scan found {len(gate)}") found |= gate + # The mirror's own refusals (the queue, the buffers and the kinds copy of a heap token dispatch). + mirror_path = REPO_ROOT / "src" / "startup_stubs" / "heap_token_mirror.inl" + if not mirror_path.exists(): + failures.append("heap_token_mirror.inl not found") + return + mirror = mirror_path.read_text(encoding="utf-8") + mirror_reasons = set() + for name in ("heap_mirror_flush", "heap_mirror_upload_dims", "heap_mirror_prepare"): + mirror_reasons |= literals(function_body(mirror, name)) + if len(mirror_reasons) != 4: + failures.append(f"the heap token mirror should carry 4 refusal texts, the scan found {sorted(mirror_reasons)}") + found |= mirror_reasons missing = sorted(s for s in found if s not in triage_run.COMPUTE_DISPATCH_REASONS) if missing: failures.append("source reasons missing from COMPUTE_DISPATCH_REASONS: " + ", ".join(repr(s) for s in missing)) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index e6d444e401..b56881c94e 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -231,8 +231,9 @@ 'entry value, input or output count', 'formatted D16 write has an incompatible typed buffer UAV', 'formatted D16 write needs the original typed buffer view', + "heap token lines that are not the translator's complete set", 'heap token textures are not bound yet', - 'heap tokens are not bound yet (runtime binding in progress)', + 'heap token words without the three heap token views', 'heap tokens need a GPU-visible view heap', 'heap tokens need a directly indexed resource heap', 'heap tokens need id tokens', @@ -255,6 +256,9 @@ 'the descriptor table is larger than the ring', 'the device does not take a directly indexed resource heap', 'the device does not take a directly indexed sampler heap', + 'the heap token buffers could not be created', + 'the heap token kinds could not be uploaded', + 'the heap token queue could not be taken', 'the indirect argument buffer is also a bound shader resource', 'the list type has no Dispatch', 'the sampler heap could not be created', From 2d917ccbdf840093653d28af5f0ed7303f9a0a57 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 07:19:08 +0100 Subject: [PATCH 17/19] d3d12 runtime: heap token binding review fixes Review of the heap token binding commit: - The token dispatch holds COM references: HeapMirrorBinding keeps the alias buffer, kinds table and miss counter as ComPtrs, and heap_mirror_prepare retains the alias buffer and its heap with the recording (retain_with_recording, new heap overload and allocator holds), so a title releasing its view heap between recording and execution cannot free what the list reads. The reference is taken before anything else in prepare, closing the CPU window until the view is written. - The mirror takes its own reference on a desktop resource with the liveness check and the AddRef as one step (retire_acquire_desktop, under retire_lock), before CreateShaderResourceView. - The miss readback logs a delta of 0 for a copy older than the last one and never moves the logged mark back (heap_token_miss_advance). - An id whose resource wrapper is alive but has no desktop object yet is queued again at the next flush. Known limit, not changed: the kinds copy recorded in a list that is never submitted or is reset is not re-recorded; its ids read kind 0 (a counted miss, never a wrong view), because the list bookkeeping has no cheap per-list span to re-dirty. - heap_token_gate_text no longer looks at the view heap alias (the answer is cached per program); heap_mirror_prepare refuses a Dispatch whose list has no alias with the same "heap tokens need a GPU-visible view heap" through the normal reason path. - Ring cursor stays inside the ring (no jump at the 32-bit wrap with the 196,603-slot ring); the mirror's entry table is allocated before the queue is taken, so flush cannot throw under draw_lock (named refusal). - Tests: the Dispatch-time alias refusal and a release-before-execute run on hardware (recording holds one heap), exact Dispatch outcome in the native check's bound branch, counter read after the fence before the logged dispatch, unit checks and mutation controls for the ring cursor and the miss delta. On WARP the program is refused for its 32-lane waves before any Dispatch can bind it. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 17 +++- .../experiments/native-heap-token-textures.md | 9 +- src/startup_stubs/d3d12_compute_dispatch.inl | 11 ++- src/startup_stubs/d3d12_xs_device.cpp | 76 ++++++++++++++-- src/startup_stubs/heap_token_binding.h | 36 +++++--- src/startup_stubs/heap_token_mirror.inl | 90 ++++++++++++++----- tests/heap_token_binding_check.cpp | 57 +++++++++--- tests/heap_token_kinds_check.cpp | 15 ++++ .../startup_compute_dispatch_native_check.py | 27 ++++-- .../startup_compute_dispatch_texture_check.py | 13 ++- tests/startup_compute_heap_token_check.py | 15 ++-- ...artup_compute_heap_token_dispatch_check.py | 51 +++++++++-- tests/startup_stream_consumer.cpp | 29 +++++- tests/startup_triage_run_check.py | 11 +-- tools/startup/triage_run.py | 2 + 15 files changed, 355 insertions(+), 104 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index dcef013601..83bcac599a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2480,7 +2480,7 @@ heap_token_binding_mutant(region-overlap "return heap_token_ring_size(heap_slots) + id; }" "return heap_token_ring_size(heap_slots) + id - 1; }" "FAIL: the mirror does not start where the ring ends") heap_token_binding_mutant(ring-wrap-dropped - "if (first + n > ring_size) {" "if (false) {" + "if (first + n > ring_size) first = 0;" "if (false) first = 0;" "FAIL: a reservation of 5 slots 3 below the end of the ring does not start at 0") heap_token_binding_mutant(ring-oversize-taken "if (n > ring_size || n > 0x7fffffffu) return heap_token_ring_refused;" "" @@ -2498,9 +2498,18 @@ heap_token_binding_mutant(root-flag-dropped "(heap_tokens_bound ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE)" "D3D12_ROOT_SIGNATURE_FLAG_NONE" "FAIL: a heap token program's root lacks the view heap flag") -heap_token_binding_mutant(gate-alias-ignored - "if (!view_heap_alias) return \"heap tokens need a GPU-visible view heap\";" "" - "FAIL gate no GPU-visible view heap:") +heap_token_binding_mutant(gate-capability-ignored + "if (lacks_resource_heap) return \"heap tokens need a directly indexed resource heap\";" "" + "FAIL gate adapter lacks the resource heap:") +heap_token_binding_mutant(ring-cursor-runs-on + "const UINT next = first + n == ring_size ? 0 : first + n;" "const UINT next = static_cast(seen) + n;" + "FAIL: the cursor left the ring") +heap_token_binding_mutant(miss-delta-underflows + "const std::uint32_t delta = total >= logged ? total - logged : 0;" "const std::uint32_t delta = total - logged;" + "FAIL: an older readback does not give a delta of 0") +heap_token_binding_mutant(miss-mark-moves-back + "if (total > logged) logged = total;" "logged = total;" + "FAIL: an older readback moved the logged mark back") heap_token_binding_mutant(null-2d-word-wrong "case 5: return heap_token_null_slot(heap_slots, null_2d);" "case 5: return heap_token_null_slot(heap_slots, null_1d);" "FAIL: null2d is not the 2D null slot") diff --git a/docs/experiments/native-heap-token-textures.md b/docs/experiments/native-heap-token-textures.md index 4876b15362..99bb0ce1a6 100644 --- a/docs/experiments/native-heap-token-textures.md +++ b/docs/experiments/native-heap-token-textures.md @@ -40,12 +40,13 @@ those two words at the guest byte address and maps the id to a host descriptor. `native_compute_output_revision` is 4 (see Revision below). The native-only route (no manifest reader) refuses a program with token words with the same text as the manifest reader, `heap token textures are not bound yet`. The root signature of the pipeline sets `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for them. -- The refusal has four texts, the same on both routes (`heap_token_refusal` in `src/startup_stubs/d3d12_compute_dispatch.inl`): +- The translation-time refusal has three texts, the same on both routes (`heap_token_refusal` in `src/startup_stubs/d3d12_compute_dispatch.inl`): `heap token textures are not bound yet` while the opt-in `X2W_D3D12_HEAP_TOKENS=1` is unset (also when only `X2W_D3D12_VIEW_CONTENT_TOKENS=1` is set); `heap tokens need id tokens` with both set (the tokens would name content, not - view ids); `heap tokens need a directly indexed resource heap` when the adapter lacks it; `heap tokens need a GPU-visible - view heap` when no shader-visible view heap has an alias of its memory (and at the dispatch, when the heap the list bound - has none). With none of them the runtime binds the program. Both variables are read once. + view ids); `heap tokens need a directly indexed resource heap` when the adapter lacks it. With none of them the runtime + binds the program. Both variables are read once. The fourth text, `heap tokens need a GPU-visible view heap`, is the + refusal of a Dispatch whose list has bound a view heap with no alias of its memory (`heap_mirror_prepare`); it is not part + of the translation-time answer, which is cached per program while an alias can appear later. ## Tests diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 34110c6426..1e83955632 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -280,14 +280,13 @@ bool adapter_lacks_directly_indexed_resource_heap() // reader and the native-only route, so triage reads the same reason on both (heap_token_gate_text, in the order the // causes are checked): the opt-in X2W_D3D12_HEAP_TOKENS is off (today's text); it is on together with // X2W_D3D12_VIEW_CONTENT_TOKENS (the tokens would name content, not view ids); the adapter lacks the directly indexed -// resource heap; or no shader-visible view heap has a GPU alias of its memory (heap_token_alias.h). Null when none of them -// holds: the program is bound at its dispatch (heap_mirror_prepare, which refuses by name when the heap the list has bound -// has no alias). +// resource heap. Null when none of them holds: the program is bound at its dispatch (heap_mirror_prepare, which refuses by +// name when the heap the list has bound has no GPU alias of its memory, heap_token_alias.h). The alias is not part of this +// answer: it is cached per program and an alias can appear after the program was translated. const char* heap_token_refusal() { return x2w_startup::heap_token_gate_text(heap_tokens(), view_content_tokens(), - heap_tokens() && !view_content_tokens() && adapter_lacks_directly_indexed_resource_heap(), - heap_token_aliases().any()); + heap_tokens() && !view_content_tokens() && adapter_lacks_directly_indexed_resource_heap()); } // The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is @@ -1504,7 +1503,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& if (tr->uds[i].source == ComputeTranslation::heaptok_word) values[i] = x2w_startup::heap_token_word_value(static_cast(tr->uds[i].a), draw_heap_size, mirror.records); for (std::size_t i = inputs; i < count; ++i) - if (views[i].token == 3) views[i].resource = mirror.miss; // the barrier after the dispatch names it + if (views[i].token == 3) views[i].resource = mirror.miss.Get(); // the barrier after the dispatch names it } if (reason) { if (!tr->first_refusal) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 6526aa6104..352c4b8c6f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1217,6 +1217,7 @@ void clear_draw_sampler_snapshot(Wrapper* self); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists); void drain_retired_resources(); +x2w_startup::ComPtr retire_acquire_desktop(Wrapper* resource, bool& no_desktop_yet); bool retire_reasons_enabled(); void retire_diag_note_release(Wrapper* w); void drop_mesh_lease_owner(Wrapper* w); @@ -1650,6 +1651,8 @@ struct DesktopAllocator { // queue that ran it has passed its fence (the allocator is reused only when idle). std::vector> scratches; x2w_startup::UniqueRecordingHolds> retained_resources; + // The heaps behind retained aliases (the GPU alias of a title view heap's memory), released with the resources. + x2w_startup::UniqueRecordingHolds> retained_heaps; // Immutable raw SRV table slices live until the allocator's last queue fence retires. std::vector> mesh_view_pages; UINT mesh_view_cursor = 0; @@ -1811,6 +1814,26 @@ bool retain_with_recording(Wrapper* self, x2w_startup::ComPtr re return retained; } +// The same for a heap (the heap behind a retained placed alias): both or neither is kept. False if the list is not +// recording or the hold could not be stored; nothing is kept then. +bool retain_with_recording(Wrapper* self, x2w_startup::ComPtr resource, x2w_startup::ComPtr heap) +{ + bool retained = false; + AcquireSRWLockExclusive(&allocator_lock); + const auto& state = self->own(); + const auto found = list_recordings.find(self); + if (state.list_open && found != list_recordings.end() && found->second) { + try { + found->second->retained_heaps.retain(std::move(heap)); + found->second->retained_resources.retain(std::move(resource)); + retained = true; // a heap kept without its resource is harmless: it is released with the recording + } catch (const std::bad_alloc&) { + } + } + ReleaseSRWLockExclusive(&allocator_lock); + return retained; +} + // Fixture query includes every backing allocator, including old recordings still pending on a queue. extern "C" __declspec(dllexport) UINT x2w_d3d12_allocator_sampler_snapshots(void* guest_allocator) { @@ -1840,6 +1863,21 @@ extern "C" __declspec(dllexport) UINT x2w_d3d12_recording_scratches(void* guest_ return held; } +// Fixture query (startup_compute_heap_token_dispatch): how many resources and heaps the recording of a list retains (the alias +// of a heap token dispatch's view heap is one heap and one resource). False for a list that has no recording. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_recording_retained(void* guest_list, UINT* resources, UINT* heaps) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind || !resources || !heaps) return FALSE; + AcquireSRWLockShared(&allocator_lock); + const auto found = list_recordings.find(self); + const bool have = found != list_recordings.end() && found->second; + *resources = have ? static_cast(found->second->retained_resources.size()) : 0; + *heaps = have ? static_cast(found->second->retained_heaps.size()) : 0; + ReleaseSRWLockShared(&allocator_lock); + return have; +} + // Fixture query for two closed recordings before either is submitted. extern "C" __declspec(dllexport) BOOL x2w_d3d12_distinct_rect_scratch(void* first, void* second) { @@ -1899,6 +1937,7 @@ HRESULT __stdcall allocator_reset(Wrapper* self) std::vector> retired_validation; std::vector> retired_scratches; decltype(DesktopAllocator::retained_resources) retired_resources; + decltype(DesktopAllocator::retained_heaps) retired_heaps; std::vector> retired_mesh_pages; std::vector> retired_sampler_snapshots; AcquireSRWLockExclusive(&allocator_lock); @@ -1927,6 +1966,7 @@ HRESULT __stdcall allocator_reset(Wrapper* self) retired_validation.swap(next->indexed_validation); std::swap(retired_scratches, next->scratches); std::swap(retired_resources, next->retained_resources); + std::swap(retired_heaps, next->retained_heaps); std::swap(retired_mesh_pages, next->mesh_view_pages); next->mesh_view_cursor = 0; next->mesh86_page.Reset(); @@ -2100,6 +2140,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) std::vector> retired_validation; std::vector> retired_scratches; decltype(DesktopAllocator::retained_resources) retired_resources; + decltype(DesktopAllocator::retained_heaps) retired_heaps; std::vector> retired_mesh_pages; std::vector> retired_sampler_snapshots; AcquireSRWLockExclusive(&allocator_lock); @@ -2117,6 +2158,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) retired_validation.swap(spare->indexed_validation); std::swap(retired_scratches, spare->scratches); std::swap(retired_resources, spare->retained_resources); + std::swap(retired_heaps, spare->retained_heaps); std::swap(retired_mesh_pages, spare->mesh_view_pages); spare->mesh_view_cursor = 0; spare->mesh86_page.Reset(); @@ -5243,14 +5285,15 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); // What a translated compute Dispatch with heap token views (X2W_D3D12_HEAP_TOKENS) writes into its table: the alias of the // title view heap's memory, the kinds table, the miss counter, and the number of view records. The functions are defined in -// heap_token_mirror.inl, below translate_srv_desc, which they use. +// heap_token_mirror.inl, below translate_srv_desc, which they use. The binding holds COM references: the alias buffer is +// also retained with the recording (and its heap), so the title releasing its view heap cannot free what the list reads. struct HeapMirrorBinding { bool active = false; - ID3D12Resource* tokens = nullptr; // the alias of the title view heap's memory - UINT token_elements = 0; // raw (dword) elements of the token view: entries * 8 - ID3D12Resource* dims = nullptr; - ID3D12Resource* miss = nullptr; - UINT records = 0; // view records at this dispatch (the program's count word) + x2w_startup::ComPtr tokens; // the alias of the title view heap's memory + UINT token_elements = 0; // raw (dword) elements of the token view: entries * 8 + x2w_startup::ComPtr dims; + x2w_startup::ComPtr miss; + UINT records = 0; // view records at this dispatch (the program's count word) }; const char* heap_mirror_prepare(Wrapper* self, ID3D12GraphicsCommandList* list, Pass& pass, HeapMirrorBinding& out); void heap_mirror_write_view(Wrapper* self, const HeapMirrorBinding& binding, int token, D3D12_CPU_DESCRIPTOR_HANDLE dest); @@ -6827,6 +6870,27 @@ bool retire_hold(Wrapper* list, Wrapper* resource) return true; } +// A reference of its own on the desktop object of a live title resource wrapper, or null. The liveness check (the wrapper +// still has references) and the AddRef are one step under retire_lock, which the drain also holds when it clears own().real, +// so the wrapper cannot die between them. no_desktop_yet: the wrapper is live but has no desktop object (yet). +x2w_startup::ComPtr retire_acquire_desktop(Wrapper* resource, bool& no_desktop_yet) +{ + no_desktop_yet = false; + x2w_startup::ComPtr held; + if (!resource || resource->own().kind != resource_kind) return held; + AcquireSRWLockExclusive(&retire_lock); + if (InterlockedCompareExchange(&resource->own().refs, 0, 0)) { + if (auto* real = static_cast(resource->own().real)) { + real->AddRef(); + held.Attach(real); + } else { + no_desktop_yet = true; + } + } + ReleaseSRWLockExclusive(&retire_lock); + return held; +} + void retire_discard_holds(Wrapper* list) { list->own().retire_hold_stamp = 0; // the next hold opens a new set; resources stamped with the old one miss diff --git a/src/startup_stubs/heap_token_binding.h b/src/startup_stubs/heap_token_binding.h index 1e798aede0..077d57a0dd 100644 --- a/src/startup_stubs/heap_token_binding.h +++ b/src/startup_stubs/heap_token_binding.h @@ -43,19 +43,31 @@ constexpr UINT heap_token_null_slot(UINT heap_slots, HeapTokenNull which) // What heap_token_ring_reserve returns for a reservation larger than the ring. constexpr UINT heap_token_ring_refused = ~0u; -// Reserves n consecutive ring slots and returns the first. `cursor` only grows (it wraps through 32 bits, which the -// modulus survives); a reservation that does not fit before the end of the ring starts again at 0. A reservation larger -// than the whole ring fits nowhere without reaching the region: it is refused with heap_token_ring_refused and the -// cursor is left alone. +// Reserves n consecutive ring slots and returns the first. The cursor is kept inside [0, ring_size): the next reservation +// starts where this one ends (a cursor outside the ring, such as a fixture's start, is taken modulo the ring once and +// never again), so the position never jumps when a 32-bit counter would wrap (2^32 is no multiple of the ring of +// 196,603). A reservation that does not fit before the end of the ring starts again at 0. A reservation larger than the +// whole ring fits nowhere without reaching the region: it is refused with heap_token_ring_refused and the cursor is left +// alone. inline UINT heap_token_ring_reserve(volatile LONG* cursor, UINT n, UINT ring_size) { if (n > ring_size || n > 0x7fffffffu) return heap_token_ring_refused; - UINT first = static_cast(InterlockedExchangeAdd(cursor, static_cast(n))) % ring_size; - if (first + n > ring_size) { - first = 0; - InterlockedExchange(cursor, static_cast(n)); + for (;;) { + const LONG seen = *cursor; + UINT first = static_cast(seen) % ring_size; + if (first + n > ring_size) first = 0; + const UINT next = first + n == ring_size ? 0 : first + n; + if (InterlockedCompareExchange(cursor, static_cast(next), seen) == seen) return first; } - return first; +} + +// The miss counter's periodic readback: a copy that is not fenced may be older than the last one logged, so the delta is +// clamped to 0 and `logged` never moves backwards. Returns the delta to log. +inline std::uint32_t heap_token_miss_advance(std::uint32_t total, std::uint32_t& logged) +{ + const std::uint32_t delta = total >= logged ? total - logged : 0; + if (total > logged) logged = total; + return delta; } // The typed null of a kind: a null resource reads no more of the description than its format and dimension. @@ -132,13 +144,13 @@ inline D3D12_ROOT_SIGNATURE_FLAGS compute_root_flags(bool sampler_heap, bool hea // Why a translated compute program with heap token lines cannot run, in the order the causes are checked: null when nothing // static stops it (the runtime then binds the views, or refuses by name at the dispatch). One text for the manifest reader -// and the native-only route. -inline const char* heap_token_gate_text(bool opt_in, bool content_tokens, bool lacks_resource_heap, bool view_heap_alias) +// and the native-only route. The answer is cached per program, so it holds only what does not change: whether the list's +// view heap has a GPU alias (heap tokens need a GPU-visible view heap) is checked at every dispatch, heap_mirror_prepare. +inline const char* heap_token_gate_text(bool opt_in, bool content_tokens, bool lacks_resource_heap) { if (!opt_in) return "heap token textures are not bound yet"; if (content_tokens) return "heap tokens need id tokens"; if (lacks_resource_heap) return "heap tokens need a directly indexed resource heap"; - if (!view_heap_alias) return "heap tokens need a GPU-visible view heap"; return nullptr; } diff --git a/src/startup_stubs/heap_token_mirror.inl b/src/startup_stubs/heap_token_mirror.inl index b1856656e0..46039da363 100644 --- a/src/startup_stubs/heap_token_mirror.inl +++ b/src/startup_stubs/heap_token_mirror.inl @@ -15,12 +15,16 @@ // UAV into its table (no new root parameter). // heap_mirror_after_dispatch the miss counter's periodic readback (logged every 4096 dispatches). // +// The alias of the list's view heap (the token memory) is retained, with its heap, by the recording of every heap token +// dispatch (retain_with_recording), so the title releasing its view heap cannot free it under a list that has not run yet. +// // Known limits until the release path exists (a later commit): a mirror entry is never released (the resource stays alive, the -// descriptor stays written, its kind stays); an id whose record was reassigned keeps its first entry and reads kind 0; a -// resource the title has not made on the desktop when the id is flushed is never retried; resources a list tracks in a write -// state are not transitioned for a token read (the title's barriers are the only states they get); the kinds copy is -// recorded in the list of the first dispatch that sees the change, so a list that is recorded but never submitted loses it -// (its ids read kind 0, a miss, never a wrong view). Every member of the mirror: draw_lock held. +// descriptor stays written, its kind stays); an id whose record was reassigned keeps its first entry and reads kind 0; +// resources a list tracks in a write state are not transitioned for a token read (the title's barriers are the only states +// they get); the kinds copy is recorded in the list of the first dispatch that sees the change, so a list that is recorded +// but never submitted, or reset, loses it and the span is not copied again (its ids read kind 0, a counted miss, never a +// wrong view). An id whose resource wrapper is alive but has no desktop object yet is queued again at the next flush. +// Every member of the mirror: draw_lock held. struct HeapMirrorEntry { x2w_startup::ComPtr resource; // the mirror's own reference on the desktop resource @@ -106,6 +110,18 @@ std::uint32_t heap_mirror_default_view_kind(const D3D12_RESOURCE_DESC& resource) // dispatch is then refused and the ids stay queued), or null; an id that gets no descriptor is counted in the mirror's totals. const char* heap_mirror_flush(HeapMirror& m) { + // The table of entries is allocated whole before the queue is taken: nothing below can throw under draw_lock, and a + // failure leaves every id queued for the next dispatch. + if (m.entries.size() < x2w_startup::heap_token_mirror_capacity) { + try { + m.entries.resize(x2w_startup::heap_token_mirror_capacity); + } catch (const std::bad_alloc&) { + ++m.flush_failures; + static LONG logged; + if (first_calls(logged, 4)) log("x2w-draw heap token mirror could not allocate its entries (out of memory); retried at the next dispatch"); + return "the heap token mirror could not allocate its entries"; + } + } std::vector taken; std::vector records; AcquireSRWLockExclusive(¬e_lock); @@ -136,6 +152,17 @@ const char* heap_mirror_flush(HeapMirror& m) ReleaseSRWLockShared(¬e_lock); ID3D12Device* const device = device_of(the_device); const D3D12_CPU_DESCRIPTOR_HANDLE start = draw_heap->GetCPUDescriptorHandleForHeapStart(); + std::vector requeue; // ids whose resource has no desktop object yet: queued again behind this flush + struct Requeue { + std::vector& ids; + ~Requeue() + { + if (ids.empty()) return; + AcquireSRWLockExclusive(¬e_lock); + for (const std::uint32_t id : ids) heap_mirror_pending().note_record(id, false, true); // same generation, deduplicated + ReleaseSRWLockExclusive(¬e_lock); + } + } requeue_at_exit{requeue}; for (std::size_t i = 0; i < taken.size(); ++i) { const std::uint32_t id = taken[i].id; if (!still_current[i]) continue; // reassigned since it was queued: its own entry is queued behind this one @@ -144,8 +171,7 @@ const char* heap_mirror_flush(HeapMirror& m) x2w_startup::heap_token_mirror_capacity); continue; } - if (m.entries.size() <= id) m.entries.resize(std::size_t{id} + 1); - HeapMirrorEntry& entry = m.entries[id]; + HeapMirrorEntry& entry = m.entries[id]; // sized to the capacity above if (entry.written) { // the id holds another record now: entries are not released yet, so it keeps the first one if (entry.generation != taken[i].generation) { ++m.reassigned; @@ -154,14 +180,21 @@ const char* heap_mirror_flush(HeapMirror& m) continue; } const ViewRecord& record = records[i]; + if (record.slot != 18 || record.desc_bytes < ViewRecord::srv_desc_bytes) { + ++m.unresolved; + continue; + } + // The mirror's own reference, taken before anything uses the resource, in one step with the check that the wrapper + // is alive. A wrapper that is alive without a desktop object (yet) is tried again at the next flush; a dead one is not. Wrapper* const wrapper = as_wrapper(reinterpret_cast(record.resource)); - ID3D12Resource* const resource = wrapper && wrapper->own().kind == resource_kind && - InterlockedCompareExchange(&wrapper->own().refs, 0, 0) - ? static_cast(wrapper->own().real) : nullptr; - if (!resource || record.slot != 18 || record.desc_bytes < ViewRecord::srv_desc_bytes) { + bool no_desktop_yet = false; + x2w_startup::ComPtr held = retire_acquire_desktop(wrapper, no_desktop_yet); + if (!held) { ++m.unresolved; + if (no_desktop_yet) requeue.push_back(id); continue; } + ID3D12Resource* const resource = held.Get(); if (wrapper->own().tiled_address_srv) { // a texture by title address: what it samples is another object (sampled_address_texture) ++m.skipped; continue; @@ -183,7 +216,7 @@ const char* heap_mirror_flush(HeapMirror& m) const D3D12_CPU_DESCRIPTOR_HANDLE slot{start.ptr + std::size_t{x2w_startup::heap_token_mirror_slot(draw_heap_size, id)} * draw_heap_increment}; device->CreateShaderResourceView(resource, srv.check.default_view ? nullptr : &srv.desc, slot); - entry.resource = resource; // the mirror's own reference + entry.resource = std::move(held); // the mirror keeps the reference taken above entry.generation = taken[i].generation; entry.kind = kind; entry.written = true; @@ -223,20 +256,28 @@ const char* heap_mirror_upload_dims(Wrapper* self, ID3D12GraphicsCommandList* li const char* heap_mirror_prepare(Wrapper* self, ID3D12GraphicsCommandList* list, Pass& pass, HeapMirrorBinding& out) { HeapMirror& m = heap_mirror(); + // Whether the list's view heap has a GPU alias is decided here, at every dispatch (the translation-time gate is cached + // per program and does not know the alias). `find` copies the entry: `alias` holds its own references on the alias + // buffer and heap from here on, so the title releasing its view heap cannot free them before the view is written. x2w_startup::HeapTokenAlias alias; - if (!pass.title_view_heap.address || !heap_token_aliases().find(pass.title_view_heap.address, alias) || !alias.alias.buffer) + if (!pass.title_view_heap.address || !heap_token_aliases().find(pass.title_view_heap.address, alias) || !alias.alias.buffer || + !alias.alias.heap) return "heap tokens need a GPU-visible view heap"; if (!heap_mirror_create_buffers(m)) return "the heap token buffers could not be created"; + // The list reads the alias when it executes, possibly after the title released its view heap (which drops the alias): + // the recording keeps the buffer and its heap until every queue that ran it has passed its fence. + if (!retain_with_recording(self, alias.alias.buffer, alias.alias.heap)) + return "the heap token alias could not be kept with the recording"; if (const char* why = heap_mirror_flush(m)) return why; if (const char* why = heap_mirror_upload_dims(self, list, m)) return why; AcquireSRWLockShared(¬e_lock); out.records = static_cast((std::min)(view_records().size(), x2w_startup::heap_token_mirror_capacity)); ReleaseSRWLockShared(¬e_lock); out.active = true; - out.tokens = alias.alias.buffer.Get(); + out.tokens = alias.alias.buffer; out.token_elements = alias.num_elements; - out.dims = m.dims.Get(); - out.miss = m.miss.Get(); + out.dims = m.dims; + out.miss = m.miss; ++m.dispatches; return nullptr; } @@ -247,7 +288,7 @@ void heap_mirror_write_view(Wrapper* self, const HeapMirrorBinding& binding, int { ID3D12Device* const device = device_of(the_device); if (token == 1 || token == 2) { - ID3D12Resource* const resource = token == 1 ? binding.tokens : binding.dims; + ID3D12Resource* const resource = token == 1 ? binding.tokens.Get() : binding.dims.Get(); require_state(self, resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; desc.Format = DXGI_FORMAT_R32_TYPELESS; @@ -258,13 +299,13 @@ void heap_mirror_write_view(Wrapper* self, const HeapMirrorBinding& binding, int device->CreateShaderResourceView(resource, &desc, dest); return; } - require_state(self, binding.miss, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + require_state(self, binding.miss.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; desc.Buffer.NumElements = 1; desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; - device->CreateUnorderedAccessView(binding.miss, nullptr, &desc, dest); + device->CreateUnorderedAccessView(binding.miss.Get(), nullptr, &desc, dest); } // Every 4096th heap token dispatch copies the miss counter into a small readback ring; the delta since the previous copy is @@ -283,13 +324,14 @@ void heap_mirror_after_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, std::memcpy(&total, static_cast(mapped) + range.Begin, sizeof(total)); const D3D12_RANGE none{}; m.readback->Unmap(0, &none); - log("x2w-draw heap token misses: %u in total, %u since the last readback (%llu heap token dispatches)", total, - total - m.logged_misses, static_cast(m.dispatches)); - m.logged_misses = total; + // A readback older than the last one logged (the copy is not fenced) logs a delta of 0 and does not move the mark back. + const std::uint32_t delta = x2w_startup::heap_token_miss_advance(total, m.logged_misses); + log("x2w-draw heap token misses: %u in total, %u since the last readback (%llu heap token dispatches)", total, delta, + static_cast(m.dispatches)); } } - require_state(self, binding.miss, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->CopyBufferRegion(m.readback.Get(), std::size_t{m.readback_slot} * heap_mirror_readback_stride, binding.miss, 0, 4); + require_state(self, binding.miss.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(m.readback.Get(), std::size_t{m.readback_slot} * heap_mirror_readback_stride, binding.miss.Get(), 0, 4); m.readback_slot = (m.readback_slot + 1) % heap_mirror_readback_slots; m.readback_pending = true; } diff --git a/tests/heap_token_binding_check.cpp b/tests/heap_token_binding_check.cpp index fd516300d6..9921910be9 100644 --- a/tests/heap_token_binding_check.cpp +++ b/tests/heap_token_binding_check.cpp @@ -46,10 +46,11 @@ void ring() for (const LONG start : {LONG{0}, LONG{196000}, LONG{0x7fffff00}, LONG{-300}, static_cast(0x80000000u)}) { volatile LONG cursor = start; UINT highest = 0, wraps = 0, previous_first = 0; - bool inside = true, touched_region = false; + bool inside = true, touched_region = false, cursor_in_ring = true; for (int i = 0; i < 20000; ++i) { const UINT n = sizes[(i * 7 + i / 3) % (sizeof(sizes) / sizeof(sizes[0]))]; const UINT first = heap_token_ring_reserve(&cursor, n, ring_size); + cursor_in_ring = cursor_in_ring && static_cast(cursor) < ring_size; inside = inside && first != heap_token_ring_refused && first + n <= ring_size; touched_region = touched_region || first + n > region_start; // a slot at or above the region's first if (first + n > highest) highest = first + n; @@ -57,11 +58,33 @@ void ring() previous_first = first; } expect(inside, "a reservation left the ring"); + expect(cursor_in_ring, "the cursor left the ring (it must never run on to a 32-bit wrap)"); expect(!touched_region, "a ring reservation reached the region"); expect(highest <= region_start, "the highest ring slot is inside the region"); expect(wraps > 5, "the ring never wrapped in the test run"); expect(highest > region_start - 4096, "the ring does not use its top (the check may be too weak)"); } + // The ring is contiguous across the values a 32-bit counter would wrap at: 2^32 is no multiple of the ring (196,603), so a + // free-running cursor taken modulo the ring jumps there. Starting 4 below the wrap, each one-slot reservation starts where + // the previous one ended. + for (const LONG start : {LONG{-4}, LONG{0x7ffffffc}, static_cast(0xfffffffcu)}) { + volatile LONG cursor = start; + UINT previous = heap_token_ring_reserve(&cursor, 1, ring_size); + bool contiguous = true; + for (int i = 0; i < 12; ++i) { + const UINT first = heap_token_ring_reserve(&cursor, 1, ring_size); + contiguous = contiguous && first == (previous + 1) % ring_size; + previous = first; + } + expect(contiguous, "the ring is not contiguous across the 32-bit wrap of the cursor"); + } + { + // Filling the ring exactly leaves the cursor at 0, not at the ring's size. + volatile LONG cursor = 0; + expect(heap_token_ring_reserve(&cursor, ring_size - 7, ring_size) == 0 && heap_token_ring_reserve(&cursor, 7, ring_size) == ring_size - 7 && + cursor == 0, + "a ring filled exactly does not leave the cursor at 0"); + } // A table that does not fit before the end of the ring starts at slot 0; the old whole-heap modulus put it in the region. { volatile LONG cursor = static_cast(ring_size - 3); @@ -157,21 +180,18 @@ void gate() const char* off = "heap token textures are not bound yet"; const char* content = "heap tokens need id tokens"; const char* capability = "heap tokens need a directly indexed resource heap"; - const char* no_heap = "heap tokens need a GPU-visible view heap"; const char* const none = nullptr; // nothing static stops the program: the runtime binds the views - struct Row { const char* name; bool opt_in, content, lacks, alias; const char* want; }; + struct Row { const char* name; bool opt_in, content, lacks; const char* want; }; const Row rows[] = { - {"opt-in off", false, false, false, false, off}, - {"opt-in off, everything else wrong", false, true, true, false, off}, - {"content tokens", true, true, false, true, content}, - {"content tokens beat the capability", true, true, true, false, content}, - {"adapter lacks the resource heap", true, false, true, true, capability}, - {"capability is checked before the alias", true, false, true, false, capability}, - {"no GPU-visible view heap", true, false, false, false, no_heap}, - {"everything holds", true, false, false, true, none}, + {"opt-in off", false, false, false, off}, + {"opt-in off, everything else wrong", false, true, true, off}, + {"content tokens", true, true, false, content}, + {"content tokens beat the capability", true, true, true, content}, + {"adapter lacks the resource heap", true, false, true, capability}, + {"everything holds", true, false, false, none}, }; for (const Row& r : rows) { - const char* got = heap_token_gate_text(r.opt_in, r.content, r.lacks, r.alias); + const char* got = heap_token_gate_text(r.opt_in, r.content, r.lacks); ++cases; if (got != r.want && (!got || !r.want || std::strcmp(got, r.want))) { ++failures; @@ -180,6 +200,18 @@ void gate() } } +// The miss counter's readback: an older value than the last one logged gives a delta of 0 and does not move the mark back. +void misses() +{ + std::uint32_t logged = 0; + expect(heap_token_miss_advance(49152, logged) == 49152 && logged == 49152, "the first readback is not logged in full"); + expect(heap_token_miss_advance(49200, logged) == 48 && logged == 49200, "a later readback is not the difference"); + expect(heap_token_miss_advance(49200, logged) == 0 && logged == 49200, "an unchanged readback is not a delta of 0"); + expect(heap_token_miss_advance(49000, logged) == 0, "an older readback does not give a delta of 0 (it would underflow)"); + expect(logged == 49200, "an older readback moved the logged mark back"); + expect(heap_token_miss_advance(49300, logged) == 100 && logged == 49300, "the delta after an older readback is not from the highest mark"); +} + // The nine entry words the runtime gives a heap token program, by the translator's names and order. void words() { @@ -247,6 +279,7 @@ int main(int argc, char**) alias(); root_flags(); gate(); + misses(); words(); shadow(); std::printf("%d of %d checks failed\n", failures, cases); diff --git a/tests/heap_token_kinds_check.cpp b/tests/heap_token_kinds_check.cpp index 8030fe2c31..71b0ce7bda 100644 --- a/tests/heap_token_kinds_check.cpp +++ b/tests/heap_token_kinds_check.cpp @@ -171,6 +171,21 @@ void pending() expect(q.lost() == 0, "ids were lost without an allocation failure"); expect(q.epoch_bumps() == 0 && q.take_failures() == 0, "an allocation failure was counted without one"); } + { + // Queued again (the flush does this for an id whose resource has no desktop object yet): the same generation, once + // however often it is noted, and the id comes back at the next take. + HeapMirrorPending q; + q.start(0, all); + q.note_record(4, true, true); // generation 1 + auto entries = q.take(); + expect(entries.size() == 1 && entries[0].id == 4 && entries[0].generation == 1, "the first take lacks the id or its generation"); + q.note_record(4, false, true); + q.note_record(4, false, true); + entries = q.take(); + expect(entries.size() == 1 && entries[0].id == 4 && entries[0].generation == 1, + "an id queued again is not returned once with the generation it had"); + expect(q.take().empty(), "an id queued again stayed queued after its take"); + } } // Allocation failures (std::bad_alloc injected through the test hooks of heap_token_pending.h). diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index b2bc403aec..662efd1541 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -377,14 +377,17 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal): HEAP_TOKEN_REFUSAL = 'heap token textures are not bound yet' -# The refusals of the heap token gate: X2W_D3D12_HEAP_TOKENS unset (also with only the content tokens on), on alone (bound, or the -# named refusal of a view heap without an alias; startup_compute_heap_token_dispatch checks what a bound program reads), and +# The refusals of the heap token gate: X2W_D3D12_HEAP_TOKENS unset (also with only the content tokens on), on alone (bound, or +# the pipeline refusal of an adapter without 32-lane waves; startup_compute_heap_token_dispatch checks what a bound program reads and +# the Dispatch-time refusal of a view heap without an alias), and # on together with X2W_D3D12_VIEW_CONTENT_TOKENS. HEAP_TOKEN_CASES = (({}, HEAP_TOKEN_REFUSAL), ({'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, HEAP_TOKEN_REFUSAL), - ({'X2W_D3D12_HEAP_TOKENS': '1'}, None), # bound when the view heap has a GPU alias, else NEED_VIEW_HEAP + ({'X2W_D3D12_HEAP_TOKENS': '1'}, None), # bound (32-lane waves and a 32-byte stride), else the adapter's own refusal ({'X2W_D3D12_HEAP_TOKENS': '1', 'X2W_D3D12_VIEW_CONTENT_TOKENS': '1'}, 'heap tokens need id tokens')) NEED_VIEW_HEAP = 'heap tokens need a GPU-visible view heap' # the opt-in alone, when the view heap got no GPU alias +NO_WAVES = 'the adapter has no 32-lane waves' # the opt-in alone on WARP: the pipeline is refused before a Dispatch binds views +BOUND_TABLE_REFUSAL = 'a table descriptor is not bound' # what the bound program's Dispatch is refused for in this rig HEAP_TOKEN_TEXTS = tuple(sorted({text for _, text in HEAP_TOKEN_CASES if text} | {NEED_VIEW_HEAP})) @@ -417,24 +420,30 @@ def heap_token_refusal(directory, consumer, dxc_dir, adapter): reason = lines(result, 'not translated natively: ') want = expected if expected is None: - # With the opt-in alone the text follows the adapter's CBV/SRV/UAV descriptor stride, which the open - # logs from the device (not from its result): only a 32-byte stride gets an alias (WARP's is 64 - # bytes). Another stride expects the named refusal; 32 needs the alias to have succeeded. + # With the opt-in alone the translation-time gate no longer looks at the view heap alias (it is cached per + # program; the alias is checked at every Dispatch). The program is then translated on an adapter with + # 32-lane waves and a 32-byte descriptor stride, which gets an alias (the open logs the stride from the + # device, not from its result). WARP has neither (64-byte stride, no 32-lane waves): its pipeline is refused + # for the waves before any Dispatch could bind the views. aliases = lines(result, 'heap token alias of ') assert len(aliases) == 1, (extra, aliases) stride = re.search(r'view stride (\d+)\) -> (0x[0-9a-f]{8})$', aliases[0]) assert stride, aliases if int(stride.group(1)) != 32: - want = NEED_VIEW_HEAP + want = NO_WAVES else: assert stride.group(2) == '0x00000000', f'the alias failed on a 32-byte stride adapter: {aliases[0]}' want = None # the runtime binds the program if want is None: # Bound: the program translates natively and takes the runtime's views. This rig puts the table at root - # parameter 1 and the token root's table is parameter 0, so its Dispatch is refused for the table; - # startup_compute_heap_token_dispatch binds a table at parameter 0 and checks what the program reads. + # parameter 1 and the token root's table is parameter 0, so its Dispatch is refused for the table (before + # any view is bound); startup_compute_heap_token_dispatch binds a table at parameter 0 and checks what the + # program reads. The exact Dispatch outcome is asserted: no other reason, and no heap token text. assert not reason, (extra, reason) assert len(lines(result, 'translated natively: 7 entry values, 3 inputs, 2 outputs')) == 1, result.stderr[-3000:] + outcome = lines(result, 'Dispatch(3, 2, 2) ') + assert len(outcome) == 1 and outcome[0].endswith('Dispatch(3, 2, 2) refused: ' + BOUND_TABLE_REFUSAL), ( + extra, outcome, result.stderr[-3000:]) for text in HEAP_TOKEN_TEXTS: assert not lines(result, 'refused: ' + text), (extra, result.stderr[-3000:]) else: diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 6d7c3fa600..86a0edbe8d 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -155,18 +155,15 @@ def check_manifest_refusal(case, variant, reason, extra_env=None): readback, dispatch_result = run(directory, consumer, dict(env, **(extra_env or {})), 'texture-store', layout) refusals = [message for message in lines(dispatch_result, 'Dispatch(') if ' refused: ' in message] if reason == INCOMPLETE_SET: - # With the opt-in alone the lines are read when the gate lets them through, which follows the adapter's CBV/SRV/UAV - # descriptor stride, which the open logs from - # the device (not from its result): only a 32-byte stride gets an alias (WARP's is 64 bytes). Another stride - # expects the named refusal; 32 needs the alias to have succeeded and the lines (one view or one word of a - # program that has no complete set) are refused as an incomplete set. + # With the opt-in alone the reader's gate lets the lines through on every adapter (whether the list's view heap has a + # GPU alias is the Dispatch's question, not a cached translation-time one), so one view or one word of a program + # that has no complete set is refused as an incomplete set whatever the descriptor stride. The alias is still made + # on a 32-byte stride adapter (WARP's stride is 64 bytes, which gets none). aliases = lines(dispatch_result, 'heap token alias of ') assert len(aliases) == 1, (case, aliases) stride = re.search(r'view stride (\d+)\) -> (0x[0-9a-f]{8})$', aliases[0]) assert stride, aliases - if int(stride.group(1)) != 32: - reason = 'heap tokens need a GPU-visible view heap' - else: + if int(stride.group(1)) == 32: assert stride.group(2) == '0x00000000', f'the alias failed on a 32-byte stride adapter: {aliases[0]}' suffix = 'Dispatch(2, 1, 1) refused: ' + reason assert len(refusals) == 1 and refusals[0].endswith(suffix), (case, refusals, dispatch_result.stderr[-3000:]) diff --git a/tests/startup_compute_heap_token_check.py b/tests/startup_compute_heap_token_check.py index 7388be61cf..e7d85018a2 100644 --- a/tests/startup_compute_heap_token_check.py +++ b/tests/startup_compute_heap_token_check.py @@ -25,10 +25,11 @@ Releasing the descriptor heap drops its alias (0 live afterwards). The production HeapTokenAliases::open is also driven directly (x2w_d3d12_heap_token_alias_open): an address opened twice, or reopened after its release, keeps one entry and the entry is the fresh one (generation); a 64-byte stride, a span too small for the records and an - interior pointer are refused and counted. The refusal a heap token program gets (x2w_d3d12_heap_token_refusal) - follows: "heap tokens need a GPU-visible view heap" while no view heap has an alias, then no refusal at all once one has - (or the capability text when the adapter lacks the directly indexed resource heap). With the switch off no - alias is made and the text is the old one. WARP's CBV/SRV/UAV stride may be 64 bytes: the heap created through + interior pointer are refused and counted. The refusal a heap token program gets at translation + (x2w_d3d12_heap_token_refusal, cached per program) does not depend on the alias: with the switch on it is no refusal at + all (or the capability text when the adapter lacks the directly indexed resource heap) before any alias, with one and + after its release; "heap tokens need a GPU-visible view heap" is the refusal of a Dispatch whose list has no alias + (startup_compute_heap_token_dispatch). With the switch off no alias is made and the text is the old one. WARP's CBV/SRV/UAV stride may be 64 bytes: the heap created through CreateDescriptorHeap is then the refusal case, and the success case is covered by the direct open only. 7. The mirror (x2w_d3d12_heap_mirror_flush, the flush a dispatch runs, here without a list): a 2D texture, a raw buffer, a @@ -314,7 +315,6 @@ def view_heap(flags, backing): return out OLD = 'heap token textures are not bound yet' - NEED_HEAP = 'heap tokens need a GPU-visible view heap' NEED_ROOT = 'heap tokens need a directly indexed resource heap' SHADER_VISIBLE = 1 state = alias(0) @@ -322,7 +322,8 @@ def view_heap(flags, backing): fails.expect(state.alias_any == 0 and state.alias_failed == 0, 'an alias or a failure before any shader-visible view heap') # The heaps created above are not shader visible: no alias even with the switch on. fails.expect(alias(memory).found == 0, 'a heap that is not shader visible got an alias') - fails.expect(refusal() == (NEED_ROOT if on and lacks else NEED_HEAP if on else OLD), + # The translation-time answer does not name the alias (it is cached per program; an alias can appear later). + fails.expect(refusal() == (NEED_ROOT if on and lacks else '' if on else OLD), 'refusal before any alias: "%s"' % refusal()) def cpu_start(heap): @@ -333,7 +334,7 @@ def release_heap(heap): vcall(heap, 2, ctypes.c_ulong, []) unsupported_stride = stride != 32 # WARP may give 64: the heaps below are then the refusal case - MIN_REFUSAL = NEED_ROOT if on and lacks else NEED_HEAP if on else OLD + MIN_REFUSAL = NEED_ROOT if on and lacks else '' if on else OLD # Memory the title supplied is never aliased (the runtime cannot see when the title frees it), whether it is an # allocation base or an interior pointer; it is counted for the measurement. diff --git a/tests/startup_compute_heap_token_dispatch_check.py b/tests/startup_compute_heap_token_dispatch_check.py index 454bd63f2c..8af94f5638 100644 --- a/tests/startup_compute_heap_token_dispatch_check.py +++ b/tests/startup_compute_heap_token_dispatch_check.py @@ -27,8 +27,15 @@ 5. The debug layer reports no error. 6. Opt-in off (the control): the program is refused with the old text, the output is untouched and no miss counter exists (the consumer prints 4294967295). -WARP (a 64-byte descriptor stride, so no GPU alias of the view heap): the same program is refused by name, the output is -untouched and no miss counter exists. Exit 77 when the adapter is not available. +7. A view heap the title gave memory for has no GPU alias: the Dispatch is refused at the Dispatch, by name ("heap tokens need + a GPU-visible view heap", from heap_mirror_prepare, not from the translation-time gate, which is cached per program), the + output is untouched, no miss counter exists and the translation itself is not refused. +8. The title releases its view heap after recording the Dispatch and before the list runs: the recording retains the alias + buffer and its heap (x2w_d3d12_recording_retained: one heap), the list runs, and the debug layer reports no error. +WARP (a 64-byte descriptor stride, no 32-lane waves): the program is refused before a Dispatch can bind it (the pipeline +needs 32-lane waves; the capability text when the adapter lacks the directly indexed resource heap), the output is untouched +and no miss counter exists. The Dispatch-time alias refusal (7) needs a program that translated, so it runs on hardware. +Exit 77 when the adapter is not available. """ from pathlib import Path import re @@ -43,6 +50,8 @@ UNTOUCHED = [C.SENTINEL] * C.WORDS NEED_VIEW_HEAP = 'heap tokens need a GPU-visible view heap' +NO_WAVES = 'the adapter has no 32-lane waves' +PIPELINE_NO_WAVES = 'pipeline creation failed (adapter has no 32-lane waves)' # the manifest route's text for the same CAPABILITY = 'heap tokens need a directly indexed resource heap' OFF = 'heap token textures are not bound yet' LANES = 32 @@ -133,10 +142,12 @@ def main(consumer, dxc_dir, adapter, compiler): got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3) if adapter == 'warp' or stride != 32: - # No GPU alias of a view heap with another stride than one record: the program is refused by name. + # No 32-lane waves (or no directly indexed resource heap): the program is not translated, so no Dispatch can bind it. + # (The alias refusal is the Dispatch's, heap_mirror_prepare: it is checked on hardware below.) reason = refusal(result) assert got == UNTOUCHED, 'a refused Dispatch wrote the output' - assert len(reason) == 1 and (reason[0].endswith(NEED_VIEW_HEAP) or reason[0].endswith(CAPABILITY)), result.stderr[-3000:] + assert len(reason) == 1 and (reason[0].endswith(NO_WAVES) or reason[0].endswith(CAPABILITY)), result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] assert misses == NO_COUNTER, f'a refused program created a miss counter ({misses})' assert not debug_errors(result), debug_errors(result)[0] if adapter == 'hardware': @@ -150,6 +161,27 @@ def main(consumer, dxc_dir, adapter, compiler): print(f'FAIL: the token program was refused on hardware: {refusal(result)[0]}\n{result.stderr[-2000:]}') return 1 + # A view heap with memory the title supplied has no alias: refused at the Dispatch by name, nothing bound, and the program + # itself was translated (the gate does not know the alias). + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3, {'X2W_TEST_VIEWTOK_SUPPLIED_HEAP': '1'}) + dispatch_refusals = lines(result, 'Dispatch(3, 2, 2) refused: ') + assert got == UNTOUCHED, 'a Dispatch without a view heap alias wrote the output' + assert not refusal(result), ('the gate refused a program the Dispatch should refuse', refusal(result)) + assert len(dispatch_refusals) == 1 and dispatch_refusals[0].endswith(': ' + NEED_VIEW_HEAP), (dispatch_refusals, result.stderr[-3000:]) + assert misses == NO_COUNTER, f'a Dispatch refused for its alias created a miss counter ({misses})' + assert not debug_errors(result), debug_errors(result)[0] + + # The title releases its view heap after recording the Dispatch and before the list runs: the recording holds the alias. + got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3, {'X2W_TEST_VIEWTOK_RELEASE_HEAP': '1'}) + held = re.search(r'recording retains: (\d+) resources (\d+) heaps \(recording found\)', result.stdout) + assert held and int(held.group(1)) >= 1 and int(held.group(2)) == 1, (held and held.group(0), result.stdout[-1500:]) + assert 'title view heap released before the list runs' in result.stdout, result.stdout[-1500:] + assert not refusal(result) and not lines(result, 'Dispatch(3, 2, 2) refused'), result.stderr[-3000:] + assert lines(result, 'Dispatch(3, 2, 2) translated'), result.stderr[-3000:] + assert not debug_errors(result), debug_errors(result)[0] + assert got == texture_words(109.0) and misses == 0, ('the list that ran after the heap was released read other words', got[:8], misses) + released = (held.group(1), held.group(2)) + checked = 0 for label, words, entry, expected in VALID: got, result, stride, misses = run(directory, consumer, on, words, entry) @@ -174,6 +206,11 @@ def main(consumer, dxc_dir, adapter, compiler): # token (12 waves each) add up, and the copy taken at the 4096th is logged when the 8192nd is recorded. got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 2, {'X2W_TEST_VIEWTOK_REPEAT': '4096'}) assert not refusal(result) and not debug_errors(result), (refusal(result), debug_errors(result)[:1]) + # The consumer waits for the list that holds the 4096th Dispatch (the guest fence) and reads the counter on a queue of its + # own before it records the list whose 8192nd Dispatch logs the copy: the dispatches of the first list (1) and of the + # first round (4096) have all counted by then, so the log below does not depend on how far the GPU has come. + after_first = re.search(r'heap token misses after the first round: (\d+)', result.stdout) + assert after_first and int(after_first.group(1)) == 12 * (1 + 4096), (after_first and after_first.group(0), result.stdout[-1500:]) assert misses == 12 * (1 + 2 * 4096), f'{misses} misses after {1 + 2 * 4096} dispatches of a missing token' logged = lines(result, 'x2w-draw heap token misses: ') assert len(logged) == 1 and f'{12 * 4096} in total, {12 * 4096} since the last readback (8192 heap token dispatches)' in logged[0], ( @@ -182,7 +219,9 @@ def main(consumer, dxc_dir, adapter, compiler): via_manifest = published(directory, consumer, dxc_dir, compiler, adapter, env) print(f'startup_compute_heap_token_dispatch: PASS on hardware (view stride {stride}): {checked} valid tokens read the texels ' f'or raw words of their own view with no miss; {len(MISSES)} tokens of another kind, an empty entry and a table ' - f'descriptor read the null view with {waves} misses (one per wave); opt-in off refused with "{OFF}", no counter; ' + f'descriptor read the null view with {waves} misses (one per wave); a heap without an alias is refused at the Dispatch as ' + f'"{NEED_VIEW_HEAP}"; releasing the view heap before the list runs keeps {released[1]} heap and {released[0]} resources with the recording; ' + f'opt-in off refused with "{OFF}", no counter; ' f'a published manifest and bytecode give {via_manifest}, and {len(MANIFEST_CONTROLS)} edits of its token lines are refused; ' f'debug layer: {"enabled, no error message" if layer and "0x00000000" in layer[0] else "unavailable"}') return 0 @@ -252,7 +291,7 @@ def published(directory, consumer, dxc_dir, compiler, adapter, base_env): else: got, result, stride, misses = run(directory, consumer, on, K.PROGRAMS['tex2d'], 3) reason = lines(result, 'Dispatch(3, 2, 2) refused: ') - assert got == UNTOUCHED and len(reason) == 1 and (reason[0].endswith(NEED_VIEW_HEAP) or reason[0].endswith(CAPABILITY)), ( + assert got == UNTOUCHED and len(reason) == 1 and (reason[0].endswith(PIPELINE_NO_WAVES) or reason[0].endswith(CAPABILITY)), ( reason, result.stderr[-3000:]) assert misses == NO_COUNTER wanted = f'refused as "{reason[0].split(": ")[-1]}"' diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index f96470bfef..45d30d54df 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -30,6 +30,7 @@ extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, extern "C" __declspec(dllimport) void x2w_d3d12_compute_census(); extern "C" __declspec(dllimport) UINT64 x2w_d3d12_snapshot_pool_used(); extern "C" __declspec(dllimport) UINT x2w_d3d12_heap_token_misses(); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_recording_retained(void* list, UINT* resources, UINT* heaps); // The ring of per-dispatch descriptor tables (startup_compute_dispatch_ring_check.py): set its cursor, read back what the // reservations since did. struct HeapTokenRingProbe { @@ -394,11 +395,20 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin descriptors[0][1] = static_cast(address >> 32) | fields[0][0] << 16; } const bool heap_short = mode == "dispatch-heap-waterfall-short"; - const struct { + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_waterfall ? (heap_short ? 3u : 5u) : mode == "dispatch-viewtok" ? 16u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (mode == "dispatch-viewtok" && std::getenv("X2W_TEST_VIEWTOK_SUPPLIED_HEAP")) { + // The title gives the view heap memory of its own: the runtime makes no GPU alias of it, so a heap token Dispatch of this + // list is refused by name at the Dispatch ("heap tokens need a GPU-visible view heap"). + const UINT64 supplied_stride = static_cast(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + void* const supplied = VirtualAlloc(nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (!supplied || !supplied_stride) return 73; + heap_desc.backing = reinterpret_cast(supplied); + heap_desc.bytes = supplied_stride * heap_desc.desc.NumDescriptors; + } void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; // dispatch-sampled-compute records the same calls on a compute list and queue. const D3D12_COMMAND_LIST_TYPE list_type = mode == "dispatch-sampled-compute" ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; @@ -1028,6 +1038,16 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin // An attempted read of the very placement whose UAV could not be made guest-visible. invoke(list, 15, word(placed[1]), 16, word(copied_token_output), 16, 16); } + if (mode == "dispatch-viewtok" && std::getenv("X2W_TEST_VIEWTOK_RELEASE_HEAP")) { + // The title releases its view heap after recording the Dispatch and before the list runs: the runtime frees the GPU + // alias of the heap's memory then, so the list must hold what it reads (the recording retains the alias and its heap). + UINT retained_resources = 0, retained_heaps = 0; + const BOOL have = x2w_d3d12_recording_retained(list, &retained_resources, &retained_heaps); + std::printf("recording retains: %u resources %u heaps (%s)\n", retained_resources, retained_heaps, have ? "recording found" : "no recording"); + invoke(heap, 2); + std::puts("title view heap released before the list runs"); + std::fflush(stdout); + } if (const int rc = submit(pixel || mode == "dispatch-viewtok" ? 2 : 1)) return rc; if (mode == "dispatch-viewtok") { // X2W_TEST_VIEWTOK_REPEAT=: two more lists of n Dispatches each, every list submitted and completed before the next @@ -1042,6 +1062,13 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin invoke(list, 35, 0, table_gpu); for (UINT i = 0; i < repeat; ++i) invoke(list, 14, 3, 2, 2); if (const int rc = submit(3 + round)) return rc; + if (round == 0) { + // The list that holds the 4096th heap token Dispatch (and its copy of the counter) has completed: the guest fence + // above is the wait. The counter is read here, on a queue of its own after that wait, so the check of the next + // list's log line does not depend on how far the GPU has come. + std::printf("heap token misses after the first round: %u\n", x2w_d3d12_heap_token_misses()); + std::fflush(stdout); + } } std::printf("heap token misses: %u\n", x2w_d3d12_heap_token_misses()); std::fflush(stdout); diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 30b223cfa4..ab8d7a9f84 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -452,10 +452,11 @@ def function_body(text: str, name: str) -> str: found |= literals(function_body(root_path.read_text(encoding="utf-8"), "compute_root_refusal")) # The heap token gate (heap_token_refusal gives its text to the manifest reader and the native route). gate = literals(function_body(gate_path.read_text(encoding="utf-8"), "heap_token_gate_text")) - if len(gate) != 4: - failures.append(f"heap_token_gate_text should carry 4 refusal texts, the scan found {len(gate)}") + if len(gate) != 3: + failures.append(f"heap_token_gate_text should carry 3 refusal texts, the scan found {len(gate)}") found |= gate - # The mirror's own refusals (the queue, the buffers and the kinds copy of a heap token dispatch). + # The mirror's own refusals (the queue and its entries, the buffers, the alias of the list's view heap and the kinds copy of a + # heap token dispatch). The alias refusal is decided here, per dispatch, not in the cached gate above. mirror_path = REPO_ROOT / "src" / "startup_stubs" / "heap_token_mirror.inl" if not mirror_path.exists(): failures.append("heap_token_mirror.inl not found") @@ -464,8 +465,8 @@ def function_body(text: str, name: str) -> str: mirror_reasons = set() for name in ("heap_mirror_flush", "heap_mirror_upload_dims", "heap_mirror_prepare"): mirror_reasons |= literals(function_body(mirror, name)) - if len(mirror_reasons) != 4: - failures.append(f"the heap token mirror should carry 4 refusal texts, the scan found {sorted(mirror_reasons)}") + if len(mirror_reasons) != 6 or "heap tokens need a GPU-visible view heap" not in mirror_reasons: + failures.append(f"the heap token mirror should carry 6 refusal texts (with the view heap alias), the scan found {sorted(mirror_reasons)}") found |= mirror_reasons missing = sorted(s for s in found if s not in triage_run.COMPUTE_DISPATCH_REASONS) if missing: diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index b56881c94e..b23d4a3703 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -256,8 +256,10 @@ 'the descriptor table is larger than the ring', 'the device does not take a directly indexed resource heap', 'the device does not take a directly indexed sampler heap', + 'the heap token alias could not be kept with the recording', 'the heap token buffers could not be created', 'the heap token kinds could not be uploaded', + 'the heap token mirror could not allocate its entries', 'the heap token queue could not be taken', 'the indirect argument buffer is also a bound shader resource', 'the list type has no Dispatch', From eb79f7fdd69c8b8fe70614c28acb1e696f960d77 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 11:09:35 +0100 Subject: [PATCH 18/19] d3d12 runtime: heap token mirror review fixes (dead wrapper, comments) A wrapper the retire drain dropped has a negative refs count; the mirror treated it as alive and queued its id again at every flush. Alive is now refs > 0. Test: a released and drained texture is counted once and not queued again. Comments state the reassignment limit honestly; a check message in heap_token_binding_check matches its expectation. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/d3d12_xs_device.cpp | 17 +++++++++- src/startup_stubs/heap_token_mirror.inl | 22 ++++++++----- tests/heap_token_binding_check.cpp | 2 +- tests/startup_compute_heap_token_check.py | 40 +++++++++++++++++++++++ 4 files changed, 70 insertions(+), 11 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index df5949033a..e1508334ba 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -7406,7 +7406,8 @@ x2w_startup::ComPtr retire_acquire_desktop(Wrapper* resource, bo x2w_startup::ComPtr held; if (!resource || resource->own().kind != resource_kind) return held; AcquireSRWLockExclusive(&retire_lock); - if (InterlockedCompareExchange(&resource->own().refs, 0, 0)) { + // Alive only while refs > 0: the drain sets a dropped wrapper to retired_refs (negative), and a zero is already dead. + if (InterlockedCompareExchange(&resource->own().refs, 0, 0) > 0) { if (auto* real = static_cast(resource->own().real)) { real->AddRef(); held.Attach(real); @@ -8017,6 +8018,20 @@ extern "C" __declspec(dllexport) ULONG x2w_d3d12_heap_mirror_refs(UINT id) ReleaseSRWLockExclusive(&draw_lock); return refs; } +// The ids the mirror flush could not resolve to a descriptor-bearing record or a live resource wrapper since the start +// (startup_compute_heap_token: a dead wrapper is counted once and not queued again). +extern "C" __declspec(dllexport) unsigned long long x2w_d3d12_heap_mirror_unresolved() +{ + AcquireSRWLockExclusive(&draw_lock); + const unsigned long long unresolved = heap_mirror().unresolved; + ReleaseSRWLockExclusive(&draw_lock); + return unresolved; +} +// Fixture only (startup_compute_heap_token): one pass of the retire drain, the one ExecuteCommandLists and Present run first. +extern "C" __declspec(dllexport) void x2w_d3d12_retire_drain() +{ + drain_retired_resources(); +} extern "C" __declspec(dllexport) ULONG x2w_d3d12_desktop_resource_refs(void* title_resource) { Wrapper* const wrapper = as_wrapper(title_resource); diff --git a/src/startup_stubs/heap_token_mirror.inl b/src/startup_stubs/heap_token_mirror.inl index 46039da363..67def81fc4 100644 --- a/src/startup_stubs/heap_token_mirror.inl +++ b/src/startup_stubs/heap_token_mirror.inl @@ -18,12 +18,15 @@ // The alias of the list's view heap (the token memory) is retained, with its heap, by the recording of every heap token // dispatch (retain_with_recording), so the title releasing its view heap cannot free it under a list that has not run yet. // -// Known limits until the release path exists (a later commit): a mirror entry is never released (the resource stays alive, the -// descriptor stays written, its kind stays); an id whose record was reassigned keeps its first entry and reads kind 0; +// Known limits until the fenced release path exists (a later commit): a mirror entry is never released (the resource stays +// alive, the descriptor stays written, its kind stays); an id whose record was reassigned keeps its first entry's descriptor and +// gets kind 0 in the shadow, but the kinds copy reaches the GPU only in the list that took the dirty span, so a list recorded +// after the reassignment and submitted before that list can still read the old kind and the old view of the id. By design a +// reassignment does not happen with heap tokens (content tokens are refused), the generation check is a guard only; // resources a list tracks in a write state are not transitioned for a token read (the title's barriers are the only states -// they get); the kinds copy is recorded in the list of the first dispatch that sees the change, so a list that is recorded -// but never submitted, or reset, loses it and the span is not copied again (its ids read kind 0, a counted miss, never a -// wrong view). An id whose resource wrapper is alive but has no desktop object yet is queued again at the next flush. +// they get); a list that is recorded but never submitted, or reset, loses the kinds copy and the span is not copied again +// (its ids keep reading kind 0, a counted miss). An id whose resource wrapper is alive (refs > 0) but has no desktop object +// yet is queued again at the next flush; a dead wrapper is not. // Every member of the mirror: draw_lock held. struct HeapMirrorEntry { @@ -172,7 +175,7 @@ const char* heap_mirror_flush(HeapMirror& m) continue; } HeapMirrorEntry& entry = m.entries[id]; // sized to the capacity above - if (entry.written) { // the id holds another record now: entries are not released yet, so it keeps the first one + if (entry.written) { // the id holds another record now: entries are not released yet, so it keeps the first descriptor (see the limits above) if (entry.generation != taken[i].generation) { ++m.reassigned; m.kinds.set(id, 0); @@ -185,7 +188,8 @@ const char* heap_mirror_flush(HeapMirror& m) continue; } // The mirror's own reference, taken before anything uses the resource, in one step with the check that the wrapper - // is alive. A wrapper that is alive without a desktop object (yet) is tried again at the next flush; a dead one is not. + // is alive (refs > 0). A wrapper that is alive without a desktop object (yet) is tried again at the next flush; a dead + // one (refs zero or the drain's negative retired_refs) is not. Wrapper* const wrapper = as_wrapper(reinterpret_cast(record.resource)); bool no_desktop_yet = false; x2w_startup::ComPtr held = retire_acquire_desktop(wrapper, no_desktop_yet); @@ -228,8 +232,8 @@ const char* heap_mirror_flush(HeapMirror& m) } // Records the copy of the kinds table's changed span into the list. The kinds buffer is in COMMON between lists (the list -// that uses it returns it at Close, like every tracked resource), so one list's copy is ordered before this list's reads by -// the single direct queue they run on. +// that uses it returns it at Close, like every tracked resource). The copy is ordered before the reads of lists submitted +// after the list that carries it; a list recorded later but submitted earlier does not see it (the limit above). const char* heap_mirror_upload_dims(Wrapper* self, ID3D12GraphicsCommandList* list, HeapMirror& m) { UINT first = 0, count = 0; diff --git a/tests/heap_token_binding_check.cpp b/tests/heap_token_binding_check.cpp index 9921910be9..d54d8f0967 100644 --- a/tests/heap_token_binding_check.cpp +++ b/tests/heap_token_binding_check.cpp @@ -99,7 +99,7 @@ void ring() } { volatile LONG cursor = 0; - expect(heap_token_ring_reserve(&cursor, ring_size, ring_size) == 0, "a reservation of exactly the whole ring is not accepted at slot 0"); + expect(heap_token_ring_reserve(&cursor, ring_size, ring_size) == 0, "a reservation of exactly the whole ring is refused or does not start at slot 0"); } } diff --git a/tests/startup_compute_heap_token_check.py b/tests/startup_compute_heap_token_check.py index e7d85018a2..12542c95c4 100644 --- a/tests/startup_compute_heap_token_check.py +++ b/tests/startup_compute_heap_token_check.py @@ -444,6 +444,44 @@ def release_heap(heap): print('child %s: %s' % (switch, 'PASS' if not fails.count else '%d failures' % fails.count), flush=True) return 1 if fails.count else 0 + # 8. A dead wrapper is not queued again (retire_acquire_desktop: alive only while refs > 0). A view id is noted for a + # texture of the retire class, the texture is released and the retire drain drops it (X2W_D3D12_RELEASE_RETIRED=1, + # drained (x2w_d3d12_retire_drain) once the release-time fence of the guest queue passed; its descriptor is overwritten first so no + # tracked view keeps it). The drain sets the wrapper's refs to a negative value: the flush must count the id once as + # unresolved and leave the queue empty. With the old test (refs != 0) the id is queued again at every flush. + # WARP reaches this path (no dispatch needed); the dispatch-time queue behaviour is the same flush. + xs.x2w_d3d12_heap_mirror_unresolved.restype = ctypes.c_ulonglong + guest_queue = ctypes.c_void_p() + queue_desc = (ctypes.c_uint * 4)(0, 0, 0, 0) # D3D12_COMMAND_QUEUE_DESC: DIRECT, normal priority, no flags, node 0 + fails.expect(vcall(device, 8, ctypes.c_long, [ctypes.c_void_p] * 3, ctypes.byref(queue_desc), + ctypes.byref(guid('0ec870a6-5d7e-4c22-8cfc-5baae07616ed')), ctypes.byref(guest_queue)) >= 0, + 'CreateCommandQueue') + dying = committed(3, 16, 16, 28, 0) + fails.expect(queue() == 0, 'ids are still queued before the dying view (%d)' % queue()) + fails.expect(xs.x2w_d3d12_create_srv(device, handle(7), dying, texture_view) == 1, 'create_srv dying texture') + dying_id = struct.unpack('<8I', ctypes.string_at(handle(7), 32))[1] + fails.expect(queue() == 1, 'the dying view queued %d ids, expected 1' % queue()) + # Overwrite the descriptor (an existing record, already mirrored): the tracked view no longer names the texture. + fails.expect(xs.x2w_d3d12_create_srv(device, handle(7), buffer, buffer_view) == 1, 'create_srv overwrite') + fails.expect(queue() == 1, 'the overwrite changed the queue to %d ids' % queue()) + vcall(dying, 2, ctypes.c_ulong, []) # the title's last Release: the retire class queues it behind the fence + dropped = False + for _ in range(400): + xs.x2w_d3d12_retire_drain() # the drain ExecuteCommandLists and Present run first + if xs.x2w_d3d12_desktop_resource_refs(dying) == 0: + dropped = True + break + kernel.Sleep(5) + if fails.expect(dropped, 'the retire drain never dropped the released texture'): + unresolved_before = xs.x2w_d3d12_heap_mirror_unresolved() + for flush_number in (1, 2, 3): + xs.x2w_d3d12_heap_mirror_flush() + fails.expect(queue() == 0, 'flush %d: a dead wrapper stays queued (%d ids)' % (flush_number, queue())) + grown = xs.x2w_d3d12_heap_mirror_unresolved() - unresolved_before + fails.expect(grown == 1, 'the dead wrapper was counted unresolved %d times in 3 flushes, expected once' % grown) + fails.expect(xs.x2w_d3d12_heap_mirror_kind(dying_id) == 0, 'a dead wrapper got a kind') + fails.expect(xs.x2w_d3d12_heap_mirror_refs(dying_id) == 0, 'a dead wrapper got a mirror reference') + # The production open, driven directly (any descriptor stride): memory the test owns, so it can be opened again. before = alias(0).count mem = kernel.VirtualAlloc(None, 0x2000, 0x3000, 0x04) @@ -509,6 +547,8 @@ def main(): env = dict(os.environ, **BUDGET_ENV, X2W_TRAP_LOG=str(Path(scratch) / ('trap_' + switch + '.log'))) env.pop('X2W_D3D12_VIEW_CONTENT_TOKENS', None) env['X2W_D3D12_HEAP_TOKENS'] = '1' if switch == 'on' else '0' + if switch == 'on': + env['X2W_D3D12_RELEASE_RETIRED'] = '1' # section 8: the retire drain drops a released texture result = subprocess.run([sys.executable, '-I', '-B', os.path.abspath(__file__), '--child', dll, switch], env=env, capture_output=True, text=True, timeout=120) sys.stdout.write(result.stdout) From 4bc3d4ad241c4b6971b4b795f1646538b680da1d Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 1 Dec 2026 12:29:22 +0100 Subject: [PATCH 19/19] ci: build native_heap_token_texture in the pr preset The pr test filter runs native_.*_controls, so native_heap_token_texture_controls was selected without its executable and reported Not Run. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- CMakePresets.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..48eebdea33 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -36,7 +36,8 @@ "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", - "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" + "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check", + "native_heap_token_texture" ] }, { "name": "release", "configurePreset": "release" },