upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:09:38 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:09:38 -0500
commit5115f0887940595aa0f46fed7fc9db28b64151ff (patch)
tree98b4df97d3b97af290331ea9893587e250c0fac0 /runtime/src
parentc8f7515e2e6fb2a2a61eb1e986ee8c6fd4431399 (diff)
parentb07b9ecb09b47fa6496f01ad9d8fe87d205bd5d8 (diff)
Merge main into RT-DIRECT-HEAP-COMPUTE (#1064)
main already supplies the directly indexed heaps to compute dispatches (integration #984, the tree this pull request was split from): with_direct_heaps()/compute_user_data() on Dispatch and the ExecuteIndirect dispatch path, RootArgumentLayout::compute_arguments_end (kNoSgpr for a spilled signature), LEONIDA_COMPUTE_DIRECT_HEAPS=0, and the first form of this test (direct dispatch, indirect after a resource-only rebind, the GPU read through the heap). That form stays. What this pull request adds beyond it is carried onto it: the review-round reports, the extra recorded-argument checks, the census tool and its evidence. Conflicts: - runtime/shims/d3d12_com.cpp: main's with_direct_heaps()/compute_user_data() and its one-argument note_direct_heap_indexing(). Carried: compute_user_data() makes the note itself, so an ExecuteIndirect dispatch with no heap bound is reported too (record_dispatch's own call removed), and a heap with no inline dword left is reported once per heap kind ("compute root arguments leave no inline SGPR for the resource/sampler heap"); a spilled signature (main: kNoSgpr) gets one note of its own. Dropped: the PR's GetEnvironmentVariableA switch (main's direct_heaps_enabled) and its "graphics heap-base SGPR is not supplied" notes (main supplies the graphics heaps). - runtime/shims/d3d12_com.h, runtime/shims/d3d12_vulkan_device.cpp: main's (compute_arguments_end and graphics_arguments_end with their comment; compute_arguments_end only when the compute arguments do not spill). - runtime/test/glsl/cs_user_data.comp: main's; its direct-indexing mode (s5 = 0xFFFFFFFC, heap at s9) is this pull request's, byte for byte. - runtime/test/d3d12_compute_test.cpp: the PR's block replaces main's earlier form of it (a superset: adds the bundle dispatch that inherits the parent's heaps, an indirect dispatch with only the sampler heap, signatures ending at s30 and s31, and the LEONIDA_COMPUTE_DIRECT_HEAPS=0 expectations). - docs/d3d12_vulkan.md: main's section 3.4 (the BatchCull s7 and PreSkin s9 evidence), with the PR's census paragraph (tools/compute_heap_layout_census.py, the seven paired layouts, the heap order as a hypothesis) and the no-room and spill reports. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/active_input.h17
-rw-r--r--runtime/src/arena_size.h5
-rw-r--r--runtime/src/bcpack.cpp423
-rw-r--r--runtime/src/bcpack.h33
-rw-r--r--runtime/src/bcpack_stream.h222
-rw-r--r--runtime/src/buffer_va_index.h6
-rw-r--r--runtime/src/clzero_patch.h200
-rw-r--r--runtime/src/command_list.h17
-rw-r--r--runtime/src/console_texture_layout.h611
-rw-r--r--runtime/src/d3d12_xs_frame_events.h47
-rw-r--r--runtime/src/deferred_image_binding.h31
-rw-r--r--runtime/src/depth24_fragment.h18
-rw-r--r--runtime/src/descriptor_table.h69
-rw-r--r--runtime/src/dstorage_swizzle.h29
-rw-r--r--runtime/src/dstorage_trace.h12
-rw-r--r--runtime/src/frame_pacer.h49
-rw-r--r--runtime/src/fsdraw_probe.h236
-rw-r--r--runtime/src/gfx10_descriptors.h32
-rw-r--r--runtime/src/gpu_label_memory.h94
-rw-r--r--runtime/src/image_memory.h231
-rw-r--r--runtime/src/local_diagnostics.h29
-rw-r--r--runtime/src/main.cpp215
-rw-r--r--runtime/src/mem_probe.h570
-rw-r--r--runtime/src/native_pso.h342
-rw-r--r--runtime/src/pe_loader.cpp477
-rw-r--r--runtime/src/pe_loader.h14
-rw-r--r--runtime/src/pipeline_cache_file.h68
-rw-r--r--runtime/src/pipeline_cache_store.h69
-rw-r--r--runtime/src/pipeline_profile.h70
-rw-r--r--runtime/src/present_dump.h256
-rw-r--r--runtime/src/quad_index_expand.comp44
-rw-r--r--runtime/src/quad_index_expand.h182
-rw-r--r--runtime/src/quad_index_expand_spv.h148
-rw-r--r--runtime/src/queue_families.h23
-rw-r--r--runtime/src/rect_list_geometry.h263
-rw-r--r--runtime/src/rgba4_fragment.h81
-rw-r--r--runtime/src/root_signature.cpp27
-rw-r--r--runtime/src/root_signature.h29
-rw-r--r--runtime/src/shader_directory.h56
-rw-r--r--runtime/src/shader_library.h208
-rw-r--r--runtime/src/subgroup_size.h8
-rw-r--r--runtime/src/thread_stacks.cpp237
-rw-r--r--runtime/src/thread_stacks.h38
-rw-r--r--runtime/src/title_geometry_watch.h123
-rw-r--r--runtime/src/title_page_watch.h700
-rw-r--r--runtime/src/title_texture_memory.h58
-rw-r--r--runtime/src/title_texture_refresh.h45
-rw-r--r--runtime/src/title_va_alias.h318
-rw-r--r--runtime/src/tls_host.cpp13
-rw-r--r--runtime/src/vulkan13_features.h6
-rw-r--r--runtime/src/vulkan_backend.h502
-rw-r--r--runtime/src/vulkan_bindless.h396
-rw-r--r--runtime/src/vulkan_depth24.h14
-rw-r--r--runtime/src/vulkan_device_fault.h429
-rw-r--r--runtime/src/vulkan_gpu_labels.h299
-rw-r--r--runtime/src/vulkan_graphics_shader_modules.h65
-rw-r--r--runtime/src/vulkan_memory.h6
-rw-r--r--runtime/src/vulkan_present.h438
-rw-r--r--runtime/src/vulkan_present_splash.h63
-rw-r--r--runtime/src/vulkan_replay.h929
-rw-r--r--runtime/src/vulkan_scratch.h24
-rw-r--r--runtime/src/vulkan_title_image_pool.h113
62 files changed, 9890 insertions, 487 deletions
diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h
index c0f7451b1..55b67d3bb 100644
--- a/runtime/src/active_input.h
+++ b/runtime/src/active_input.h
@@ -95,7 +95,8 @@ public:
95 const InputEdge edge = edge_between(it->second, now); 95 const InputEdge edge = edge_between(it->second, now);
96 it->second = now; 96 it->second = now;
97 if (edge == InputEdge::None || family == tracked_) return InputEdge::None; 97 if (edge == InputEdge::None || family == tracked_) return InputEdge::None;
98 if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None; 98 if (changed_once_ && (time_us < changed_at_ || time_us - changed_at_ < thresholds_.min_switch_us))
99 return InputEdge::None;
99 const InputFamily before = active(); 100 const InputFamily before = active();
100 tracked_ = family; 101 tracked_ = family;
101 changed_at_ = time_us; 102 changed_at_ = time_us;
@@ -125,11 +126,17 @@ private:
125 InputEdge edge_between(const InputSample& was, const InputSample& now) const { 126 InputEdge edge_between(const InputSample& was, const InputSample& now) const {
126 if (now.buttons & ~was.buttons) return InputEdge::Button; 127 if (now.buttons & ~was.buttons) return InputEdge::Button;
127 const float t = thresholds_.trigger; 128 const float t = thresholds_.trigger;
128 if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t)) 129 const auto trigger_rose = [t](float prev, float cur) {
130 return std::isfinite(prev) && std::isfinite(cur) && prev <= t && cur > t;
131 };
132 if (trigger_rose(was.left_trigger, now.left_trigger) || trigger_rose(was.right_trigger, now.right_trigger))
129 return InputEdge::Trigger; 133 return InputEdge::Trigger;
130 const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; }; 134 const auto stick_left = [this](float px, float py, float cx, float cy) {
131 if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) || 135 if (!std::isfinite(px) || !std::isfinite(py) || !std::isfinite(cx) || !std::isfinite(cy)) return false;
132 (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y))) 136 return std::hypot(px, py) <= thresholds_.stick && std::hypot(cx, cy) > thresholds_.stick;
137 };
138 if (stick_left(was.left_x, was.left_y, now.left_x, now.left_y) ||
139 stick_left(was.right_x, was.right_y, now.right_x, now.right_y))
133 return InputEdge::Stick; 140 return InputEdge::Stick;
134 return InputEdge::None; 141 return InputEdge::None;
135 } 142 }
diff --git a/runtime/src/arena_size.h b/runtime/src/arena_size.h
index 8f4ca4caf..196b03e3e 100644
--- a/runtime/src/arena_size.h
+++ b/runtime/src/arena_size.h
@@ -60,7 +60,10 @@ struct ArenaSize {
60// invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). 60// invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB).
61inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { 61inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) {
62 VkDeviceSize megabytes = kArenaDefaultMiB; 62 VkDeviceSize megabytes = kArenaDefaultMiB;
63 if (env && *env) megabytes = std::clamp<VkDeviceSize>(std::strtoull(env, nullptr, 10), kArenaMinMiB, kArenaMaxMiB); 63 // Signed, so "-5" clamps to the floor (strtoull wraps it to a huge value, which clamps to the maximum).
64 if (env && *env)
65 megabytes = VkDeviceSize(std::clamp<long long>(std::strtoll(env, nullptr, 10), (long long)kArenaMinMiB,
66 (long long)kArenaMaxMiB));
64 ArenaSize size; 67 ArenaSize size;
65 size.requested = size.bytes = megabytes * kArenaMiB; 68 size.requested = size.bytes = megabytes * kArenaMiB;
66 VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; 69 VkDeviceSize by_buffer = size.requested, by_allocation = size.requested;
diff --git a/runtime/src/bcpack.cpp b/runtime/src/bcpack.cpp
new file mode 100644
index 000000000..bb4646787
--- /dev/null
+++ b/runtime/src/bcpack.cpp
@@ -0,0 +1,423 @@
1// C++ port of tools/bcpack.py. The build derives the model and BCn format
2// constants from that same reference.
3#include "bcpack.h"
4#include "bcpack_stream.h"
5#include <algorithm>
6#include <array>
7#include <bit>
8#include <cstring>
9
10namespace leonida::bcpack {
11namespace {
12using namespace detail;
13
14void color(uint8_t *dst, const int *e, int a, int b, int c, int d) {
15 for (int i = 0; i < 2; ++i, e += 3) {
16 const int rgb = (e[0] << 11) | (e[1] << 5) | e[2];
17 dst[i * 2] = uint8_t(rgb);
18 dst[i * 2 + 1] = uint8_t(rgb >> 8);
19 }
20 dst[4] = uint8_t((a & 15) | (b << 4));
21 dst[5] = uint8_t((a >> 4) | (b & 240));
22 dst[6] = uint8_t((c & 15) | (d << 4));
23 dst[7] = uint8_t((c >> 4) | (d & 240));
24}
25
26struct Endpoints {
27 int v[8]{};
28};
29
30bool rebuild_classic(unsigned codec, size_t i, const Symbols &a,
31 const Symbols &b, array<Endpoints, 256> &past,
32 uint8_t *dst, bool allow_fitted, Quality &quality) {
33 const bool single = codec == 1 || codec == 4;
34 if (a[1] || b[1])
35 return false;
36 const unsigned distance = unzig(single ? a[0] : interleave(a[0], b[0])) & 255;
37 Endpoints e;
38 const int count = codec == 1 ? 6 : codec == 3 ? 8 : codec == 4 ? 2 : 4;
39 if (!distance) {
40 if (codec != 1)
41 fill_n(e.v, codec == 5 ? 4 : 2, 128);
42 } else if (distance <= i) {
43 e = past[(i - distance) & 255];
44 } else {
45 const unsigned slot = (i - distance) & 255;
46 const Seed &seed = codec == 1 ? history1[slot]
47 : codec == 3 ? history3[slot]
48 : codec == 4 ? history4[slot]
49 : history5[slot];
50 if (seed.values[0] < 0 || (seed.fitted && !allow_fitted))
51 return false;
52 if (seed.fitted)
53 quality = Quality::fitted;
54 copy_n(seed.values, count, e.v);
55 }
56 const int alpha = codec == 1 ? 0 : codec == 5 ? 4 : 2;
57 for (int k = 0; k < count; ++k) {
58 const int coord = k - alpha;
59 const int mask = coord < 0 ? 255 : coord % 3 == 1 ? 63 : 31;
60 const int symbol = single ? a[2 + k]
61 : coord < 0 ? (k % 2 ? b : a)[2 + k / 2]
62 : (coord < 3 ? a : b)[7 + coord % 3];
63 e.v[k] = (e.v[k] + unzig(symbol)) & mask;
64 }
65 past[i & 255] = e;
66 for (int ch = 0; ch < alpha / 2; ++ch) {
67 const auto *pairs = codec == 3 ? pair3 : codec == 4 ? pair4 : pair5;
68 uint64_t bits = 0;
69 for (int row = 0; row < 4; ++row) {
70 const int lane =
71 codec == 4 ? 4 + 2 * row : (codec == 3 ? 3 : 4 + 4 * ch) + row;
72 const int right = single ? a[lane + 1] : b[lane];
73 bits |= uint64_t(pairs[a[lane]] | (pairs[right] << 6)) << (12 * row);
74 }
75 *dst++ = uint8_t(e.v[ch * 2]);
76 *dst++ = uint8_t(e.v[ch * 2 + 1]);
77 for (int j = 0; j < 6; ++j)
78 *dst++ = uint8_t(bits >> (8 * j));
79 }
80 if (codec == 1)
81 color(dst, e.v, quad1[a[8]], quad1[a[9]], quad1[a[10]], quad1[a[11]]);
82 if (codec == 3)
83 color(dst, e.v + 2, quad3[a[10]], quad3[b[10]], quad3[a[11]], quad3[b[11]]);
84 return true;
85}
86
87struct BitWriter {
88 uint8_t *dst;
89 int pos{}, violations{};
90 void put(int value, int bits) {
91 while (bits > 0) {
92 const int n = min(bits, 8 - pos % 8);
93 dst[pos / 8] |= uint8_t((value & ((1 << n) - 1)) << (pos % 8));
94 value >>= n;
95 bits -= n;
96 pos += n;
97 }
98 }
99};
100
101// Endpoints and indices have independent predictors, with distances limited to
102// eight bits.
103struct BptcState {
104 array<int, 24> ep{};
105 array<int, 32> ix{};
106 int ep_root = -1, ix_root = -1;
107};
108int mod_bits(int v, int n) { return v & ((1 << n) - 1); }
109
110void index_row(int a, int b, int row, int bits, const int *ref, int *value,
111 int *history) {
112 for (int x = 0; x < 4; ++x) {
113 const int s = (x < 2 ? a : b) >> ((x % 2) ^ (row < 3));
114 const int delta =
115 (s & 1) | ((s >> 1) & 2) | ((s >> 2) & 4) | ((s >> 3) & 8);
116 const int p = 4 * row + x;
117 value[p] = mod_bits((ref[p] >> (4 - bits)) + unzig(delta), bits);
118 history[p] = value[p] << (4 - bits);
119 }
120}
121
122bool put_indices(BitWriter &writer, const int *values, int bits,
123 int anchor1 = -1, int anchor2 = -1) {
124 for (int p = 0; p < 16; ++p) {
125 const int n = bits - (p == 0 || p == anchor1 || p == anchor2);
126 if (values[p] >> n)
127 ++writer.violations;
128 writer.put(values[p], n);
129 }
130 return true;
131}
132
133bool bc6(const Symbols &a, const Symbols &b, const BptcState &ep,
134 const BptcState &ix, BptcState &next, BitWriter &writer) {
135 if (a[15] >= 14)
136 return false;
137 const auto &m = bc6Modes[a[15]];
138 const int partition = min<int>(b[15], 31), base_shift = 16 - m.base;
139 int fields[3][4]{};
140 for (int c = 0; c < 3; ++c) {
141 const int n = m.delta[c], shift = max(0, 6 - n);
142 const auto *ref = &ep.ep[c * 4];
143 const int w = mod_bits((ref[0] >> base_shift) +
144 unzig(interleave(a[2 + c], b[2 + c], 8)),
145 m.base);
146 const int x = mod_bits(
147 (ref[1] >> (10 - n)) + unzig(interleave(a[5 + c], b[5 + c], 5)), n);
148 const int y = mod_bits((ref[2] >> shift) + unzig(a[8 + c]), n);
149 const int z = mod_bits((ref[3] >> shift) + unzig(b[8 + c]), n);
150 auto *state = &next.ep[c * 4];
151 state[0] = w << base_shift;
152 state[1] = x << (10 - n);
153 if (m.regions == 2) {
154 state[2] = y << shift;
155 state[3] = z << shift;
156 } else {
157 const int v = mod_bits(w, n) ^ (m.transformed << (n - 1));
158 state[2] = n >= 6 ? v >> (n - 6) : v << shift;
159 state[3] = state[1] >> 4;
160 }
161 fields[c][0] = w;
162 if (a[15] >= 12) {
163 fields[c][0] &= 1023;
164 for (int bit = 10; bit < m.base; ++bit)
165 fields[c][0] |= ((w >> bit) & 1) << (m.base + 9 - bit);
166 }
167 fields[c][1] = x;
168 fields[c][2] = y;
169 fields[c][3] = z;
170 }
171 writer.put(m.code, m.code < 2 ? 2 : 5);
172 for (int j = 0; j < m.count; ++j) {
173 const auto &f = bc6Plan[m.first + j];
174 writer.put((f[0] < 0 ? partition : fields[f[0]][f[1]]) >> f[2], 1);
175 }
176 int values[16];
177 const int bits = m.regions == 2 ? 3 : 4;
178 for (int y = 0; y < 4; ++y)
179 index_row(a[11 + y], b[11 + y], y, bits, ix.ix.data(), values,
180 next.ix.data());
181 return put_indices(writer, values, bits,
182 m.regions == 2 ? anchor2[partition] : -1);
183}
184
185bool bc7(const Symbols &a, const Symbols &b, const BptcState &ep,
186 const BptcState &ix, BptcState &next, BitWriter &writer) {
187 if (a[15] >= 32 || b[15] >= 16)
188 return false;
189 const auto &cfg = bc7Config[a[15] * 16 + b[15]];
190 const auto [tag, part, rot, isel] = cfg;
191 const int mode = tag & 127;
192 if (mode > 7 || part >= 64)
193 return false;
194 const auto &f = bc7_formats[mode];
195 int widths[4] = {f.color, f.color, f.color, f.alpha};
196 if (rot)
197 swap(widths[rot - 1], widths[3]);
198 constexpr int lane[3][4] = {{2, 3, 4, 5}, {6, 7, 8, 9}, {10, 5, 9, -1}};
199 int v[3][2][4]{};
200 for (int sub = 0; sub < f.subsets; ++sub) {
201 for (int end = 0; end < 2; ++end) {
202 for (int c = 0; c < 4; ++c) {
203 if (!widths[c] || lane[sub][c] < 0)
204 continue;
205 const int n = widths[c] + (f.pbits && c == 0);
206 const int k = 8 * sub + 4 * end + c;
207 v[sub][end][c] = mod_bits(
208 (ep.ep[k] >> (8 - n)) + unzig((end ? b : a)[lane[sub][c]]), n);
209 next.ep[k] = v[sub][end][c] << (8 - n);
210 }
211 }
212 if (f.pbits == 2 && ((v[sub][0][0] ^ v[sub][1][0]) & 1))
213 ++writer.violations;
214 }
215 for (int sub = f.subsets; sub < 3; ++sub)
216 copy_n(next.ep.begin(), 8, next.ep.begin() + 8 * sub);
217 int primary[16], secondary[16];
218 constexpr int second_rows[] = {6, 7, 8, 10};
219 const bool two = mode == 4 || mode == 5;
220 for (int y = 0; y < 4; ++y) {
221 index_row(a[11 + y], b[11 + y], y, f.index, ix.ix.data(), primary,
222 next.ix.data());
223 if (two)
224 index_row(a[second_rows[y]], b[second_rows[y]], y, 2, ix.ix.data() + 16,
225 secondary, next.ix.data() + 16);
226 }
227 if (mode == 0 && part == 0 &&
228 ranges::all_of(next.ep, [](int v) { return !v; }) &&
229 ranges::all_of(primary, [](int v) { return !v; }))
230 return true;
231
232 writer.put(1 << mode, mode + 1);
233 writer.put(part, f.partition);
234 if (two)
235 writer.put(rot, 2);
236 if (mode == 4)
237 writer.put(isel, 1);
238 for (int c = 0; c < 4; ++c) {
239 const int src = rot && c == rot - 1 ? 3 : rot && c == 3 ? rot - 1 : c;
240 for (int sub = 0; sub < f.subsets; ++sub)
241 for (int end = 0; end < 2; ++end)
242 writer.put(v[sub][end][src] >> (f.pbits && src == 0),
243 c == 3 ? f.alpha : f.color);
244 }
245 if (f.pbits) {
246 for (int sub = 0; sub < f.subsets; ++sub)
247 for (int end = 0; end < (f.pbits == 1 ? 2 : 1); ++end)
248 writer.put(v[sub][end][0], 1);
249 }
250 const int anc1 = f.subsets == 2 ? anchor2[part]
251 : f.subsets == 3 ? anchor3a[part]
252 : -1;
253 const int anc2 = f.subsets == 3 ? anchor3b[part] : -1;
254 if (mode == 4)
255 return put_indices(writer, secondary, 2) &&
256 put_indices(writer, primary, f.index);
257 return put_indices(writer, primary, f.index, anc1, anc2) &&
258 (!two || put_indices(writer, secondary, 2));
259}
260
261// A predictor can influence later blocks through either independent reference
262// chain. A bit-depth gap discovered during the first 256 blocks also affects
263// earlier uses of the slot.
264struct Coverage {
265 array<bool, 256> missing_ep{}, missing_ix{};
266 size_t lost{}, inconsistent{}, limit{};
267 bool lost_endpoints{}, lost_indices{};
268 void note_missing(const BptcState &block) {
269 const bool ep = block.ep_root >= 0 && missing_ep[block.ep_root];
270 const bool ix = block.ix_root >= 0 && missing_ix[block.ix_root];
271 lost += ep || ix;
272 lost_endpoints |= ep;
273 lost_indices |= ix;
274 }
275};
276
277bool rebuild_bptc(unsigned codec, size_t i, size_t blocks, const Symbols &a,
278 const Symbols &b, array<BptcState, 256> &past, uint8_t *dest,
279 const Calibration *history, bool allow_fitted,
280 Quality &quality, Coverage &coverage, const char*& reason) {
281 const unsigned di = interleave(a[1], b[1]);
282 const unsigned de = (di + unzig(interleave(a[0], b[0]))) & 255;
283 if ((di > i || de > i) && !history) {
284 reason = "missing-profile";
285 return false;
286 }
287 const int islot = di > i ? int(256 + i - di) : -1;
288 const int eslot = de > i ? int(256 + i - de) : -1;
289 bool fitted = false;
290 BptcState zero{};
291 if (codec == 6) {
292 for (int c = 0; c < 3; ++c) {
293 zero.ep[4 * c] = 32768;
294 zero.ep[4 * c + 1] = 512;
295 zero.ep[4 * c + 2] = zero.ep[4 * c + 3] = 32;
296 }
297 zero.ix.fill(8);
298 }
299 if (codec == 6) {
300 if (a[15] >= 14)
301 return false;
302 const auto &m = bc6Modes[a[15]];
303 if (eslot >= 0) {
304 const auto &row = history->bc6[eslot];
305 for (int c = 0; c < 3; ++c) {
306 const int needs[] = {m.base, m.delta[c],
307 m.regions == 2 ? m.delta[c] : 0,
308 m.regions == 2 ? m.delta[c] : 0};
309 for (int k = 0; k < 4; ++k) {
310 const int j = 4 * c + k;
311 zero.ep[j] = row.ep[2 * j] | (row.ep[2 * j + 1] << 8);
312 fitted |= row.ep_confirmed[j] < needs[k];
313 }
314 }
315 fitted |= row.ep_class != 3;
316 coverage.missing_ep[eslot] |= !row.ep_class;
317 }
318 if (islot >= 0) {
319 const auto &row = history->bc6[islot];
320 copy(row.ix.begin(), row.ix.end(), zero.ix.begin());
321 fitted |=
322 row.ix_class != 3 || ranges::any_of(row.ix_confirmed, [&](int n) {
323 return n < (m.regions == 2 ? 3 : 4);
324 });
325 coverage.missing_ix[islot] |= !row.ix_class;
326 }
327 } else {
328 if (a[15] >= 32 || b[15] >= 16)
329 return false;
330 const auto &cfg = bc7Config[a[15] * 16 + b[15]];
331 const unsigned mode = cfg[0] & 127;
332 if (mode >= 8 || cfg[1] >= 64)
333 return false;
334 if (cfg[0] & 128)
335 fitted = true;
336 const auto &format = bc7_formats[mode];
337 if (eslot >= 0) {
338 const auto &row = history->bc7[eslot];
339 copy(row.ep.begin(), row.ep.end(), zero.ep.begin());
340 int width[] = {format.color, format.color, format.color, format.alpha};
341 if (cfg[2])
342 swap(width[3], width[cfg[2] - 1]);
343 width[0] += format.pbits != 0;
344 for (int j = 0; j < 8 * format.subsets; ++j) {
345 const int need = width[j % 4];
346 fitted |= row.ep_confirmed[j] < need || row.ep_bits[j] < need;
347 coverage.missing_ep[eslot] |= row.ep_bits[j] < min(need, 4);
348 }
349 }
350 if (islot >= 0) {
351 const auto &row = history->bc7[islot];
352 copy(row.ix.begin(), row.ix.end(), zero.ix.begin());
353 for (int j = 0; j < (mode == 4 || mode == 5 ? 32 : 16); ++j) {
354 int need = j < 16 ? format.index : 2;
355 fitted |= row.ix_confirmed[j] < need || row.ix_bits[j] < need;
356 coverage.missing_ix[islot] |= row.ix_bits[j] < need;
357 }
358 }
359 }
360 if (fitted) {
361 if (!allow_fitted) {
362 reason = "unconfirmed-predictor";
363 return false;
364 }
365 quality = Quality::fitted;
366 }
367 const auto &ep = de && eslot < 0 ? past[(i - de) & 255] : zero;
368 const auto &ix = di && islot < 0 ? past[(i - di) & 255] : zero;
369 auto &next = past[i & 255];
370 next = {};
371 next.ep_root = eslot >= 0 ? eslot : ep.ep_root;
372 next.ix_root = islot >= 0 ? islot : ix.ix_root;
373 fill_n(dest, 16, 0);
374 BitWriter writer{dest};
375 const bool valid = codec == 6 ? bc6(a, b, ep, ix, next, writer)
376 : bc7(a, b, ep, ix, next, writer);
377 coverage.inconsistent +=
378 codec == 6 ? writer.violations : int(writer.violations != 0);
379 if (i + 1 == min<size_t>(256, blocks)) {
380 for (size_t k = 0; k <= i; ++k)
381 coverage.note_missing(past[k]);
382 } else if (i >= 256)
383 coverage.note_missing(next);
384 if (!valid) return false;
385 if (coverage.lost > coverage.limit) {
386 reason = coverage.lost_endpoints && coverage.lost_indices ? "missing-endpoint-and-index" :
387 coverage.lost_endpoints ? "missing-endpoint" : "missing-index";
388 return false;
389 }
390 if (coverage.inconsistent > coverage.limit) { reason = "anchor-or-pbit"; return false; }
391 return true;
392}
393} // namespace
394
395Quality decode(unsigned codec, std::span<const uint8_t> source,
396 std::span<uint8_t> output, bool allow_fitted,
397 const Calibration *history, const char** failure, bool fast_entropy) {
398 const char* reason = "bcpack-stream";
399 if (failure) *failure = reason;
400 Quality quality = Quality::confirmed;
401 if (!codec || codec == 2 || codec > 7)
402 return Quality::failed;
403 const bool single = codec == 1 || codec == 4;
404 const unsigned block_size = single ? 8 : 16;
405 if (output.size() % block_size)
406 return Quality::failed;
407 array<Endpoints, 256> classic{};
408 array<BptcState, 256> bptc{};
409 Coverage coverage{};
410 coverage.limit = allow_fitted && history
411 ? max<size_t>(2, output.size() / block_size / 1024)
412 : 0;
413 const bool valid = visit_blocks(codec, source, output.size(), [&](size_t i, const Symbols &first, const Symbols &tuple) {
414 auto *dst = output.data() + i * block_size;
415 if (codec >= 6)
416 return rebuild_bptc(codec, i, output.size() / block_size, first, tuple, bptc, dst, history, allow_fitted, quality, coverage, reason);
417 return rebuild_classic(codec, i, first, tuple, classic, dst, allow_fitted, quality);
418 }, fast_entropy);
419 if (valid && (!coverage.inconsistent || quality == Quality::fitted)) return quality;
420 if (failure) *failure = coverage.inconsistent && valid ? "anchor-or-pbit" : reason;
421 return Quality::failed;
422}
423} // namespace leonida::bcpack
diff --git a/runtime/src/bcpack.h b/runtime/src/bcpack.h
new file mode 100644
index 000000000..9c34a074b
--- /dev/null
+++ b/runtime/src/bcpack.h
@@ -0,0 +1,33 @@
1// C++ BCPack decoder. Publish the caller's staged output only on success.
2#pragma once
3#include <array>
4#include <cstdint>
5#include <span>
6
7namespace leonida::bcpack {
8enum class Quality { failed, confirmed, fitted };
9
10// Fixed-size little-endian sidecar produced by
11// tools/gen_bcpack_runtime_tables.py --profile. All fields are bytes: BC6H's 12
12// endpoint quantities are stored as little-endian uint16 pairs.
13struct Calibration {
14 struct BC6 {
15 std::array<std::uint8_t, 24> ep;
16 std::array<std::uint8_t, 16> ix;
17 std::array<std::uint8_t, 12> ep_confirmed;
18 std::array<std::uint8_t, 16> ix_confirmed;
19 std::uint8_t ep_class, ix_class;
20 };
21 struct BC7 {
22 std::array<std::uint8_t, 24> ep, ep_bits, ep_confirmed;
23 std::array<std::uint8_t, 32> ix, ix_bits, ix_confirmed;
24 };
25 std::array<BC6, 256> bc6;
26 std::array<BC7, 256> bc7;
27};
28static_assert(sizeof(Calibration) == 256 * (70 + 168));
29Quality decode(unsigned codec, std::span<const std::uint8_t> source,
30 std::span<std::uint8_t> output, bool allow_fitted = false,
31 const Calibration *history = nullptr, const char** failure = nullptr,
32 bool fast_entropy = true);
33} // namespace leonida::bcpack
diff --git a/runtime/src/bcpack_stream.h b/runtime/src/bcpack_stream.h
new file mode 100644
index 000000000..787686929
--- /dev/null
+++ b/runtime/src/bcpack_stream.h
@@ -0,0 +1,222 @@
1// Shared rANS block stream used by the runtime decoder and the offline history fitter.
2#pragma once
3#include <algorithm>
4#include <array>
5#include <bit>
6#include <cstdint>
7#include <span>
8
9namespace leonida::bcpack::detail {
10using namespace std;
11struct Seed {
12 int16_t values[8];
13 bool fitted;
14};
15struct BC6Mode {
16 int code, transformed, base, delta[3], regions, first, count;
17};
18#include "bcpack_tables.inc"
19
20using Symbols = array<uint16_t, 16>;
21constexpr uint32_t home = 1u << 24;
22
23struct Model {
24 uint32_t base[11]{};
25 const uint32_t *frequency{};
26 int width{};
27 array<uint8_t, 256> first{};
28 uint64_t reciprocal[9]{};
29 void init(int w, int q) {
30 width = w;
31 frequency = freq[w][q];
32 for (int p = 1; p <= w; ++p) {
33 base[p] = base[p - 1] + (frequency[p - 1] << max(0, p - 2));
34 reciprocal[p] = ((uint64_t{1} << 32) + frequency[p] - 1) / frequency[p];
35 }
36 unsigned p = 0;
37 for (unsigned window = 0; window < first.size(); ++window) {
38 while (p < unsigned(width) && base[p + 1] <= (window << 8)) ++p;
39 first[window] = uint8_t(p);
40 }
41 }
42 int symbol(uint32_t state, bool fast) const {
43 const uint32_t cf = state & 65535;
44 if (fast) {
45 unsigned p = first[cf >> 8];
46 while (p < unsigned(width) && cf >= base[p + 1]) ++p;
47 if (!p) return 0;
48 const auto quotient = uint32_t(((cf - base[p]) * reciprocal[p]) >> 32);
49 return int((1u << (p - 1)) + quotient);
50 }
51 int p = width;
52 while (p && cf < base[p]) --p;
53 return p ? (1 << (p - 1)) + (cf - base[p]) / frequency[p] : 0;
54 }
55 uint32_t advance(uint32_t state, unsigned sym) const {
56 const int p = bit_width(sym);
57 uint32_t f = frequency[p],
58 c = base[p] + f * (sym - (p ? 1u << (p - 1) : 0u));
59 if (!c) {
60 --f;
61 ++c;
62 }
63 return f * (state >> 16) + (state & 65535) - c;
64 }
65};
66
67// VIctory's GPL-3.0 BCPack decoder uses the high slot byte to locate a bucket.
68// Build this accelerator solely from Leonida's own rANS frequencies.
69inline const Model& model_for(int w, int q) {
70 static const auto models = [] {
71 array<array<Model, 16>, 8> result{};
72 for (int width = 1; width <= 8; ++width)
73 for (int quality = 0; quality < 16; ++quality)
74 result[width - 1][quality].init(width, quality);
75 return result;
76 }();
77 return models[w - 1][q];
78}
79
80enum class Phase { header, length, long_length, symbols };
81struct Lane {
82 Phase phase{Phase::header};
83 const Model* model{};
84 uint32_t state{};
85 int bytes{}, byte{}, zeros{}, symbol{}, slot{};
86 size_t remaining{};
87 bool flush{}, extended{}, buffered{}, held{}, full{}, done{};
88
89 bool step(int width, span<const uint8_t> &input, int &budget, bool fast) {
90 if (done || (held && full))
91 return true;
92 if (!buffered && (phase != Phase::symbols || bytes)) {
93 if (!budget)
94 return true;
95 if (input.empty())
96 return false;
97 --budget;
98 byte = input.front();
99 input = input.subspan(1);
100 buffered = true;
101 }
102 if (held) {
103 state = model->advance(state, symbol);
104 slot = symbol;
105 full = true;
106 held = false;
107 }
108 if (phase == Phase::header) {
109 model = &model_for(width - (byte >> 6), byte & 15);
110 flush = (byte & 16) != 0;
111 extended = (byte & 32) != 0;
112 zeros = 0;
113 buffered = false;
114 phase = Phase::length;
115 } else if (phase == Phase::length || phase == Phase::long_length) {
116 if (phase == Phase::long_length) {
117 bytes += (byte << 8) + 257;
118 phase = Phase::symbols;
119 } else {
120 bytes = byte + !extended;
121 phase = extended ? Phase::long_length : Phase::symbols;
122 }
123 buffered = false;
124 } else {
125 if (state < home) {
126 if (bytes) {
127 state = (state << 8) | byte;
128 buffered = false;
129 --bytes;
130 } else if (!flush) {
131 done = remaining == 0;
132 phase = Phase::header;
133 return true;
134 }
135 if (!bytes && flush && state < home) {
136 if (!state || zeros >= 8)
137 return false;
138 while (state < home && zeros < 8) {
139 state <<= 8;
140 ++zeros;
141 }
142 }
143 }
144 held = state > home && remaining;
145 if (held) {
146 symbol = model->symbol(state, fast);
147 if (symbol >= (1 << model->width))
148 return false;
149 --remaining;
150 }
151 if (!bytes && flush && state == home) {
152 done = !remaining;
153 phase = Phase::header;
154 state = 0;
155 } else if (!bytes && !flush && !remaining && !held) {
156 done = true;
157 } else if (state == home || (state > home && !held)) {
158 return false;
159 }
160 }
161 return true;
162 }
163};
164
165inline int unzig(int value) { return value & 1 ? -((value + 1) >> 1) : value >> 1; }
166inline int interleave(int a, int b, int bits = 4) {
167 int v = 0;
168 for (int k = 0; k < bits; ++k)
169 v |= (((a >> k) & 1) | (((b >> k) & 1) << 1)) << (2 * k);
170 return v;
171}
172
173struct BC7Format {
174 int subsets, color, alpha, pbits, index, partition;
175};
176constexpr BC7Format bc7_formats[] = {{3, 4, 0, 1, 3, 4}, {2, 6, 0, 2, 3, 6},
177 {3, 5, 0, 0, 2, 6}, {2, 7, 0, 1, 2, 6},
178 {1, 5, 6, 0, 3, 0}, {1, 7, 8, 0, 2, 0},
179 {1, 7, 7, 1, 4, 0}, {2, 5, 5, 1, 2, 6}};
180
181
182template<class Block>
183bool visit_blocks(unsigned codec, span<const uint8_t> source, size_t size, Block block, bool fast = true) {
184 const bool single = codec == 1 || codec == 4;
185 const unsigned count = codec >= 6 ? 16 : 12;
186 const size_t elements = size / 8;
187 array<Lane, 16> lanes{};
188 for (auto &lane : lanes) lane.remaining = elements;
189 Symbols first{};
190 size_t emitted = 0;
191 while (elements) {
192 bool ready = true, done = true;
193 int budget = 8;
194 for (unsigned l = 0; l < count; ++l) {
195 auto &lane = lanes[l];
196 if (!lane.step(widths[codec][l], source, budget, fast))
197 return false;
198 ready &= lane.full;
199 done &= lane.done;
200 }
201 if (ready) {
202 if (emitted == elements)
203 return false;
204 Symbols tuple{};
205 for (unsigned l = 0; l < count; ++l) {
206 tuple[l] = uint16_t(lanes[l].slot);
207 lanes[l].full = false;
208 }
209 if (single || emitted % 2) {
210 const size_t i = single ? emitted : emitted / 2;
211 if (!block(i, single ? tuple : first, tuple)) return false;
212 } else {
213 first = tuple;
214 }
215 ++emitted;
216 }
217 if (done)
218 break;
219 }
220 return emitted == elements && ranges::all_of(source, [](uint8_t v) { return v == 0; });
221}
222} // namespace leonida::bcpack::detail
diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h
index 2ea0f9380..6fbba5b05 100644
--- a/runtime/src/buffer_va_index.h
+++ b/runtime/src/buffer_va_index.h
@@ -83,6 +83,12 @@ public:
83 return found; 83 return found;
84 } 84 }
85 85
86 // find() can return a shorter alias. Only a complete range can serve the view without new backing.
87 bool covers(std::uint64_t va, std::uint64_t bytes) const {
88 Hit hit{};
89 return find(va, hit, bytes) && bytes <= hit.size - (va - hit.start);
90 }
91
86 std::size_t size() const { return ranges_.size(); } 92 std::size_t size() const { return ranges_.size(); }
87 std::uint64_t longest() const { return longest_; } 93 std::uint64_t longest() const { return longest_; }
88 94
diff --git a/runtime/src/clzero_patch.h b/runtime/src/clzero_patch.h
new file mode 100644
index 000000000..7ab90e303
--- /dev/null
+++ b/runtime/src/clzero_patch.h
@@ -0,0 +1,200 @@
1// Moves the title's CLZERO loops off the #UD path on a CPU without CLZERO (docs/cpu_features.md).
2//
3// The executable's 10 CLZERO sites are one leaf routine that zeroes buffers a 64-byte line at a time. Emulated on #UD
4// (cpu_emulation.h), every line costs an exception dispatch and two VirtualQuery calls: measured on an i9-13900K,
5// the routine took ~99% of one thread for the whole boot and the title presented at ~3 frames a second. Each site sits
6// in one of two loop shapes, which are matched exactly (register forms only, nothing that refers to RIP):
7//
8// A (12 bytes) clzero; add rax, 40h; cmp rax, END; jb A (END: rdx or r8-r15)
9// B (15 bytes) mov rax, CUR; add CUR, 40h; clzero; cmp CUR, END; jb B (CUR, END: rdx or r8-r15)
10//
11// The loop's first instruction becomes a `jmp rel32` to a copy of the loop in a stub page within 2 GiB of the image,
12// and the rest of the loop becomes int3 (nothing branches into a loop's middle: its jb targets its first byte). In the
13// copy, CLZERO is eight 8-byte stores of zero to the line rAX points into, with RCX saved around them; the loop's own
14// instructions are copied unchanged, so the registers and flags the loop leaves are the ones the original leaves. The
15// copy ends with a jmp to the instruction after the original jb. A line the title cannot write faults in the stub, as
16// the original would fault at its CLZERO; the stub page is logged so such an address can be placed.
17//
18// Run before any of the image's code and before its sections are protected. LEONIDA_CLZERO_PATCH=0 keeps the #UD path.
19#pragma once
20
21#ifdef _WIN32
22#include <windows.h>
23
24#include <cstddef>
25#include <cstdint>
26#include <cstdlib>
27#include <cstring>
28#include <utility>
29#include <vector>
30
31namespace rt::clzero_patch {
32
33struct Site {
34 uint32_t head; // offset of the loop's first byte from the scanned code's start
35 uint32_t length; // 12 (shape A) or 15 (shape B)
36 uint32_t clzero; // offset of the CLZERO within the loop
37};
38
39// `cmp r/m64, r64` (REX.W 39 /r, register form) or `mov`/`add` with the given register as ModRM r/m, for rdx or
40// r8-r15: the registers the routine uses. rcx is excluded because the stub saves it around its stores.
41inline bool is_cmp_rr(const uint8_t* p) {
42 return (p[0] == 0x48 || p[0] == 0x49 || p[0] == 0x4C || p[0] == 0x4D) && p[1] == 0x39 && (p[2] & 0xC0) == 0xC0;
43}
44
45inline bool clzero_at(const uint8_t* p) { return p[0] == 0x0F && p[1] == 0x01 && p[2] == 0xFC; }
46
47// Register number (0-15) of ModRM.rm / ModRM.reg with REX.
48inline unsigned rm_reg(uint8_t rex, uint8_t modrm) { return (modrm & 7) | ((rex & 1) << 3); }
49inline unsigned reg_reg(uint8_t rex, uint8_t modrm) { return ((modrm >> 3) & 7) | ((rex & 4) << 1); }
50
51// Finds the loops in `code[0, size)`. A CLZERO that is in neither shape is left to the #UD path.
52inline std::vector<Site> find(const uint8_t* code, size_t size) {
53 std::vector<Site> sites;
54 for (size_t k = 0; k + 3 <= size; ++k) {
55 if (!clzero_at(code + k)) continue;
56 // Shape A: the CLZERO is the loop's first instruction.
57 if (k + 12 <= size) {
58 const uint8_t* p = code + k;
59 const bool add = p[3] == 0x48 && p[4] == 0x83 && p[5] == 0xC0 && p[6] == 0x40; // add rax, 40h
60 // cmp rax, END: REX.W (+R for r8-r15) 39 /r with rm = rax.
61 const bool cmp = is_cmp_rr(p + 7) && rm_reg(p[7], p[9]) == 0 && (p[7] & 1) == 0;
62 const unsigned end = cmp ? reg_reg(p[7], p[9]) : 0;
63 const bool jb = p[10] == 0x72 && int8_t(p[11]) == -12;
64 if (add && cmp && jb && end != 0 && end != 1 && end != 4) {
65 sites.push_back({uint32_t(k), 12, 0});
66 k += 2;
67 continue;
68 }
69 }
70 // Shape B: mov rax, CUR; add CUR, 40h before the CLZERO; cmp CUR, END; jb after it.
71 if (k >= 7 && k + 8 <= size) {
72 const uint8_t* p = code + k - 7;
73 // mov rax, CUR: REX.W(+R) 89 /r, rm = rax, reg = CUR.
74 const bool mov = (p[0] == 0x48 || p[0] == 0x4C) && p[1] == 0x89 && (p[2] & 0xC7) == 0xC0;
75 const unsigned cur = mov ? reg_reg(p[0], p[2]) : 0;
76 // add CUR, 40h: REX.W(+B) 83 /0 ib with rm = CUR.
77 const bool add = (p[3] == 0x48 || p[3] == 0x49) && p[4] == 0x83 && (p[5] & 0xF8) == 0xC0 &&
78 rm_reg(p[3], p[5]) == cur && p[6] == 0x40;
79 // cmp CUR, END: REX.W 39 /r with rm = CUR, reg = END.
80 const bool cmp = is_cmp_rr(p + 10) && rm_reg(p[10], p[12]) == cur;
81 const unsigned end = cmp ? reg_reg(p[10], p[12]) : 0;
82 const bool jb = p[13] == 0x72 && int8_t(p[14]) == -15;
83 const auto ok = [](unsigned r) { return r == 2 || r >= 8; };
84 if (mov && add && cmp && jb && ok(cur) && ok(end) && cur != end) {
85 sites.push_back({uint32_t(k - 7), 15, 7});
86 k += 7;
87 continue;
88 }
89 }
90 }
91 return sites;
92}
93
94// The stub for one loop: its instructions before the CLZERO, the zeroing block, its instructions after the CLZERO up
95// to the jb, a jb back to the stub's start, then a jmp to `resume` (the instruction after the original jb).
96inline std::vector<uint8_t> stub(const uint8_t* loop, const Site& s, uint64_t stub_at, uint64_t resume) {
97 std::vector<uint8_t> out(loop, loop + s.clzero); // shape B: mov rax, CUR; add CUR, 40h
98 const uint8_t zero_line[] = {
99 0x51, // push rcx
100 0x48, 0x89, 0xC1, // mov rcx, rax
101 0x48, 0x83, 0xE1, 0xC0, // and rcx, -64
102 0x48, 0xC7, 0x01, 0, 0, 0, 0, // mov qword [rcx], 0
103 0x48, 0xC7, 0x41, 0x08, 0, 0, 0, 0, // mov qword [rcx+8], 0
104 0x48, 0xC7, 0x41, 0x10, 0, 0, 0, 0,
105 0x48, 0xC7, 0x41, 0x18, 0, 0, 0, 0,
106 0x48, 0xC7, 0x41, 0x20, 0, 0, 0, 0,
107 0x48, 0xC7, 0x41, 0x28, 0, 0, 0, 0,
108 0x48, 0xC7, 0x41, 0x30, 0, 0, 0, 0,
109 0x48, 0xC7, 0x41, 0x38, 0, 0, 0, 0,
110 0x59, // pop rcx
111 };
112 out.insert(out.end(), std::begin(zero_line), std::end(zero_line));
113 // The instructions between the CLZERO and the jb (shape A: add rax, 40h; cmp; shape B: cmp).
114 out.insert(out.end(), loop + s.clzero + 3, loop + s.length - 2);
115 const int back = -int(out.size() + 2);
116 out.push_back(0x72);
117 out.push_back(uint8_t(int8_t(back)));
118 out.push_back(0xE9);
119 const int64_t rel = int64_t(resume) - int64_t(stub_at + out.size() + 4);
120 const int32_t rel32 = int32_t(rel);
121 const auto* b = reinterpret_cast<const uint8_t*>(&rel32);
122 out.insert(out.end(), b, b + 4);
123 return out;
124}
125
126// Reserves a page within 2 GiB above or below [lo, hi) for the stubs (the image does not move after this).
127inline uint8_t* stub_page(uint64_t lo, uint64_t hi, size_t size) {
128 SYSTEM_INFO si;
129 GetSystemInfo(&si);
130 const uint64_t gran = si.dwAllocationGranularity;
131 const uint64_t limit = uint64_t(1) << 31;
132 for (uint64_t at = (hi + gran - 1) & ~(gran - 1); at + size < lo + limit - 0x1000; at += gran) {
133 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))
134 return static_cast<uint8_t*>(p);
135 }
136 for (uint64_t at = (lo - size) & ~(gran - 1); at > gran && hi - at < limit - 0x1000; at -= gran) {
137 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))
138 return static_cast<uint8_t*>(p);
139 }
140 return nullptr;
141}
142
143inline bool enabled() {
144 char v[8] = {};
145 size_t n = 0;
146 return !(getenv_s(&n, v, "LEONIDA_CLZERO_PATCH") == 0 && n == 2 && v[0] == '0');
147}
148
149struct Result {
150 size_t sites = 0;
151 uint8_t* stubs = nullptr;
152 size_t stub_bytes = 0;
153};
154
155// Patches every loop found in the executable ranges `ranges` (pairs of start address and size, all inside
156// [image_lo, image_hi)). The ranges must be writable. On any failure nothing is patched.
157inline Result patch(const std::vector<std::pair<uint8_t*, size_t>>& ranges, uint64_t image_lo, uint64_t image_hi) {
158 Result r;
159 std::vector<std::pair<uint8_t*, Site>> all;
160 for (const auto& [code, size] : ranges)
161 for (const Site& s : find(code, size)) all.push_back({code, s});
162 if (all.empty()) return r;
163 const size_t page = 0x10000;
164 uint8_t* const stubs = stub_page(image_lo, image_hi, page);
165 if (!stubs) return r;
166 size_t used = 0;
167 std::vector<std::vector<uint8_t>> bodies;
168 for (const auto& [code, s] : all) {
169 uint8_t* const loop = code + s.head;
170 const uint64_t at = uint64_t(stubs + used);
171 bodies.push_back(stub(loop, s, at, uint64_t(loop + s.length)));
172 used += (bodies.back().size() + 15) & ~size_t(15);
173 if (used > page) {
174 VirtualFree(stubs, 0, MEM_RELEASE);
175 return r;
176 }
177 }
178 used = 0;
179 for (size_t i = 0; i < all.size(); ++i) {
180 const auto& [code, s] = all[i];
181 uint8_t* const loop = code + s.head;
182 uint8_t* const at = stubs + used;
183 std::memcpy(at, bodies[i].data(), bodies[i].size());
184 used += (bodies[i].size() + 15) & ~size_t(15);
185 const int32_t rel = int32_t(int64_t(at) - int64_t(loop + 5));
186 loop[0] = 0xE9;
187 std::memcpy(loop + 1, &rel, 4);
188 std::memset(loop + 5, 0xCC, s.length - 5);
189 }
190 DWORD old = 0;
191 VirtualProtect(stubs, page, PAGE_EXECUTE_READ, &old);
192 FlushInstructionCache(GetCurrentProcess(), stubs, page);
193 r.sites = all.size();
194 r.stubs = stubs;
195 r.stub_bytes = used;
196 return r;
197}
198
199} // namespace rt::clzero_patch
200#endif
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index a7578b8ff..010abbbc0 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -1,4 +1,5 @@
1#pragma once 1#pragma once
2#include "gpu_label_memory.h"
2 3
3// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until 4// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until
4// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and 5// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and
@@ -527,6 +528,7 @@ struct UavView {
527 std::uint32_t mip; // texture 528 std::uint32_t mip; // texture
528 std::uint32_t first_layer; 529 std::uint32_t first_layer;
529 std::uint32_t layer_count; 530 std::uint32_t layer_count;
531 bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format
530}; 532};
531 533
532// ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are 534// ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are
@@ -597,6 +599,9 @@ enum class IndirectKind : std::uint8_t {
597 draw = 0, 599 draw = 0,
598 draw_indexed = 1, 600 draw_indexed = 1,
599 dispatch = 2, 601 dispatch = 2,
602 // D3D12_DISPATCH_MESH_ARGUMENTS. Created on a device with mesh shaders; ExecuteIndirect with it records nothing
603 // yet (the replay is #3777's), so a title that only creates such a signature at startup goes on.
604 dispatch_mesh = 3,
600}; 605};
601 606
602struct ExecuteIndirect { 607struct ExecuteIndirect {
@@ -664,7 +669,7 @@ struct AccelerationStructurePostbuild {
664using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier, 669using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier,
665 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture, 670 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture,
666 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource, 671 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource,
667 WriteImmediate, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker, 672 WriteImmediate, label::Write, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker,
668 ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure, 673 ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure,
669 AccelerationStructurePostbuild>; 674 AccelerationStructurePostbuild>;
670 675
@@ -698,10 +703,11 @@ public:
698 return append(barrier); 703 return append(barrier);
699 } 704 }
700 705
706 // LayoutAfter UNDEFINED is legal: the subresources' contents are no longer needed, as before their memory is
707 // aliased (the retail title ends a depth buffer's use this way, #984; WARP closes such a list,
708 // d3d12_close_parity_test). Replay keeps the image's Vulkan layout and orders the accesses only.
701 bool barrier(const TextureBarrier& barrier) { 709 bool barrier(const TextureBarrier& barrier) {
702 if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; 710 if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false;
703 if (barrier.layout_after == d3d12_layout::undefined && barrier.layout_before != d3d12_layout::undefined)
704 return false;
705 if (barrier.flags & ~texture_barrier_discard) return false; 711 if (barrier.flags & ~texture_barrier_discard) return false;
706 if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; 712 if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false;
707 if (barrier.sync_after == d3d12_sync::split) return !closed_; 713 if (barrier.sync_after == d3d12_sync::split) return !closed_;
@@ -793,6 +799,11 @@ public:
793 } 799 }
794 800
795 // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes. 801 // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes.
802 bool write_gpu_label(const label::Write& write) {
803 if(write.target.owner.expired() || write.clock>2) return false;
804 return append(write);
805 }
806
796 bool write_immediate(const WriteImmediate& write) { 807 bool write_immediate(const WriteImmediate& write) {
797 if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false; 808 if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false;
798 return append(write); 809 return append(write);
diff --git a/runtime/src/console_texture_layout.h b/runtime/src/console_texture_layout.h
new file mode 100644
index 000000000..393e0adee
--- /dev/null
+++ b/runtime/src/console_texture_layout.h
@@ -0,0 +1,611 @@
1// Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and alignment, where each mip and array slice
2// starts, the address of each element, and copies between tiled memory and linear rows. Used by the xg_xs.dll shim
3// (runtime/shims/xg_xs.cpp), whose texture computer answers the title's layout and copy calls from it.
4//
5// Ported from Marvisak/VIctory (GPL-3.0-or-later; translated from Rust to C++ and changed for Leonida),
6// crates/victory-formats/src/texture.rs at commit d2a4bae1f, which follows
7// AMD's address library (addrlib) as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement and mip
8// tails from gfx10addrlib.cpp and addrlib2.cpp (ComputeSurfaceInfoMacroTiled, ComputeThinBlockDimension,
9// GetMipTailDim, GetMaxNumMipsInTail, HwlComputeSurfaceInfoLinear, ComputeSurfaceAddrFromCoordMacroTiled), and the
10// 256-byte micro tile patterns in kMicro from gfx10SwizzlePattern.h (the RB+ tables, as on RDNA2). addrlib carries
11// this notice:
12//
13// Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved.
14// SPDX-License-Identifier: MIT
15//
16// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
17// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
18// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
19// to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above
20// copyright notice and this permission notice shall be included in all copies or substantial portions of the
21// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
22//
23// Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth
24// slab of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block)
25// at offset 0, mip 0 last.
26#pragma once
27
28#include <algorithm>
29#include <array>
30#include <bit>
31#include <cstddef>
32#include <cstdint>
33#include <cstring>
34#include <optional>
35#include <vector>
36
37namespace leonida::console_texture {
38
39// A swizzle mode, by its hardware number (addrlib's ADDR_SW_* order).
40enum : uint32_t {
41 kLinear = 0,
42 kSw256bS = 1,
43 kSw256bD = 2,
44 kSw4kbS = 5,
45 kSw4kbD = 6,
46 kSw64kbS = 9,
47 kSw64kbD = 10,
48 kSw64kbST = 17,
49 kSw64kbDT = 18,
50 kSw4kbSX = 21,
51 kSw4kbDX = 22,
52 kSw4kbRX = 23,
53 kSw64kbZX = 24,
54 kSw64kbSX = 25,
55 kSw64kbDX = 26,
56 kSw64kbRX = 27,
57};
58
59// log2 of the block size in bytes (0 for linear); nullopt for modes GFX10 does not have.
60inline std::optional<uint32_t> block_log2(uint32_t swizzle) {
61 switch (swizzle) {
62 case 0: return 0;
63 case 1: case 2: return 8;
64 case 5: case 6: case 21: case 22: case 23: return 12;
65 case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16;
66 default: return std::nullopt;
67 }
68}
69inline bool is_standard(uint32_t s) { return s == 1 || s == 5 || s == 9 || s == 17 || s == 21 || s == 25; }
70inline bool is_display(uint32_t s) { return s == 2 || s == 6 || s == 10 || s == 18 || s == 22 || s == 26; }
71inline bool is_z_order(uint32_t s) { return s == 24; }
72// Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration.
73inline bool is_xor(uint32_t s) { return s >= 16; }
74
75enum class Dimension { tex1d, tex2d, tex3d };
76
77enum class Error {
78 ok,
79 invalid, // the description makes no texture, or a coordinate or subresource lies outside it
80 unsupported, // a valid layout whose addressing is not implemented here
81 too_small, // a buffer is smaller than the layout or the rows need
82};
83
84// One plane of a texture.
85struct Desc {
86 Dimension dimension = Dimension::tex2d;
87 uint32_t width = 1, height = 1; // in texels
88 uint32_t depth = 1; // depth of a 3D texture, else the array size
89 uint32_t mips = 1;
90 uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16
91 uint32_t block = 1; // texels per element side: 1, or 4 for block compression
92 uint32_t samples = 1;
93 uint32_t swizzle = kLinear;
94};
95
96struct Tail {
97 uint32_t offset = 0; // byte offset inside the tail block
98 uint32_t x = 0, y = 0; // element position the mip starts at
99};
100
101// Where one mip lives inside a slice.
102struct Mip {
103 uint32_t width = 0, height = 0, depth = 0; // size in elements (depth 1 unless the texture is 3D)
104 uint32_t pitch = 0, rows = 0, depth_pitch = 0; // padded size in elements: whole blocks, or the tail's share
105 uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail)
106 std::optional<Tail> tail;
107};
108
109namespace detail {
110
111constexpr uint32_t div_ceil(uint32_t a, uint32_t b) { return (a + b - 1) / b; }
112constexpr uint32_t round_up(uint32_t a, uint32_t b) { return div_ceil(a, b) * b; }
113
114// Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), then
115// round up to whole elements.
116constexpr uint32_t dim(uint32_t texels, uint32_t mip, uint32_t block) {
117 return div_ceil(std::max(texels >> mip, 1u), block);
118}
119// Elements along one side of mip `mip` for placement (padding, tail, offsets): addrlib halves mip 0's elements
120// rounding up, which can be one more than dim() for odd sizes.
121constexpr uint32_t padded_dim(uint32_t texels, uint32_t mip, uint32_t block) {
122 return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip);
123}
124
125// Micro tile (256 bytes) patterns by log2 of the element size: for each address bit, the element coordinate bit it
126// takes (x0, y1, z0...), "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes). From
127// addrlib's GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS patterns; the larger blocks add
128// bits Y, X (thin) or Y, X, Z (thick) in turn.
129inline constexpr const char* kMicro[3][5] = {
130 {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"},
131 {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"},
132 {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"},
133};
134
135// For each axis, the address bit each coordinate bit lands on.
136inline std::array<std::vector<uint32_t>, 3> pattern(int kind, uint32_t element_log2, uint32_t block_log2) {
137 std::array<std::vector<uint32_t>, 3> axes;
138 const char* micro = kMicro[kind][element_log2];
139 for (uint32_t bit = 0; bit < 8; ++bit) {
140 const char a = micro[2 * bit];
141 const int axis = a == 'x' ? 0 : a == 'y' ? 1 : a == 'z' ? 2 : -1;
142 if (axis < 0) continue;
143 const size_t index = static_cast<size_t>(micro[2 * bit + 1] - '0');
144 auto& to = axes[static_cast<size_t>(axis)];
145 if (to.size() <= index) to.resize(index + 1, 0);
146 to[index] = bit;
147 }
148 static constexpr int kThin[2] = {1, 0};
149 static constexpr int kThick[3] = {1, 0, 2};
150 const int* order = kind == 2 ? kThick : kThin;
151 const uint32_t n = kind == 2 ? 3u : 2u;
152 for (uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) axes[static_cast<size_t>(order[i % n])].push_back(bit);
153 return axes;
154}
155
156// Byte offsets inside a block for coordinates 0..2^bits of one axis.
157inline std::vector<uint32_t> spread(const std::vector<uint32_t>& bits) {
158 std::vector<uint32_t> out(size_t{1} << bits.size());
159 for (uint32_t c = 0; c < out.size(); ++c) {
160 uint32_t v = 0;
161 for (size_t i = 0; i < bits.size(); ++i) v |= ((c >> i) & 1u) << bits[i];
162 out[c] = v;
163 }
164 return out;
165}
166
167} // namespace detail
168
169constexpr uint32_t kMaxMips = 16;
170// The largest width, height and depth (or array size) accepted, in texels. GFX10's image descriptors hold at most
171// 16384 texels per side, so no texture the GPU can use is refused. The bound also keeps every size computed below
172// within uint64_t (and its uint32_t steps), which unchecked values from a title would otherwise overflow.
173constexpr uint32_t kMaxExtent = 1u << 14;
174
175// 256-byte micro tile dimensions by log2 element size, 2D and 3D.
176inline constexpr uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}};
177inline constexpr uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}};
178inline constexpr uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}};
179
180class Layout {
181public:
182 Desc desc;
183 std::array<uint32_t, 3> block{}; // block dimensions in elements (linear: the pitch alignment, 1, 1)
184 bool thick = false; // 3D blocks span block[2] depth slices (GFX10 3D S and D modes)
185 // Array slices, depth slabs of block[2] slices (thick), or depth slices (thin and linear 3D).
186 uint32_t slices = 0;
187 uint64_t slice_size = 0; // bytes of one slice: its whole mip chain
188 uint64_t size = 0;
189 uint64_t alignment = 0;
190 uint32_t first_tail_mip = 0; // the first mip in the tail; mips.size() without one
191 std::vector<Mip> mips;
192
193 static std::optional<Layout> make(const Desc& d) {
194 const auto log2 = block_log2(d.swizzle);
195 if (!log2) return std::nullopt;
196 const auto in = [](uint32_t v, uint32_t lo, uint32_t hi) { return v >= lo && v <= hi; };
197 const bool valid =
198 in(d.width, 1, kMaxExtent) && in(d.height, 1, kMaxExtent) && in(d.depth, 1, kMaxExtent) &&
199 in(d.mips, 1, kMaxMips) && std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 &&
200 (d.block == 1 || d.block == 4) && std::has_single_bit(d.samples) && d.samples <= 8 &&
201 (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) &&
202 (d.dimension != Dimension::tex1d || d.height == 1) &&
203 (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 ||
204 d.swizzle == 17 || d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27));
205 if (!valid) return std::nullopt;
206 return *log2 == 0 ? linear(d) : tiled(d, *log2);
207 }
208
209 // Whether offset() and the copies work for this layout: linear and the modes without pipe or bank XOR,
210 // single-sampled. The XOR modes (_X, _T) and MSAA need the GPU's pipe and bank configuration (Series X and S
211 // differ); titles use them for render targets and depth, which the host renders.
212 bool addressable() const { return desc.swizzle == kLinear || !pattern_[0].empty(); }
213
214 // Depth slices a subresource of mip `mip` covers: the mip's depth for 3D textures, else 1 (one array slice).
215 uint32_t subresource_depth(uint32_t mip) const { return mip < mips.size() ? mips[mip].depth : 0; }
216
217 // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`. Coordinates must lie inside.
218 Error offset(uint32_t mip, uint32_t x, uint32_t y, uint32_t z, uint64_t& out) const {
219 if (mip >= mips.size()) return Error::invalid;
220 const Mip& m = mips[mip];
221 const uint32_t depth = desc.dimension == Dimension::tex3d ? m.depth : slices;
222 const bool inside = x < m.width && y < m.height && z < depth;
223 if (!inside) return Error::invalid;
224 if (!addressable()) return Error::unsupported;
225 const auto [slice, inner] = split(z);
226 const uint64_t base = uint64_t{slice} * slice_size + m.offset;
227 if (desc.swizzle == kLinear) {
228 out = base + (uint64_t{y} * m.pitch + x) * desc.element_bytes;
229 return Error::ok;
230 }
231 out = base + row(m, y, inner) + column(m, x);
232 return Error::ok;
233 }
234
235 // Copies one subresource out of tiled memory (the whole texture, `size` bytes) into linear rows: mip `mip` of
236 // array slice `slice` (3D: every depth slice of the mip, slice 0). Rows are row_pitch bytes apart, depth slices
237 // depth_pitch.
238 Error detile(const uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, uint8_t* linear,
239 size_t linear_len, size_t row_pitch, size_t depth_pitch) const {
240 return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) {
241 std::memcpy(linear + l, tiled + t, n);
242 });
243 }
244 // The reverse of detile(): linear rows into tiled memory.
245 Error tile(uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, const uint8_t* linear,
246 size_t linear_len, size_t row_pitch, size_t depth_pitch) const {
247 return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) {
248 std::memcpy(tiled + t, linear + l, n);
249 });
250 }
251
252 // Byte offsets inside a block of each element coordinate bit, per axis; empty for linear and XOR/MSAA modes.
253 const std::array<std::vector<uint32_t>, 3>& pattern() const { return pattern_; }
254
255private:
256 std::array<std::vector<uint32_t>, 3> pattern_;
257
258 // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices
259 // each hold the chain.
260 static Layout linear(const Desc& d) {
261 using namespace detail;
262 Layout l;
263 l.desc = d;
264 const uint64_t bpe = d.element_bytes;
265 const uint32_t align = 256 / d.element_bytes;
266 const bool three_d = d.dimension == Dimension::tex3d;
267 uint64_t offset = 0;
268 for (uint32_t i = d.mips; i-- > 0;) {
269 const uint32_t h = padded_dim(d.height, i, d.block);
270 const uint32_t pitch = round_up(padded_dim(d.width, i, d.block), align);
271 Mip m;
272 m.width = dim(d.width, i, d.block);
273 m.height = dim(d.height, i, d.block);
274 m.depth = three_d ? dim(d.depth, i, 1) : 1;
275 m.pitch = pitch;
276 m.rows = h;
277 m.depth_pitch = three_d ? d.depth : 1;
278 m.offset = offset;
279 l.mips.push_back(m);
280 offset += uint64_t{pitch} * h * bpe;
281 }
282 std::reverse(l.mips.begin(), l.mips.end());
283 l.block = {align, 1, 1};
284 l.slices = d.depth;
285 l.slice_size = offset;
286 l.size = offset * d.depth;
287 l.alignment = 256;
288 l.first_tail_mip = d.mips;
289 return l;
290 }
291
292 static Layout tiled(const Desc& d, uint32_t block_log2) {
293 using namespace detail;
294 Layout l;
295 l.desc = d;
296 const uint32_t element_log2 = static_cast<uint32_t>(std::countr_zero(d.element_bytes));
297 const uint64_t bpe = d.element_bytes;
298 const uint64_t block_bytes = uint64_t{1} << block_log2;
299 const bool thick = d.dimension == Dimension::tex3d && (is_standard(d.swizzle) || is_display(d.swizzle));
300 std::array<uint32_t, 3> block{};
301 if (thick) { // ComputeThickBlockDimension
302 const uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3;
303 const auto* b = kBlock1k_3d[element_log2];
304 block = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1u : 0u))};
305 } else { // ComputeThinBlockDimension
306 const uint32_t samples_log2 = static_cast<uint32_t>(std::countr_zero(d.samples));
307 const uint32_t elements_log2 = block_log2 - element_log2 - samples_log2;
308 const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0;
309 const uint32_t w = (elements_log2 + (wide ? 1u : 0u)) / 2;
310 block = {1u << w, 1u << (elements_log2 - w), 1};
311 }
312 uint32_t slices = round_up(d.depth, block[2]);
313 const bool three_d = d.dimension == Dimension::tex3d;
314 // Mip depths placed by a thick layout (thin ones store depth as slices).
315 const auto mip_depth = [&](uint32_t i) { return thick ? padded_dim(d.depth, i, 1) : 1u; };
316 const auto depth_of = [&](uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; };
317 const auto width = [&](uint32_t i) { return dim(d.width, i, d.block); };
318 const auto height = [&](uint32_t i) { return dim(d.height, i, d.block); };
319 uint32_t first_tail_mip = d.mips;
320 uint64_t slice_size = 0;
321 if (d.mips == 1) {
322 Mip m;
323 m.width = width(0);
324 m.height = height(0);
325 m.depth = depth_of(0);
326 m.pitch = round_up(width(0), block[0]);
327 m.rows = round_up(height(0), block[1]);
328 m.depth_pitch = three_d ? slices : 1;
329 l.mips.push_back(m);
330 slice_size = uint64_t{m.pitch} * m.rows * bpe * d.samples;
331 } else {
332 // GetMipTailDim: the largest mip the tail takes.
333 std::array<uint32_t, 3> tail_max = block;
334 if (thick) {
335 switch (block_log2 % 3) {
336 case 0: tail_max[1] >>= 1; break;
337 case 1: tail_max[0] >>= 1; break;
338 default: tail_max[2] >>= 1; break;
339 }
340 } else {
341 tail_max[0] >>= 1;
342 }
343 // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled).
344 const uint32_t effective = thick ? block_log2 - (block_log2 - 8) / 3 : block_log2;
345 const uint32_t max_in_tail = effective == 8 ? 0
346 : (effective >= 9 && effective <= 11) ? 1 + (1u << (effective - 9))
347 : effective - 4;
348 // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit.
349 std::array<uint32_t, 3> fixed = tail_max;
350 if (is_z_order(d.swizzle) && element_log2 <= 1) {
351 const auto* b = kBlock256_2d[element_log2];
352 fixed[0] /= b[0] / kBlock256_2d[2][0];
353 fixed[1] /= b[1] / kBlock256_2d[2][1];
354 }
355 std::vector<uint64_t> sizes;
356 for (uint32_t i = 0; i < d.mips; ++i) {
357 const uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block);
358 if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) {
359 first_tail_mip = i;
360 slice_size += block_bytes / block[2];
361 break;
362 }
363 const uint32_t pitch = round_up(w, block[0]), rows = round_up(h, block[1]);
364 const uint32_t depth = round_up(mip_depth(i), block[2]);
365 const uint64_t one = uint64_t{pitch} * rows * bpe;
366 slice_size += one;
367 sizes.push_back(one * block[2]);
368 Mip m;
369 m.width = width(i);
370 m.height = height(i);
371 m.depth = depth_of(i);
372 m.pitch = pitch;
373 m.rows = rows;
374 m.depth_pitch = three_d ? depth : 1;
375 l.mips.push_back(m);
376 }
377 // Standard mips from the smallest up, after the tail block.
378 uint64_t offset = first_tail_mip < d.mips ? block_bytes : 0;
379 for (uint32_t i = first_tail_mip; i-- > 0;) {
380 l.mips[i].offset = offset;
381 offset += sizes[i];
382 }
383 uint32_t micro[2];
384 if (thick) {
385 micro[0] = kBlock256_3d[element_log2][0];
386 micro[1] = kBlock256_3d[element_log2][1];
387 } else {
388 micro[0] = kBlock256_2d[element_log2][0];
389 micro[1] = kBlock256_2d[element_log2][1];
390 }
391 uint32_t pitch = tail_max[0], rows = tail_max[1];
392 for (uint32_t i = first_tail_mip; i < d.mips; ++i) {
393 const uint32_t m = max_in_tail - 1 - (i - first_tail_mip);
394 const uint32_t offset_in_tail = m > 6 ? 16u << m : m << 8;
395 // Address bits 8.. of the offset, odd ones x, even ones y.
396 const auto bits = [&](uint32_t from) {
397 uint32_t v = 0;
398 for (uint32_t b = 0; b < 6; ++b) v |= ((offset_in_tail >> (from + 2 * b)) & 1u) << b;
399 return v;
400 };
401 uint32_t x = bits(9), y = bits(8);
402 if ((block_log2 & 1) != 0) {
403 std::swap(x, y);
404 if ((element_log2 & 1) != 0) {
405 y = (y << 1) | (x & 1);
406 x >>= 1;
407 }
408 }
409 Mip t;
410 t.width = width(i);
411 t.height = height(i);
412 t.depth = depth_of(i);
413 t.pitch = pitch;
414 t.rows = rows;
415 t.depth_pitch = thick ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1;
416 t.offset = 0;
417 t.tail = Tail{offset_in_tail, x * micro[0], y * micro[1]};
418 l.mips.push_back(t);
419 pitch = std::max(pitch >> 1, micro[0]);
420 rows = std::max(rows >> 1, micro[1]);
421 }
422 }
423 // Thick layouts store each depth slab's chain together.
424 const uint64_t slab = thick ? block[2] : 1;
425 slice_size *= slab;
426 slices /= block[2];
427 if (!is_xor(d.swizzle) && d.samples == 1) {
428 const int kind = thick ? 2 : (is_display(d.swizzle) ? 1 : 0);
429 const auto bits = detail::pattern(kind, element_log2, block_log2);
430 for (size_t a = 0; a < 3; ++a) l.pattern_[a] = detail::spread(bits[a]);
431 }
432 l.block = block;
433 l.thick = thick;
434 l.slices = slices;
435 l.slice_size = slice_size;
436 l.size = slice_size * slices;
437 l.alignment = block_bytes;
438 l.first_tail_mip = first_tail_mip;
439 return l;
440 }
441
442 // The slice and the depth inside it for z (an array slice or a 3D depth slice).
443 std::pair<uint32_t, uint32_t> split(uint32_t z) const {
444 return thick ? std::pair{z / block[2], z % block[2]} : std::pair{z, 0u};
445 }
446
447 // The part of an address that depends on the row (and depth in a thick block).
448 uint64_t row(const Mip& m, uint32_t y, uint32_t z) const {
449 const uint32_t bw = block[0], bh = block[1];
450 const int log2 = std::countr_zero(alignment);
451 // In the tail the pattern of the shifted position gives the mip's offset inside the tail block.
452 y += m.tail ? m.tail->y : 0;
453 const uint64_t blocks = uint64_t{y / bh} * (m.pitch / bw);
454 return (blocks << log2) + (pattern_[1][y % bh] | pattern_[2][z]);
455 }
456
457 // The part of an address that depends on the column.
458 uint64_t column(const Mip& m, uint32_t x) const {
459 const uint32_t bw = block[0];
460 x += m.tail ? m.tail->x : 0;
461 return (uint64_t{x / bw} << std::countr_zero(alignment)) + pattern_[0][x % bw];
462 }
463
464 // Visits contiguous runs as (tiled byte offset, linear byte offset, length).
465 template <class Copy>
466 Error walk(size_t tiled_len, uint32_t mip, uint32_t slice, size_t linear_len, size_t row_pitch,
467 size_t depth_pitch, Copy&& copy) const {
468 if (mip >= mips.size()) return Error::invalid;
469 const Mip& m = mips[mip];
470 const uint32_t depth = m.depth;
471 uint32_t first = slice;
472 if (desc.dimension == Dimension::tex3d) {
473 if (slice != 0) return Error::invalid;
474 first = 0;
475 }
476 if (first >= slices) return Error::invalid;
477 if (!addressable()) return Error::unsupported;
478 const size_t n = desc.element_bytes;
479 const size_t bytes = size_t{m.width} * n;
480 // need = (depth - 1) * depth_pitch + (height - 1) * row_pitch + bytes, refused on overflow.
481 const size_t dz = depth - 1u, dy = m.height - 1u;
482 if ((dz && depth_pitch > SIZE_MAX / dz) || (dy && row_pitch > SIZE_MAX / dy)) return Error::too_small;
483 const size_t depth_offset = dz * depth_pitch, row_offset = dy * row_pitch;
484 if (depth_offset > SIZE_MAX - row_offset || depth_offset + row_offset > SIZE_MAX - bytes)
485 return Error::too_small;
486 const size_t need = depth_offset + row_offset + bytes;
487 if (tiled_len < size || linear_len < need || row_pitch < bytes) return Error::too_small;
488 const bool is_linear = desc.swizzle == kLinear;
489 // The row and depth contribute one common base to every column, so the same contiguous runs repeat on
490 // every row, including mip tails.
491 struct Run {
492 size_t tiled, linear, len;
493 };
494 std::vector<Run> runs;
495 if (!is_linear) {
496 size_t first_linear = 0, first_tiled = static_cast<size_t>(column(m, 0));
497 for (uint32_t x = 1; x < m.width; ++x) {
498 const size_t off = static_cast<size_t>(column(m, x));
499 const size_t at = x * n;
500 if (off != first_tiled + (at - first_linear)) {
501 runs.push_back({first_tiled, first_linear, at - first_linear});
502 first_tiled = off;
503 first_linear = at;
504 }
505 }
506 runs.push_back({first_tiled, first_linear, bytes - first_linear});
507 }
508 for (uint32_t z = 0; z < depth; ++z) {
509 const auto [s, inner] = split(first + z);
510 const uint64_t base = uint64_t{s} * slice_size + m.offset;
511 for (uint32_t y = 0; y < m.height; ++y) {
512 const size_t linear_row = z * depth_pitch + y * row_pitch;
513 if (is_linear) {
514 copy(static_cast<size_t>(base + uint64_t{y} * m.pitch * n), linear_row, bytes);
515 } else {
516 const size_t tiled_row = static_cast<size_t>(base + row(m, y, inner));
517 for (const Run& r : runs) copy(tiled_row + r.tiled, linear_row + r.linear, r.len);
518 }
519 }
520 }
521 return Error::ok;
522 }
523};
524
525// What a DXGI format stores per element: bytes, texels per element side (4 for block compression), and whether its
526// stencil is a second plane (the GPU keeps depth and stencil apart). nullopt for 96-bit, 1-bit, packed 4:2:2 and
527// video formats, which have no layout here.
528struct Format {
529 uint32_t bytes, block;
530 bool stencil;
531};
532inline std::optional<Format> format(uint32_t dxgi) {
533 const auto in = [&](uint32_t lo, uint32_t hi) { return dxgi >= lo && dxgi <= hi; };
534 if (in(1, 4)) return Format{16, 1, false};
535 if (in(9, 18)) return Format{8, 1, false};
536 if (in(19, 22) || in(44, 47)) return Format{4, 1, true};
537 if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) return Format{4, 1, false};
538 if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) return Format{2, 1, false};
539 if (in(118, 120)) return Format{2, 1, true};
540 if (in(60, 65)) return Format{1, 1, false};
541 if (in(70, 72) || in(79, 81)) return Format{8, 4, false};
542 if (in(73, 78) || in(82, 84) || in(94, 99)) return Format{16, 4, false};
543 return std::nullopt;
544}
545
546// A texture as the console allocates it: a D3D12-style description with a swizzle mode.
547struct TextureDesc {
548 Dimension dimension = Dimension::tex2d;
549 uint32_t width = 1, height = 1; // in texels
550 uint32_t depth_or_array = 1; // depth of a 3D texture, else the array size
551 uint32_t mips = 1; // 0: the full chain
552 uint32_t format = 0; // DXGI format number
553 uint32_t samples = 1;
554 uint32_t swizzle = kLinear;
555};
556
557struct Plane {
558 uint64_t offset = 0; // from the start of the texture
559 bool stencil = false;
560 Layout layout;
561};
562
563// Every data plane of a texture (depth, then stencil), placed one after the other. No compression metadata planes
564// (HTILE, CMASK, FMASK, DCC): the console adds them to render targets and depth buffers unless the description
565// denies them, so those are smaller here than on the console; the host GPU renders them, so nothing reads that
566// memory.
567struct Texture {
568 std::vector<Plane> planes;
569 uint64_t size = 0;
570 uint64_t alignment = 0;
571
572 static std::optional<Texture> make(const TextureDesc& desc) {
573 const auto f = format(desc.format);
574 if (!f) return std::nullopt;
575 const uint32_t depth3d = desc.dimension == Dimension::tex3d ? desc.depth_or_array : 1;
576 const uint32_t mips =
577 desc.mips ? desc.mips
578 : 32u - static_cast<uint32_t>(std::countl_zero(
579 std::max({desc.width, desc.height, depth3d, 1u})));
580 const auto plane = [&](uint32_t bytes) {
581 Desc d;
582 d.dimension = desc.dimension;
583 d.width = desc.width;
584 d.height = desc.height;
585 d.depth = desc.depth_or_array;
586 d.mips = mips;
587 d.element_bytes = bytes;
588 d.block = f->block;
589 d.samples = std::max(desc.samples, 1u);
590 d.swizzle = desc.swizzle;
591 return d;
592 };
593 Texture t;
594 auto main = Layout::make(plane(f->bytes));
595 if (!main) return std::nullopt;
596 t.planes.push_back({0, false, std::move(*main)});
597 if (f->stencil) {
598 auto s = Layout::make(plane(1));
599 if (!s) return std::nullopt;
600 const uint64_t a = s->alignment;
601 const uint64_t offset = (t.planes[0].layout.size + a - 1) / a * a;
602 t.planes.push_back({offset, true, std::move(*s)});
603 }
604 const Plane& last = t.planes.back();
605 t.size = last.offset + last.layout.size;
606 for (const Plane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment);
607 return t;
608 }
609};
610
611} // namespace leonida::console_texture
diff --git a/runtime/src/d3d12_xs_frame_events.h b/runtime/src/d3d12_xs_frame_events.h
new file mode 100644
index 000000000..b4a128fb9
--- /dev/null
+++ b/runtime/src/d3d12_xs_frame_events.h
@@ -0,0 +1,47 @@
1#pragma once
2
3// Portable Xbox Series D3D12 device slot 81 (GetFrameEventsX) ABI model (no Windows or Vulkan dependency).
4//
5// Observed call shape (static ABI inspection, offsets and stride only):
6// HRESULT GetFrameEventsX(uint64_t frameToken, uint32_t flags, uint32_t* pNumEvents, XboxFrameEvent* pEvents)
7//
8// Each output event record has stride 0x38 bytes:
9// +0x00: uint32_t event_type
10// +0x08: uint8_t status (0 = ok)
11// +0x18: uint64_t timestamp
12
13#include <cstddef>
14#include <cstdint>
15
16namespace leonida::d3d12_xs {
17
18// Device slot 81 (GetFrameEventsX) output event record (exact stride 0x38 bytes).
19struct XboxFrameEvent {
20 std::uint32_t event_type = 0; // +0x00
21 std::uint32_t reserved0 = 0; // +0x04
22 std::uint8_t status = 0; // +0x08 (0 = ok)
23 std::uint8_t pad[15] = {}; // +0x09..+0x17
24 std::uint64_t timestamp = 0; // +0x18
25 std::uint64_t reserved1[3] = {}; // +0x20..+0x37
26};
27static_assert(sizeof(XboxFrameEvent) == 0x38);
28static_assert(offsetof(XboxFrameEvent, event_type) == 0x00);
29static_assert(offsetof(XboxFrameEvent, status) == 0x08);
30static_assert(offsetof(XboxFrameEvent, timestamp) == 0x18);
31
32enum class FrameEventQueryStatus : std::uint32_t {
33 ok = 0,
34 null_count = 1,
35 null_buffer = 2,
36};
37
38// Validates GetFrameEventsX output parameters and reports zero pending frame events.
39// With no hardware flip-event history yet, reporting *num_events = 0 is cleanly handled by callers.
40inline FrameEventQueryStatus query_frame_events_empty(std::uint32_t* num_events, XboxFrameEvent* events) {
41 if (!num_events) return FrameEventQueryStatus::null_count;
42 if (*num_events > 0 && !events) return FrameEventQueryStatus::null_buffer;
43 *num_events = 0;
44 return FrameEventQueryStatus::ok;
45}
46
47} // namespace leonida::d3d12_xs
diff --git a/runtime/src/deferred_image_binding.h b/runtime/src/deferred_image_binding.h
new file mode 100644
index 000000000..668cf593d
--- /dev/null
+++ b/runtime/src/deferred_image_binding.h
@@ -0,0 +1,31 @@
1#pragma once
2
3#include <atomic>
4#include <mutex>
5
6namespace leonida {
7
8// A placed image can be named concurrently by command replay and descriptor creation.
9// Vulkan permits one successful bind for the lifetime of an ordinary image.
10class DeferredImageBinding {
11public:
12 using Bind = bool (*)(void*);
13 DeferredImageBinding(void* owner, Bind bind) : owner_(owner), bind_(bind) {}
14 bool bound() const { return bound_.load(std::memory_order_acquire); }
15 bool ensure() {
16 if (bound()) return true;
17 std::lock_guard lock(mutex_);
18 if (bound()) return true;
19 if (!bind_(owner_)) return false;
20 bound_.store(true, std::memory_order_release);
21 return true;
22 }
23
24private:
25 void* owner_;
26 Bind bind_;
27 std::mutex mutex_;
28 std::atomic<bool> bound_{false};
29};
30
31} // namespace leonida
diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h
index 10f0dada8..d32f975b2 100644
--- a/runtime/src/depth24_fragment.h
+++ b/runtime/src/depth24_fragment.h
@@ -37,12 +37,13 @@ struct Depth24Bias {
37 int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias 37 int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias
38 float slope = 0.0f; // SlopeScaledDepthBias 38 float slope = 0.0f; // SlopeScaledDepthBias
39 float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it 39 float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it
40 float levels = 16777215.0f;
40 bool any() const { return constant != 0 || slope != 0.0f; } 41 bool any() const { return constant != 0 || slope != 0.0f; }
41}; 42};
42 43
43// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1). 44// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1).
44inline float depth24_bias_constant(int bias) { 45inline float depth24_bias_constant(int bias, float levels=16777215.0f) {
45 return float(bias) * float(1.0 / 16777215.0); 46 return float(bias) * float(1.0 / double(levels));
46} 47}
47 48
48namespace spirv24 { 49namespace spirv24 {
@@ -141,7 +142,7 @@ private:
141// The edit, on a parsed module. Globals are collected first and spliced in at their section's end. 142// The edit, on a parsed module. Globals are collected first and spliced in at their section's end.
142class Patch { 143class Patch {
143public: 144public:
144 Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) { 145 Patch(Module& m, std::uint32_t entry, float levels) : m_(m), entry_(entry), levels_(levels) {
145 // Copies: apply() moves the module's instructions while the code at returns still looks types up. 146 // Copies: apply() moves the module's instructions while the code at returns still looks types up.
146 for (const Inst& i : m.insts()) { 147 for (const Inst& i : m.insts()) {
147 if (opcode(i) == op_function) break; 148 if (opcode(i) == op_function) break;
@@ -185,7 +186,7 @@ public:
185 void prime_quantise() { 186 void prime_quantise() {
186 t_bool(); 187 t_bool();
187 glsl(); 188 glsl();
188 for (float f : {16777215.0f, 0.0f}) f32(f); 189 for (float f : {levels_, 0.0f}) f32(f);
189 for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u); 190 for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u);
190 } 191 }
191 std::uint32_t f32(float f) { return constant(t_float(), bits(f)); } 192 std::uint32_t f32(float f) { return constant(t_float(), bits(f)); }
@@ -248,11 +249,11 @@ public:
248 std::uint32_t quantise(std::vector<Inst>& code, std::uint32_t z) { 249 std::uint32_t quantise(std::vector<Inst>& code, std::uint32_t z) {
249 const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool(); 250 const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool();
250 const std::uint32_t b = emit(code, op_bitcast, tu, {z}); 251 const std::uint32_t b = emit(code, op_bitcast, tu, {z});
251 const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)}); 252 const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(levels_)});
252 const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product}); 253 const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product});
253 // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there). 254 // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there).
254 const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}), 255 const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}),
255 f32(16777215.0f)}); 256 f32(levels_)});
256 const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe}); 257 const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe});
257 const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)}); 258 const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)});
258 const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid}); 259 const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid});
@@ -327,6 +328,7 @@ public:
327 } 328 }
328 329
329private: 330private:
331 float levels_;
330 Module& m_; 332 Module& m_;
331 std::uint32_t entry_; 333 std::uint32_t entry_;
332 std::vector<Inst> existing_; 334 std::vector<Inst> existing_;
@@ -369,7 +371,7 @@ inline std::vector<std::uint32_t> depth24_patch_fragment(const std::vector<std::
369 if (opcode(i) == op_function) break; 371 if (opcode(i) == op_function) break;
370 } 372 }
371 373
372 Patch p(m, entry); 374 Patch p(m, entry, bias.levels);
373 const std::uint32_t tf = p.t_float(); 375 const std::uint32_t tf = p.t_float();
374 p.prime_quantise(); 376 p.prime_quantise();
375 std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth); 377 std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth);
@@ -396,7 +398,7 @@ inline std::vector<std::uint32_t> depth24_patch_fragment(const std::vector<std::
396 const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})}); 398 const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})});
397 const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy}); 399 const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy});
398 std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope}); 400 std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope});
399 amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant))}); 401 amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant,bias.levels))});
400 if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)}); 402 if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)});
401 if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)}); 403 if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)});
402 z = p.emit(entry_code, op_f_add, tf, {z, amount}); 404 z = p.emit(entry_code, op_f_add, tf, {z, amount});
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
index 69857c4c6..a0d80968a 100644
--- a/runtime/src/descriptor_table.h
+++ b/runtime/src/descriptor_table.h
@@ -26,7 +26,19 @@ inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu;
26// S# key is 4 dwords followed by 4x 0xFFFFFFFF. 26// S# key is 4 dwords followed by 4x 0xFFFFFFFF.
27using DescriptorKey = std::array<std::uint32_t, 8>; 27using DescriptorKey = std::array<std::uint32_t, 8>;
28 28
29inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) { 29// Which hash the table, and every module it serves, probe with. Both run the same FNV-1a loop over the key's dwords;
30// fnv1a_fmix32 then finalizes it with MurmurHash3's fmix32, which spreads keys whose low FNV-1a bits cluster (the T#s
31// that differ only in a high nibble of dword 0 all land in one slot today). A translated index.json declares its
32// modules' kind in the per-module meta (`descriptor_hash`); the runtime picks one kind for its table before the first
33// insert and uses it for every insert, lookup, relocation and rehash.
34enum class DescriptorHashKind : std::uint8_t { fnv1a = 0, fnv1a_fmix32 = 1 };
35
36inline constexpr const char* descriptor_hash_kind_name(DescriptorHashKind kind) {
37 return kind == DescriptorHashKind::fnv1a_fmix32 ? "fnv1a_fmix32" : "fnv1a";
38}
39
40// The bare FNV-1a loop: the hash every module has probed with until the marker says otherwise.
41inline std::uint32_t hash_descriptor_key_fnv1a(const std::uint32_t key[8]) {
30 std::uint32_t h = kFnvOffsetBasis; 42 std::uint32_t h = kFnvOffsetBasis;
31 for (int i = 0; i < 8; ++i) { 43 for (int i = 0; i < 8; ++i) {
32 h = (h ^ key[i]) * kFnvPrime; 44 h = (h ^ key[i]) * kFnvPrime;
@@ -34,6 +46,30 @@ inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) {
34 return h; 46 return h;
35} 47}
36 48
49// MurmurHash3's fmix32 finalizer (logical shifts, arithmetic mod 2^32): what fnv1a_fmix32 applies after the FNV loop.
50inline std::uint32_t finalize_descriptor_hash(std::uint32_t h) {
51 h ^= h >> 16;
52 h *= 0x85EBCA6Bu;
53 h ^= h >> 13;
54 h *= 0xC2B2AE35u;
55 h ^= h >> 16;
56 return h;
57}
58
59inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8], DescriptorHashKind kind) {
60 const std::uint32_t h = hash_descriptor_key_fnv1a(key);
61 return kind == DescriptorHashKind::fnv1a_fmix32 ? finalize_descriptor_hash(h) : h;
62}
63
64inline std::uint32_t hash_descriptor_key(const DescriptorKey& key, DescriptorHashKind kind) {
65 return hash_descriptor_key(key.data(), kind);
66}
67
68// The old default, so a table or a test that does not name a kind keeps probing with bare FNV-1a.
69inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) {
70 return hash_descriptor_key(key, DescriptorHashKind::fnv1a);
71}
72
37inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) { 73inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) {
38 return hash_descriptor_key(key.data()); 74 return hash_descriptor_key(key.data());
39} 75}
@@ -69,7 +105,12 @@ class DescriptorTable {
69public: 105public:
70 enum class InsertResult { added, unchanged, replaced, added_with_relocation }; 106 enum class InsertResult { added, unchanged, replaced, added_with_relocation };
71 107
72 explicit DescriptorTable(std::uint32_t initial_capacity = 16) { 108 // `hash_kind` is the finalizer every insert, lookup, relocation and rehash of this table uses. It is fixed here,
109 // before the first insert: one table serves all the device's shaders, which all probe with the kind the device
110 // chose from their indexes (or LEONIDA_DESCRIPTOR_HASH). The default is the old bare FNV-1a.
111 explicit DescriptorTable(std::uint32_t initial_capacity = 16,
112 DescriptorHashKind hash_kind = DescriptorHashKind::fnv1a)
113 : hash_kind_(hash_kind) {
73 // Slots use nonnegative int indices internally. Larger powers also wrap the capacity counter. 114 // Slots use nonnegative int indices internally. Larger powers also wrap the capacity counter.
74 if (initial_capacity > max_capacity) throw std::length_error("Descriptor table capacity exceeds slot range"); 115 if (initial_capacity > max_capacity) throw std::length_error("Descriptor table capacity exceeds slot range");
75 std::uint32_t cap = 16; 116 std::uint32_t cap = 16;
@@ -78,6 +119,9 @@ public:
78 entries_.resize(cap); 119 entries_.resize(cap);
79 } 120 }
80 121
122 // The kind this table places and finds keys with (immutable after construction).
123 DescriptorHashKind hash_kind() const { return hash_kind_; }
124
81 // Inserts or updates a key -> index mapping. 125 // Inserts or updates a key -> index mapping.
82 // If the key already exists in one of the 8 probe slots, its index is updated. 126 // If the key already exists in one of the 8 probe slots, its index is updated.
83 // Try one bounded relocation before growing. Load never exceeds 50%. 127 // Try one bounded relocation before growing. Load never exceeds 50%.
@@ -99,7 +143,7 @@ public:
99 // Queries the index associated with key. Returns 0 if not found. 143 // Queries the index associated with key. Returns 0 if not found.
100 std::uint32_t lookup(const std::uint32_t key[8]) const { 144 std::uint32_t lookup(const std::uint32_t key[8]) const {
101 std::lock_guard lock(mutex_); 145 std::lock_guard lock(mutex_);
102 const std::uint32_t h = hash_descriptor_key(key); 146 const std::uint32_t h = hash_descriptor_key(key, hash_kind_);
103 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 147 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
104 const std::uint32_t slot = (h + k) & mask_; 148 const std::uint32_t slot = (h + k) & mask_;
105 const auto& entry = entries_[slot]; 149 const auto& entry = entries_[slot];
@@ -116,7 +160,7 @@ public:
116 160
117 bool contains(const std::uint32_t key[8]) const { 161 bool contains(const std::uint32_t key[8]) const {
118 std::lock_guard lock(mutex_); 162 std::lock_guard lock(mutex_);
119 const std::uint32_t h = hash_descriptor_key(key); 163 const std::uint32_t h = hash_descriptor_key(key, hash_kind_);
120 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 164 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
121 const std::uint32_t slot = (h + k) & mask_; 165 const std::uint32_t slot = (h + k) & mask_;
122 const auto& entry = entries_[slot]; 166 const auto& entry = entries_[slot];
@@ -249,7 +293,7 @@ private:
249 // to the first empty slot beyond that window, within its own eight probes. 293 // to the first empty slot beyond that window, within its own eight probes.
250 // A later hole is farther from every resident, so failure here is final for a single move. 294 // A later hole is farther from every resident, so failure here is final for a single move.
251 // `moved_to` receives the hole the resident moved into, so the caller can mark that slot changed too. 295 // `moved_to` receives the hole the resident moved into, so the caller can mark that slot changed too.
252 static int make_probe_slot(std::vector<DescriptorEntry>& entries, std::uint32_t hash, 296 static int make_probe_slot(std::vector<DescriptorEntry>& entries, std::uint32_t hash, DescriptorHashKind kind,
253 std::uint32_t* moved_to = nullptr) { 297 std::uint32_t* moved_to = nullptr) {
254 const auto mask = static_cast<std::uint32_t>(entries.size() - 1); 298 const auto mask = static_cast<std::uint32_t>(entries.size() - 1);
255 for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) { 299 for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) {
@@ -257,7 +301,7 @@ private:
257 if (entries[hole].pad == kSlotOccupiedMarker) continue; 301 if (entries[hole].pad == kSlotOccupiedMarker) continue;
258 for (auto k = kDescriptorProbes; k > 0; --k) { 302 for (auto k = kDescriptorProbes; k > 0; --k) {
259 const auto slot = (hash + k - 1) & mask; 303 const auto slot = (hash + k - 1) & mask;
260 const auto home = hash_descriptor_key(entries[slot].key); 304 const auto home = hash_descriptor_key(entries[slot].key, kind);
261 if (((hole - home) & mask) < kDescriptorProbes) { 305 if (((hole - home) & mask) < kDescriptorProbes) {
262 entries[hole] = entries[slot]; 306 entries[hole] = entries[slot];
263 if (moved_to) *moved_to = hole; 307 if (moved_to) *moved_to = hole;
@@ -271,7 +315,7 @@ private:
271 315
272 InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index) { 316 InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index) {
273 while (true) { 317 while (true) {
274 const std::uint32_t h = hash_descriptor_key(key); 318 const std::uint32_t h = hash_descriptor_key(key, hash_kind_);
275 int empty_slot = -1; 319 int empty_slot = -1;
276 320
277 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 321 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
@@ -300,14 +344,14 @@ private:
300 std::uint32_t same_hash = 0; 344 std::uint32_t same_hash = 0;
301 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 345 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
302 const auto& entry = entries_[(h + k) & mask_]; 346 const auto& entry = entries_[(h + k) & mask_];
303 if (hash_descriptor_key(entry.key) == h) ++same_hash; 347 if (hash_descriptor_key(entry.key, hash_kind_) == h) ++same_hash;
304 } 348 }
305 if (same_hash == kDescriptorProbes) 349 if (same_hash == kDescriptorProbes)
306 throw std::length_error("Descriptor hash collision exceeds shader probe limit"); 350 throw std::length_error("Descriptor hash collision exceeds shader probe limit");
307 } 351 }
308 const bool relocate = empty_slot < 0; 352 const bool relocate = empty_slot < 0;
309 std::uint32_t moved_to = 0; 353 std::uint32_t moved_to = 0;
310 if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to); 354 if (relocate) empty_slot = make_probe_slot(entries_, h, hash_kind_, &moved_to);
311 if (empty_slot >= 0) { 355 if (empty_slot >= 0) {
312 auto& entry = entries_[empty_slot]; 356 auto& entry = entries_[empty_slot];
313 std::memcpy(entry.key, key, sizeof(entry.key)); 357 std::memcpy(entry.key, key, sizeof(entry.key));
@@ -324,7 +368,7 @@ private:
324 } 368 }
325 369
326 bool erase_locked(const std::uint32_t key[8]) { 370 bool erase_locked(const std::uint32_t key[8]) {
327 const std::uint32_t h = hash_descriptor_key(key); 371 const std::uint32_t h = hash_descriptor_key(key, hash_kind_);
328 std::uint32_t found_slot = 0; 372 std::uint32_t found_slot = 0;
329 bool found = false; 373 bool found = false;
330 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 374 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
@@ -355,7 +399,7 @@ private:
355 399
356 for (const auto& old : entries_) { 400 for (const auto& old : entries_) {
357 if (old.pad != kSlotOccupiedMarker) continue; 401 if (old.pad != kSlotOccupiedMarker) continue;
358 const std::uint32_t h = hash_descriptor_key(old.key); 402 const std::uint32_t h = hash_descriptor_key(old.key, hash_kind_);
359 int slot = -1; 403 int slot = -1;
360 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 404 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
361 const std::uint32_t s = (h + k) & new_mask; 405 const std::uint32_t s = (h + k) & new_mask;
@@ -364,7 +408,7 @@ private:
364 break; 408 break;
365 } 409 }
366 } 410 }
367 if (slot < 0) slot = make_probe_slot(new_entries, h); 411 if (slot < 0) slot = make_probe_slot(new_entries, h, hash_kind_);
368 if (slot < 0) { 412 if (slot < 0) {
369 rehash_ok = false; 413 rehash_ok = false;
370 break; 414 break;
@@ -386,6 +430,7 @@ private:
386 430
387 static constexpr std::uint32_t max_capacity = std::uint32_t{1} << 31; 431 static constexpr std::uint32_t max_capacity = std::uint32_t{1} << 31;
388 mutable std::mutex mutex_; 432 mutable std::mutex mutex_;
433 const DescriptorHashKind hash_kind_;
389 std::uint32_t mask_ = 15; 434 std::uint32_t mask_ = 15;
390 std::vector<DescriptorEntry> entries_; 435 std::vector<DescriptorEntry> entries_;
391 std::size_t occupied_count_ = 0; 436 std::size_t occupied_count_ = 0;
diff --git a/runtime/src/dstorage_swizzle.h b/runtime/src/dstorage_swizzle.h
new file mode 100644
index 000000000..45186fcf8
--- /dev/null
+++ b/runtime/src/dstorage_swizzle.h
@@ -0,0 +1,29 @@
1#pragma once
2#include <cstdint>
3#include <cstring>
4#include <span>
5
6namespace leonida::dstorage {
7// The public Xbox-GDK-Samples DirectStorageTextureShuffling example stores each BC component
8// plane across the whole request. The MDU interleaves a stripe of each plane per group. The
9// sample's compute shader does the remaining intra-group shuffle; surface tiling is already baked in.
10inline constexpr unsigned stripes[][5] = {{}, {1, 1, 2}, {1, 1, 6}, {1, 3, 1, 1, 2}, {1, 3, 1, 3}};
11
12inline size_t group_size(unsigned mode) { return mode == 1 ? 16384 : 32768; }
13
14inline bool unshuffle(unsigned mode, std::span<const uint8_t> input, std::span<uint8_t> out) {
15 if (!mode || mode > 4 || input.size() != out.size() || input.size() % group_size(mode)) return false;
16 const size_t group = group_size(mode), groups = input.size() / group;
17 size_t source = 0, offset = 0;
18 for (unsigned pages : stripes[mode]) {
19 if (!pages) break;
20 const size_t bytes = pages * 4096;
21 for (size_t i = 0; i < groups; ++i) {
22 std::memcpy(out.data() + i * group + offset, input.data() + source, bytes);
23 source += bytes;
24 }
25 offset += bytes;
26 }
27 return true;
28}
29} // namespace leonida::dstorage
diff --git a/runtime/src/dstorage_trace.h b/runtime/src/dstorage_trace.h
new file mode 100644
index 000000000..3c2eda217
--- /dev/null
+++ b/runtime/src/dstorage_trace.h
@@ -0,0 +1,12 @@
1#pragma once
2#include <windows.h>
3
4namespace leonida::dstorage {
5inline bool trace_enabled() {
6 static const bool enabled = [] {
7 char value[2]{};
8 return GetEnvironmentVariableA("LEONIDA_DSTORAGE_TRACE", value, sizeof value) == 1 && value[0] == '1';
9 }();
10 return enabled;
11}
12} // namespace leonida::dstorage
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index afeaf191e..2c9f1fd7e 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -1,4 +1,6 @@
1#pragma once 1#pragma once
2#include <utility>
3#include <memory>
2 4
3// Frame pacing for the Xbox presentation path (docs/d3d12_vulkan.md section 4.5): what SetFrameIntervalX, 5// Frame pacing for the Xbox presentation path (docs/d3d12_vulkan.md section 4.5): what SetFrameIntervalX,
4// ScheduleFrameEventX, WaitFrameEventX and GetFrameStatisticsX do, and the token check and flip bookkeeping that 6// ScheduleFrameEventX, WaitFrameEventX and GetFrameStatisticsX do, and the token check and flip bookkeeping that
@@ -39,7 +41,9 @@
39#include <deque> 41#include <deque>
40#include <functional> 42#include <functional>
41#include <limits> 43#include <limits>
44#include <memory>
42#include <mutex> 45#include <mutex>
46#include <utility>
43#include <vector> 47#include <vector>
44 48
45namespace leonida { 49namespace leonida {
@@ -113,6 +117,7 @@ inline constexpr std::uint32_t frame_event_flip = 2;
113inline constexpr std::uint32_t frame_event_count = 3; 117inline constexpr std::uint32_t frame_event_count = 3;
114// Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE). 118// Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE).
115inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2; 119inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2;
120inline constexpr std::uint32_t wait_flag_current_token = frame_wait_flag_token_on_timeout;
116// Statistics types (bit mask). Interval and render entries are never produced here. 121// Statistics types (bit mask). Interval and render entries are never produced here.
117inline constexpr std::uint32_t stat_frame_interval = 0x01; 122inline constexpr std::uint32_t stat_frame_interval = 0x01;
118inline constexpr std::uint32_t stat_frame_event = 0x02; 123inline constexpr std::uint32_t stat_frame_event = 0x02;
@@ -171,9 +176,21 @@ struct FramePacingSummary {
171 std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us 176 std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us
172}; 177};
173 178
179class FrameTokenSource {
180public:
181 std::uint64_t issue() { return last_.fetch_add(1, std::memory_order_acq_rel) + 1; }
182 std::uint64_t issued() const { return last_.load(std::memory_order_acquire); }
183
184private:
185 std::atomic<std::uint64_t> last_{0};
186};
187
174class FramePacer { 188class FramePacer {
175public: 189public:
176 explicit FramePacer(FrameClock& clock) : clock_(clock) { 190 explicit FramePacer(FrameClock& clock, std::shared_ptr<FrameTokenSource> tokens = nullptr,
191 bool current_origin_poll = false)
192 : clock_(clock), tokens_(tokens ? std::move(tokens) : std::make_shared<FrameTokenSource>()),
193 current_origin_poll_(current_origin_poll) {
177 clock_.set_wake([this] { 194 clock_.set_wake([this] {
178 { std::lock_guard guard(mutex_); } 195 { std::lock_guard guard(mutex_); }
179 cv_.notify_all(); 196 cv_.notify_all();
@@ -239,6 +256,8 @@ public:
239 if (event >= frame_event_count) return pacer_hr::invalid_arg; 256 if (event >= frame_event_count) return pacer_hr::invalid_arg;
240 if (event == frame_event_origin && !token) return pacer_hr::invalid_arg; 257 if (event == frame_event_origin && !token) return pacer_hr::invalid_arg;
241 std::unique_lock lock(mutex_); 258 std::unique_lock lock(mutex_);
259 if (current_origin_poll_ && event == frame_event_origin && timeout_ms == 0 && (flags & wait_flag_current_token))
260 return current_token_locked(token);
242 ++waiters_; 261 ++waiters_;
243 const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token); 262 const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token);
244 if (--waiters_ == 0) cv_.notify_all(); 263 if (--waiters_ == 0) cv_.notify_all();
@@ -295,7 +314,7 @@ public:
295 std::lock_guard guard(mutex_); 314 std::lock_guard guard(mutex_);
296 if (issue) *issue = TokenIssue::none; 315 if (issue) *issue = TokenIssue::none;
297 if (suspended_) return pacer_hr::invalid_state; 316 if (suspended_) return pacer_hr::invalid_state;
298 if (token > issued_) return pacer_hr::invalid_arg; 317 if (token > tokens_->issued()) return pacer_hr::invalid_arg;
299 if (issue) { 318 if (issue) {
300 if (token == 0) *issue = TokenIssue::null_token; 319 if (token == 0) *issue = TokenIssue::null_token;
301 else if (token == last_presented_) *issue = TokenIssue::repeated; 320 else if (token == last_presented_) *issue = TokenIssue::repeated;
@@ -394,7 +413,8 @@ public:
394 } 413 }
395 414
396 bool suspended() const { std::lock_guard guard(mutex_); return suspended_; } 415 bool suspended() const { std::lock_guard guard(mutex_); return suspended_; }
397 std::uint64_t tokens_issued() const { std::lock_guard guard(mutex_); return issued_; } 416 std::uint64_t tokens_issued() const { return tokens_->issued(); }
417 const std::shared_ptr<FrameTokenSource>& token_source() const { return tokens_; }
398 std::uint32_t frames_in_flight() { 418 std::uint32_t frames_in_flight() {
399 std::lock_guard guard(mutex_); 419 std::lock_guard guard(mutex_);
400 retire_locked(clock_.now_us()); 420 retire_locked(clock_.now_us());
@@ -500,12 +520,30 @@ private:
500 } 520 }
501 } 521 }
502 522
523 std::int32_t current_token_locked(std::uint64_t* token) {
524 if (shutdown_ || suspended_) return pacer_hr::invalid_state;
525 if (!interval_set_ || !event_armed_[frame_event_origin]) {
526 *token = tokens_->issue();
527 return pacer_hr::ok;
528 }
529 const auto now = clock_.now_us();
530 retire_locked(now);
531 const auto offset = event_offset_us_[frame_event_origin];
532 const auto first = epoch_us_ + offset;
533 const auto newest = now >= first ? static_cast<std::int64_t>((now - first) / period_us_) : 0;
534 auto& tick = last_event_tick_[frame_event_origin];
535 tick = std::max(tick, newest);
536 const auto origin = first + static_cast<std::uint64_t>(tick) * period_us_;
537 *token = issue_token_locked(origin, origin - offset + period_us_);
538 return pacer_hr::ok;
539 }
540
503 bool any_armed_locked() const { 541 bool any_armed_locked() const {
504 return event_armed_[0] || event_armed_[1] || event_armed_[2]; 542 return event_armed_[0] || event_armed_[1] || event_armed_[2];
505 } 543 }
506 544
507 std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) { 545 std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) {
508 const std::uint64_t tok = ++issued_; 546 const std::uint64_t tok = tokens_->issue(); // the shared token source (the device proxy and PresentX pace with it)
509 Record record; 547 Record record;
510 record.token = tok; 548 record.token = tok;
511 record.origin_us = origin_us; 549 record.origin_us = origin_us;
@@ -580,7 +618,8 @@ private:
580 std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0}; 618 std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0};
581 std::uint64_t epoch_us_ = 0; 619 std::uint64_t epoch_us_ = 0;
582 std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed 620 std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed
583 std::uint64_t issued_ = 0; 621 std::shared_ptr<FrameTokenSource> tokens_;
622 bool current_origin_poll_ = false;
584 std::uint64_t last_presented_ = 0; 623 std::uint64_t last_presented_ = 0;
585 std::uint64_t immediate_presents_ = 0; 624 std::uint64_t immediate_presents_ = 0;
586 std::uint64_t presents_recorded_ = 0; 625 std::uint64_t presents_recorded_ = 0;
diff --git a/runtime/src/fsdraw_probe.h b/runtime/src/fsdraw_probe.h
new file mode 100644
index 000000000..38c0ca58c
--- /dev/null
+++ b/runtime/src/fsdraw_probe.h
@@ -0,0 +1,236 @@
1#pragma once
2
3// LOCAL DIAGNOSTIC (not for upstream): fsdraw probe. Follows the title's fullscreen draws back from the backbuffer:
4// what each pipeline is (shaders, target formats, blend, write mask), what the draw's descriptor tables hold on the
5// CPU and what the GPU address arena holds at the same VA (the shader's heap_base + VA), which T#s have a bindless
6// entry, and which render targets the present-probe should read back as well.
7
8#include <array>
9#include <atomic>
10#include <cstdint>
11#include <cstdio>
12#include <cstring>
13#include <cstdlib>
14#include <mutex>
15#include <set>
16#include <string>
17#include <unordered_map>
18#include <vector>
19
20namespace leonida::fsdraw {
21
22struct State {
23 std::mutex mutex;
24 std::unordered_map<std::uintptr_t, std::string> pipelines; // graphics PSO id -> description
25 std::set<std::array<std::uint32_t, 8>> tsharps; // T#s that have a bindless entry
26 const std::uint8_t* arena = nullptr; // the GPU address arena's host mapping
27 std::uint64_t arena_size = 0;
28 std::vector<std::uint64_t> readback; // render targets of fullscreen draws (besides the presented source)
29 std::uint64_t presented_source = 0;
30 std::unordered_map<std::uint64_t, std::uint64_t> table_origin; // translated table VA -> title VA
31 std::unordered_map<std::uint64_t, std::pair<std::uint64_t, std::uint32_t>> cbv_origin; // V# base -> location, size
32};
33
34inline State& state() {
35 static State s;
36 return s;
37}
38
39inline void note_pipeline(std::uintptr_t id, std::string text) {
40 std::lock_guard lock(state().mutex);
41 state().pipelines[id] = std::move(text);
42}
43
44inline std::size_t pipeline_count() { // LOCAL DIAGNOSTIC (mem probe)
45 std::lock_guard lock(state().mutex);
46 return state().pipelines.size();
47}
48
49inline std::string pipeline(std::uintptr_t id) {
50 std::lock_guard lock(state().mutex);
51 const auto it = state().pipelines.find(id);
52 return it == state().pipelines.end() ? std::string("(not registered)") : it->second;
53}
54
55inline void note_tsharp(const std::uint32_t* words) {
56 std::array<std::uint32_t, 8> key{};
57 std::memcpy(key.data(), words, sizeof(key));
58 std::lock_guard lock(state().mutex);
59 state().tsharps.insert(key);
60}
61
62inline bool has_tsharp(const std::uint32_t* words) {
63 std::array<std::uint32_t, 8> key{};
64 std::memcpy(key.data(), words, sizeof(key));
65 std::lock_guard lock(state().mutex);
66 return state().tsharps.count(key) != 0;
67}
68
69inline void note_arena(const std::uint8_t* mapped, std::uint64_t size) {
70 std::lock_guard lock(state().mutex);
71 state().arena = mapped;
72 state().arena_size = size;
73}
74
75// A test or application may create multiple devices. Never inspect a released
76// mapping; destroying an older device must leave the current mapping alone.
77inline void forget_arena(const std::uint8_t* mapped) {
78 std::lock_guard lock(state().mutex);
79 if (state().arena == mapped) {
80 state().arena = nullptr;
81 state().arena_size = 0;
82 }
83}
84
85// A render target a fullscreen draw wrote: the present-probe reads it back with the source (at most 4 kept).
86inline void note_target(std::uint64_t id) {
87 if (!id) return;
88 std::lock_guard lock(state().mutex);
89 auto& r = state().readback;
90 for (const std::uint64_t x : r)
91 if (x == id) return;
92 if (r.size() < 4) r.push_back(id);
93}
94
95inline std::vector<std::uint64_t> targets() {
96 std::lock_guard lock(state().mutex);
97 return state().readback;
98}
99
100inline void note_table(std::uint64_t translated, std::uint64_t original) {
101 std::lock_guard lock(state().mutex);
102 auto& m = state().table_origin;
103 if (m.size() > 8192) m.clear();
104 m[translated] = original;
105}
106
107inline std::uint64_t table_origin(std::uint64_t va) {
108 std::lock_guard lock(state().mutex);
109 const auto it = state().table_origin.find(va);
110 return it == state().table_origin.end() ? va : it->second;
111}
112
113inline void note_cbv(std::uint64_t base, std::uint64_t location, std::uint32_t size) {
114 std::lock_guard lock(state().mutex);
115 auto& m = state().cbv_origin;
116 if (m.size() > 8192) m.clear();
117 m[base] = {location, size};
118}
119
120inline bool cbv_origin(std::uint64_t base, std::uint64_t& location) {
121 std::lock_guard lock(state().mutex);
122 const auto it = state().cbv_origin.find(base);
123 if (it == state().cbv_origin.end()) return false;
124 location = it->second.first;
125 return true;
126}
127
128inline std::string hex_words(const std::uint32_t* w, std::size_t n) {
129 std::string s;
130 char b[16];
131 for (std::size_t i = 0; i < n; ++i) {
132 std::snprintf(b, sizeof b, i ? " %08x" : "%08x", w[i]);
133 s += b;
134 }
135 return s;
136}
137
138// The 8 dwords at arena offset `va`, if the arena holds them.
139inline bool arena_words(std::uint64_t va, std::uint32_t* out, std::size_t n) {
140 std::lock_guard lock(state().mutex);
141 const State& s = state();
142 if (!s.arena || va + n * 4 > s.arena_size || va + n * 4 < va) return false;
143 std::memcpy(out, s.arena + va, n * 4);
144 return true;
145}
146
147inline std::uint64_t arena_size() {
148 std::lock_guard lock(state().mutex);
149 return state().arena_size;
150}
151
152// Logs one descriptor table: `cpu` is the layer's host view of the slot at `va` (null when no heap holds `va`).
153// For each slot: the CPU bytes, the arena bytes at the same VA (what a shader's heap_base + VA loads), and what the
154// CPU bytes are (null, V# with its base, or T# with whether it has a bindless entry). A V# whose base is inside the
155// arena has its first 16 dwords printed from the arena.
156inline void describe_table(const char* tag, std::uint64_t va, std::uint32_t slots, const std::uint8_t* cpu,
157 const char* heap_kind) {
158 const std::uint32_t shown = slots < 4 ? slots : 4;
159 std::fprintf(stderr, "[rt] fsdraw: %s table va 0x%llx slots %u heap %s (arena size 0x%llx)\n", tag,
160 static_cast<unsigned long long>(va), slots, heap_kind, static_cast<unsigned long long>(arena_size()));
161 for (std::uint32_t i = 0; i < shown; ++i) {
162 const std::uint64_t at = va + std::uint64_t(i) * 32;
163 std::uint32_t c[8]{}, g[8]{};
164 const bool have_cpu = cpu != nullptr;
165 if (have_cpu) std::memcpy(c, cpu + std::size_t(i) * 32, sizeof c);
166 const bool have_gpu = arena_words(at, g, 8);
167 const bool same = have_cpu && have_gpu && std::memcmp(c, g, sizeof c) == 0;
168 std::fprintf(stderr, "[rt] fsdraw: %s slot %u cpu [%s] gpu [%s]%s\n", tag, i,
169 have_cpu ? hex_words(c, 8).c_str() : "no heap", have_gpu ? hex_words(g, 8).c_str() : "OUT OF ARENA",
170 have_cpu && have_gpu ? (same ? " (same)" : " (DIFFER)") : "");
171 const std::uint32_t* w = have_cpu ? c : have_gpu ? g : nullptr;
172 if (!w) continue;
173 if (!(w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) {
174 std::fprintf(stderr, "[rt] fsdraw: %s slot %u is null\n", tag, i);
175 continue;
176 }
177 if (!(w[3] >> 30)) { // buffer V# (TYPE in dword 3 bits 30-31 is 0)
178 const std::uint64_t base = std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32);
179 const std::uint32_t stride = (w[1] >> 16) & 0x3FFFu;
180 std::uint32_t data[16]{};
181 const bool in_arena = arena_words(base, data, 16);
182 std::size_t nonzero = 0;
183 if (in_arena) {
184 std::vector<std::uint32_t> all(std::min<std::uint32_t>(w[2] ? w[2] : 256, 4096) / 4);
185 if (!all.empty() && arena_words(base, all.data(), all.size()))
186 for (const std::uint32_t x : all) nonzero += x != 0;
187 }
188 std::uint64_t location = 0;
189 const bool made = cbv_origin(base, location);
190 std::fprintf(stderr, "[rt] fsdraw: %s slot %u V# base 0x%llx stride %u records %u -> %s [%s] nonzero dwords "
191 "%zu%s\n",
192 tag, i, static_cast<unsigned long long>(base), stride, w[2],
193 in_arena ? "arena" : "outside the arena buffer", in_arena ? hex_words(data, 16).c_str() : "",
194 nonzero, made ? "" : " (no CreateConstantBufferView made this V#)");
195 if (made && !in_arena && location) { // the CB as the title wrote it (title memory, CPU view)
196 std::uint32_t cb[16]{};
197 std::memcpy(cb, reinterpret_cast<const void*>(static_cast<std::uintptr_t>(location)), sizeof cb);
198 std::fprintf(stderr, "[rt] fsdraw: %s slot %u CB at title 0x%llx: [%s]\n", tag, i,
199 static_cast<unsigned long long>(location), hex_words(cb, 16).c_str());
200 }
201 } else {
202 std::fprintf(stderr, "[rt] fsdraw: %s slot %u T# bindless entry %s\n", tag, i,
203 has_tsharp(w) ? "yes" : "NO (a lookup misses: index 0, zeros)");
204 }
205 }
206}
207
208// LEONIDA_FSDRAW_POKE_CB=1 (experiment): before a submission, the CB that a bound table's slot-0 V# names gets a
209// known colour in dwords 8..11 (what PS_BlitColour multiplies the vertex colour by), written into the title's own
210// copy. A non-zero render target afterwards proves table -> V# -> CB -> pixel shader -> target works on the GPU.
211inline bool poke_enabled() {
212 static const bool on = [] {
213 const char* v = std::getenv("LEONIDA_FSDRAW_POKE_CB");
214 return v && *v && *v != '0';
215 }();
216 return on;
217}
218
219inline void poke_cb(const std::uint8_t* table_cpu) {
220 if (!table_cpu || !poke_enabled()) return;
221 std::uint32_t w[4];
222 std::memcpy(w, table_cpu, sizeof w);
223 if (!(w[0] | w[1] | w[2] | w[3]) || (w[3] >> 30) || w[2] < 48) return;
224 const std::uint64_t base = std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32);
225 std::uint64_t location = 0;
226 if (!cbv_origin(base, location) || !location) return;
227 const float colour[4] = {1.0f, 0.5f, 0.25f, 1.0f};
228 std::memcpy(reinterpret_cast<void*>(static_cast<std::uintptr_t>(location + 32)), colour, sizeof colour);
229 static std::atomic<std::uint64_t> poked{0};
230 const std::uint64_t n = ++poked;
231 if (n <= 4 || n % 600 == 0)
232 std::fprintf(stderr, "[rt] fsdraw: POKE #%llu: CB at title 0x%llx dwords 8..11 = 1.0 0.5 0.25 1.0\n",
233 static_cast<unsigned long long>(n), static_cast<unsigned long long>(location));
234}
235
236} // namespace leonida::fsdraw
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index a4a9b4448..9dad4ed7a 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -146,6 +146,26 @@ inline ImageWords encode(const Image& image) {
146// TYPE names an image, so these eight dwords are a T# and not a V# followed by something else. 146// TYPE names an image, so these eight dwords are a T# and not a V# followed by something else.
147inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; } 147inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; }
148 148
149// Synthetic volume UAV metadata distinguishes the storage view from SRVs of the same mip, and distinct W
150// ranges from one another. Sampled fetches use it because Vulkan only applies slicing to storage views.
151// WORD4[31] is reserved on GFX10/GFX103; hardware uses WORD7 for metadata addresses. DEPTH and BASE_ARRAY
152// stay unchanged. D3D12 depth is at most 2048, so count - 1 and offset fit 11 bits.
153inline constexpr std::uint32_t volume_uav_flag = 0x80000000;
154inline constexpr std::uint32_t volume_uav_tag = 0xD7800000;
155inline constexpr std::uint32_t volume_uav_tag_mask = 0xff800000;
156// RGB9E5 emulation uses R32_UINT storage, not the logical float format in T# word 1. The same tag marks packed
157// 1D-family UAVs (without a W range). No ordinary SRV or raw hardware T# has this synthetic metadata.
158inline constexpr std::uint32_t packed_uav_flag = 0x00400000;
159inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) {
160 return volume_uav_tag | ((count - 1) << 11) | offset;
161}
162inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) {
163 const auto mip_depth = image.depth >> image.first_mip;
164 return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) &&
165 (words[7] & volume_uav_tag_mask) == volume_uav_tag &&
166 (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u);
167}
168
149inline constexpr float image_min_lod(const ImageWords& words) { 169inline constexpr float image_min_lod(const ImageWords& words) {
150 return float(detail::get(words[1], 8, 12)) / 256.0f; 170 return float(detail::get(words[1], 8, 12)) / 256.0f;
151} 171}
@@ -218,6 +238,7 @@ struct FormatRow {
218}; 238};
219 239
220inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one}; 240inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one};
241inline constexpr Swizzle channels_a{select_zero, select_zero, select_zero, select_x};
221inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one}; 242inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one};
222inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one}; 243inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one};
223inline constexpr Swizzle channels_rgba = identity_swizzle; 244inline constexpr Swizzle channels_rgba = identity_swizzle;
@@ -227,6 +248,10 @@ inline constexpr Swizzle channels_abgr{select_w, select_z, select_y, select_x};
227 248
228inline constexpr FormatRow format_table[] = { 249inline constexpr FormatRow format_table[] = {
229 {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM 250 {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM
251#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
252 // An A8 render target: the same console format as the R8 row above, in the image format that can be rendered to.
253 {1, VK_FORMAT_A8_UNORM_KHR, channels_a}, // GFX10_FORMAT_8_UNORM
254#endif
230 {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM 255 {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM
231 {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED 256 {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED
232 {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED 257 {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED
@@ -379,6 +404,13 @@ inline constexpr VkFormat vulkan_view_format(VkFormat image_format, std::uint32_
379 if (!image) return VK_FORMAT_UNDEFINED; 404 if (!image) return VK_FORMAT_UNDEFINED;
380 if (image->gfx10 == gfx10_format) return image_format; 405 if (image->gfx10 == gfx10_format) return image_format;
381 if (is_depth_stencil_format(image_format)) return VK_FORMAT_UNDEFINED; 406 if (is_depth_stencil_format(image_format)) return VK_FORMAT_UNDEFINED;
407 // An R9G9B9E5 render target on a GPU that cannot render to E5B9G9R9 is an R11G11B10F image (the D3D12 device's
408 // r9g9b9e5_target_stand_in): a T# that names 5_9_9_9 views it in the image's own format. The image is not
409 // mutable, and the two formats have the same channels, so the swizzle is unchanged.
410 if (image_format == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && gfx10_format == 132) return image_format;
411 // The same for a B4G4R4A4 render target stored as BGRA8 (b4g4r4a4_target_stand_in): 4_4_4_4 names its channels
412 // in the order BGRA8 has them.
413 if (image_format == VK_FORMAT_B8G8R8A8_UNORM && gfx10_format == 136) return image_format;
382 const FormatRow* fallback = nullptr; 414 const FormatRow* fallback = nullptr;
383 for (const FormatRow& row : format_table) { 415 for (const FormatRow& row : format_table) {
384 if (row.gfx10 != gfx10_format || is_depth_stencil_format(row.vulkan)) continue; 416 if (row.gfx10 != gfx10_format || is_depth_stencil_format(row.vulkan)) continue;
diff --git a/runtime/src/gpu_label_memory.h b/runtime/src/gpu_label_memory.h
new file mode 100644
index 000000000..744622087
--- /dev/null
+++ b/runtime/src/gpu_label_memory.h
@@ -0,0 +1,94 @@
1#pragma once
2#include <cstdint>
3#include <map>
4#include <memory>
5#include <mutex>
6#include <limits>
7
8namespace leonida::label {
9struct Region {
10 std::uintptr_t begin, end, allocation_base;
11 bool heap;
12 std::uint64_t generation = 1;
13};
14struct Target {
15 std::weak_ptr<const Region> owner;
16 std::uintptr_t address = 0;
17 unsigned bytes = 0;
18 std::uint64_t generation = 0;
19};
20struct Write {
21 Target target;
22 std::uint64_t value{};
23 unsigned clock{}; // 0: supplied value; 1: GPU timestamp; 2: system timestamp
24};
25class Memory {
26 std::mutex mutex_;
27 std::map<std::uintptr_t, std::shared_ptr<Region>> regions_;
28
29 public:
30 void track(std::uintptr_t base, std::uintptr_t bytes, std::uintptr_t allocation_base, bool heap) {
31 if (!base || !bytes || !allocation_base || bytes > std::numeric_limits<std::uintptr_t>::max() - base) return;
32 const auto end = base + bytes;
33 std::lock_guard lock(mutex_);
34 auto previous = regions_.upper_bound(base);
35 if (!heap && previous != regions_.begin()) {
36 --previous;
37 const auto &r = *previous->second;
38 if (!r.heap && r.allocation_base == allocation_base && base >= r.begin && end <= r.end) return;
39 }
40 regions_[base] = std::make_shared<Region>(Region{base, end, allocation_base, heap});
41 }
42 void release_heap(std::uintptr_t base) {
43 std::lock_guard lock(mutex_);
44 regions_.erase(base);
45 }
46 template <class Release>
47 bool release_pages(std::uintptr_t base, std::uintptr_t bytes, bool entire, Release &&release) {
48 std::lock_guard lock(mutex_);
49 if (!release()) return false;
50 for (auto i = regions_.begin(); i != regions_.end();) {
51 const auto &r = *i->second;
52 if (r.heap || (entire ? r.allocation_base != base
53 : (!bytes ? r.allocation_base != base
54 : (base >= r.end || (base < r.begin && r.begin - base >= bytes))))) {
55 ++i;
56 continue;
57 }
58 if (entire || i->second->generation == std::numeric_limits<std::uint64_t>::max())
59 i = regions_.erase(i);
60 else {
61 ++i->second->generation;
62 ++i;
63 }
64 }
65 return true;
66 }
67 Target capture(std::uintptr_t address, unsigned bytes) {
68 if ((bytes != 4 && bytes != 8) || (address & (bytes - 1))) return {};
69 std::lock_guard lock(mutex_);
70 auto it = regions_.upper_bound(address);
71 while (it != regions_.begin()) {
72 --it;
73 const auto &r = *it->second;
74 if (address < r.end && r.end - address >= bytes) return {it->second, address, bytes, r.generation};
75 }
76 return {};
77 }
78 template <class Store> bool publish(const Target &target, Store &&store) {
79 std::lock_guard lock(mutex_);
80 const auto region = target.owner.lock();
81 if (!region || target.generation != region->generation || (target.bytes != 4 && target.bytes != 8) ||
82 (target.address & (target.bytes - 1)) || target.address < region->begin || target.address >= region->end ||
83 region->end - target.address < target.bytes)
84 return false;
85 const auto it = regions_.find(region->begin);
86 if (it == regions_.end() || it->second != region) return false;
87 return store(target.address, target.bytes, region->allocation_base);
88 }
89};
90inline Memory &memory() {
91 static Memory m;
92 return m;
93}
94} // namespace leonida::label
diff --git a/runtime/src/image_memory.h b/runtime/src/image_memory.h
new file mode 100644
index 000000000..3a473192b
--- /dev/null
+++ b/runtime/src/image_memory.h
@@ -0,0 +1,231 @@
1#pragma once
2
3// Memory for textures, handed out as ranges of larger blocks instead of one driver allocation each. Making and freeing
4// an allocation is a kernel call that costs tens to hundreds of microseconds, where a range costs a map lookup; a title
5// that streams textures makes and frees them all the time. Vulkan also guarantees only 4096 live allocations
6// (maxMemoryAllocationCount).
7//
8// No Vulkan or Windows dependency: the caller allocates and frees the blocks (ImageMemoryPool's two callbacks), so the
9// policy is checked on the CPU (test/image_memory_test.cpp). All the images of a block are optimal-tiled, so
10// bufferImageGranularity, which separates linear from optimal resources, does not apply.
11
12#include <algorithm>
13#include <cstddef>
14#include <cstdint>
15#include <functional>
16#include <iterator>
17#include <map>
18#include <memory>
19#include <mutex>
20#include <set>
21#include <utility>
22#include <vector>
23
24namespace leonida {
25
26// The free space of one block: the smallest free piece that holds the request is used (best fit), and a released range
27// is merged with the free pieces beside it.
28class BlockRanges {
29public:
30 explicit BlockRanges(std::uint64_t size) : size_(size) { insert(0, size); }
31
32 // False when no free piece holds `size` bytes at `alignment`. `reused`: the range starts in bytes some earlier range
33 // of this block held, so it may hold that range's data.
34 bool allocate(std::uint64_t size, std::uint64_t alignment, std::uint64_t& offset, bool& reused) {
35 if (!size || !alignment || size > size_) return false;
36 for (auto it = by_size_.lower_bound({size, 0}); it != by_size_.end(); ++it) {
37 const auto [piece_size, piece] = *it;
38 const std::uint64_t start = (piece + alignment - 1) / alignment * alignment;
39 const std::uint64_t lead = start - piece;
40 if (lead > piece_size || size > piece_size - lead) continue;
41 erase(piece, piece_size);
42 insert(piece, lead);
43 insert(start + size, piece_size - lead - size);
44 offset = start;
45 reused = start < touched_;
46 touched_ = std::max(touched_, start + size);
47 in_use_ += size;
48 return true;
49 }
50 return false;
51 }
52
53 // Gives back a range allocate() returned.
54 void release(std::uint64_t offset, std::uint64_t size) {
55 in_use_ -= size;
56 if (const auto next = by_offset_.lower_bound(offset); next != by_offset_.end() && offset + size == next->first) {
57 const std::uint64_t next_size = next->second;
58 erase(next->first, next_size);
59 size += next_size;
60 }
61 if (auto previous = by_offset_.lower_bound(offset); previous != by_offset_.begin()) {
62 previous = std::prev(previous);
63 const auto [start, previous_size] = *previous;
64 if (start + previous_size == offset) {
65 erase(start, previous_size);
66 offset = start;
67 size += previous_size;
68 }
69 }
70 insert(offset, size);
71 }
72
73 bool empty() const { return in_use_ == 0; }
74 std::uint64_t size() const { return size_; }
75 std::uint64_t in_use() const { return in_use_; }
76 // The largest free piece, so a full block is passed over without a search.
77 std::uint64_t largest() const { return by_size_.empty() ? 0 : by_size_.rbegin()->first; }
78
79private:
80 void insert(std::uint64_t offset, std::uint64_t size) {
81 if (!size) return;
82 by_offset_[offset] = size;
83 by_size_.insert({size, offset});
84 }
85 void erase(std::uint64_t offset, std::uint64_t size) {
86 by_offset_.erase(offset);
87 by_size_.erase({size, offset});
88 }
89
90 std::uint64_t size_;
91 std::uint64_t in_use_ = 0;
92 std::uint64_t touched_ = 0; // bytes below this were handed out before
93 std::map<std::uint64_t, std::uint64_t> by_offset_; // offset -> size
94 std::set<std::pair<std::uint64_t, std::uint64_t>> by_size_; // (size, offset)
95};
96
97// Blocks of device memory, by memory type, split into ranges. Thread-safe. Every Range must be gone before the pool is.
98template<typename Memory>
99class ImageMemoryPool {
100public:
101 // A null Memory{}: the driver has no room in the type.
102 using AllocateFn = std::function<Memory(std::uint32_t type, std::uint64_t bytes)>;
103 using FreeFn = std::function<void(Memory)>;
104
105 // One image's range. Destroying it gives the bytes back to the block, so it is destroyed when no submission that
106 // used the image is still running (DeferredDeletionQueue).
107 class Range {
108 public:
109 Range(const Range&) = delete;
110 Range& operator=(const Range&) = delete;
111 ~Range() { pool_.release(*this); }
112
113 Memory memory() const { return memory_; }
114 std::uint64_t offset() const { return offset_; }
115 // The bytes may hold what an earlier range left; the memory of a new block was never given to one.
116 bool reused() const { return reused_; }
117
118 private:
119 friend class ImageMemoryPool;
120 Range(ImageMemoryPool& pool, void* block, Memory memory, std::uint64_t offset, std::uint64_t size, bool reused)
121 : pool_(pool), block_(block), memory_(memory), offset_(offset), size_(size), reused_(reused) {}
122
123 ImageMemoryPool& pool_;
124 void* block_;
125 Memory memory_;
126 std::uint64_t offset_;
127 std::uint64_t size_;
128 bool reused_;
129 };
130
131 struct Stats {
132 std::uint64_t blocks = 0; // live driver allocations
133 std::uint64_t block_bytes = 0; // their size
134 std::uint64_t ranges = 0; // live ranges in them
135 };
136
137 ImageMemoryPool(AllocateFn allocate, FreeFn free) : allocate_(std::move(allocate)), free_(std::move(free)) {}
138 ImageMemoryPool(const ImageMemoryPool&) = delete;
139 ImageMemoryPool& operator=(const ImageMemoryPool&) = delete;
140 ~ImageMemoryPool() {
141 for (auto& [type, pool] : types_)
142 for (const auto& block : pool.blocks) free_(block->memory);
143 }
144
145 // A range of a block of `type`, in a new block of `block_bytes` when no block has room. Null when the driver has no
146 // room for that block; the caller then makes its own allocation.
147 std::unique_ptr<Range> allocate(std::uint32_t type, std::uint64_t size, std::uint64_t alignment,
148 std::uint64_t block_bytes) {
149 std::lock_guard lock(mutex_);
150 Type& pool = types_[type];
151 std::uint64_t offset = 0;
152 bool reused = false;
153 for (const auto& block : pool.blocks) {
154 if (block->ranges.largest() < size || !block->ranges.allocate(size, alignment, offset, reused)) continue;
155 ++ranges_;
156 return std::unique_ptr<Range>(new Range(*this, block.get(), block->memory, offset, size, reused));
157 }
158 // A failed driver allocation is slow, and a full heap stays full until something is given back: do not ask for
159 // another block at every texture until a range is released, or that many textures later.
160 if (size > block_bytes || (pool.skip && pool.skip--)) return nullptr;
161 const Memory memory = allocate_(type, block_bytes);
162 if (!memory) {
163 pool.skip = kRetryAfter;
164 return nullptr;
165 }
166 auto block = std::make_unique<Block>(type, memory, block_bytes);
167 if (!block->ranges.allocate(size, alignment, offset, reused)) {
168 free_(memory);
169 return nullptr;
170 }
171 ++ranges_;
172 pool.blocks.push_back(std::move(block));
173 return std::unique_ptr<Range>(new Range(*this, pool.blocks.back().get(), memory, offset, size, reused));
174 }
175
176 Stats stats() const {
177 std::lock_guard lock(mutex_);
178 Stats result;
179 result.ranges = ranges_;
180 for (const auto& [type, pool] : types_)
181 for (const auto& block : pool.blocks) {
182 ++result.blocks;
183 result.block_bytes += block->ranges.size();
184 }
185 return result;
186 }
187
188private:
189 static constexpr std::uint32_t kRetryAfter = 64;
190
191 struct Block {
192 Block(std::uint32_t t, Memory m, std::uint64_t bytes) : type(t), memory(m), ranges(bytes) {}
193 std::uint32_t type;
194 Memory memory;
195 BlockRanges ranges;
196 };
197 struct Type {
198 std::vector<std::unique_ptr<Block>> blocks;
199 std::uint32_t skip = 0;
200 };
201
202 void release(const Range& range) {
203 Memory dead{};
204 bool free_block = false;
205 {
206 std::lock_guard lock(mutex_);
207 Block& block = *static_cast<Block*>(range.block_);
208 Type& pool = types_[block.type];
209 block.ranges.release(range.offset_, range.size_);
210 pool.skip = 0;
211 --ranges_;
212 // One empty block is kept, so a title that frees and makes the same textures does not ask the driver each
213 // time.
214 if (block.ranges.empty() && std::count_if(pool.blocks.begin(), pool.blocks.end(),
215 [](const auto& b) { return b->ranges.empty(); }) > 1) {
216 dead = block.memory;
217 free_block = true;
218 std::erase_if(pool.blocks, [&](const auto& b) { return b.get() == &block; });
219 }
220 }
221 if (free_block) free_(dead);
222 }
223
224 mutable std::mutex mutex_;
225 AllocateFn allocate_;
226 FreeFn free_;
227 std::map<std::uint32_t, Type> types_;
228 std::uint64_t ranges_ = 0;
229};
230
231} // namespace leonida
diff --git a/runtime/src/local_diagnostics.h b/runtime/src/local_diagnostics.h
new file mode 100644
index 000000000..50155479d
--- /dev/null
+++ b/runtime/src/local_diagnostics.h
@@ -0,0 +1,29 @@
1#pragma once
2
3// LEONIDA_LOCAL_DIAGNOSTICS=1 turns on the boot diagnostics that write to stderr from the draw, clear, present and
4// descriptor paths (the lines tagged present-probe, fsdraw, heap-probe, desc-probe and "PresentX diag"). They were
5// written to follow one frame of the retail title from its draws to the window and cost a lock and a line on paths
6// that run for every draw, so they are off unless asked for. Read once; any value that does not start with '0'
7// turns them on. No Windows dependency: the headers that use it are built into portable tests too.
8
9#include <cstddef>
10#include <cstdlib>
11
12namespace leonida {
13
14inline bool local_diagnostics() {
15 static const bool on = [] {
16#ifdef _WIN32
17 char value[8]{};
18 std::size_t length = 0;
19 return getenv_s(&length, value, sizeof value, "LEONIDA_LOCAL_DIAGNOSTICS") == 0 && length > 1 &&
20 value[0] != '0';
21#else
22 const char* value = std::getenv("LEONIDA_LOCAL_DIAGNOSTICS");
23 return value && *value && *value != '0';
24#endif
25 }();
26 return on;
27}
28
29} // namespace leonida
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 098a8ee40..8e3767740 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -18,6 +18,7 @@
18// (--overlay, default <game-dir>/overlay) so the package is never modified (shims/file_system.cpp). 18// (--overlay, default <game-dir>/overlay) so the package is never modified (shims/file_system.cpp).
19#include <windows.h> 19#include <windows.h>
20 20
21#include <cstdint>
21#include <cstdio> 22#include <cstdio>
22#include <cstdlib> 23#include <cstdlib>
23#include <exception> 24#include <exception>
@@ -27,15 +28,113 @@
27#include <system_error> 28#include <system_error>
28#include <vector> 29#include <vector>
29 30
31#include <cstring>
32
33namespace {
34
35// The retail executable (1.0.2.1) runs a hang watchdog thread (function at RVA 0x2215a60): when the game's main loop
36// has not set its "kick" byte (RVA 0x71b6331) for 30 one-second ticks, it calls a crash callback and then writes to
37// address 0 (`movl $0, 0` at RVA 0x2215c35). Under the runtime the game thread can legitimately stall for longer than
38// that, e.g. while the driver compiles pipelines against a cold cache (first boot after a driver update), and the
39// title then kills itself. By default the watchdog stays armed, as on the console. With LEONIDA_TITLE_WATCHDOG=0, and
40// only when that exact trap instruction sits where it does in this build, a runtime thread sets the kick byte twice a
41// second so the title's watchdog never fires.
42constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35;
43constexpr std::uint32_t kWatchdogKickRva = 0x71b6331;
44constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0
45
46void keep_title_watchdog_kicked(std::uint8_t* base) {
47 char value[4]{};
48 if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", value, sizeof(value)) != 1 || value[0] != '0') return;
49 MEMORY_BASIC_INFORMATION trap{}, kick{};
50 if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT ||
51 std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0)
52 return; // not the build this was measured on: leave the title's watchdog alone
53 const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
54 if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT ||
55 !(kick.Protect & writable))
56 return;
57 volatile std::uint8_t* const byte = base + kWatchdogKickRva;
58 const HANDLE thread = CreateThread(
59 nullptr, 0,
60 [](LPVOID p) -> DWORD {
61 auto* b = static_cast<volatile std::uint8_t*>(p);
62 for (;;) {
63 *b = 1;
64 Sleep(500);
65 }
66 },
67 const_cast<std::uint8_t*>(byte), 0, nullptr);
68 if (thread) {
69 CloseHandle(thread);
70 std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG=0; unset or 1 keeps it armed)\n");
71 }
72}
73
74// LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the
75// title's image (":n" = n consecutive values) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this
76// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly
77// that. Reads are checked; nothing is written.
78void start_title_peek(std::uint8_t* base) {
79 static char spec[1024];
80 const DWORD n = GetEnvironmentVariableA("LEONIDA_PEEK", spec, sizeof(spec));
81 if (!n || n >= sizeof(spec)) return;
82 static std::uint8_t* image = base;
83 const HANDLE thread = CreateThread(
84 nullptr, 0,
85 [](LPVOID) -> DWORD {
86 char seconds[16]{};
87 DWORD period = 10;
88 if (GetEnvironmentVariableA("LEONIDA_PEEK_SECONDS", seconds, sizeof(seconds)) > 0)
89 period = std::max<DWORD>(1, static_cast<DWORD>(std::strtoul(seconds, nullptr, 10)));
90 for (unsigned tick = 0;; ++tick) {
91 std::string line = "[rt] peek t=" + std::to_string(tick * period) + "s:";
92 for (const char* at = spec; *at;) {
93 char* end = nullptr;
94 const std::uint64_t rva = std::strtoull(at, &end, 16);
95 if (end == at) break;
96 unsigned count = 1;
97 if (*end == ':') count = static_cast<unsigned>(std::strtoul(end + 1, &end, 10));
98 char text[40];
99 std::snprintf(text, sizeof(text), " 0x%llx=", static_cast<unsigned long long>(rva));
100 line += text;
101 for (unsigned i = 0; i < count && i < 16; ++i) {
102 std::uint64_t value = 0;
103 SIZE_T got = 0;
104 const bool ok = ReadProcessMemory(GetCurrentProcess(), image + rva + 8ull * i, &value,
105 sizeof(value), &got) && got == sizeof(value);
106 std::snprintf(text, sizeof(text), ok ? "%s%llx" : "%s?", i ? "," : "",
107 static_cast<unsigned long long>(value));
108 line += text;
109 }
110 at = *end == ',' ? end + 1 : end;
111 if (at == end && *end) break;
112 }
113 std::fprintf(stderr, "%s\n", line.c_str());
114 Sleep(period * 1000);
115 }
116 },
117 nullptr, 0, nullptr);
118 if (thread) CloseHandle(thread);
119}
120
121} // namespace
122
30#include "base_reservation.h" 123#include "base_reservation.h"
31#include "code_hooks.h" 124#include "code_hooks.h"
32#include "cpu_emulation.h" 125#include "cpu_emulation.h"
33#include "host_cpu.h" 126#include "host_cpu.h"
34#include "mods.h" 127#include "mods.h"
35#include "pe_loader.h" 128#include "pe_loader.h"
129#include "thread_stacks.h"
130#include "title_page_watch.h"
131#include "title_geometry_watch.h"
36#include "../shims/d3d12_trace.h" 132#include "../shims/d3d12_trace.h"
37#include "../shims/d3d12_xs_device.h" 133#include "../shims/d3d12_xs_device.h"
38#include "../shims/file_system.h" 134#include "../shims/file_system.h"
135#ifdef LEONIDA_VULKAN_DEVICE
136#include "../shims/package_splash.h"
137#endif
39#include "../shims/process_shim.h" 138#include "../shims/process_shim.h"
40#include "../shims/shims.h" 139#include "../shims/shims.h"
41#include "../shims/startup_trace.h" 140#include "../shims/startup_trace.h"
@@ -52,22 +151,76 @@ const char* binding_name(rt::Binding b) {
52 } 151 }
53} 152}
54 153
154// Module TLS index 0 for the game's executable (rt::reserve_tls_index0), from the CRT's initializer table: .CRT$XCT
155// runs after the C runtime is set up and before every C++ dynamic initializer of gta6rt (.CRT$XCU), so before any of
156// gta6rt's code can have started a thread. The frames above it (wmainCRTStartup, __scrt_common_main_seh, _initterm)
157// hold no TLS slot address. The result is read again where an image is run.
158void __cdecl reserve_tls_index0_at_start() { rt::reserve_tls_index0(); }
159#pragma section(".CRT$XCT", read)
160extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_tls_index0)() =
161 reserve_tls_index0_at_start;
162#pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0")
163
164// Select the settings used to display the offline first-run UI. Keep explicit caller settings.
165bool configure_first_run_ui(const std::filesystem::path& package, std::filesystem::path& overlay) {
166 // A variable that is set but empty is not a setting: Windows cannot hold one, but a caller on Wine can pass one
167 // (NAME= in the environment), and asking for the size alone reports it as present there.
168 const auto set_default = [](const wchar_t* name, const wchar_t* value) {
169 wchar_t first[2]{};
170 return GetEnvironmentVariableW(name, first, 2) != 0 || _wputenv_s(name, value) == 0;
171 };
172 const struct { const wchar_t* name; const wchar_t* value; } settings[] = {
173 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"},
174 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"},
175 {L"LEONIDA_GPU_LABELS", L"1"}, {L"LEONIDA_FRAME_PACING", L"1"},
176 {L"LEONIDA_KEYBOARD_PAD", L"always"},
177 };
178 for (const auto& setting : settings) {
179 if (!set_default(setting.name, setting.value)) return false;
180 }
181 std::wstring executable(32768, L'\0');
182 const DWORD length = GetModuleFileNameW(nullptr, executable.data(), static_cast<DWORD>(executable.size()));
183 if (!length || length >= executable.size()) return false;
184 executable.resize(length);
185 const auto state = std::filesystem::path(executable).parent_path() / L"first-run-ui";
186 if (overlay.empty()) overlay = state / L"overlay";
187 if (!GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", nullptr, 0)) {
188 std::error_code error;
189 const auto backing = state / L"xmem";
190 std::filesystem::create_directories(backing, error);
191 if (error || !set_default(L"LEONIDA_XMEM_BACKING_DIR", backing.c_str())) return false;
192 }
193 return SetCurrentDirectoryW(package.c_str()) != FALSE;
194}
195
55int usage() { 196int usage() {
56 std::fprintf(stderr, 197 std::fprintf(stderr,
57 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" 198 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n"
58 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" 199 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n"
200 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n"
59 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); 201 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n");
60 return 2; 202 return 2;
61} 203}
62 204
63} // namespace 205} // namespace
64 206
207#ifdef LEONIDA_VULKAN_DEVICE
208static BOOL WINAPI show_package_window(HWND window, int command) {
209 const BOOL previous = ShowWindow(window, command);
210 const DWORD error = GetLastError();
211 if (command != SW_HIDE && rt::package_splash::paint_window(window))
212 rt::startup_trace::event("package_splash_window");
213 SetLastError(error);
214 return previous;
215}
216#endif
217
65int wmain(int argc, wchar_t** argv) { 218int wmain(int argc, wchar_t** argv) {
66 std::filesystem::path image, game_dir, overlay_dir, mods_dir; 219 std::filesystem::path image, game_dir, overlay_dir, mods_dir;
67 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash 220 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash
68 int archetype_lookup_arg = 0; 221 int archetype_lookup_arg = 0;
69 uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context 222 uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context
70 bool dry_run = false, init = false, run = false, trace_d3d12 = false; 223 bool dry_run = false, init = false, run = false, trace_d3d12 = false, first_run_ui = false;
71 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84) 224 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84)
72 std::wstring trace_file; 225 std::wstring trace_file;
73 for (int i = 1; i < argc; ++i) { 226 for (int i = 1; i < argc; ++i) {
@@ -78,6 +231,7 @@ int wmain(int argc, wchar_t** argv) {
78 } 231 }
79 if (a == L"--dry-run") dry_run = true; 232 if (a == L"--dry-run") dry_run = true;
80 else if (a == L"--init") init = true; 233 else if (a == L"--init") init = true;
234 else if (a == L"--first-run-ui") first_run_ui = true;
81 else if (a == L"--run") run = true; 235 else if (a == L"--run") run = true;
82 else if (a == L"--trace-d3d12") trace_d3d12 = true; 236 else if (a == L"--trace-d3d12") trace_d3d12 = true;
83 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; 237 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i];
@@ -104,7 +258,8 @@ int wmain(int argc, wchar_t** argv) {
104 } 258 }
105 if (image.empty()) return usage(); 259 if (image.empty()) return usage();
106 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. 260 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point.
107 if (dry_run + init + run != 1) return usage(); 261 if (dry_run + init + run + first_run_ui != 1) return usage();
262 run = run || first_run_ui;
108 // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h). 263 // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h).
109 if ((init || run) && !rt::host_cpu::check_skipped()) 264 if ((init || run) && !rt::host_cpu::check_skipped())
110 if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) { 265 if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) {
@@ -119,7 +274,21 @@ int wmain(int argc, wchar_t** argv) {
119 std::filesystem::path a = std::filesystem::absolute(p, ec); 274 std::filesystem::path a = std::filesystem::absolute(p, ec);
120 return ec ? p : a; 275 return ec ? p : a;
121 }; 276 };
277 if (first_run_ui) {
278 image = absolute_or_same(image);
279 if (!mods_dir.empty()) mods_dir = absolute_or_same(mods_dir);
280 if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring();
281 }
122 game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); 282 game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir);
283 // An unattended run can select a fresh write root even when its launcher supplies --overlay.
284 if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", nullptr, 0)) {
285 std::wstring dir(size, 0);
286 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", dir.data(), size);
287 if (n && n < size) {
288 dir.resize(n);
289 overlay_dir = dir;
290 }
291 }
123 if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); 292 if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir);
124 // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. 293 // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved.
125 if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) { 294 if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) {
@@ -135,8 +304,24 @@ int wmain(int argc, wchar_t** argv) {
135 if (!rt::base_reservation::inherited()) 304 if (!rt::base_reservation::inherited())
136 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range); 305 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range);
137 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. 306 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package.
307 if (first_run_ui && !configure_first_run_ui(game_dir, overlay_dir)) {
308 std::fprintf(stderr, "cannot initialize the first-run UI paths or graphics settings\n");
309 return 1;
310 }
138 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; 311 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay";
139 rt::fs::configure(game_dir, overlay_dir); 312 rt::fs::configure(game_dir, overlay_dir);
313#ifdef LEONIDA_VULKAN_DEVICE
314 if (run) {
315 rt::package_splash::configure(game_dir);
316 if (rt::package_splash::configured()) {
317 const rt::shims::Entry window_imports[] = {
318 {"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow", reinterpret_cast<void*>(&show_package_window)},
319 {"user32.dll", "ShowWindow", reinterpret_cast<void*>(&show_package_window)},
320 };
321 rt::shims::Table{window_imports, std::size(window_imports)};
322 }
323 }
324#endif
140 // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here; 325 // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here;
141 // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version. 326 // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version.
142 if (mods_dir.empty()) { 327 if (mods_dir.empty()) {
@@ -168,6 +353,10 @@ int wmain(int argc, wchar_t** argv) {
168 rt::d3d12_trace::set_enabled(trace_d3d12); 353 rt::d3d12_trace::set_enabled(trace_d3d12);
169 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. 354 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first.
170 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); 355 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range);
356 // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h).
357 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases);
358 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range);
359 rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data);
171 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { 360 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) {
172 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" 361 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n"
173 : "error: cannot create the trace file\n"); 362 : "error: cannot create the trace file\n");
@@ -186,6 +375,20 @@ int wmain(int argc, wchar_t** argv) {
186 try { 375 try {
187 rt::Loader loader(game_dir); 376 rt::Loader loader(game_dir);
188 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code 377 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
378 // An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which
379 // is gta6rt's own (or another executable's), so no code of it may run.
380 const auto* main_nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(
381 main_module.base + reinterpret_cast<const IMAGE_DOS_HEADER*>(main_module.base)->e_lfanew);
382 const bool main_is_exe = (main_nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
383 if ((init || run) && main_is_exe && main_module.tls_slot != rt::kNoTlsIndex && main_module.tls_index != 0) {
384 std::string why;
385 if (rt::reserve_tls_index0(&why)) why = "another mapped executable holds it";
386 std::fprintf(stderr,
387 "error: %s cannot have module TLS index 0 (%s); code built with /GA would read and write "
388 "another module's TLS through slot 0, so it is not run\n",
389 main_module.name.c_str(), why.c_str());
390 return 1;
391 }
189 // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA 392 // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA
190 // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup. 393 // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup.
191 if (view_mode_getter_rva) { 394 if (view_mode_getter_rva) {
@@ -272,7 +475,13 @@ int wmain(int argc, wchar_t** argv) {
272 } 475 }
273 std::printf("running %s\n", main_module.name.c_str()); 476 std::printf("running %s\n", main_module.name.c_str());
274 std::fflush(stdout); 477 std::fflush(stdout);
275 const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); 478 keep_title_watchdog_kicked(main_module.base);
479 start_title_peek(main_module.base);
480 int code;
481 {
482 auto stacks = rt::start_thread_stacks();
483 code = rt::process::run_entry(main_module.base + main_module.entry_rva);
484 }
276 std::fflush(stdout); 485 std::fflush(stdout);
277 std::printf("game exited with code %d\n", code); 486 std::printf("game exited with code %d\n", code);
278 rt::shims::report_called_unimplemented(); 487 rt::shims::report_called_unimplemented();
diff --git a/runtime/src/mem_probe.h b/runtime/src/mem_probe.h
new file mode 100644
index 000000000..a36d38bfe
--- /dev/null
+++ b/runtime/src/mem_probe.h
@@ -0,0 +1,570 @@
1#pragma once
2
3// LOCAL DIAGNOSTIC (not for upstream): mem probe. Where the game process's memory goes.
4// LEONIDA_MEM_PROBE=<seconds> turns it on (absent or 0: off, and nothing below is installed). Every <seconds> it logs
5// [rt] mem-probe t=...: the live Vulkan objects the runtime made (pipelines by kind, shader modules and their SPIR-V
6// bytes, VkDeviceMemory per memory type, split into allocated and imported), what the device
7// adds (pipeline cache bytes, arena, title memory), and
8// [rt] mem-probe smaps: /proc/self/smaps of the Wine process, Rss and Swap per kind of mapping: title memory,
9// other PE private memory (runtime + title heaps), PE images, PE sections, memory the Vulkan
10// driver mapped for us, /dev/nvidia* mappings, other native (Unix-side) anonymous memory
11// (driver heaps, glibc arenas), and files.
12// The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own
13// pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects.
14
15#include <windows.h>
16#include <vulkan/vulkan.h>
17
18#include <algorithm>
19#include <atomic>
20#include <cctype>
21#include <chrono>
22#include <cstdint>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <functional>
27#include <map>
28#include <mutex>
29#include <string>
30#include <thread>
31#include <unordered_map>
32#include <utility>
33#include <vector>
34
35namespace leonida::mem_probe {
36
37struct Allocation {
38 std::uint32_t type = 0;
39 std::uint64_t bytes = 0;
40 bool imported = false;
41 std::uintptr_t mapped = 0;
42 std::uint64_t mapped_bytes = 0;
43};
44
45struct State {
46 PFN_vkAllocateMemory allocate = nullptr;
47 PFN_vkFreeMemory free = nullptr;
48 PFN_vkMapMemory map = nullptr;
49 PFN_vkUnmapMemory unmap = nullptr;
50 PFN_vkCreateShaderModule create_module = nullptr;
51 PFN_vkDestroyShaderModule destroy_module = nullptr;
52 PFN_vkCreateGraphicsPipelines create_graphics = nullptr;
53 PFN_vkCreateComputePipelines create_compute = nullptr;
54 PFN_vkDestroyPipeline destroy_pipeline = nullptr;
55
56 std::mutex mutex;
57 std::unordered_map<VkDeviceMemory, Allocation> allocations;
58 std::unordered_map<VkShaderModule, std::uint64_t> modules;
59 std::unordered_map<VkPipeline, std::uint8_t> pipelines; // 0 graphics, 1 compute
60 std::uint64_t module_bytes = 0, modules_made = 0, module_bytes_made = 0;
61 std::uint64_t graphics_live = 0, compute_live = 0, graphics_made = 0, compute_made = 0;
62 std::uint64_t graphics_ns = 0, compute_ns = 0; // time inside vkCreate*Pipelines
63 std::uint64_t installed = 0;
64 ULONGLONG started = 0;
65};
66
67inline State& state() {
68 static State s;
69 return s;
70}
71
72inline unsigned interval_seconds() {
73 static const unsigned seconds = [] {
74 char text[16] = {};
75 DWORD n = GetEnvironmentVariableA("LEONIDA_MEM_PROBE", text, sizeof text);
76 if (!n || n >= sizeof text) return 0u;
77 return unsigned(std::strtoul(text, nullptr, 10));
78 }();
79 return seconds;
80}
81
82inline bool imported_memory(const VkMemoryAllocateInfo* info) {
83 for (auto* p = static_cast<const VkBaseInStructure*>(info->pNext); p; p = p->pNext)
84 if (p->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT ||
85 p->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR ||
86 p->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR)
87 return true;
88 return false;
89}
90
91inline VKAPI_ATTR VkResult VKAPI_CALL allocate_memory(VkDevice device, const VkMemoryAllocateInfo* info,
92 const VkAllocationCallbacks* callbacks, VkDeviceMemory* out) {
93 State& s = state();
94 const VkResult result = s.allocate(device, info, callbacks, out);
95 if (result == VK_SUCCESS && out && *out) {
96 std::lock_guard lock(s.mutex);
97 s.allocations[*out] = {info->memoryTypeIndex, info->allocationSize, imported_memory(info), 0, 0};
98 }
99 return result;
100}
101
102inline VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice device, VkDeviceMemory memory,
103 const VkAllocationCallbacks* callbacks) {
104 State& s = state();
105 if (memory) {
106 std::lock_guard lock(s.mutex);
107 s.allocations.erase(memory);
108 }
109 s.free(device, memory, callbacks);
110}
111
112inline VKAPI_ATTR VkResult VKAPI_CALL map_memory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset,
113 VkDeviceSize size, VkMemoryMapFlags flags, void** data) {
114 State& s = state();
115 const VkResult result = s.map(device, memory, offset, size, flags, data);
116 if (result == VK_SUCCESS && data && *data) {
117 std::lock_guard lock(s.mutex);
118 if (auto it = s.allocations.find(memory); it != s.allocations.end()) {
119 it->second.mapped = reinterpret_cast<std::uintptr_t>(*data);
120 it->second.mapped_bytes = size == VK_WHOLE_SIZE ? it->second.bytes - offset : size;
121 }
122 }
123 return result;
124}
125
126inline VKAPI_ATTR void VKAPI_CALL unmap_memory(VkDevice device, VkDeviceMemory memory) {
127 State& s = state();
128 {
129 std::lock_guard lock(s.mutex);
130 if (auto it = s.allocations.find(memory); it != s.allocations.end()) it->second.mapped = 0;
131 }
132 s.unmap(device, memory);
133}
134
135inline VKAPI_ATTR VkResult VKAPI_CALL create_shader_module(VkDevice device, const VkShaderModuleCreateInfo* info,
136 const VkAllocationCallbacks* callbacks,
137 VkShaderModule* out) {
138 State& s = state();
139 const VkResult result = s.create_module(device, info, callbacks, out);
140 if (result == VK_SUCCESS && out && *out) {
141 std::lock_guard lock(s.mutex);
142 s.modules[*out] = info->codeSize;
143 s.module_bytes += info->codeSize;
144 ++s.modules_made;
145 s.module_bytes_made += info->codeSize;
146 }
147 return result;
148}
149
150inline VKAPI_ATTR void VKAPI_CALL destroy_shader_module(VkDevice device, VkShaderModule module,
151 const VkAllocationCallbacks* callbacks) {
152 State& s = state();
153 if (module) {
154 std::lock_guard lock(s.mutex);
155 if (auto it = s.modules.find(module); it != s.modules.end()) {
156 s.module_bytes -= it->second;
157 s.modules.erase(it);
158 }
159 }
160 s.destroy_module(device, module, callbacks);
161}
162
163inline std::uint64_t now_ns() {
164 return std::uint64_t(
165 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch())
166 .count());
167}
168
169inline void note_pipelines(std::uint8_t kind, std::uint32_t count, const VkPipeline* made, std::uint64_t ns) {
170 State& s = state();
171 std::lock_guard lock(s.mutex);
172 (kind ? s.compute_ns : s.graphics_ns) += ns;
173 for (std::uint32_t i = 0; i < count; ++i) {
174 if (!made[i]) continue;
175 s.pipelines[made[i]] = kind;
176 ++(kind ? s.compute_live : s.graphics_live);
177 ++(kind ? s.compute_made : s.graphics_made);
178 }
179}
180
181inline double mib(std::uint64_t bytes) { return double(bytes) / 1048576.0; }
182
183// One line per pipeline call that takes 1 s or more: how long, and how big its SPIR-V was.
184inline void note_slow(const char* kind, std::uint64_t ns, std::uint64_t spirv_bytes, std::uint32_t stages) {
185 if (ns < 1000000000ull) return;
186 std::fprintf(stderr, "[rt] mem-probe slow %s pipeline: %.1f s, %u stages, %.1f MiB SPIR-V\n", kind,
187 double(ns) / 1e9, stages, mib(spirv_bytes));
188}
189
190inline std::uint64_t module_size(VkShaderModule module) {
191 State& s = state();
192 std::lock_guard lock(s.mutex);
193 const auto it = s.modules.find(module);
194 return it == s.modules.end() ? 0 : it->second;
195}
196
197inline VKAPI_ATTR VkResult VKAPI_CALL create_graphics_pipelines(VkDevice device, VkPipelineCache cache,
198 std::uint32_t count,
199 const VkGraphicsPipelineCreateInfo* infos,
200 const VkAllocationCallbacks* callbacks,
201 VkPipeline* out) {
202 const std::uint64_t t0 = now_ns();
203 const VkResult result = state().create_graphics(device, cache, count, infos, callbacks, out);
204 const std::uint64_t ns = now_ns() - t0;
205 if (result >= 0 && out) note_pipelines(0, count, out, ns);
206 if (ns >= 1000000000ull && count == 1) {
207 std::uint64_t bytes = 0;
208 for (std::uint32_t i = 0; i < infos[0].stageCount; ++i) bytes += module_size(infos[0].pStages[i].module);
209 note_slow("graphics", ns, bytes, infos[0].stageCount);
210 }
211 return result;
212}
213
214inline VKAPI_ATTR VkResult VKAPI_CALL create_compute_pipelines(VkDevice device, VkPipelineCache cache,
215 std::uint32_t count,
216 const VkComputePipelineCreateInfo* infos,
217 const VkAllocationCallbacks* callbacks,
218 VkPipeline* out) {
219 const std::uint64_t t0 = now_ns();
220 const VkResult result = state().create_compute(device, cache, count, infos, callbacks, out);
221 const std::uint64_t ns = now_ns() - t0;
222 if (result >= 0 && out) note_pipelines(1, count, out, ns);
223 if (ns >= 1000000000ull && count == 1) note_slow("compute", ns, module_size(infos[0].stage.module), 1);
224 return result;
225}
226
227inline VKAPI_ATTR void VKAPI_CALL destroy_pipeline(VkDevice device, VkPipeline pipeline,
228 const VkAllocationCallbacks* callbacks) {
229 State& s = state();
230 if (pipeline) {
231 std::lock_guard lock(s.mutex);
232 if (auto it = s.pipelines.find(pipeline); it != s.pipelines.end()) {
233 --(it->second ? s.compute_live : s.graphics_live);
234 s.pipelines.erase(it);
235 }
236 }
237 s.destroy_pipeline(device, pipeline, callbacks);
238}
239
240// Wraps the runtime's function table (leonida::VulkanDeviceFunctions). Once per process: the first device wins.
241template<typename Functions>
242void install(Functions& vk) {
243 if (!interval_seconds()) return;
244 State& s = state();
245 std::lock_guard lock(s.mutex);
246 if (s.installed++) return;
247 if (!vk.vkAllocateMemory || !vk.vkFreeMemory || !vk.vkMapMemory || !vk.vkUnmapMemory ||
248 !vk.vkCreateShaderModule || !vk.vkDestroyShaderModule || !vk.vkCreateGraphicsPipelines ||
249 !vk.vkCreateComputePipelines || !vk.vkDestroyPipeline)
250 return;
251 s.started = GetTickCount64();
252 s.allocate = vk.vkAllocateMemory, vk.vkAllocateMemory = allocate_memory;
253 s.free = vk.vkFreeMemory, vk.vkFreeMemory = free_memory;
254 s.map = vk.vkMapMemory, vk.vkMapMemory = map_memory;
255 s.unmap = vk.vkUnmapMemory, vk.vkUnmapMemory = unmap_memory;
256 s.create_module = vk.vkCreateShaderModule, vk.vkCreateShaderModule = create_shader_module;
257 s.destroy_module = vk.vkDestroyShaderModule, vk.vkDestroyShaderModule = destroy_shader_module;
258 s.create_graphics = vk.vkCreateGraphicsPipelines, vk.vkCreateGraphicsPipelines = create_graphics_pipelines;
259 s.create_compute = vk.vkCreateComputePipelines, vk.vkCreateComputePipelines = create_compute_pipelines;
260 s.destroy_pipeline = vk.vkDestroyPipeline, vk.vkDestroyPipeline = destroy_pipeline;
261 std::fprintf(stderr, "[rt] mem-probe: installed, every %u s\n", interval_seconds());
262}
263
264// ---- /proc/self/smaps, classified ----
265enum Bucket {
266 b_title, // the title's memory (XMem / title VirtualAlloc ranges)
267 b_pe_private, // other PE private memory: the runtime's and the title's heaps, stacks
268 b_pe_high, // PE private memory at 0x7f0000000000 and above (where native mmaps land: a check on Wine views)
269 b_pe_image, // PE images (exe/dll)
270 b_pe_mapped, // PE sections (file mappings, pagefile-backed sections)
271 b_vk_mapped, // memory the Vulkan driver mapped for vkMapMemory
272 b_nvidia, // other /dev/nvidia* mappings
273 b_native_anon, // native anonymous memory Wine does not know: driver heaps, glibc arenas, [heap], [stack]
274 b_file, // native file mappings (.so, ...)
275 b_count
276};
277inline const char* bucket_name(int b) {
278 static const char* names[b_count] = {"title", "pe-private", "pe-private@7f", "pe-image", "pe-section",
279 "vk-mapped", "nvidia-dev", "native-anon", "native-file"};
280 return names[b];
281}
282
283struct Usage {
284 std::uint64_t rss = 0, anon = 0, swap = 0, vmas = 0;
285};
286
287using Ranges = std::vector<std::pair<std::uint64_t, std::uint64_t>>; // [begin, end), sorted
288
289inline bool in_ranges(const Ranges& ranges, std::uint64_t va) {
290 auto it = std::upper_bound(ranges.begin(), ranges.end(), std::make_pair(va, UINT64_MAX));
291 if (it == ranges.begin()) return false;
292 --it;
293 return va >= it->first && va < it->second;
294}
295
296inline std::string read_small(const std::string& path) {
297 HANDLE file = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0,
298 nullptr);
299 if (file == INVALID_HANDLE_VALUE) return {};
300 std::string text;
301 std::vector<char> buffer(16384);
302 DWORD got = 0;
303 while (ReadFile(file, buffer.data(), DWORD(buffer.size()), &got, nullptr) && got) text.append(buffer.data(), got);
304 CloseHandle(file);
305 return text;
306}
307
308// The Unix process of this Wine process. Wine opens files in wineserver, so Z:\proc\self is the server: the game is
309// the /proc entry whose command line names gta6rt and whose address space is the largest (one boot at a time).
310inline std::string proc_dir() {
311 static std::string found;
312 if (!found.empty()) return found;
313 WIN32_FIND_DATAA data{};
314 HANDLE find = FindFirstFileA("Z:\\proc\\*", &data);
315 if (find == INVALID_HANDLE_VALUE) return {};
316 std::uint64_t best = 0;
317 do {
318 if (data.cFileName[0] < '1' || data.cFileName[0] > '9') continue;
319 const std::string dir = std::string("Z:\\proc\\") + data.cFileName;
320 std::string cmdline = read_small(dir + "\\cmdline");
321 for (char& c : cmdline) c = char(std::tolower(static_cast<unsigned char>(c)));
322 if (cmdline.find("gta6rt") == std::string::npos) continue;
323 const std::string status = read_small(dir + "\\status");
324 const std::size_t at = status.find("VmSize:");
325 const std::uint64_t vm = at == std::string::npos ? 0 : std::strtoull(status.c_str() + at + 7, nullptr, 10);
326 if (vm > best) {
327 best = vm;
328 found = dir;
329 }
330 } while (FindNextFileA(find, &data));
331 FindClose(find);
332 if (!found.empty()) std::fprintf(stderr, "[rt] mem-probe: this process is %s (VmSize %llu kB)\n", found.c_str(),
333 (unsigned long long)best);
334 return found;
335}
336
337// Parses /proc/<pid>/smaps (Wine reaches the Unix /proc through Z:). Classifies each VMA by its start address.
338inline bool read_smaps(const Ranges& title, const Ranges& vk_mapped, Usage (&usage)[b_count], std::string& top_files,
339 std::string& error) {
340 const std::string dir = proc_dir();
341 if (dir.empty()) {
342 error = "no /proc entry names gta6rt";
343 return false;
344 }
345 HANDLE file = CreateFileA((dir + "\\smaps").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
346 OPEN_EXISTING, 0, nullptr);
347 if (file == INVALID_HANDLE_VALUE) {
348 error = "open failed " + std::to_string(GetLastError());
349 return false;
350 }
351 std::vector<char> buffer(1 << 20);
352 std::string carry;
353 int bucket = -1;
354 std::string path;
355 std::map<std::string, Usage> files;
356 const auto field = [](const char* line, const char* name, std::uint64_t& out) {
357 const std::size_t n = std::strlen(name);
358 if (std::strncmp(line, name, n) != 0) return false;
359 out = std::strtoull(line + n, nullptr, 10) * 1024;
360 return true;
361 };
362 const auto header = [&](const char* line) {
363 // 7f0000000000-7f0000001000 rw-p 00000000 00:00 0 [path]
364 char* end = nullptr;
365 const std::uint64_t begin = std::strtoull(line, &end, 16);
366 if (!end || *end != '-') return false;
367 const char* p = line;
368 for (int fields = 0; fields < 5 && *p; ++fields) { // skip range perms offset dev inode
369 while (*p && *p != ' ') ++p;
370 while (*p == ' ') ++p;
371 }
372 path = p;
373 while (!path.empty() && (path.back() == '\n' || path.back() == '\r' || path.back() == ' ')) path.pop_back();
374 if (in_ranges(title, begin)) {
375 bucket = b_title;
376 } else if (in_ranges(vk_mapped, begin)) {
377 bucket = b_vk_mapped;
378 } else if (path.rfind("/dev/nvidia", 0) == 0) {
379 bucket = b_nvidia;
380 } else {
381 MEMORY_BASIC_INFORMATION region{};
382 const bool known = VirtualQuery(reinterpret_cast<const void*>(begin), &region, sizeof region) &&
383 region.State == MEM_COMMIT;
384 if (known && region.Type == MEM_IMAGE) bucket = b_pe_image;
385 else if (known && region.Type == MEM_MAPPED) bucket = b_pe_mapped;
386 else if (known && region.Type == MEM_PRIVATE) bucket = begin >= 0x7f0000000000ull ? b_pe_high : b_pe_private;
387 else if (!path.empty() && path[0] == '/' ) bucket = b_file;
388 else bucket = b_native_anon;
389 }
390 ++usage[bucket].vmas;
391 return true;
392 };
393 const auto line_of = [&](const char* line) {
394 std::uint64_t value = 0;
395 if ((line[0] >= '0' && line[0] <= '9') || (line[0] >= 'a' && line[0] <= 'f')) {
396 if (header(line)) return;
397 }
398 if (bucket < 0) return;
399 if (field(line, "Rss:", value)) {
400 usage[bucket].rss += value;
401 if (bucket == b_file || bucket == b_pe_image || bucket == b_pe_mapped) files[path].rss += value;
402 } else if (field(line, "Anonymous:", value)) {
403 usage[bucket].anon += value;
404 } else if (field(line, "Swap:", value)) {
405 usage[bucket].swap += value;
406 if (bucket == b_file || bucket == b_pe_image || bucket == b_pe_mapped) files[path].swap += value;
407 }
408 };
409 DWORD got = 0;
410 while (ReadFile(file, buffer.data(), DWORD(buffer.size()), &got, nullptr) && got) {
411 carry.append(buffer.data(), got);
412 std::size_t start = 0;
413 for (std::size_t nl; (nl = carry.find('\n', start)) != std::string::npos; start = nl + 1) {
414 carry[nl] = 0;
415 line_of(carry.c_str() + start);
416 }
417 carry.erase(0, start);
418 }
419 CloseHandle(file);
420 std::vector<std::pair<std::uint64_t, std::string>> ranked;
421 for (auto& [name, u] : files) ranked.push_back({u.rss + u.swap, name});
422 std::sort(ranked.rbegin(), ranked.rend());
423 char text[256];
424 for (std::size_t i = 0; i < ranked.size() && i < 4; ++i) {
425 std::string name = ranked[i].second.empty() ? "(none)" : ranked[i].second;
426 if (name.size() > 60) name = "..." + name.substr(name.size() - 57);
427 std::snprintf(text, sizeof text, "%s%s %.0f", i ? ", " : "", name.c_str(), mib(ranked[i].first));
428 top_files += text;
429 }
430 return true;
431}
432
433// Sums the Linux-side totals the kernel keeps (/proc/<pid>/smaps_rollup), for a check of the buckets.
434inline std::string read_rollup() {
435 const std::string dir = proc_dir();
436 const std::string text = dir.empty() ? std::string() : read_small(dir + "\\smaps_rollup");
437 if (text.empty()) return "rollup: open failed";
438 std::string out = "rollup MiB:";
439 for (const char* name : {"Rss:", "Anonymous:", "Swap:", "Pss_File:", "Pss_Shmem:"}) {
440 const std::size_t at = text.find(std::string("\n") + name);
441 if (at == std::string::npos) continue;
442 const std::uint64_t kb = std::strtoull(text.c_str() + at + 1 + std::strlen(name), nullptr, 10);
443 char item[64];
444 std::snprintf(item, sizeof item, " %.*s %.0f", int(std::strlen(name) - 1), name, double(kb) / 1024.0);
445 out += item;
446 }
447 return out;
448}
449
450// What the device adds to the line: pipeline cache bytes, arena use, title memory ranges.
451struct DeviceFacts {
452 std::function<std::string()> describe; // one text fragment
453 std::function<Ranges()> title_ranges; // the title's memory
454 VkPhysicalDeviceMemoryProperties memory{};
455};
456
457inline std::string type_flags(VkMemoryPropertyFlags f) {
458 std::string s;
459 if (f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) s += "DL";
460 if (f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) s += s.empty() ? "HV" : "+HV";
461 if (f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) s += "+HC";
462 if (f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) s += "+HCa";
463 return s.empty() ? "none" : s;
464}
465
466inline std::string wall_clock() {
467 SYSTEMTIME now{};
468 GetLocalTime(&now);
469 char text[16];
470 std::snprintf(text, sizeof text, "%02u:%02u:%02u", now.wHour, now.wMinute, now.wSecond);
471 return text;
472}
473
474inline void sample(const DeviceFacts& facts) {
475 State& s = state();
476 const double t = double(GetTickCount64() - s.started) / 1000.0;
477 std::uint64_t type_count[VK_MAX_MEMORY_TYPES] = {}, type_bytes[VK_MAX_MEMORY_TYPES] = {};
478 std::uint64_t import_count[VK_MAX_MEMORY_TYPES] = {}, import_bytes[VK_MAX_MEMORY_TYPES] = {};
479 Ranges vk_mapped;
480 std::uint64_t modules = 0, module_bytes = 0, modules_made = 0, module_bytes_made = 0;
481 std::uint64_t graphics = 0, compute = 0, graphics_made = 0, compute_made = 0, graphics_ns = 0, compute_ns = 0;
482 {
483 std::lock_guard lock(s.mutex);
484 for (const auto& [memory, a] : s.allocations) {
485 const std::uint32_t i = a.type < VK_MAX_MEMORY_TYPES ? a.type : 0;
486 if (a.imported) {
487 ++import_count[i];
488 import_bytes[i] += a.bytes;
489 } else {
490 ++type_count[i];
491 type_bytes[i] += a.bytes;
492 }
493 if (a.mapped && !a.imported) vk_mapped.push_back({a.mapped, a.mapped + a.mapped_bytes});
494 }
495 modules = s.modules.size();
496 module_bytes = s.module_bytes;
497 modules_made = s.modules_made;
498 module_bytes_made = s.module_bytes_made;
499 graphics = s.graphics_live;
500 compute = s.compute_live;
501 graphics_made = s.graphics_made;
502 compute_made = s.compute_made;
503 graphics_ns = s.graphics_ns;
504 compute_ns = s.compute_ns;
505 }
506 std::sort(vk_mapped.begin(), vk_mapped.end());
507 std::string memory_text;
508 char item[256];
509 for (std::uint32_t i = 0; i < facts.memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) {
510 if (!type_count[i] && !import_count[i]) continue;
511 std::snprintf(item, sizeof item, " type %u %s heap %u: %llu x %.0f MiB", i,
512 type_flags(facts.memory.memoryTypes[i].propertyFlags).c_str(),
513 facts.memory.memoryTypes[i].heapIndex, (unsigned long long)type_count[i], mib(type_bytes[i]));
514 memory_text += item;
515 if (import_count[i]) {
516 std::snprintf(item, sizeof item, " (+%llu imported, %.0f MiB)", (unsigned long long)import_count[i],
517 mib(import_bytes[i]));
518 memory_text += item;
519 }
520 memory_text += ';';
521 }
522 std::fprintf(stderr,
523 "[rt] mem-probe t=%.0fs (%s): pipelines live graphics %llu compute %llu (made %llu / %llu, %.1f s / %.1f s "
524 "in vkCreate*Pipelines); shader modules live %llu, %.0f MiB SPIR-V (made %llu, %.0f MiB); "
525 "vk memory:%s %s\n",
526 t, wall_clock().c_str(), (unsigned long long)graphics, (unsigned long long)compute, (unsigned long long)graphics_made,
527 (unsigned long long)compute_made, double(graphics_ns) / 1e9, double(compute_ns) / 1e9,
528 (unsigned long long)modules, mib(module_bytes), (unsigned long long)modules_made,
529 mib(module_bytes_made), memory_text.c_str(), facts.describe ? facts.describe().c_str() : "");
530 Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{};
531 std::sort(title.begin(), title.end());
532 Usage usage[b_count];
533 std::string top_files, error;
534 const std::uint64_t t0 = now_ns();
535 if (!read_smaps(title, vk_mapped, usage, top_files, error)) {
536 std::fprintf(stderr, "[rt] mem-probe smaps t=%.0fs: %s\n", t, error.c_str());
537 return;
538 }
539 std::string text;
540 std::uint64_t rss = 0, swap = 0;
541 for (int b = 0; b < b_count; ++b) {
542 rss += usage[b].rss;
543 swap += usage[b].swap;
544 std::snprintf(item, sizeof item, " %s %.0f+%.0f (anon %.0f, %llu vmas);", bucket_name(b), mib(usage[b].rss),
545 mib(usage[b].swap), mib(usage[b].anon), (unsigned long long)usage[b].vmas);
546 text += item;
547 }
548 std::fprintf(stderr,
549 "[rt] mem-probe smaps t=%.0fs (%.0f ms): total rss %.0f + swap %.0f MiB; rss+swap per kind:%s top "
550 "files: %s; %s\n",
551 t, double(now_ns() - t0) / 1e6, mib(rss), mib(swap), text.c_str(), top_files.c_str(),
552 read_rollup().c_str());
553}
554
555// Starts the sampling thread (once). The thread runs until the process ends.
556inline void start(DeviceFacts facts) {
557 const unsigned seconds = interval_seconds();
558 if (!seconds) return;
559 static std::once_flag once;
560 std::call_once(once, [&] {
561 std::thread([facts = std::move(facts), seconds] {
562 for (;;) {
563 Sleep(seconds * 1000);
564 sample(facts);
565 }
566 }).detach();
567 });
568}
569
570} // namespace leonida::mem_probe
diff --git a/runtime/src/native_pso.h b/runtime/src/native_pso.h
new file mode 100644
index 000000000..8982c701a
--- /dev/null
+++ b/runtime/src/native_pso.h
@@ -0,0 +1,342 @@
1#pragma once
2
3// Source: adapted from enx/leonida, commit 5c175db901f8486bcdefd03746b578b657e3151f on the original author's git
4// mirror (https://git.notrexed.dev/enx/leonida), a fork of this project. Licence: GPL-3.0-or-later as a fork of this
5// project. That server could not be reached on 2026-11-25, when this file was merged, so the source and its licence
6// could not be read there; the maintainer accepted the file because the source is a fork of this same
7// GPL-3.0-or-later project (the README links the server as the original author's mirror) and because
8// tools/native_pso_hashes.py is adapted from the same commit. Changed, as the pull request that brought it describes
9// it (the source could not be compared): the parsing is standard-library code of its own, apart from the D3D12 part
10// (runtime/shims/d3d12_xs_native_pso.h), and a stage is taken from the translator's index entry of the container
11// its records name, not from the position of its block.
12//
13// The description Xbox device slot 57 receives (native graphics pipelines) and how its stages find the game's own
14// shader containers. Standard library only, so the parsing is tested on every platform.
15//
16// Layout measured by LooperSalty on 1.0.2.1 and implemented by enx in 5c175db90: 0x108 bytes, the root
17// signature at +0x00, pairs at +0x08 and +0x18, then seven blocks {code, size, records, size} at +0x28 + k * 0x20.
18// Measured by KkelebekK: pair 0 is state blob A (380-388 bytes: blend, raster,
19// depth, not decoded), pair 1 is state blob B (80-188 bytes: formats and input layout, decode_state_b), and each
20// stage's records blob carries the source container's HASH digest after its 0x43 word (docs/fspx.md, kind 7).
21// The block index is not trusted as the stage: the stage comes from the translator's index entry of the container.
22
23#include <array>
24#include <cstddef>
25#include <cstdint>
26#include <cstring>
27#include <map>
28#include <optional>
29#include <span>
30#include <set>
31#include <string>
32#include <string_view>
33#include <utility>
34#include <vector>
35
36namespace leonida::native_pso {
37
38struct Pair {
39 const void* data;
40 std::uint64_t size;
41};
42
43struct StageBlock {
44 Pair code; // +0x00: the stage's native program
45 Pair records; // +0x10: kind-7 style records holding the container's HASH digest
46};
47
48inline constexpr std::size_t kStageBlocks = 7;
49
50struct GraphicsDesc {
51 const void* root_signature; // +0x00
52 Pair state_a; // +0x08
53 Pair state_b; // +0x18
54 StageBlock stages[kStageBlocks]; // +0x28
55};
56
57static_assert(sizeof(Pair) == 0x10 && sizeof(StageBlock) == 0x20, "pairs are {pointer, u64 size}");
58static_assert(offsetof(GraphicsDesc, state_a) == 0x08 && offsetof(GraphicsDesc, state_b) == 0x18);
59static_assert(offsetof(GraphicsDesc, stages) == 0x28 && sizeof(GraphicsDesc) == 0x108,
60 "the slot-57 description has a 0x108-byte prefix");
61
62// Far above the largest blob measured (a few KiB), and small enough for 32-bit offsets inside one.
63inline constexpr std::uint64_t kPairLimit = 16u << 20;
64
65// The size, not the pointer, determines whether a pair is absent.
66enum class PairState { absent, present, malformed };
67
68// A table entry with size 0 is absent whatever its pointer (the title passes base + offset, measured on 1.0.2.1).
69inline PairState pair_state(const Pair& p) {
70 if (!p.size) return PairState::absent;
71 if (!p.data || p.size > kPairLimit) return PairState::malformed;
72 return PairState::present;
73}
74
75inline std::span<const std::uint8_t> bytes(const Pair& p) {
76 if (pair_state(p) != PairState::present) return {};
77 return {static_cast<const std::uint8_t*>(p.data), static_cast<std::size_t>(p.size)};
78}
79
80inline std::uint32_t read_u32(std::span<const std::uint8_t> b, std::size_t at) {
81 std::uint32_t v = 0;
82 if (at + 4 <= b.size()) std::memcpy(&v, b.data() + at, 4);
83 return v;
84}
85
86struct InputElement {
87 std::string name;
88 std::uint32_t semantic_index = 0;
89 std::uint32_t format = 0;
90 std::uint32_t input_slot = 0;
91 std::uint32_t aligned_byte_offset = 0;
92 std::uint32_t classification = 0;
93 std::uint32_t step_rate = 0;
94};
95
96// State blob B. The u32 field widths after each name are a hypothesis that fits the
97// measured sizes: 0x50 bytes with no element, and 188 bytes with POSITION, COLOR and TEXCOORD.
98struct FixedState {
99 std::array<std::uint8_t, 8> rtv_formats{}; // +0x10, DXGI_FORMAT values
100 std::uint32_t sample_mask = 0; // +0x1c
101 std::uint8_t dsv_format = 0; // +0x24
102 std::uint8_t rt_count = 0; // +0x25
103 std::uint8_t topology_type = 0; // +0x26, low nibble
104 std::uint8_t sample_count = 1; // +0x28
105 std::vector<InputElement> elements; // count at +0x4c, packed from +0x50
106};
107
108inline constexpr std::size_t kStateBHeader = 0x50;
109inline constexpr std::uint32_t kMaxInputElements = 32; // D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT
110inline constexpr std::uint32_t kMaxSemanticName = 256;
111
112// Empty for a blob that is too short, names more than 8 targets, a topology type past PATCH (4), or an element
113// list that runs past the blob or has a malformed name. Bytes after the last element are allowed.
114inline std::optional<FixedState> decode_state_b(std::span<const std::uint8_t> b, const char** why = nullptr) {
115 const auto fail = [&](const char* reason) {
116 if (why) *why = reason;
117 return std::nullopt;
118 };
119 if (b.size() < kStateBHeader) return fail("blob B shorter than its header");
120 FixedState s;
121 std::memcpy(s.rtv_formats.data(), b.data() + 0x10, 8);
122 s.sample_mask = read_u32(b, 0x1c);
123 s.dsv_format = b[0x24];
124 s.rt_count = b[0x25];
125 s.topology_type = b[0x26] & 0x0f;
126 s.sample_count = b[0x28] ? b[0x28] : 1;
127 if (s.rt_count > 8) return fail("blob B render target count over 8");
128 if (s.topology_type > 4) return fail("blob B topology type over 4");
129 const std::uint32_t count = read_u32(b, 0x4c);
130 if (count > kMaxInputElements) return fail("blob B input element count over 32");
131 std::size_t at = kStateBHeader;
132 for (std::uint32_t i = 0; i < count; ++i) {
133 if (at + 4 > b.size()) return fail("blob B input element past the end");
134 const std::uint32_t length = read_u32(b, at);
135 at += 4;
136 if (length < 2 || length > kMaxSemanticName || at + length + 24 > b.size())
137 return fail("blob B semantic name length out of range");
138 const auto* name = reinterpret_cast<const char*>(b.data() + at);
139 if (name[length - 1] != '\0' || std::memchr(name, '\0', length - 1))
140 return fail("blob B semantic name not one NUL-terminated string");
141 InputElement e;
142 e.name.assign(name, length - 1);
143 at += length;
144 e.semantic_index = read_u32(b, at);
145 e.format = read_u32(b, at + 4);
146 e.input_slot = read_u32(b, at + 8);
147 e.aligned_byte_offset = read_u32(b, at + 12);
148 e.classification = read_u32(b, at + 16);
149 e.step_rate = read_u32(b, at + 20);
150 at += 24;
151 s.elements.push_back(std::move(e));
152 }
153 return s;
154}
155
156using Digest = std::array<std::uint8_t, 16>;
157
158// Every 16 bytes that follow a 4-aligned 0x43 word, without duplicates. A register number can also read 0x43, so
159// all candidates are returned and the map decides which one names a container.
160inline std::vector<Digest> record_digests(std::span<const std::uint8_t> records) {
161 std::vector<Digest> out;
162 std::set<Digest> seen;
163 for (std::size_t at = 0; at + 4 + 16 <= records.size(); at += 4) {
164 if (read_u32(records, at) != 0x43) continue;
165 Digest d;
166 std::memcpy(d.data(), records.data() + at + 4, 16);
167 if (seen.insert(d).second) out.push_back(d);
168 }
169 return out;
170}
171
172inline std::string hex(const Digest& d) {
173 static constexpr char kHex[] = "0123456789abcdef";
174 std::string s;
175 for (const std::uint8_t b : d) {
176 s += kHex[b >> 4];
177 s += kHex[b & 15];
178 }
179 return s;
180}
181
182inline std::optional<Digest> parse_digest(std::string_view text) {
183 if (text.size() != 32) return std::nullopt;
184 Digest d{};
185 for (std::size_t i = 0; i < 32; ++i) {
186 const char c = text[i];
187 int v = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;
188 if (v < 0) return std::nullopt;
189 d[i / 2] = static_cast<std::uint8_t>(d[i / 2] << 4 | v);
190 }
191 return d;
192}
193
194struct ShaderRef {
195 Digest digest;
196 std::string stage; // the translator's stage: "vs", "ps", "gs", "ms", "cs"
197 std::string path; // the container, relative to the map file's folder, '/' separated
198};
199
200// native_hashes.txt, written by tools/native_pso_hashes.py next to the translator's index.json: a first line
201// "# native_pso_hashes 1", then one "<32 hex digest>\t<stage>\t<relative container path>" line per digest.
202class HashMap {
203public:
204 static constexpr std::string_view kHeader = "# native_pso_hashes 1";
205
206 bool parse(std::string_view text, std::string* error = nullptr) {
207 const auto fail = [&](std::string why) {
208 if (error) *error = std::move(why);
209 map_.clear();
210 return false;
211 };
212 map_.clear();
213 std::size_t line_no = 0;
214 bool header = false;
215 while (!text.empty()) {
216 const std::size_t end = text.find('\n');
217 std::string_view line = text.substr(0, end);
218 text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1);
219 ++line_no;
220 if (!line.empty() && line.back() == '\r') line.remove_suffix(1);
221 if (line_no == 1) {
222 if (line != kHeader) return fail("native_hashes.txt: unknown header");
223 header = true;
224 continue;
225 }
226 if (line.empty() || line.front() == '#') continue;
227 const std::size_t t1 = line.find('\t');
228 const std::size_t t2 = t1 == std::string_view::npos ? t1 : line.find('\t', t1 + 1);
229 if (t2 == std::string_view::npos || t2 + 1 >= line.size())
230 return fail("native_hashes.txt line " + std::to_string(line_no) + ": expected three fields");
231 const auto digest = parse_digest(line.substr(0, t1));
232 const std::string_view stage = line.substr(t1 + 1, t2 - t1 - 1);
233 if (!digest || stage.empty())
234 return fail("native_hashes.txt line " + std::to_string(line_no) + ": bad digest or stage");
235 const std::string_view path = line.substr(t2 + 1);
236 const auto [it, inserted] = map_.try_emplace(*digest, ShaderRef{*digest, std::string(stage), std::string(path)});
237 if (!inserted && (it->second.stage != stage || it->second.path != path))
238 return fail("native_hashes.txt line " + std::to_string(line_no) + ": conflicting digest");
239 }
240 if (!header) return fail("native_hashes.txt is empty");
241 return true;
242 }
243
244 const ShaderRef* find(const Digest& d) const {
245 const auto it = map_.find(d);
246 return it == map_.end() ? nullptr : &it->second;
247 }
248
249 std::size_t size() const { return map_.size(); }
250
251private:
252 std::map<Digest, ShaderRef> map_;
253};
254
255struct PlannedStage {
256 std::size_t block = 0;
257 const ShaderRef* shader = nullptr;
258};
259
260enum class PlanStatus {
261 ok,
262 malformed, // a pair is malformed or blob B does not decode
263 missing, // a stage has no records, or its digest names no translated container
264 ambiguous, // a stage's records name two different containers
265 unsupported, // a stage kind this path does not build (hs, ds, cs), two of one kind, or no VS/MS
266};
267
268struct Plan {
269 PlanStatus status = PlanStatus::malformed;
270 FixedState state;
271 std::vector<PlannedStage> stages; // in block order
272 std::size_t failed_block = 0; // for missing/ambiguous/unsupported/malformed blocks
273 const char* reason = ""; // why a description is malformed
274 bool mesh = false; // an MS stage: the pipeline goes through a pipeline state stream
275
276 const ShaderRef* stage(std::string_view name) const {
277 for (const PlannedStage& s : stages)
278 if (s.shader->stage == name) return s.shader;
279 return nullptr;
280 }
281};
282
283inline Plan plan(const GraphicsDesc& desc, const HashMap& map) {
284 Plan p;
285 if (pair_state(desc.state_a) == PairState::malformed) {
286 p.reason = "blob A pair malformed";
287 return p;
288 }
289 if (pair_state(desc.state_b) != PairState::present) {
290 p.reason = "blob B pair absent or malformed";
291 return p;
292 }
293 auto state = decode_state_b(bytes(desc.state_b), &p.reason);
294 if (!state) return p;
295 p.state = std::move(*state);
296 for (std::size_t k = 0; k < kStageBlocks; ++k) {
297 const StageBlock& block = desc.stages[k];
298 const PairState code = pair_state(block.code), records = pair_state(block.records);
299 p.failed_block = k;
300 if (code == PairState::malformed || records == PairState::malformed) {
301 p.reason = "a stage pair malformed";
302 return p;
303 }
304 if (code == PairState::absent && records == PairState::absent) continue;
305 if (records != PairState::present) { // code without records: nothing names its container
306 p.status = PlanStatus::missing;
307 return p;
308 }
309 const ShaderRef* found = nullptr;
310 for (const Digest& d : record_digests(bytes(block.records))) {
311 const ShaderRef* ref = map.find(d);
312 if (!ref) continue;
313 if (found && found != ref) {
314 p.status = PlanStatus::ambiguous;
315 p.failed_block = k;
316 return p;
317 }
318 found = ref;
319 }
320 p.failed_block = k;
321 if (!found) {
322 p.status = PlanStatus::missing;
323 return p;
324 }
325 const std::string& s = found->stage;
326 if (!(s == "vs" || s == "ps" || s == "gs" || s == "ms") || p.stage(s)) {
327 p.status = PlanStatus::unsupported;
328 return p;
329 }
330 p.stages.push_back({k, found});
331 }
332 const bool vs = p.stage("vs"), ms = p.stage("ms");
333 if (vs == ms || (ms && p.stage("gs"))) {
334 p.status = PlanStatus::unsupported;
335 return p;
336 }
337 p.mesh = ms;
338 p.status = PlanStatus::ok;
339 return p;
340}
341
342} // namespace leonida::native_pso
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index c29a288a9..3558cffb5 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -19,6 +19,8 @@
19#include "../shims/shims.h" 19#include "../shims/shims.h"
20#include "../shims/startup_trace.h" 20#include "../shims/startup_trace.h"
21#include "base_reservation.h" 21#include "base_reservation.h"
22#include "clzero_patch.h"
23#include "cpu_emulation.h"
22 24
23namespace rt { 25namespace rt {
24 26
@@ -126,8 +128,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
126// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader 128// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader
127// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent 129// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent
128// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). 130// module TLS index for each simultaneous module (up to kMaxMappedTlsModules).
131//
132// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads
133// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the
134// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively
135// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0
136// belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each
137// test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct
138// gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner
139// off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of
140// the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS
141// starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction:
142// nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy
143// replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit.
144// It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index]
145// across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then
146// reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a
147// thread's TLS would also stay where it was, at index 0.
129constexpr DWORD kMaxModuleTlsSlots = 64; 148constexpr DWORD kMaxModuleTlsSlots = 64;
130constexpr size_t kMaxMappedTlsModules = 16; 149constexpr size_t kMaxMappedTlsModules = 16;
150// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second
151// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables.
152constexpr size_t kMainImageSlot = kMaxMappedTlsModules;
153constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1;
131void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 154void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
132 155
133void __cdecl on_host_thread_event(DWORD reason); 156void __cdecl on_host_thread_event(DWORD reason);
@@ -135,6 +158,7 @@ void __cdecl on_host_thread_event(DWORD reason);
135struct TlsHostModule { 158struct TlsHostModule {
136 HMODULE module = nullptr; 159 HMODULE module = nullptr;
137 DWORD index = TLS_OUT_OF_INDEXES; 160 DWORD index = TLS_OUT_OF_INDEXES;
161 bool hooked = false; // its DllMain reports thread events to on_host_thread_event
138}; 162};
139 163
140std::filesystem::path tls_host_base_path() { 164std::filesystem::path tls_host_base_path() {
@@ -167,20 +191,39 @@ struct TlsCloneRecord {
167 191
168std::mutex g_tls_alloc_mutex; 192std::mutex g_tls_alloc_mutex;
169std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 193std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
170std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 194std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{};
171std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; 195std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{};
172std::atomic<uint64_t> g_next_tls_generation{1}; 196std::atomic<uint64_t> g_next_tls_generation{1};
173std::vector<TlsCloneRecord> g_tls_clones; 197// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a
198// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under
199// g_tls_alloc_mutex, as are its records.
200std::vector<TlsCloneRecord>* g_tls_clones = nullptr;
201
202// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under
203// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index.
204// Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic
205// initializers of this file, which would otherwise reset what it wrote.
206struct Index0Move {
207 bool moved = false;
208 bool traced = false; // the startup trace opens after the move; the first executable map reports it
209 TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed
210 char owner[260] = {}; // UTF-8 file name of the image that held index 0
211 char why[160] = "reserve_tls_index0 was not called at process start";
212};
213Index0Move g_index0;
174 214
175// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; 215// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the
176// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it 216// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before
177// only when no mapped code can run again: it unmaps the helper images. 217// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper
218// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the
219// next run's sweep deletes it.
178void cleanup_tls_clones_internal() { 220void cleanup_tls_clones_internal() {
179 for (const auto& rec : g_tls_clones) { 221 if (!g_tls_clones) return;
222 for (const auto& rec : *g_tls_clones) {
180 if (rec.module) FreeLibrary(rec.module); 223 if (rec.module) FreeLibrary(rec.module);
181 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 224 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
182 } 225 }
183 g_tls_clones.clear(); 226 g_tls_clones->clear();
184} 227}
185 228
186void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } 229void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
@@ -204,10 +247,14 @@ DWORD clone_owner_pid(const wchar_t* name) {
204bool process_alive(DWORD pid) { 247bool process_alive(DWORD pid) {
205 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the 248 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
206 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. 249 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
250 // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a
251 // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides.
207 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); 252 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
208 if (!p) return false; 253 if (!p) return false;
254 DWORD code = 0;
255 const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE;
209 CloseHandle(p); 256 CloseHandle(p);
210 return true; 257 return alive;
211} 258}
212 259
213// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a 260// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
@@ -262,45 +309,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t
262 if (hook_thread_events) { 309 if (hook_thread_events) {
263 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. 310 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots.
264 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); 311 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
265 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) 312 auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"));
313 if (set) {
266 set(&on_host_thread_event); 314 set(&on_host_thread_event);
315 host.hooked = true;
316 }
267 } 317 }
268 return host; 318 return host;
269} 319}
270 320
271// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). 321// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event
272TlsHostModule ensure_tls_host(size_t slot) { 322// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the
273 if (slot >= kMaxMappedTlsModules) return {}; 323// Windows loader lock).
274 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; 324// A helper without the thread-event export is refused: no thread started later would get its copies.
275 325bool ensure_primary_tls_host() {
326 if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true;
276 const std::filesystem::path primary = tls_host_base_path(); 327 const std::filesystem::path primary = tls_host_base_path();
277 if (primary.empty()) return {}; 328 if (primary.empty()) return false;
278 329 TlsHostModule host = load_tls_host_image(primary, true);
279 if (slot == 0) { 330 if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) {
280 g_tls_hosts[0] = load_tls_host_image(primary, true); 331 FreeLibrary(host.module);
281 return g_tls_hosts[0]; 332 return false;
282 }
283
284 // Ensure slot 0 is loaded first so thread attach/detach events are hooked.
285 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) {
286 g_tls_hosts[0] = load_tls_host_image(primary, true);
287 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {};
288 } 333 }
334 g_tls_hosts[0] = host;
335 return host.index != TLS_OUT_OF_INDEXES;
336}
289 337
338// Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the
339// clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and
340// the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule
341// as ensure_primary_tls_host.
342TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path,
343 const std::vector<uint8_t>* image = nullptr) {
344 const std::filesystem::path primary = tls_host_base_path();
345 if (primary.empty()) return {};
290 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). 346 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem).
291 const std::filesystem::path dir = tls_host_clone_dir(); 347 const std::filesystem::path dir = tls_host_clone_dir();
292 static bool swept = false; 348 static bool swept = false;
293 if (!swept) { 349 if (!swept) {
294 swept = true; 350 swept = true;
295 sweep_stale_tls_clones(dir); 351 sweep_stale_tls_clones(dir);
296 std::atexit(&cleanup_tls_clones_at_exit);
297 } 352 }
298 const std::wstring name = 353 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll";
299 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 354 clone_path = dir / name;
300 const std::filesystem::path clone_path = dir / name;
301 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. 355 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
302 const std::filesystem::path staging = clone_path.wstring() + L".new"; 356 const std::filesystem::path staging = clone_path.wstring() + L".new";
303 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; 357 if (image) {
358 HANDLE out =
359 CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
360 if (out == INVALID_HANDLE_VALUE) return {};
361 DWORD written = 0;
362 const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) &&
363 written == image->size();
364 CloseHandle(out);
365 if (!ok) {
366 DeleteFileW(staging.c_str());
367 return {};
368 }
369 } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) {
370 return {};
371 }
304 372
305 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename 373 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename
306 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone 374 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone
@@ -320,18 +388,34 @@ TlsHostModule ensure_tls_host(size_t slot) {
320 TlsHostModule loaded = load_tls_host_image(clone_path, false); 388 TlsHostModule loaded = load_tls_host_image(clone_path, false);
321 CloseHandle(guard); 389 CloseHandle(guard);
322 390
323 if (loaded.index == TLS_OUT_OF_INDEXES) { 391 if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str());
392 return loaded;
393}
394
395// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock).
396TlsHostModule ensure_tls_host(size_t slot) {
397 if (slot >= kMaxMappedTlsModules) return {};
398 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot];
399 // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked.
400 if (!ensure_primary_tls_host()) return {};
401 if (slot == 0) return g_tls_hosts[0];
402
403 std::filesystem::path clone_path;
404 TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path);
405 if (loaded.index == TLS_OUT_OF_INDEXES) return {};
406 // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS.
407 bool taken = loaded.index == 0 || loaded.index == g_index0.home.index;
408 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index;
409 if (taken) {
410 FreeLibrary(loaded.module);
324 DeleteFileW(clone_path.c_str()); 411 DeleteFileW(clone_path.c_str());
325 return {}; 412 return {};
326 } 413 }
327 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 414 if (!g_tls_clones) {
328 if (i != slot && g_tls_hosts[i].index == loaded.index) { 415 g_tls_clones = new std::vector<TlsCloneRecord>;
329 FreeLibrary(loaded.module); 416 std::atexit(&cleanup_tls_clones_at_exit);
330 DeleteFileW(clone_path.c_str());
331 return {};
332 }
333 } 417 }
334 g_tls_clones.push_back({loaded.module, clone_path}); 418 g_tls_clones->push_back({loaded.module, clone_path});
335 g_tls_hosts[slot] = loaded; 419 g_tls_hosts[slot] = loaded;
336 return g_tls_hosts[slot]; 420 return g_tls_hosts[slot];
337} 421}
@@ -347,7 +431,7 @@ struct ThreadTlsSlot {
347}; 431};
348 432
349// Per-thread installation state for each reserved TLS slot. 433// Per-thread installation state for each reserved TLS slot.
350thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; 434thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{};
351 435
352// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared 436// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared
353// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows 437// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
@@ -366,10 +450,185 @@ struct ExclusiveTlsLock {
366 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; 450 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
367}; 451};
368 452
453// gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its
454// .rdata and that array's size.
455constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template";
456constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size";
457
458// File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one
459// section's raw data.
460size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) {
461 const auto* sec = IMAGE_FIRST_SECTION(nt);
462 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
463 if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break;
464 if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData)
465 continue;
466 const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress);
467 return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX;
468 }
469 return SIZE_MAX;
470}
471
472// The RVA of a named export in an image file held in memory, 0 when it has none.
473uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) {
474 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT);
475 const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY));
476 if (!dir.Size || ed_off == SIZE_MAX) return 0;
477 const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off);
478 const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames);
479 const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames);
480 const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions);
481 if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0;
482 const size_t wanted_len = std::strlen(wanted) + 1;
483 for (uint32_t i = 0; i < ed->NumberOfNames; ++i) {
484 uint32_t name_rva, func_rva;
485 uint16_t ord;
486 std::memcpy(&name_rva, file.data() + names + 4 * i, 4);
487 std::memcpy(&ord, file.data() + ords + 2 * i, 2);
488 const size_t name = file_offset(file, nt, name_rva, wanted_len);
489 if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue;
490 if (ord >= ed->NumberOfFunctions) return 0;
491 std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4);
492 return func_rva;
493 }
494 return 0;
495}
496
497// Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which
498// starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the
499// array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home
500// index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too:
501// LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's
502// Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not.
503std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) {
504 if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated";
505 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data());
506 if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 ||
507 static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
508 return "gta6rt_tls_host.dll has no PE header";
509 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
510 if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
511 return "gta6rt_tls_host.dll is not a 64-bit image";
512 const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport);
513 const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport);
514 const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t));
515 if (!array_rva || !size_rva || size_off == SIZE_MAX)
516 return "gta6rt_tls_host.dll has no gta6rt_tls_home_template";
517 uint32_t capacity;
518 std::memcpy(&capacity, file.data() + size_off, sizeof(capacity));
519 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
520 const uint64_t total = raw + owner.SizeOfZeroFill;
521 if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity)
522 return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" +
523 std::to_string(capacity) + " bytes)";
524 const size_t array_off = file_offset(file, nt, array_rva, capacity);
525 const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
526 const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64));
527 if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX)
528 return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file";
529 std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw);
530 std::memset(file.data() + array_off + raw, 0, capacity - raw);
531 auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off);
532 tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva;
533 tls->EndAddressOfRawData = tls->StartAddressOfRawData + total;
534 tls->SizeOfZeroFill = 0;
535 tls->Characteristics =
536 (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK);
537 return {};
538}
539
540std::string module_file_name(HMODULE module) {
541 wchar_t path[MAX_PATH];
542 const DWORD n = GetModuleFileNameW(module, path, MAX_PATH);
543 if (!n || n >= MAX_PATH) return "?";
544 const wchar_t* name = path;
545 for (const wchar_t* p = path; *p; ++p)
546 if (*p == L'\\' || *p == L'/') name = p + 1;
547 const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr);
548 if (bytes <= 1) return "?";
549 std::string out(static_cast<size_t>(bytes - 1), '\0');
550 WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr);
551 return out;
552}
553
554// The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After
555// it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads.
556__declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) {
557 void** slots = module_tls_slots();
558 std::swap(slots[0], slots[home]);
559 *owner_index = home;
560}
561
562// See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads
563// no thread_local data and runs no code that does, before or after the move.
564std::string reserve_index0() {
565 // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE
566 // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too.
567 const HMODULE exe = GetModuleHandleW(nullptr);
568 auto* base = reinterpret_cast<uint8_t*>(exe);
569 auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew);
570 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
571 if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its";
572 const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress);
573 auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex);
574 if (!owner_index) return "the process executable's TLS directory has no index";
575 if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0";
576 if (!module_tls_slots()) return "this thread has no TLS array";
577 if (!ensure_primary_tls_host())
578 return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event";
579
580 std::vector<uint8_t> image;
581 try {
582 image = read_file(tls_host_base_path());
583 } catch (const std::exception& e) {
584 return e.what();
585 }
586 if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why;
587 std::filesystem::path path;
588 const TlsHostModule home = load_tls_host_clone(L"home", path, &image);
589 if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded";
590 auto drop = [&](std::string why) {
591 FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet
592 DeleteFileW(path.c_str());
593 return why;
594 };
595 bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots;
596 for (const auto& host : g_tls_hosts) taken |= host.index == home.index;
597 if (taken) return drop("the home clone got an unusable module TLS index");
598 // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size.
599 auto* home_base = reinterpret_cast<uint8_t*>(home.module);
600 auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew);
601 const auto* home_tls =
602 at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress);
603 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
604 if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill ||
605 std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData),
606 reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0)
607 return drop("the home clone's mapped TLS template is not the owner's");
608
609 // Everything that can throw comes first: past the move this records the result and nothing more.
610 const std::string name = module_file_name(exe);
611 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section.
612 DWORD old_protect = 0;
613 if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect))
614 return drop("the owner's _tls_index cannot be written");
615 move_index0_on_this_thread(owner_index, home.index);
616 VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect);
617
618 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the
619 // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped
620 // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until
621 // a later run's sweep.
622 g_index0.home = home;
623 std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str());
624 g_index0.moved = true;
625 return {};
626}
627
369// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this 628// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
370// thread's record, so it also works after the module that installed the copy is gone. 629// thread's record, so it also works after the module that installed the copy is gone.
371void release_thread_slot(size_t slot) { 630void release_thread_slot(size_t slot) {
372 if (slot >= kMaxMappedTlsModules) return; 631 if (slot >= kTlsSlotCount) return;
373 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 632 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
374 if (!entry.module && !entry.block) return; 633 if (!entry.module && !entry.block) return;
375 if (entry.ga_view) { 634 if (entry.ga_view) {
@@ -438,7 +697,7 @@ void** make_ga_view(const Module& m, void* block) {
438} 697}
439 698
440void install_thread_block(Module& m) { 699void install_thread_block(Module& m) {
441 if (m.tls_slot >= kMaxMappedTlsModules) return; 700 if (m.tls_slot >= kTlsSlotCount) return;
442 const size_t slot = m.tls_slot; 701 const size_t slot = m.tls_slot;
443 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 702 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
444 if (entry.module == &m && entry.generation == m.tls_generation) return; 703 if (entry.module == &m && entry.generation == m.tls_generation) return;
@@ -530,7 +789,7 @@ bool ga_tls_patch_enabled() {
530} 789}
531 790
532void uninstall_thread_block(Module& m) { 791void uninstall_thread_block(Module& m) {
533 if (m.tls_slot >= kMaxMappedTlsModules) return; 792 if (m.tls_slot >= kTlsSlotCount) return;
534 const size_t slot = m.tls_slot; 793 const size_t slot = m.tls_slot;
535 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 794 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
536 if (entry.module != &m || entry.generation != m.tls_generation) return; 795 if (entry.module != &m || entry.generation != m.tls_generation) return;
@@ -697,7 +956,7 @@ constexpr size_t kMaxEndedThreads = 1024;
697// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. 956// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
698void install_on_existing_threads(Module& m) { 957void install_on_existing_threads(Module& m) {
699 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; 958 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
700 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; 959 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return;
701 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which 960 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
702 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. 961 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
703 if (!query_thread_fn()) return; 962 if (!query_thread_fn()) return;
@@ -882,7 +1141,11 @@ void release_existing_blocks_of_this_thread() {
882// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 1141// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
883// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 1142// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
884// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 1143// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
885// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 1144// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates
1145// every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain,
1146// for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the
1147// callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the
1148// executable's slot, each releasing its copy after its callbacks.
886void __cdecl on_host_thread_event(DWORD reason) { 1149void __cdecl on_host_thread_event(DWORD reason) {
887 SharedTlsLock lock; 1150 SharedTlsLock lock;
888 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 1151 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
@@ -893,14 +1156,25 @@ void __cdecl on_host_thread_event(DWORD reason) {
893 } catch (const std::exception& e) { 1156 } catch (const std::exception& e) {
894 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); 1157 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
895 } 1158 }
896 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 1159 std::array<Module*, kTlsSlotCount> installed{};
1160 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
897 Module* m = g_tls_slot_owners[slot].load(); 1161 Module* m = g_tls_slot_owners[slot].load();
898 if (!m) continue; 1162 if (!m) continue;
899 try { 1163 try {
900 install_thread_block(*m); 1164 install_thread_block(*m);
901 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 1165 installed[slot] = m;
1166 } catch (const std::exception& e) {
1167 // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs.
1168 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
1169 e.what());
1170 }
1171 }
1172 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
1173 Module* m = installed[slot];
1174 if (!m || !m->initialised) continue;
1175 try {
1176 run_callbacks(*m, DLL_THREAD_ATTACH);
902 } catch (const std::exception& e) { 1177 } catch (const std::exception& e) {
903 // The thread runs on without this module's TLS; later slots still get theirs.
904 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), 1178 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
905 e.what()); 1179 e.what());
906 } 1180 }
@@ -913,7 +1187,8 @@ void __cdecl on_host_thread_event(DWORD reason) {
913 } catch (const std::exception& e) { 1187 } catch (const std::exception& e) {
914 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); 1188 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
915 } 1189 }
916 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 1190 for (size_t step = 0; step < kTlsSlotCount; ++step) {
1191 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot;
917 Module* m = g_tls_slot_owners[i].load(); 1192 Module* m = g_tls_slot_owners[i].load();
918 if (m && g_thread_tls_slots[i].module == m && 1193 if (m && g_thread_tls_slots[i].module == m &&
919 g_thread_tls_slots[i].generation == m->tls_generation) { 1194 g_thread_tls_slots[i].generation == m->tls_generation) {
@@ -1017,6 +1292,26 @@ void redirect_pc_to_file_header_at(const void* resolved) {
1017// Declared in pe_loader.h; the body needs the internal clone registry above. 1292// Declared in pe_loader.h; the body needs the internal clone registry above.
1018void cleanup_tls_clones() { cleanup_tls_clones_internal(); } 1293void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
1019 1294
1295bool reserve_tls_index0(std::string* why) {
1296 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1297 static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code
1298 if (!attempted) {
1299 attempted = true;
1300 // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed
1301 // reservation like any other: gta6rt calls this before main, where an exception would end it with no message.
1302 try {
1303 const std::string reason = reserve_index0();
1304 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str());
1305 } catch (const std::exception& e) {
1306 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what());
1307 } catch (...) {
1308 std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it");
1309 }
1310 }
1311 if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why);
1312 return g_index0.moved;
1313}
1314
1020namespace { 1315namespace {
1021bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 1316bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
1022 return static_cast<Loader*>(ctx)->find_address(address, module, rva); 1317 return static_cast<Loader*>(ctx)->find_address(address, module, rva);
@@ -1094,11 +1389,12 @@ Loader::~Loader() {
1094 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored 1389 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored
1095 } 1390 }
1096 } 1391 }
1392 shims::remove_xmem_allocation_hooks(this);
1097 shims::remove_bundled_loader(this); 1393 shims::remove_bundled_loader(this);
1098 shims::remove_module_lookup(this); 1394 shims::remove_module_lookup(this);
1099 for (auto* m : order_) { 1395 for (auto* m : order_) {
1100 // TLS state must go away before the image and its TLS block are unmapped. 1396 // TLS state must go away before the image and its TLS block are unmapped.
1101 if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { 1397 if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) {
1102 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a 1398 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
1103 // thread that still holds a copy frees it when it ends (on_host_thread_event). 1399 // thread that still holds a copy frees it when it ends (on_host_thread_event).
1104 { 1400 {
@@ -1498,6 +1794,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1498 // installed here, before bind_imports can return control to the caller and before any image code can run. 1794 // installed here, before bind_imports can return control to the caller and before any image code can run.
1499 initialize_tls(*m); 1795 initialize_tls(*m);
1500 parse_exports(*m); 1796 parse_exports(*m);
1797 if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) {
1798 const auto offset = static_cast<uint64_t>(static_cast<uint8_t*>(it->second) - m->base);
1799 if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) {
1800 shims::add_xmem_allocation_hooks(this, static_cast<const shims::XMemAllocationHooks*>(it->second));
1801 }
1802 }
1501 return *m; 1803 return *m;
1502} 1804}
1503 1805
@@ -1507,7 +1809,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1507// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 1809// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
1508// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone 1810// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
1509// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than 1811// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
1510// silently sharing (and corrupting) a slot. 1812// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows.
1511void Loader::initialize_tls(Module& m) { 1813void Loader::initialize_tls(Module& m) {
1512 auto* tls = tls_directory(m); 1814 auto* tls = tls_directory(m);
1513 if (!tls) return; 1815 if (!tls) return;
@@ -1536,26 +1838,51 @@ void Loader::initialize_tls(Module& m) {
1536 1838
1537 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 1839 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
1538 1840
1539 size_t slot = kMaxMappedTlsModules; 1841 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1842 const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
1843
1844 size_t slot = kTlsSlotCount;
1540 DWORD index = TLS_OUT_OF_INDEXES; 1845 DWORD index = TLS_OUT_OF_INDEXES;
1541 { 1846 {
1542 std::lock_guard alloc_lock(g_tls_alloc_mutex); 1847 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1543 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 1848 if (executable) {
1544 if (g_tls_slot_owners[i].load() == nullptr) { 1849 if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) {
1545 slot = i; 1850 slot = kMainImageSlot;
1546 break; 1851 index = 0;
1852 if (!g_index0.traced && startup_trace::enabled()) {
1853 g_index0.traced = true;
1854 startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) +
1855 ",\"moved_to\":" + std::to_string(g_index0.home.index));
1856 }
1857 } else {
1858 // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write
1859 // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to
1860 // run such an image (main.cpp); a Loader user must not run its code either.
1861 std::fprintf(stderr,
1862 "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use "
1863 "another module's TLS\n",
1864 m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why);
1547 } 1865 }
1548 } 1866 }
1549 if (slot >= kMaxMappedTlsModules) 1867 if (slot == kTlsSlotCount) {
1550 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + 1868 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
1551 " manually mapped static TLS slots are in use"); 1869 if (g_tls_slot_owners[i].load() == nullptr) {
1552 1870 slot = i;
1553 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with 1871 break;
1554 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). 1872 }
1555 index = ensure_tls_host(slot).index; 1873 }
1556 if (index == TLS_OUT_OF_INDEXES) 1874 if (slot >= kMaxMappedTlsModules)
1557 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); 1875 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1558 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); 1876 " manually mapped static TLS slots are in use");
1877
1878 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1879 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1880 index = ensure_tls_host(slot).index;
1881 if (index == TLS_OUT_OF_INDEXES)
1882 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1883 if (index >= kMaxModuleTlsSlots)
1884 throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1885 }
1559 1886
1560 // The fields are complete before a thread event can see the owner. 1887 // The fields are complete before a thread event can see the owner.
1561 ExclusiveTlsLock lock; 1888 ExclusiveTlsLock lock;
@@ -1857,6 +2184,24 @@ void Loader::bind_imports(Module& m) {
1857void Loader::protect_sections(Module& m) { 2184void Loader::protect_sections(Module& m) {
1858 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 2185 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1859 DWORD old; 2186 DWORD old;
2187 // On a CPU without CLZERO, the image's CLZERO loops run from stubs instead of taking a #UD per cache line
2188 // (clzero_patch.h). The sections are still writable here, and none of the image's code has run.
2189 static const bool clzero_missing = !rt::cpu_emulation::detect_host().clzero;
2190 if (clzero_missing && rt::clzero_patch::enabled()) {
2191 std::vector<std::pair<uint8_t*, size_t>> code;
2192 const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt);
2193 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) {
2194 if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue;
2195 const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData),
2196 m.size - cs->VirtualAddress);
2197 if (size) code.push_back({m.base + cs->VirtualAddress, static_cast<size_t>(size)});
2198 }
2199 const auto patched = rt::clzero_patch::patch(code, uint64_t(m.base), uint64_t(m.base) + m.size);
2200 if (patched.sites)
2201 std::fprintf(stderr,
2202 "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n",
2203 m.name.c_str(), patched.sites, static_cast<void*>(patched.stubs), patched.stub_bytes);
2204 }
1860 VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); 2205 VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old);
1861 auto* sec = IMAGE_FIRST_SECTION(nt); 2206 auto* sec = IMAGE_FIRST_SECTION(nt);
1862 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { 2207 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index fda924440..f75426e41 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -54,11 +54,15 @@ struct Module {
54 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array 54 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array
55 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading 55 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading
56 // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). 56 // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time).
57 // An executable gets index 0, as Windows gives the process EXE, because code built with /GA reads slot 0 without
58 // _tls_index. That needs reserve_tls_index0() at process start; without it, and for a second executable mapped
59 // while one holds index 0, the executable gets a helper index and a note on stderr, and its /GA code would use
60 // another module's TLS, so its code must not run (gta6rt refuses).
57 // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back 61 // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back
58 // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from 62 // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from
59 // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends. 63 // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends.
60 uint32_t tls_index = kNoTlsIndex; 64 uint32_t tls_index = kNoTlsIndex;
61 uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool 65 uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool ; 16 is index 0, an executable's
62 uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses 66 uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses
63 void* tls_block = nullptr; // calling thread's copy of the image's template 67 void* tls_block = nullptr; // calling thread's copy of the image's template
64 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader 68 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader
@@ -182,6 +186,14 @@ private:
182// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. 186// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images.
183void cleanup_tls_clones(); 187void cleanup_tls_clones();
184 188
189// Moves the runtime's own EXE off module TLS index 0, which Windows gave it, so that a mapped executable can have it
190// (Module::tls_index): its TLS moves to the index of one more helper clone, whose template is a copy of the EXE's.
191// Call it once at process start, before any other thread has run this EXE's code (gta6rt does it from a CRT
192// initializer): MSVC code keeps the address of its TLS slot across calls, so a thread that is already running cannot
193// be moved, and its TLS would stay at index 0. Returns false, with the reason in *why, when it cannot; later calls
194// return the first result.
195bool reserve_tls_index0(std::string* why = nullptr);
196
185std::string lower(std::string s); 197std::string lower(std::string s);
186 198
187} // namespace rt 199} // namespace rt
diff --git a/runtime/src/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h
new file mode 100644
index 000000000..98e5788a8
--- /dev/null
+++ b/runtime/src/pipeline_cache_file.h
@@ -0,0 +1,68 @@
1// Publish a checkpoint only after every byte has reached a closed, same-directory staging file.
2//
3// Used by vk_pipeline_check (its corpus checkpoints) and by the runtime, which writes the session cache on device
4// teardown (pipeline_cache_store.h; a reader of the old file keeps it open until its rename completes) and fills a
5// mapped session staging file directly (d3d12_pipeline_checkpoint.h).
6#pragma once
7
8#include <algorithm>
9#include <cerrno>
10#include <chrono>
11#include <cstdio>
12#include <filesystem>
13#include <string>
14#include <system_error>
15
16#ifdef _WIN32
17#include <thread>
18#include <windows.h>
19#endif
20
21inline std::error_code write_pipeline_cache_file(const std::filesystem::path& destination,
22 const char* data, size_t size) {
23 namespace fs = std::filesystem;
24 const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
25 fs::path staged;
26 std::FILE* file = nullptr;
27 for (int attempt = 0; attempt < 8; ++attempt) {
28 staged = destination;
29 staged += ".tmp." + std::to_string(stamp) + "." + std::to_string(attempt);
30#ifdef _WIN32
31 file = _wfopen(staged.c_str(), L"wbx");
32#else
33 file = std::fopen(staged.c_str(), "wbx");
34#endif
35 if (file || errno != EEXIST) break;
36 }
37 if (!file) return {errno, std::generic_category()};
38
39 std::error_code error;
40 // Keep individual CRT writes small even when the cache is several GiB.
41 while (size > 0) {
42 const size_t chunk = (std::min)(size, size_t{16} << 20);
43 if (std::fwrite(data, 1, chunk, file) != chunk || std::ferror(file)) {
44 error = {errno ? errno : EIO, std::generic_category()};
45 break;
46 }
47 data += chunk;
48 size -= chunk;
49 }
50 if (std::fflush(file) != 0 && !error) error = {errno ? errno : EIO, std::generic_category()};
51 if (std::fclose(file) != 0 && !error) error = {errno ? errno : EIO, std::generic_category()};
52 if (!error) {
53 fs::rename(staged, destination, error);
54#ifdef _WIN32
55 // A checker reading the previous cache can briefly block replacement if it did not share delete access.
56 for (int retry = 0; retry < 8; ++retry) {
57 if (error != std::errc::permission_denied && error.value() != ERROR_SHARING_VIOLATION) break;
58 std::this_thread::sleep_for(std::chrono::milliseconds(25));
59 fs::rename(staged, destination, error);
60 }
61#endif
62 }
63 if (error) {
64 std::error_code ignored;
65 fs::remove(staged, ignored);
66 }
67 return error;
68}
diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h
new file mode 100644
index 000000000..6d519d99b
--- /dev/null
+++ b/runtime/src/pipeline_cache_store.h
@@ -0,0 +1,69 @@
1// Persisting the runtime's VkPipelineCache across launches (D3D-704).
2//
3// Two files sit beside gta6rt.exe, and they are not interchangeable:
4//
5// pipeline_cache.bin the offline corpus seed the `pipelines` build stage writes (#367). Read only.
6// pipeline_cache.session.bin what the runtime compiled last time. Written on device teardown.
7//
8// Keeping them apart means a run can never replace the multi-GB corpus cache with the handful of pipelines it
9// happened to compile. On the next launch both are loaded and merged, so the offline entries and the previous
10// session's entries are available together.
11//
12// This header is pure stdlib on purpose (it does not include vulkan.h): pipeline_cache_store_test builds on hosts
13// where CMake has no Vulkan headers. The byte layout below is VkPipelineCacheHeaderVersionOne, whose 32 bytes are
14// part of Vulkan's ABI, not something a driver chooses.
15#pragma once
16
17#include <cstddef>
18#include <cstdint>
19#include <cstring>
20#include <limits>
21
22#include "cached_pso.h"
23
24namespace leonida::pipeline_cache_store {
25
26// A session cache normally holds what one boot compiled (a few MB to a few hundred MB). The cap is what keeps a
27// cache seeded from the multi-GB corpus file -- whose data comes back as the whole union -- from being rewritten
28// at every exit. Past it the previous session file is left alone; raise the limit with
29// LEONIDA_PIPELINE_CACHE_BYTES when a session really compiles that much.
30inline constexpr std::size_t default_save_limit = std::size_t{256} << 20; // 256 MiB
31
32struct SaveLimit {
33 std::size_t bytes = default_save_limit;
34 bool valid = true; // false when the text was not a byte count; bytes then stays at the default
35};
36
37// LEONIDA_PIPELINE_CACHE_BYTES: a decimal byte count, 0 turning the session file off entirely. Empty or absent
38// means the default; stray text, a sign or an overflow is reported by the caller and the default is used.
39inline SaveLimit parse_save_limit(const char* text) {
40 if (!text || !*text) return {};
41 std::size_t value = 0;
42 for (const char* p = text; *p; ++p) {
43 if (*p < '0' || *p > '9') return {default_save_limit, false};
44 const std::size_t digit = static_cast<std::size_t>(*p - '0');
45 if (value > (std::numeric_limits<std::size_t>::max() - digit) / 10) return {default_save_limit, false};
46 value = value * 10 + digit;
47 }
48 return {value, true};
49}
50
51inline constexpr std::size_t header_bytes = 32;
52inline constexpr std::uint32_t header_version_one = 1;
53
54inline std::uint32_t read_u32(const std::uint8_t* p) {
55 return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) |
56 (std::uint32_t(p[3]) << 24);
57}
58
59// True when the blob's header names this physical device and pipeline-cache UUID, which is what a driver requires
60// before it will read the opaque payload. The header is little-endian, like the host.
61inline bool header_matches(const void* data, std::size_t size, const cached_pso::Identity& identity) {
62 if (!data || size < header_bytes) return false;
63 const auto* bytes = static_cast<const std::uint8_t*>(data);
64 return read_u32(bytes) == header_bytes && read_u32(bytes + 4) == header_version_one &&
65 read_u32(bytes + 8) == identity.vendor && read_u32(bytes + 12) == identity.device &&
66 std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0;
67}
68
69} // namespace leonida::pipeline_cache_store
diff --git a/runtime/src/pipeline_profile.h b/runtime/src/pipeline_profile.h
new file mode 100644
index 000000000..f81c00c7d
--- /dev/null
+++ b/runtime/src/pipeline_profile.h
@@ -0,0 +1,70 @@
1// Optional driver-call timing. Match begin/end by id even when startup warmup and replay overlap.
2#pragma once
3
4#include <atomic>
5#include <chrono>
6#include <cstdio>
7#include <cstdlib>
8#include <cstring>
9#ifdef _WIN32
10#include <windows.h>
11#endif
12
13namespace leonida::pipeline_profile {
14
15inline bool enabled() {
16 static const bool enable = [] {
17 const char* value = std::getenv("LEONIDA_PSO_PROFILE");
18 return value && std::strcmp(value, "1") == 0;
19 }();
20 return enable;
21}
22
23inline long long unix_ms() {
24 return std::chrono::duration_cast<std::chrono::milliseconds>(
25 std::chrono::system_clock::now().time_since_epoch()).count();
26}
27
28// CPU charged to the calling thread distinguishes synchronous compilation from time waiting in the driver.
29inline long long thread_cpu_us() {
30#ifdef _WIN32
31 FILETIME creation{}, exit{}, kernel{}, user{};
32 if (GetThreadTimes(GetCurrentThread(), &creation, &exit, &kernel, &user)) {
33 const auto ticks = [](FILETIME t) {
34 return (static_cast<unsigned long long>(t.dwHighDateTime) << 32) | t.dwLowDateTime;
35 };
36 return static_cast<long long>((ticks(kernel) + ticks(user)) / 10);
37 }
38#endif
39 return -1;
40}
41
42class DriverCall {
43public:
44 DriverCall(const char* stage, const char* origin, const char* program, const char* fragment = "-",
45 unsigned unbound = 0) {
46 if (!enabled()) return;
47 static std::atomic<unsigned long long> sequence{0};
48 id_ = sequence.fetch_add(1, std::memory_order_relaxed) + 1;
49 start_ = std::chrono::steady_clock::now();
50 cpu_start_ = thread_cpu_us();
51 std::fprintf(stderr, "[rt] pso-driver begin id=%llu unix_ms=%lld stage=%s origin=%s program=%s ps=%s mask=%u\n",
52 id_, unix_ms(), stage, origin, program, fragment, unbound);
53 }
54
55 void finish(int result) const {
56 if (!id_) return;
57 const auto us = std::chrono::duration_cast<std::chrono::microseconds>(
58 std::chrono::steady_clock::now() - start_).count();
59 const long long cpu = thread_cpu_us();
60 std::fprintf(stderr, "[rt] pso-driver end id=%llu unix_ms=%lld us=%lld cpu_us=%lld result=%d\n",
61 id_, unix_ms(), static_cast<long long>(us), cpu >= 0 && cpu_start_ >= 0 ? cpu - cpu_start_ : -1,
62 result);
63 }
64private:
65 unsigned long long id_ = 0;
66 long long cpu_start_ = -1;
67 std::chrono::steady_clock::time_point start_{};
68};
69
70} // namespace leonida::pipeline_profile
diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h
new file mode 100644
index 000000000..2e594fcb5
--- /dev/null
+++ b/runtime/src/present_dump.h
@@ -0,0 +1,256 @@
1#pragma once
2
3// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals.
4#include <vulkan/vulkan.h>
5
6#include <algorithm>
7#include <array>
8#include <atomic>
9#include <charconv>
10#include <cmath>
11#include <cstdint>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <filesystem>
16#include <memory>
17#include <mutex>
18#include <span>
19#include <string>
20#include <thread>
21#include <vector>
22
23namespace leonida::present_dump {
24
25inline unsigned texel_size(VkFormat format) {
26 switch (format) {
27 case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB:
28 case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB:
29 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4;
30 case VK_FORMAT_R16G16B16A16_SFLOAT: return 8;
31 case VK_FORMAT_R32G32B32A32_SFLOAT: return 16;
32 default: return 0;
33 }
34}
35
36inline std::uint8_t unorm8(float v) {
37 return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0;
38}
39
40inline std::uint8_t half_unorm8(std::uint16_t bits) {
41 const int exponent = bits >> 10;
42 const int fraction = bits & 1023;
43 if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0;
44 return unorm8(std::ldexp(float(1024 + fraction), exponent - 25));
45}
46
47inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) {
48 if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) {
49 std::memcpy(dst, src, size_t(width) * 4);
50 return;
51 }
52 const unsigned stride = texel_size(format);
53 for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) {
54 if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) {
55 dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3];
56 } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) {
57 std::uint16_t v[4];
58 std::memcpy(v, src, sizeof(v));
59 std::transform(v, v + 4, dst, half_unorm8);
60 } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) {
61 float v[4];
62 std::memcpy(v, src, sizeof(v));
63 std::transform(v, v + 4, dst, unorm8);
64 } else {
65 // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR.
66 // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits.
67 static const auto pq_to_sdr = [] {
68 std::array<std::uint8_t, 1024> table{};
69 for (unsigned i = 0; i < table.size(); ++i) {
70 const double p = std::pow(i / 1023.0, 1.0 / 78.84375);
71 const double linear = (10000.0 / 203.0) *
72 std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125);
73 const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055;
74 table[i] = unorm8(float(srgb));
75 }
76 return table;
77 }();
78 std::uint32_t packed;
79 std::memcpy(&packed, src, sizeof(packed));
80 for (unsigned channel = 0; channel < 3; ++channel) {
81 const unsigned bits = (packed >> (10 * channel)) & 1023;
82 dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023);
83 }
84 if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]);
85 dst[3] = std::uint8_t((packed >> 30) * 85);
86 }
87 }
88}
89
90inline std::array<std::uint8_t, 4> big_endian(std::uint32_t n) {
91 return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)};
92}
93
94inline bool chunk(std::FILE* file, const char (&type)[5], std::span<const std::uint8_t> data,
95 std::span<const std::uint8_t> prefix = {}) {
96 static constexpr auto crc_table = [] {
97 std::array<std::uint32_t, 256> table{};
98 for (unsigned i = 0; i < table.size(); ++i) {
99 unsigned c = i;
100 for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0);
101 table[i] = c;
102 }
103 return table;
104 }();
105 std::uint32_t crc = ~0u;
106 const auto write = [&](std::span<const std::uint8_t> bytes) {
107 for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8);
108 return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size();
109 };
110 return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 &&
111 write({reinterpret_cast<const std::uint8_t*>(type), 4}) && write(prefix) && write(data) &&
112 std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4;
113}
114
115inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) {
116 constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10};
117 std::array<std::uint8_t, 13> ihdr{};
118 const auto w = big_endian(extent.width), h = big_endian(extent.height);
119 std::copy(w.begin(), w.end(), ihdr.begin());
120 std::copy(h.begin(), h.end(), ihdr.begin() + 4);
121 ihdr[8] = 8;
122 ihdr[9] = 6; // 8-bit RGBA
123 constexpr std::uint8_t zlib_header[]{0x78, 0x01};
124 if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) ||
125 !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false;
126
127 // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies
128 // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement).
129 std::vector<std::uint8_t> row(1 + size_t(extent.width) * 4);
130 std::uint32_t a = 1, b = 0;
131 for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) {
132 rgba_row(row.data() + 1, src, extent.width, format, pq);
133 std::span<const std::uint8_t> rest(row);
134 while (!rest.empty()) {
135 auto block = rest.first(std::min<size_t>(rest.size(), 65535));
136 rest = rest.subspan(block.size());
137 const auto len = std::uint16_t(block.size());
138 const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()),
139 std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)};
140 for (auto byte : block) {
141 a = (a + byte) % 65521;
142 b = (b + a) % 65521;
143 }
144 if (!chunk(file, "IDAT", block, header)) return false;
145 }
146 }
147 return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {});
148}
149
150class PresentDump {
151public:
152 PresentDump() {
153#ifdef _WIN32
154 wchar_t* env = nullptr;
155 size_t length = 0;
156 if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) {
157 bad_value();
158 return;
159 }
160 const std::unique_ptr<wchar_t, decltype(&std::free)> owned(env, &std::free);
161#else
162 const auto* env = std::getenv("LEONIDA_PRESENT_DUMP");
163#endif
164 if (!env) return;
165 try {
166 auto value = std::filesystem::path(env).native();
167 std::uint64_t interval = 60;
168 const auto comma = value.rfind(',');
169 if (comma != value.npos) {
170 const auto n = std::filesystem::path(value.substr(comma + 1)).string();
171 const auto end = n.data() + n.size();
172 const auto parsed = std::from_chars(n.data(), end, interval);
173 if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) {
174 bad_value();
175 return;
176 }
177 value.resize(comma);
178 }
179 if (value.empty()) {
180 bad_value();
181 return;
182 }
183 dir_ = std::filesystem::absolute(value);
184 std::filesystem::create_directories(dir_);
185 interval_ = interval;
186 } catch (const std::exception&) { bad_value(); }
187 }
188
189 bool enabled() const { return interval_ != 0; }
190 bool due(std::uint64_t frames_shown) const {
191 const auto n = interval_.load();
192 return n && frames_shown % n == 0;
193 }
194 void disable(const char* why) {
195 if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why);
196 }
197 void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) {
198 try {
199 // Bound memory to one outstanding write even at N=1. Teardown joins the final writer.
200 if (writer_.joinable()) writer_.join();
201 if (!enabled()) return;
202 char name[48];
203 std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast<unsigned long long>(frame));
204 writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name,
205 bytes = std::vector<std::uint8_t>(src, src + size)] {
206 try {
207 if (publish(path, extent, format, pq, bytes.data())) {
208 const auto utf8 = path.u8string();
209 std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n",
210 static_cast<unsigned long long>(frame), reinterpret_cast<const char*>(utf8.c_str()));
211 return;
212 }
213 } catch (const std::exception&) {}
214 disable("could not write the present dump");
215 });
216 } catch (const std::exception&) { disable("could not queue the present dump"); }
217 }
218
219private:
220 static void bad_value() {
221 static std::once_flag once;
222 std::call_once(once, [] {
223 std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n");
224 });
225 }
226 static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq,
227 const std::uint8_t* src) {
228 // Never open an existing output for writing: it could be a link to a file outside the dump directory.
229 // Build a complete sibling exclusively, then replace the directory entry in a single rename.
230 auto tmp = path;
231 tmp += ".tmp";
232#ifdef _WIN32
233 std::FILE* file = nullptr;
234 _wfopen_s(&file, tmp.c_str(), L"wbx");
235#else
236 auto* file = std::fopen(tmp.c_str(), "wbx");
237#endif
238 if (!file) return false;
239 bool ok = false;
240 try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {}
241 if (std::fclose(file) != 0) ok = false;
242 std::error_code ec;
243 if (ok) {
244 std::filesystem::rename(tmp, path, ec);
245 if (!ec) return true;
246 }
247 std::filesystem::remove(tmp, ec);
248 return false;
249 }
250
251 std::filesystem::path dir_;
252 std::atomic<std::uint64_t> interval_{0};
253 std::jthread writer_; // joined before the state it uses is destroyed
254};
255
256} // namespace leonida::present_dump
diff --git a/runtime/src/quad_index_expand.comp b/runtime/src/quad_index_expand.comp
new file mode 100644
index 000000000..697cf7665
--- /dev/null
+++ b/runtime/src/quad_index_expand.comp
@@ -0,0 +1,44 @@
1// Expand the index buffer of a console quad list into triangle-list indices without reading it on the CPU
2// (quad_index_expand.h). Each quad (i0 i1 i2 i3) becomes (i0 i1 i2) (i0 i2 i3) as six 32-bit indices: both
3// triangles start at the quad's first vertex, the one a flat input is taken from.
4#version 460
5#extension GL_EXT_buffer_reference : require
6layout(local_size_x = 64) in;
7layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn {
8 uint data[];
9};
10layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer WordsOut {
11 uint data[];
12};
13layout(push_constant) uniform Params {
14 WordsIn source; // the 4-byte aligned word that holds this dispatch's first index
15 WordsOut triangles; // six words for each quad of this dispatch
16 uint first_half; // 16-bit indices: 1 when the first index is the high half of its word
17 uint index_bits; // 16 or 32
18 uint limit; // how many of this dispatch's indices the index buffer view holds; the rest read 0
19 uint quads;
20} p;
21
22uint index_at(uint i) {
23 if (i >= p.limit) return 0u;
24 if (p.index_bits == 32u) return p.source.data[i];
25 const uint slot = i + p.first_half;
26 return (p.source.data[slot >> 1u] >> ((slot & 1u) * 16u)) & 0xffffu;
27}
28
29void main() {
30 const uint quad = gl_GlobalInvocationID.x;
31 if (quad >= p.quads) return;
32 const uint first = quad * 4u;
33 const uint i0 = index_at(first);
34 const uint i1 = index_at(first + 1u);
35 const uint i2 = index_at(first + 2u);
36 const uint i3 = index_at(first + 3u);
37 const uint target = quad * 6u;
38 p.triangles.data[target] = i0;
39 p.triangles.data[target + 1u] = i1;
40 p.triangles.data[target + 2u] = i2;
41 p.triangles.data[target + 3u] = i0;
42 p.triangles.data[target + 4u] = i2;
43 p.triangles.data[target + 5u] = i3;
44}
diff --git a/runtime/src/quad_index_expand.h b/runtime/src/quad_index_expand.h
new file mode 100644
index 000000000..3c539a540
--- /dev/null
+++ b/runtime/src/quad_index_expand.h
@@ -0,0 +1,182 @@
1// Indexed console quad lists (D3D_PRIMITIVE_TOPOLOGY 19) on Vulkan, which has no quad primitive.
2//
3// A quad is four indices and Vulkan can only draw it as triangles. A triangle fan per quad reads the application's
4// index buffer in place, but gets two things wrong: a fan takes a flat input from each triangle's own first vertex
5// (the quad's second and third), where the quad takes it from its first, and one draw per quad runs every instance
6// of quad 0 before quad 1, where D3D12 draws instance by instance (visible when instances overlap). So the indices
7// are rewritten instead: a compute pass (quad_index_expand.comp) reads the application's index buffer on the GPU and
8// writes (i0 i1 i2) (i0 i2 i3) for each quad as 32-bit indices into scratch that lives until the submission
9// completes (vulkan_scratch.h), and the draw is one indexed triangle list over that scratch with the application's
10// instance count, base vertex and first instance. Both triangles start at the quad's first vertex, so a flat input
11// is the first vertex's over the whole quad, and one draw keeps D3D12's instance order.
12//
13// The indices are read on the GPU, never on the host: an index buffer can be written by a copy or a shader earlier
14// in the same list. Index values are copied as they are (a 16-bit index is zero-extended), so VertexIndex -
15// BaseVertex is still the application's index. That includes the strip-cut value: 0xFFFF and 0xFFFFFFFF are
16// ordinary indices in a quad list, as in every list topology (the replay enables primitive restart for strips only),
17// and 0xFFFF stays vertex 65535 after the widening. An index past the end of the index buffer view reads 0, as
18// D3D12 defines it, and a draw's last one to three indices that do not make a quad are dropped.
19//
20// Needs bufferDeviceAddress (the pass reads and writes through device addresses, no descriptors) and scratch with
21// INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage. Non-indexed quad lists do not come here: they draw from a shared
22// constant index buffer (ReplayFunctions::quad_indices).
23#pragma once
24#ifndef VK_NO_PROTOTYPES
25#define VK_NO_PROTOTYPES
26#endif
27#include <vulkan/vulkan.h>
28#include <algorithm>
29#include <cstdint>
30#include "quad_index_expand_spv.h"
31
32namespace leonida {
33
34// One indexed quad-list draw's expansion. `buffer` is null for a draw that needs none.
35struct QuadIndexExpansion {
36 VkBuffer buffer = VK_NULL_HANDLE; // the triangle-list indices, 32-bit: six for each quad
37 VkDeviceSize offset = 0;
38 VkDeviceAddress source = 0; // the 4-byte aligned word that holds the draw's first index
39 VkDeviceAddress triangles = 0; // `buffer` + `offset`
40 std::uint64_t readable = 0; // indices from the draw's first one that the index buffer view holds
41 std::uint32_t first_half = 0; // 16-bit indices: 1 when the first index is the high half of its word
42 std::uint32_t index_bits = 0; // 16 or 32
43 std::uint32_t quads = 0;
44};
45
46class QuadIndexExpander {
47public:
48 static constexpr std::uint32_t indices_per_quad = 6;
49 // vkCmdDrawIndexed counts the expanded indices in 32 bits.
50 static constexpr std::uint32_t max_quads = UINT32_MAX / indices_per_quad;
51 // The scratch bytes `quads` quads expand into.
52 static constexpr VkDeviceSize bytes(std::uint32_t quads) {
53 return VkDeviceSize(quads) * indices_per_quad * sizeof(std::uint32_t);
54 }
55
56 QuadIndexExpander(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits)
57 : get_(get), device_(device), limits_(limits) {}
58 ~QuadIndexExpander() {
59 if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr);
60 if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr);
61 }
62 QuadIndexExpander(const QuadIndexExpander&) = delete;
63 QuadIndexExpander& operator=(const QuadIndexExpander&) = delete;
64
65 // `quads` quads from the indices at `index_offset` in `indices` (the draw's first index), of which the view holds
66 // `readable`, into bytes(quads) of `scratch` at `scratch_offset`. The pipeline is made on the first call; the
67 // caller serializes calls. False, with `out` cleared, when the draw cannot be expanded.
68 bool prepare(VkBuffer indices, VkDeviceSize index_offset, VkIndexType type, std::uint64_t readable,
69 std::uint32_t quads, VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
70 out = {};
71 const std::uint32_t index_bytes = type == VK_INDEX_TYPE_UINT16 ? 2 : type == VK_INDEX_TYPE_UINT32 ? 4 : 0;
72 if (!indices || !scratch || !index_bytes || !quads || quads > max_quads || index_offset % index_bytes ||
73 scratch_offset % sizeof(std::uint32_t) || !limits_.maxComputeWorkGroupCount[0] || !make_pipeline())
74 return false;
75 const auto address = fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress");
76 VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
77 info.buffer = indices;
78 const VkDeviceAddress source = address(device_, &info);
79 info.buffer = scratch;
80 const VkDeviceAddress target = address(device_, &info);
81 if (!source || !target || index_offset > UINT64_MAX - source || scratch_offset > UINT64_MAX - target ||
82 (source % sizeof(std::uint32_t)) || (target % sizeof(std::uint32_t)))
83 return false;
84 out.buffer = scratch;
85 out.offset = scratch_offset;
86 // The shader reads whole words: a 16-bit index at an address of 2 modulo 4 is the high half of its word.
87 out.source = (source + index_offset) & ~VkDeviceAddress(3);
88 out.first_half = std::uint32_t((index_offset & 3) / 2);
89 out.triangles = target + scratch_offset;
90 out.readable = readable;
91 out.index_bits = index_bytes * 8;
92 out.quads = quads;
93 return true;
94 }
95
96 // Records the pass: outside a render pass, before the draw that binds job.buffer as its index buffer.
97 void emit(VkCommandBuffer cb, const QuadIndexExpansion& job) const {
98 const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
99 // Whatever wrote the application's indices earlier in the command buffer (a copy, a shader) is visible.
100 VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
101 before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
102 before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
103 barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
104 0, 1, &before, 0, nullptr, 0, nullptr);
105 fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
106 struct Push {
107 VkDeviceAddress source, triangles;
108 std::uint32_t first_half, index_bits, limit, quads;
109 };
110 static_assert(sizeof(Push) == push_bytes);
111 // A dispatch indexes its quads and their indices in 32 bits: 4 * quad + 4 and 6 * quad + 5 must fit.
112 constexpr VkDeviceSize index_limit = 1u << 28;
113 const VkDeviceSize chunk_limit =
114 std::min(VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * group_size, index_limit);
115 for (VkDeviceSize first = 0; first < job.quads;) {
116 const std::uint32_t quads = std::uint32_t(std::min<VkDeviceSize>(chunk_limit, job.quads - first));
117 const VkDeviceSize first_index = first * 4;
118 // 16-bit indices: `first_index` is even, so the chunk starts at the same half of a word as the draw.
119 const VkDeviceSize source_bytes = first_index * (job.index_bits / 8);
120 const std::uint64_t left = job.readable > first_index ? job.readable - first_index : 0;
121 const Push push{job.source + source_bytes, job.triangles + first * indices_per_quad * 4,
122 job.first_half, job.index_bits, std::uint32_t(std::min<std::uint64_t>(left, UINT32_MAX)),
123 quads};
124 fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0,
125 sizeof(push), &push);
126 fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, (quads - 1u) / group_size + 1u, 1, 1);
127 first += quads;
128 }
129 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
130 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
131 after.dstAccessMask = VK_ACCESS_INDEX_READ_BIT;
132 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
133 0, 1, &after, 0, nullptr, 0, nullptr);
134 }
135
136private:
137 static constexpr std::uint32_t group_size = 64; // local_size_x of quad_index_expand.comp
138 static constexpr std::uint32_t push_bytes = 32;
139 template<typename T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); }
140 bool make_pipeline() {
141 if (pipeline_) return true;
142 for (const char* name : {"vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule",
143 "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline",
144 "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"})
145 if (!get_(device_, name)) return false;
146 VkShaderModule module = VK_NULL_HANDLE;
147 VkPipelineLayout layout = VK_NULL_HANDLE;
148 VkPipeline pipeline = VK_NULL_HANDLE;
149 VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
150 shader.codeSize = sizeof(quad_index_expand_spirv);
151 shader.pCode = quad_index_expand_spirv;
152 bool ok = fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS;
153 const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes};
154 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
155 layout_info.pushConstantRangeCount = 1;
156 layout_info.pPushConstantRanges = &range;
157 ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS;
158 VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
159 info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
160 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
161 info.stage.module = module;
162 info.stage.pName = "main";
163 info.layout = layout;
164 ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(
165 device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS;
166 if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr);
167 if (!ok) {
168 if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr);
169 if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr);
170 return false;
171 }
172 layout_ = layout;
173 pipeline_ = pipeline;
174 return true;
175 }
176 PFN_vkGetDeviceProcAddr get_;
177 VkDevice device_;
178 VkPhysicalDeviceLimits limits_;
179 VkPipelineLayout layout_ = VK_NULL_HANDLE;
180 VkPipeline pipeline_ = VK_NULL_HANDLE;
181};
182} // namespace leonida
diff --git a/runtime/src/quad_index_expand_spv.h b/runtime/src/quad_index_expand_spv.h
new file mode 100644
index 000000000..c7bb4b5c5
--- /dev/null
+++ b/runtime/src/quad_index_expand_spv.h
@@ -0,0 +1,148 @@
1// Generated with glslang 16.6.0: glslangValidator -V --target-env vulkan1.2 -Os --spirv-val quad_index_expand.comp
2#pragma once
3#include <cstdint>
4namespace leonida {
5inline constexpr std::uint32_t quad_index_expand_spirv[] = {
6 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000149u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
7 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu,
8 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000015u,
9 0x0000004au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u,
10 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u,
11 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, 0x0000000fu, 0x61726150u,
12 0x0000736du, 0x00050006u, 0x0000000fu, 0x00000000u, 0x72756f73u, 0x00006563u, 0x00060006u, 0x0000000fu,
13 0x00000001u, 0x61697274u, 0x656c676eu, 0x00000073u, 0x00060006u, 0x0000000fu, 0x00000002u, 0x73726966u,
14 0x61685f74u, 0x0000666cu, 0x00060006u, 0x0000000fu, 0x00000003u, 0x65646e69u, 0x69625f78u, 0x00007374u,
15 0x00050006u, 0x0000000fu, 0x00000004u, 0x696d696cu, 0x00000074u, 0x00050006u, 0x0000000fu, 0x00000005u,
16 0x64617571u, 0x00000073u, 0x00040005u, 0x00000011u, 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000011u,
17 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, 0x00000013u, 0x64726f57u, 0x74754f73u, 0x00000000u,
18 0x00050006u, 0x00000013u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00030005u, 0x00000015u, 0x00000070u,
19 0x00080005u, 0x0000004au, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u,
20 0x00030047u, 0x0000000fu, 0x00000002u, 0x00050048u, 0x0000000fu, 0x00000000u, 0x00000023u, 0x00000000u,
21 0x00050048u, 0x0000000fu, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x0000000fu, 0x00000002u,
22 0x00000023u, 0x00000010u, 0x00050048u, 0x0000000fu, 0x00000003u, 0x00000023u, 0x00000014u, 0x00050048u,
23 0x0000000fu, 0x00000004u, 0x00000023u, 0x00000018u, 0x00050048u, 0x0000000fu, 0x00000005u, 0x00000023u,
24 0x0000001cu, 0x00040047u, 0x00000010u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000011u, 0x00000002u,
25 0x00040048u, 0x00000011u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000011u, 0x00000000u, 0x00000023u,
26 0x00000000u, 0x00040047u, 0x00000012u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000013u, 0x00000002u,
27 0x00040048u, 0x00000013u, 0x00000000u, 0x00000019u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u,
28 0x00000000u, 0x00040047u, 0x0000004au, 0x0000000bu, 0x0000001cu, 0x00040047u, 0x0000009au, 0x0000000bu,
29 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u,
30 0x00000020u, 0x00000000u, 0x00030027u, 0x0000000du, 0x000014e5u, 0x00030027u, 0x0000000eu, 0x000014e5u,
31 0x0008001eu, 0x0000000fu, 0x0000000du, 0x0000000eu, 0x00000006u, 0x00000006u, 0x00000006u, 0x00000006u,
32 0x0003001du, 0x00000010u, 0x00000006u, 0x0003001eu, 0x00000011u, 0x00000010u, 0x00040020u, 0x0000000du,
33 0x000014e5u, 0x00000011u, 0x0003001du, 0x00000012u, 0x00000006u, 0x0003001eu, 0x00000013u, 0x00000012u,
34 0x00040020u, 0x0000000eu, 0x000014e5u, 0x00000013u, 0x00040020u, 0x00000014u, 0x00000009u, 0x0000000fu,
35 0x0004003bu, 0x00000014u, 0x00000015u, 0x00000009u, 0x00040015u, 0x00000016u, 0x00000020u, 0x00000001u,
36 0x0004002bu, 0x00000016u, 0x00000017u, 0x00000004u, 0x00040020u, 0x00000018u, 0x00000009u, 0x00000006u,
37 0x00020014u, 0x0000001bu, 0x0004002bu, 0x00000006u, 0x0000001fu, 0x00000000u, 0x0004002bu, 0x00000016u,
38 0x00000021u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000024u, 0x00000020u, 0x0004002bu, 0x00000016u,
39 0x00000028u, 0x00000000u, 0x00040020u, 0x00000029u, 0x00000009u, 0x0000000du, 0x00040020u, 0x0000002du,
40 0x000014e5u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x00000033u, 0x00000002u, 0x0004002bu, 0x00000006u,
41 0x0000003au, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000040u, 0x00000010u, 0x0004002bu, 0x00000006u,
42 0x00000043u, 0x0000ffffu, 0x00040017u, 0x00000048u, 0x00000006u, 0x00000003u, 0x00040020u, 0x00000049u,
43 0x00000001u, 0x00000048u, 0x0004003bu, 0x00000049u, 0x0000004au, 0x00000001u, 0x00040020u, 0x0000004bu,
44 0x00000001u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x0000004fu, 0x00000005u, 0x0004002bu, 0x00000006u,
45 0x00000058u, 0x00000004u, 0x0004002bu, 0x00000006u, 0x00000065u, 0x00000002u, 0x0004002bu, 0x00000006u,
46 0x0000006bu, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000071u, 0x00000006u, 0x0004002bu, 0x00000016u,
47 0x00000073u, 0x00000001u, 0x00040020u, 0x00000074u, 0x00000009u, 0x0000000eu, 0x0004002bu, 0x00000006u,
48 0x00000095u, 0x00000005u, 0x0004002bu, 0x00000006u, 0x00000099u, 0x00000040u, 0x0006002cu, 0x00000048u,
49 0x0000009au, 0x00000099u, 0x0000003au, 0x0000003au, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
50 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x0000009bu, 0x00000000u, 0x000300fbu, 0x0000001fu,
51 0x0000009cu, 0x000200f8u, 0x0000009cu, 0x00050041u, 0x0000004bu, 0x0000004cu, 0x0000004au, 0x0000001fu,
52 0x0004003du, 0x00000006u, 0x0000004du, 0x0000004cu, 0x00050041u, 0x00000018u, 0x00000050u, 0x00000015u,
53 0x0000004fu, 0x0004003du, 0x00000006u, 0x00000051u, 0x00000050u, 0x000500aeu, 0x0000001bu, 0x00000052u,
54 0x0000004du, 0x00000051u, 0x000300f7u, 0x00000054u, 0x00000000u, 0x000400fau, 0x00000052u, 0x00000053u,
55 0x00000054u, 0x000200f8u, 0x00000053u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x00000054u, 0x00050084u,
56 0x00000006u, 0x00000059u, 0x0000004du, 0x00000058u, 0x000300f7u, 0x000000cbu, 0x00000000u, 0x000300fbu,
57 0x0000001fu, 0x000000abu, 0x000200f8u, 0x000000abu, 0x00050041u, 0x00000018u, 0x000000adu, 0x00000015u,
58 0x00000017u, 0x0004003du, 0x00000006u, 0x000000aeu, 0x000000adu, 0x000500aeu, 0x0000001bu, 0x000000afu,
59 0x00000059u, 0x000000aeu, 0x000300f7u, 0x000000b1u, 0x00000000u, 0x000400fau, 0x000000afu, 0x000000b0u,
60 0x000000b1u, 0x000200f8u, 0x000000b0u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000b1u, 0x00050041u,
61 0x00000018u, 0x000000b2u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x000000b2u,
62 0x000500aau, 0x0000001bu, 0x000000b4u, 0x000000b3u, 0x00000024u, 0x000300f7u, 0x000000bbu, 0x00000000u,
63 0x000400fau, 0x000000b4u, 0x000000b5u, 0x000000bbu, 0x000200f8u, 0x000000b5u, 0x00050041u, 0x00000029u,
64 0x000000b6u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000b7u, 0x000000b6u, 0x00060041u,
65 0x0000002du, 0x000000b9u, 0x000000b7u, 0x00000028u, 0x00000059u, 0x0006003du, 0x00000006u, 0x000000bau,
66 0x000000b9u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000bbu, 0x00050041u,
67 0x00000018u, 0x000000bdu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000beu, 0x000000bdu,
68 0x00050080u, 0x00000006u, 0x000000bfu, 0x00000059u, 0x000000beu, 0x00050041u, 0x00000029u, 0x000000c0u,
69 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000c1u, 0x000000c0u, 0x000500c2u, 0x00000006u,
70 0x000000c3u, 0x000000bfu, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000c4u, 0x000000c1u, 0x00000028u,
71 0x000000c3u, 0x0006003du, 0x00000006u, 0x000000c5u, 0x000000c4u, 0x00000002u, 0x00000004u, 0x000500c7u,
72 0x00000006u, 0x000000c7u, 0x000000bfu, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000c8u, 0x000000c7u,
73 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000c9u, 0x000000c5u, 0x000000c8u, 0x000500c7u, 0x00000006u,
74 0x000000cau, 0x000000c9u, 0x00000043u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000cbu, 0x000900f5u,
75 0x00000006u, 0x00000142u, 0x0000001fu, 0x000000b0u, 0x000000bau, 0x000000b5u, 0x000000cau, 0x000000bbu,
76 0x00050080u, 0x00000006u, 0x00000060u, 0x00000059u, 0x0000003au, 0x000300f7u, 0x000000f2u, 0x00000000u,
77 0x000300fbu, 0x0000001fu, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x000500aeu, 0x0000001bu, 0x000000d6u,
78 0x00000060u, 0x000000aeu, 0x000300f7u, 0x000000d8u, 0x00000000u, 0x000400fau, 0x000000d6u, 0x000000d7u,
79 0x000000d8u, 0x000200f8u, 0x000000d7u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000d8u, 0x00050041u,
80 0x00000018u, 0x000000d9u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000dau, 0x000000d9u,
81 0x000500aau, 0x0000001bu, 0x000000dbu, 0x000000dau, 0x00000024u, 0x000300f7u, 0x000000e2u, 0x00000000u,
82 0x000400fau, 0x000000dbu, 0x000000dcu, 0x000000e2u, 0x000200f8u, 0x000000dcu, 0x00050041u, 0x00000029u,
83 0x000000ddu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000deu, 0x000000ddu, 0x00060041u,
84 0x0000002du, 0x000000e0u, 0x000000deu, 0x00000028u, 0x00000060u, 0x0006003du, 0x00000006u, 0x000000e1u,
85 0x000000e0u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000e2u, 0x00050041u,
86 0x00000018u, 0x000000e4u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000e5u, 0x000000e4u,
87 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000060u, 0x000000e5u, 0x00050041u, 0x00000029u, 0x000000e7u,
88 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000e8u, 0x000000e7u, 0x000500c2u, 0x00000006u,
89 0x000000eau, 0x000000e6u, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000ebu, 0x000000e8u, 0x00000028u,
90 0x000000eau, 0x0006003du, 0x00000006u, 0x000000ecu, 0x000000ebu, 0x00000002u, 0x00000004u, 0x000500c7u,
91 0x00000006u, 0x000000eeu, 0x000000e6u, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000efu, 0x000000eeu,
92 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000f0u, 0x000000ecu, 0x000000efu, 0x000500c7u, 0x00000006u,
93 0x000000f1u, 0x000000f0u, 0x00000043u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000f2u, 0x000900f5u,
94 0x00000006u, 0x00000144u, 0x0000001fu, 0x000000d7u, 0x000000e1u, 0x000000dcu, 0x000000f1u, 0x000000e2u,
95 0x00050080u, 0x00000006u, 0x00000066u, 0x00000059u, 0x00000065u, 0x000300f7u, 0x00000119u, 0x00000000u,
96 0x000300fbu, 0x0000001fu, 0x000000f9u, 0x000200f8u, 0x000000f9u, 0x000500aeu, 0x0000001bu, 0x000000fdu,
97 0x00000066u, 0x000000aeu, 0x000300f7u, 0x000000ffu, 0x00000000u, 0x000400fau, 0x000000fdu, 0x000000feu,
98 0x000000ffu, 0x000200f8u, 0x000000feu, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x000000ffu, 0x00050041u,
99 0x00000018u, 0x00000100u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000101u, 0x00000100u,
100 0x000500aau, 0x0000001bu, 0x00000102u, 0x00000101u, 0x00000024u, 0x000300f7u, 0x00000109u, 0x00000000u,
101 0x000400fau, 0x00000102u, 0x00000103u, 0x00000109u, 0x000200f8u, 0x00000103u, 0x00050041u, 0x00000029u,
102 0x00000104u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000105u, 0x00000104u, 0x00060041u,
103 0x0000002du, 0x00000107u, 0x00000105u, 0x00000028u, 0x00000066u, 0x0006003du, 0x00000006u, 0x00000108u,
104 0x00000107u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000109u, 0x00050041u,
105 0x00000018u, 0x0000010bu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x0000010cu, 0x0000010bu,
106 0x00050080u, 0x00000006u, 0x0000010du, 0x00000066u, 0x0000010cu, 0x00050041u, 0x00000029u, 0x0000010eu,
107 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000010fu, 0x0000010eu, 0x000500c2u, 0x00000006u,
108 0x00000111u, 0x0000010du, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000112u, 0x0000010fu, 0x00000028u,
109 0x00000111u, 0x0006003du, 0x00000006u, 0x00000113u, 0x00000112u, 0x00000002u, 0x00000004u, 0x000500c7u,
110 0x00000006u, 0x00000115u, 0x0000010du, 0x0000003au, 0x00050084u, 0x00000006u, 0x00000116u, 0x00000115u,
111 0x00000040u, 0x000500c2u, 0x00000006u, 0x00000117u, 0x00000113u, 0x00000116u, 0x000500c7u, 0x00000006u,
112 0x00000118u, 0x00000117u, 0x00000043u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000119u, 0x000900f5u,
113 0x00000006u, 0x00000146u, 0x0000001fu, 0x000000feu, 0x00000108u, 0x00000103u, 0x00000118u, 0x00000109u,
114 0x00050080u, 0x00000006u, 0x0000006cu, 0x00000059u, 0x0000006bu, 0x000300f7u, 0x00000140u, 0x00000000u,
115 0x000300fbu, 0x0000001fu, 0x00000120u, 0x000200f8u, 0x00000120u, 0x000500aeu, 0x0000001bu, 0x00000124u,
116 0x0000006cu, 0x000000aeu, 0x000300f7u, 0x00000126u, 0x00000000u, 0x000400fau, 0x00000124u, 0x00000125u,
117 0x00000126u, 0x000200f8u, 0x00000125u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000126u, 0x00050041u,
118 0x00000018u, 0x00000127u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000128u, 0x00000127u,
119 0x000500aau, 0x0000001bu, 0x00000129u, 0x00000128u, 0x00000024u, 0x000300f7u, 0x00000130u, 0x00000000u,
120 0x000400fau, 0x00000129u, 0x0000012au, 0x00000130u, 0x000200f8u, 0x0000012au, 0x00050041u, 0x00000029u,
121 0x0000012bu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000012cu, 0x0000012bu, 0x00060041u,
122 0x0000002du, 0x0000012eu, 0x0000012cu, 0x00000028u, 0x0000006cu, 0x0006003du, 0x00000006u, 0x0000012fu,
123 0x0000012eu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000130u, 0x00050041u,
124 0x00000018u, 0x00000132u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x00000133u, 0x00000132u,
125 0x00050080u, 0x00000006u, 0x00000134u, 0x0000006cu, 0x00000133u, 0x00050041u, 0x00000029u, 0x00000135u,
126 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000136u, 0x00000135u, 0x000500c2u, 0x00000006u,
127 0x00000138u, 0x00000134u, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000139u, 0x00000136u, 0x00000028u,
128 0x00000138u, 0x0006003du, 0x00000006u, 0x0000013au, 0x00000139u, 0x00000002u, 0x00000004u, 0x000500c7u,
129 0x00000006u, 0x0000013cu, 0x00000134u, 0x0000003au, 0x00050084u, 0x00000006u, 0x0000013du, 0x0000013cu,
130 0x00000040u, 0x000500c2u, 0x00000006u, 0x0000013eu, 0x0000013au, 0x0000013du, 0x000500c7u, 0x00000006u,
131 0x0000013fu, 0x0000013eu, 0x00000043u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000140u, 0x000900f5u,
132 0x00000006u, 0x00000148u, 0x0000001fu, 0x00000125u, 0x0000012fu, 0x0000012au, 0x0000013fu, 0x00000130u,
133 0x00050084u, 0x00000006u, 0x00000072u, 0x0000004du, 0x00000071u, 0x00050041u, 0x00000074u, 0x00000075u,
134 0x00000015u, 0x00000073u, 0x0004003du, 0x0000000eu, 0x00000076u, 0x00000075u, 0x00060041u, 0x0000002du,
135 0x00000079u, 0x00000076u, 0x00000028u, 0x00000072u, 0x0005003eu, 0x00000079u, 0x00000142u, 0x00000002u,
136 0x00000004u, 0x00050080u, 0x00000006u, 0x0000007du, 0x00000072u, 0x0000003au, 0x00060041u, 0x0000002du,
137 0x0000007fu, 0x00000076u, 0x00000028u, 0x0000007du, 0x0005003eu, 0x0000007fu, 0x00000144u, 0x00000002u,
138 0x00000004u, 0x00050080u, 0x00000006u, 0x00000083u, 0x00000072u, 0x00000065u, 0x00060041u, 0x0000002du,
139 0x00000085u, 0x00000076u, 0x00000028u, 0x00000083u, 0x0005003eu, 0x00000085u, 0x00000146u, 0x00000002u,
140 0x00000004u, 0x00050080u, 0x00000006u, 0x00000089u, 0x00000072u, 0x0000006bu, 0x00060041u, 0x0000002du,
141 0x0000008bu, 0x00000076u, 0x00000028u, 0x00000089u, 0x0005003eu, 0x0000008bu, 0x00000142u, 0x00000002u,
142 0x00000004u, 0x00050080u, 0x00000006u, 0x0000008fu, 0x00000072u, 0x00000058u, 0x00060041u, 0x0000002du,
143 0x00000091u, 0x00000076u, 0x00000028u, 0x0000008fu, 0x0005003eu, 0x00000091u, 0x00000146u, 0x00000002u,
144 0x00000004u, 0x00050080u, 0x00000006u, 0x00000096u, 0x00000072u, 0x00000095u, 0x00060041u, 0x0000002du,
145 0x00000098u, 0x00000076u, 0x00000028u, 0x00000096u, 0x0005003eu, 0x00000098u, 0x00000148u, 0x00000002u,
146 0x00000004u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x0000009bu, 0x000100fdu, 0x00010038u,
147};
148} // namespace leonida
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
index 3148d0ad1..5682d9e54 100644
--- a/runtime/src/queue_families.h
+++ b/runtime/src/queue_families.h
@@ -8,10 +8,33 @@
8#include <cstddef> 8#include <cstddef>
9#include <cstdint> 9#include <cstdint>
10#include <initializer_list> 10#include <initializer_list>
11#include <optional>
11#include <span> 12#include <span>
12 13
13namespace leonida { 14namespace leonida {
14 15
16constexpr std::uint32_t queue_family_timestamp_bits(std::span<const std::uint32_t> bits, std::uint32_t family) {
17 return family < bits.size() ? bits[family] : 0;
18}
19
20// A copy queue can lease from either family. Caller-owned devices may supply only the graphics queue.
21constexpr bool copy_queue_timestamp_families_supported(std::span<const std::uint32_t> bits,
22 std::uint32_t graphics,
23 std::optional<std::uint32_t> dedicated_copy) {
24 return queue_family_timestamp_bits(bits, graphics) != 0 &&
25 (!dedicated_copy || queue_family_timestamp_bits(bits, *dedicated_copy) != 0);
26}
27
28// The device's distinct family indices. An object used on more than one family keeps its contents
29// across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers.
30template<typename CreateInfo>
31void share_across_queue_families(CreateInfo& create, std::span<const std::uint32_t> families) {
32 if (families.size() < 2) return;
33 create.sharingMode = VK_SHARING_MODE_CONCURRENT;
34 create.queueFamilyIndexCount = static_cast<std::uint32_t>(families.size());
35 create.pQueueFamilyIndices = families.data();
36}
37
15// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no 38// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no
16// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable 39// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable
17// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is 40// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is
diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h
new file mode 100644
index 000000000..c807fb2bc
--- /dev/null
+++ b/runtime/src/rect_list_geometry.h
@@ -0,0 +1,263 @@
1#pragma once
2
3// Console rectangle lists on Vulkan, which has no such primitive.
4//
5// A rectangle is three corners (v1, v2, v3) of a screen-aligned rectangle and the hardware makes the fourth, for the
6// position and for every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY
7// 17) and a pipeline whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit
8// 53af7df77c10, notes in its backlog); no code is taken from it. The corner between the other two (the right angle)
9// is not always v1: the title's own full-screen blit (VS_Blit_6e5520d1) gives (-1, 1) (-1, -1) (1, -1), the corner
10// at v2, and xcl's notes say the same of a retail title's full-screen pass and list v1, v2 and v3 as possible
11// (learned from its docs and tests, GPL-2.0-only, no code taken). Taking v1 there made the parallelogram
12// v2 + v3 - v1 = (1, -3), of which only the lower-left half of the screen is on screen.
13//
14// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after
15// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and
16// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a
17// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3)
18// the list draws, finds the corner between the other two as the one opposite the longest side (from the positions'
19// x and y; a degenerate triangle takes v1), makes the fourth corner v4 = the other two's sum minus that corner, and
20// emits the rectangle as two triangles with the winding of (v1, v2, v3) that both start at v1, so a flat input
21// (taken from a triangle's first vertex) is v1's over the whole rectangle:
22// corner v1: (v1, v2, v4) (v1, v4, v3); corner v2: (v1, v2, v3) (v1, v3, v4); corner v3: (v1, v2, v3) (v1, v4, v2). Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py),
23// and so is the stage's Position; the generated stage reads and writes exactly those.
24//
25// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or
26// ViewportIndex, or a Location output that is not a vec4 float.
27//
28// Plain word editing, standard library only.
29
30#include <algorithm>
31#include <array>
32#include <cstdint>
33#include <initializer_list>
34#include <map>
35#include <set>
36#include <string>
37#include <vector>
38
39namespace leonida {
40
41// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists.
42constexpr std::uint32_t topology_rect_list = 17;
43constexpr std::uint32_t topology_quad_list = 19;
44constexpr std::uint32_t topology_type_rect_list = 19;
45constexpr std::array<std::uint32_t, 6> quad_triangle_indices{0, 1, 2, 0, 2, 3};
46
47// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded.
48inline std::vector<std::uint32_t> rect_list_geometry(const std::vector<std::uint32_t>& vertex_words, std::string& why) {
49 enum : std::uint32_t {
50 op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22,
51 op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43,
52 op_type_bool = 20, op_composite_construct = 80, op_composite_extract = 81, op_fmul = 133,
53 op_logical_and = 167, op_logical_not = 168, op_select = 169, op_ford_greater_than_equal = 190,
54 op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65,
55 op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253,
56 op_capability = 17, op_memory_model = 14, op_execution_mode = 16,
57 deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1,
58 storage_input = 1, storage_output = 3
59 };
60 why.clear();
61 if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) {
62 why = "the vertex shader is not a SPIR-V module";
63 return {};
64 }
65 // What the vertex stage declares: types, Output variables, and the decorations that name them.
66 struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; };
67 std::map<std::uint32_t, Type> types;
68 std::map<std::uint32_t, std::uint32_t> variable_type; // Output variable -> its pointer type
69 std::map<std::uint32_t, std::uint32_t> location, builtin; // variable id -> value
70 std::set<std::uint32_t> outputs;
71 for (std::size_t i = 5; i < vertex_words.size();) {
72 const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16;
73 if (!n || i + n > vertex_words.size()) {
74 why = "the vertex shader's SPIR-V is cut short";
75 return {};
76 }
77 const std::uint32_t* w = &vertex_words[i];
78 if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]};
79 else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0};
80 else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0};
81 else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1];
82 else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3];
83 else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3];
84 i += n;
85 }
86 std::uint32_t position = 0;
87 std::vector<std::uint32_t> params; // Location values, ascending
88 for (std::uint32_t id : outputs) {
89 const auto b = builtin.find(id);
90 if (b != builtin.end()) {
91 if (b->second == builtin_position) position = id;
92 else if (b->second != builtin_point_size) {
93 why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex";
94 return {};
95 }
96 continue;
97 }
98 const auto l = location.find(id);
99 if (l == location.end()) continue;
100 const Type& ptr = types[variable_type[id]];
101 const Type& vec = types[ptr.component];
102 const Type& scalar = types[vec.component];
103 // Known limit: every vec4 float output gets the plain a + b - p corner. The translator can export an attribute
104 // as the register's raw bits with two packed f16 halves (only the pixel shader knows, through per_vertex in
105 // tools/rdna2spirv.py), and nothing on the vertex side tells those apart, so such an output would get a wrong
106 // fourth corner. Fixing it needs the pixel shader's words here and a per-channel marker from the translator.
107 if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) {
108 why = "a vertex output is not a vec4 float";
109 return {};
110 }
111 params.push_back(l->second);
112 }
113 if (!position) {
114 why = "the vertex shader writes no Position";
115 return {};
116 }
117 std::sort(params.begin(), params.end());
118 params.erase(std::unique(params.begin(), params.end()), params.end());
119
120 // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1.
121 std::uint32_t next = 1;
122 const auto id = [&] { return next++; };
123 std::vector<std::uint32_t> head, annotations, globals, body;
124 const auto emit = [](std::vector<std::uint32_t>& to, std::uint32_t op, std::initializer_list<std::uint32_t> args) {
125 to.push_back((std::uint32_t(args.size()) + 1) << 16 | op);
126 to.insert(to.end(), args.begin(), args.end());
127 };
128 const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(),
129 c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(),
130 t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id();
131 emit(globals, op_type_void, {t_void});
132 emit(globals, op_type_function, {t_fn, t_void});
133 emit(globals, op_type_int, {t_uint, 32, 0});
134 emit(globals, op_type_float, {t_float, 32});
135 emit(globals, op_type_vector, {t_v4, t_float, 4});
136 emit(globals, op_constant, {t_uint, c3, 3});
137 emit(globals, op_constant, {t_uint, c0, 0});
138 emit(globals, op_constant, {t_uint, c1, 1});
139 emit(globals, op_constant, {t_uint, c2, 2});
140 emit(globals, op_type_array, {t_arr, t_v4, c3});
141 emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr});
142 emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4});
143 emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4});
144
145 struct Var { std::uint32_t in, out; bool is_position; };
146 std::vector<Var> vars;
147 vars.push_back({id(), id(), true});
148 for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false});
149 std::vector<std::uint32_t> io_vars;
150 emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position});
151 emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position});
152 for (std::size_t i = 0; i < params.size(); ++i) {
153 emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]});
154 emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]});
155 }
156 for (const Var& v : vars) {
157 emit(globals, op_variable, {t_pin_arr, v.in, storage_input});
158 emit(globals, op_variable, {t_pout_v4, v.out, storage_output});
159 io_vars.push_back(v.in);
160 io_vars.push_back(v.out);
161 }
162
163 const std::uint32_t main_fn = id(), entry_label = id();
164 emit(body, op_function, {t_void, main_fn, 0, t_fn});
165 emit(body, op_label, {entry_label});
166 // Per variable: the three corners.
167 struct Corners { std::uint32_t v[3]; };
168 std::vector<Corners> corners;
169 const std::uint32_t cs[3] = {c0, c1, c2};
170 for (const Var& v : vars) {
171 Corners c{};
172 for (int k = 0; k < 3; ++k) {
173 const std::uint32_t ptr = id();
174 c.v[k] = id();
175 emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]});
176 emit(body, op_load, {t_v4, c.v[k], ptr});
177 }
178 corners.push_back(c);
179 }
180 // The corner between the other two, opposite the longest side: squared lengths from the positions' x and y.
181 const std::uint32_t t_bool = id(), t_bv4 = id();
182 emit(globals, op_type_bool, {t_bool});
183 emit(globals, op_type_vector, {t_bv4, t_bool, 4});
184 const auto extract = [&](std::uint32_t vector, std::uint32_t component) {
185 const std::uint32_t r = id();
186 emit(body, op_composite_extract, {t_float, r, vector, component});
187 return r;
188 };
189 const auto length2 = [&](std::uint32_t a, std::uint32_t b) {
190 const std::uint32_t d = id(), xx = id(), yy = id(), sum = id();
191 emit(body, op_fsub, {t_v4, d, a, b});
192 const std::uint32_t x = extract(d, 0), y = extract(d, 1);
193 emit(body, op_fmul, {t_float, xx, x, x});
194 emit(body, op_fmul, {t_float, yy, y, y});
195 emit(body, op_fadd, {t_float, sum, xx, yy});
196 return sum;
197 };
198 const auto at_least = [&](std::uint32_t a, std::uint32_t b) {
199 const std::uint32_t r = id();
200 emit(body, op_ford_greater_than_equal, {t_bool, r, a, b});
201 return r;
202 };
203 const auto both = [&](std::uint32_t a, std::uint32_t b) {
204 const std::uint32_t r = id();
205 emit(body, op_logical_and, {t_bool, r, a, b});
206 return r;
207 };
208 const auto splat = [&](std::uint32_t b) { // OpSelect on vectors takes a vector condition before SPIR-V 1.4
209 const std::uint32_t r = id();
210 emit(body, op_composite_construct, {t_bv4, r, b, b, b, b});
211 return r;
212 };
213 const std::uint32_t* p = corners[0].v; // vars[0] is the Position
214 const std::uint32_t l12 = length2(p[0], p[1]), l23 = length2(p[1], p[2]), l31 = length2(p[2], p[0]);
215 const std::uint32_t at_v1 = both(at_least(l23, l12), at_least(l23, l31)), not_v1 = id();
216 emit(body, op_logical_not, {t_bool, not_v1, at_v1});
217 const std::uint32_t at_v2 = both(not_v1, at_least(l31, l12));
218 const std::uint32_t c_v1 = splat(at_v1), c_v2 = splat(at_v2);
219 const auto pick = [&](std::uint32_t condition, std::uint32_t yes, std::uint32_t no) {
220 const std::uint32_t r = id();
221 emit(body, op_select, {t_v4, r, condition, yes, no});
222 return r;
223 };
224 // Per variable: the fourth corner, v1 + v2 + v3 - 2 * corner, and the six vertices of the two triangles.
225 std::vector<std::array<std::uint32_t, 6>> emitted;
226 for (const Corners& c : corners) {
227 const std::uint32_t corner = pick(c_v1, c.v[0], pick(c_v2, c.v[1], c.v[2]));
228 const std::uint32_t s12 = id(), s123 = id(), less = id(), fourth = id();
229 emit(body, op_fadd, {t_v4, s12, c.v[0], c.v[1]});
230 emit(body, op_fadd, {t_v4, s123, s12, c.v[2]});
231 emit(body, op_fsub, {t_v4, less, s123, corner});
232 emit(body, op_fsub, {t_v4, fourth, less, corner});
233 emitted.push_back({c.v[0], c.v[1], pick(c_v1, fourth, c.v[2]),
234 c.v[0], pick(c_v2, c.v[2], fourth), pick(c_v1, c.v[2], pick(c_v2, fourth, c.v[1]))});
235 }
236 for (int triangle = 0; triangle < 2; ++triangle) {
237 for (int k = 0; k < 3; ++k) {
238 for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, emitted[i][triangle * 3 + k]});
239 emit(body, op_emit_vertex, {});
240 }
241 emit(body, op_end_primitive, {});
242 }
243 emit(body, op_return, {});
244 emit(body, op_function_end, {});
245
246 std::vector<std::uint32_t> out{0x07230203u, 0x00010000u, 0, next, 0};
247 emit(out, op_capability, {2}); // Geometry
248 emit(out, op_memory_model, {0, 1}); // Logical, GLSL450
249 std::vector<std::uint32_t> entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main"
250 entry.insert(entry.end(), io_vars.begin(), io_vars.end());
251 out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point);
252 out.insert(out.end(), entry.begin(), entry.end());
253 emit(out, op_execution_mode, {main_fn, 22}); // Triangles
254 emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1
255 emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip
256 emit(out, op_execution_mode, {main_fn, 26, 6}); // OutputVertices 6
257 out.insert(out.end(), annotations.begin(), annotations.end());
258 out.insert(out.end(), globals.begin(), globals.end());
259 out.insert(out.end(), body.begin(), body.end());
260 return out;
261}
262
263} // namespace leonida
diff --git a/runtime/src/rgba4_fragment.h b/runtime/src/rgba4_fragment.h
new file mode 100644
index 000000000..b62162848
--- /dev/null
+++ b/runtime/src/rgba4_fragment.h
@@ -0,0 +1,81 @@
1#pragma once
2#include <array>
3#include <bit>
4#include <cstdint>
5#include <cstring>
6#include <map>
7#include <string>
8#include <vector>
9namespace leonida::rgba4 {
10using Inst=std::vector<std::uint32_t>;
11inline Inst instruction(std::uint32_t op,std::initializer_list<std::uint32_t> args) {
12 Inst w{(std::uint32_t(args.size()+1)<<16)|op};w.insert(w.end(),args);return w;
13}
14// Quantize only written color outputs at the requested locations. For a wider fallback attachment
15// this reproduces four-bit UNORM writes for pipelines whose affected attachments use no blending.
16inline bool quantize(Inst& words,unsigned mask) {
17 if(!mask)return true;
18 if(words.size()<5 || words[0]!=0x07230203)return false;
19 std::vector<Inst> code,declarations;
20 std::map<unsigned,unsigned> locations, pointer_type, width, scalar, variables;
21 unsigned import_id=0,next=words[3],float_type=0;
22 for(std::size_t at=5;at<words.size();) {
23 const unsigned n=words[at]>>16,op=words[at]&65535u;
24 if(!n || n>words.size()-at)return false;
25 Inst i(words.begin()+at,words.begin()+at+n);at+=n;
26 if(op==11 && n>=3) {
27 const char* s=reinterpret_cast<const char*>(i.data()+2);const auto bytes=(n-2)*4;
28 if(bytes>=13 && std::memcmp(s,"GLSL.std.450",13)==0)import_id=i[1];
29 } else if(op==71 && n==4 && i[2]==30)locations[i[1]]=i[3];
30 else if(op==22 && n==3 && i[2]==32){float_type=i[1];width[i[1]]=1;scalar[i[1]]=i[1];}
31 else if(op==23 && n==4){width[i[1]]=i[3];scalar[i[1]]=i[2];}
32 else if(op==32 && n==4 && i[2]==3)pointer_type[i[1]]=i[3];
33 else if(op==59 && n>=4 && i[3]==3)variables[i[2]]=i[1];
34 code.push_back(std::move(i));
35 }
36 if(!float_type)return false;
37 std::map<unsigned,unsigned> outputs;
38 for(auto [id,ptr]:variables)if(locations.count(id)&&locations[id]<8&&(mask&(1u<<locations[id]))&&pointer_type.count(ptr))
39 outputs[id]=pointer_type[ptr];
40 if(outputs.empty())return true;
41 const bool add_import=!import_id;if(add_import)import_id=next++;
42 std::map<unsigned,std::array<unsigned,4>> constants;
43 auto components=[&](unsigned type) -> const std::array<unsigned,4>& {
44 auto [it,inserted]=constants.try_emplace(type);
45 if(!inserted)return it->second;
46 constexpr std::array<float,4> vals{0.f,1.f,15.f,1.f/15.f};
47 std::array<unsigned,4> base{};
48 for(unsigned j=0;j<4;++j){base[j]=next++;declarations.push_back(instruction(43,{scalar[type],base[j],std::bit_cast<unsigned>(vals[j])}));}
49 if(width[type]==1){it->second=base;return it->second;}
50 for(unsigned j=0;j<4;++j){const auto id=next++;Inst c=instruction(44,{type,id});c.resize(3+width[type],base[j]);c[0]=(unsigned(c.size())<<16)|44u;declarations.push_back(std::move(c));it->second[j]=id;}
51 return it->second;
52 };
53 std::vector<Inst> rewritten;bool changed=false;
54 for(auto& i:code) {
55 const auto op=i[0]&65535u;
56 if((op==65||op==66||op==83) && i.size()>=4 && outputs.count(i[3]) && pointer_type.count(i[1]))
57 outputs[i[2]]=pointer_type[i[1]];
58 if(op==63 && i.size()>=3 && outputs.count(i[1]))return false;
59 if(op==62 && i.size()>=3 && outputs.count(i[1])) {
60 const auto type=outputs[i[1]];
61 if(!width.count(type)||width[type]<1||width[type]>4||scalar[type]!=float_type)return false;
62 const auto& c=components(type);
63 const auto clamped=next++,scaled=next++,rounded=next++,value=next++;
64 rewritten.push_back(instruction(12,{type,clamped,import_id,43,i[2],c[0],c[1]})); // GLSL FClamp
65 rewritten.push_back(instruction(133,{type,scaled,clamped,c[2]}));
66 rewritten.push_back(instruction(12,{type,rounded,import_id,2,scaled})); // GLSL RoundEven
67 rewritten.push_back(instruction(133,{type,value,rounded,c[3]}));i[2]=value;changed=true;
68 }
69 rewritten.push_back(std::move(i));
70 }
71 if(!changed)return false;
72 Inst result(words.begin(),words.begin()+5);result[3]=next;bool declared=false;
73 for(const auto& i:rewritten) {
74 const auto op=i[0]&65535u;
75 if(op==14 && add_import){Inst imp=instruction(11,{import_id,0,0,0,0});std::memcpy(imp.data()+2,"GLSL.std.450",13);result.insert(result.end(),imp.begin(),imp.end());}
76 if(op==54&&!declared){for(const auto& dec:declarations)result.insert(result.end(),dec.begin(),dec.end());declared=true;}
77 result.insert(result.end(),i.begin(),i.end());
78 }
79 if(!declared)return false;words=std::move(result);return true;
80}
81}
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
index a0eb96cce..10dd1e02c 100644
--- a/runtime/src/root_signature.cpp
+++ b/runtime/src/root_signature.cpp
@@ -59,10 +59,18 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) {
59 } 59 }
60 uint64_t cost = 0; // 64-bit, as in pack() 60 uint64_t cost = 0; // 64-bit, as in pack()
61 uint64_t next = out.base; 61 uint64_t next = out.base;
62 uint64_t spill_next = 0;
63 bool spilling = false;
62 std::vector<uint32_t> first; 64 std::vector<uint32_t> first;
65 std::vector<uint32_t> spill;
63 first.reserve(sig.params.size()); 66 first.reserve(sig.params.size());
67 spill.reserve(sig.params.size());
64 for (size_t i = 0; i < sig.params.size(); ++i) { 68 for (size_t i = 0; i < sig.params.size(); ++i) {
65 const RootParameter& p = sig.params[i]; 69 const RootParameter& p = sig.params[i];
70 if (p.type != ParamType::Constants && p.type != ParamType::Descriptor && p.type != ParamType::Table) {
71 out.error = "unknown root parameter type";
72 return out;
73 }
66 if (p.type == ParamType::Constants && p.num_values == 0) { 74 if (p.type == ParamType::Constants && p.num_values == 0) {
67 out.error = "root constant parameter needs at least 1 dword"; 75 out.error = "root constant parameter needs at least 1 dword";
68 return out; 76 return out;
@@ -73,18 +81,27 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) {
73 return out; 81 return out;
74 } 82 }
75 const uint64_t dwords = stage_dwords(p.type, p.num_values); 83 const uint64_t dwords = stage_dwords(p.type, p.num_values);
76 if (next + dwords > kMaxUserSgprs) { 84 if (!spilling && next + dwords <= kMaxUserSgprs) {
77 // The console moves this parameter and every later one to the spill array behind s[0:1]; that array's 85 first.push_back(static_cast<uint32_t>(next));
78 // layout is not modelled here, so refuse rather than drop arguments. 86 spill.push_back(kNoSpill);
87 next += dwords;
88 } else if (stage == Stage::Compute) {
89 // Compute packs this parameter and every later one contiguously into the spill array behind s[0:1]
90 // (docs/d3d12_vulkan.md §3.5 & §7). Total spill stays bounded by kMaxD3d12Cost (<= 64 dwords).
91 spilling = true;
92 first.push_back(kNoSgpr);
93 spill.push_back(static_cast<uint32_t>(spill_next));
94 spill_next += dwords;
95 } else {
79 out.error = "root parameter " + std::to_string(i) + " does not fit in the user SGPRs from s" + 96 out.error = "root parameter " + std::to_string(i) + " does not fit in the user SGPRs from s" +
80 std::to_string(out.base) + " (spill array not modelled)"; 97 std::to_string(out.base) + " (spill array not modelled)";
81 return out; 98 return out;
82 } 99 }
83 first.push_back(static_cast<uint32_t>(next));
84 next += dwords;
85 } 100 }
86 out.first_sgpr = std::move(first); 101 out.first_sgpr = std::move(first);
102 out.spill_dword = std::move(spill);
87 out.end_sgpr = static_cast<uint32_t>(next); 103 out.end_sgpr = static_cast<uint32_t>(next);
104 out.spill_dwords = static_cast<uint32_t>(spill_next);
88 out.d3d12_cost = static_cast<uint32_t>(cost); 105 out.d3d12_cost = static_cast<uint32_t>(cost);
89 out.ok = true; 106 out.ok = true;
90 return out; 107 return out;
diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h
index 376962940..e7976fc73 100644
--- a/runtime/src/root_signature.h
+++ b/runtime/src/root_signature.h
@@ -129,10 +129,15 @@ constexpr uint32_t kMaxD3d12Cost = 64;
129// in this layout equals the program's RSRC2 USER_SGPR count in 29 of 29, and the programs read the tables and 129// in this layout equals the program's RSRC2 USER_SGPR count in 29 of 29, and the programs read the tables and
130// root CBVs at exactly these SGPRs (tools/rootsig_census.py --disasm). The game's compute census agrees (lowest 130// root CBVs at exactly these SGPRs (tools/rootsig_census.py --disasm). The game's compute census agrees (lowest
131// pointer s4, one-dword tables). 131// pointer s4, one-dword tables).
132// - vertex/pixel/geometry s8 and mesh s16: a hypothesis from the corpus census only (lowest pointer SGPR per stage); 132// - vertex/pixel/geometry s8 and mesh s16: from the corpus census (lowest pointer SGPR per stage) and one live
133// no signature confirms them, and visibility is not modelled (every parameter takes its place in every stage). 133// retail frame (a VS and PS reading their tables at s8, s9, s10; issue #14, comment 7131556366); no serialized
134// signature confirms them yet, and visibility is not modelled (every parameter takes its place in every stage).
135// The graphics bind point uses Stage::Pixel (s8, as vertex and geometry); a mesh shader reads the same dwords
136// through its translator-side window (docs/d3d12_vulkan.md section 3.5).
134// A parameter that does not fit goes to the console's spill array behind s[0:1] (compute, section 7) together with 137// A parameter that does not fit goes to the console's spill array behind s[0:1] (compute, section 7) together with
135// every parameter after it; that array is not modelled, so such a signature is refused, never truncated. 138// every parameter after it. For compute that packed spill array (1 dword per 32-bit constant, 2 per root descriptor,
139// 1 per descriptor table, no alignment padding) is modelled in StagePackResult; non-compute stages still refuse spills
140// because their spill pointer SGPR is unmeasured.
136enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 }; 141enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 };
137 142
138[[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept { 143[[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept {
@@ -163,19 +168,23 @@ enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3,
163} 168}
164 169
165constexpr uint32_t kNoSgpr = 0xFFFFFFFFu; 170constexpr uint32_t kNoSgpr = 0xFFFFFFFFu;
171constexpr uint32_t kNoSpill = 0xFFFFFFFFu;
166 172
167struct StagePackResult { 173struct StagePackResult {
168 bool ok = false; 174 bool ok = false;
169 std::string error; // set when !ok; names the refusing parameter 175 std::string error; // set when !ok; names the refusing parameter
170 Stage stage = Stage::Compute; 176 Stage stage = Stage::Compute;
171 uint32_t base = 0; // stage_base(stage) 177 uint32_t base = 0; // stage_base(stage)
172 std::vector<uint32_t> first_sgpr; // per parameter: its first user SGPR (kNoSgpr when the signature is refused) 178 std::vector<uint32_t> first_sgpr; // per parameter: its first user SGPR (kNoSgpr when spilled or refused)
173 uint32_t end_sgpr = 0; // one past the last SGPR used: the RSRC2 USER_SGPR count the layout implies 179 std::vector<uint32_t> spill_dword; // per parameter: dword offset in s[0:1] spill array (kNoSpill when inline)
174 uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit 180 uint32_t end_sgpr = 0; // one past the last inline SGPR used: the RSRC2 USER_SGPR count
181 uint32_t spill_dwords = 0; // total dwords in the packed spill array (0 when nothing spills)
182 uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit
175}; 183};
176 184
177// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, a 185// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an
178// constant parameter of 0 values or the 64-dword cost limit, and on any parameter that would spill. 186// unknown parameter type, a constant parameter of 0 values, or the 64-dword cost limit. Compute spills any trailing
187// parameters from the first one that does not fit whole into spill_dword; non-compute stages refuse any spill.
179[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); 188[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage);
180 189
181// D3D12 cost of one parameter against the 64-dword limit. 190// D3D12 cost of one parameter against the 64-dword limit.
diff --git a/runtime/src/shader_directory.h b/runtime/src/shader_directory.h
new file mode 100644
index 000000000..ed7412898
--- /dev/null
+++ b/runtime/src/shader_directory.h
@@ -0,0 +1,56 @@
1// Shared shader-library location for the Vulkan and DirectStorage runtimes.
2#pragma once
3#include <windows.h>
4#include <bit>
5#include <filesystem>
6#include <fstream>
7#include <iterator>
8#include <memory>
9#include <string>
10
11namespace leonida::shader_paths {
12// The folder make_game recorded in shader_path.txt at `config`, or empty without one. Throws when the path cannot be
13// converted: MSVC's STL reports a Windows path that is not UTF-8 as std::system_error, libstdc++ as filesystem_error.
14inline std::filesystem::path shader_directory_from_file(const std::filesystem::path& config) {
15 std::ifstream file(config, std::ios::binary);
16 if (!file) return {};
17 const std::string text{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
18 if (text.empty() || text.find('\0') != std::string::npos) return {};
19
20 // make_game records an absolute Unix path on Linux. Resolve it inside the running Wine prefix.
21 if (text.front() == '/') {
22 using WineDosPath = wchar_t* (CDECL*)(const char*);
23 const auto to_dos = std::bit_cast<WineDosPath>(
24 ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "wine_get_dos_file_name"));
25 if (!to_dos) return {};
26 const auto release = [](wchar_t* path) { ::HeapFree(::GetProcessHeap(), 0, path); };
27 const std::unique_ptr<wchar_t, decltype(release)> path(to_dos(text.c_str()), release);
28 if (path) return std::filesystem::path(path.get());
29 return {};
30 }
31 return std::filesystem::path(std::u8string(text.begin(), text.end()));
32}
33
34inline std::filesystem::path configured(std::string* error = nullptr, const std::filesystem::path& config = {}) {
35 try {
36 constexpr wchar_t env_name[] = L"LEONIDA_SHADERS";
37 if (const DWORD size = ::GetEnvironmentVariableW(env_name, nullptr, 0)) {
38 std::wstring value(size, L'\0');
39 const DWORD length = ::GetEnvironmentVariableW(env_name, value.data(), size);
40 if (length && length < size) {
41 value.resize(length);
42 return std::filesystem::path(value);
43 }
44 }
45 if (!config.empty()) return shader_directory_from_file(config);
46 std::wstring exe(32768, L'\0');
47 const DWORD length = ::GetModuleFileNameW(nullptr, exe.data(), static_cast<DWORD>(exe.size()));
48 if (!length || length >= exe.size()) return {};
49 exe.resize(length);
50 return shader_directory_from_file(std::filesystem::path(exe).parent_path() / L"shader_path.txt");
51 } catch (const std::exception& e) {
52 if (error) *error = e.what();
53 return {};
54 }
55}
56} // namespace leonida::shader_paths
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 596ad0ae9..a359287cb 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -8,6 +8,7 @@
8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code: 8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code:
9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. 9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader.
10 10
11#include "descriptor_table.h"
11#include "spirv_words.h" 12#include "spirv_words.h"
12 13
13#include <algorithm> 14#include <algorithm>
@@ -220,7 +221,7 @@ inline int decode(BitReader& in, const Huffman& h) {
220} 221}
221 222
222inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const Huffman& lengths, 223inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const Huffman& lengths,
223 const Huffman& distances, std::size_t limit) { 224 const Huffman& distances, std::size_t limit, bool bulk = true) {
224 static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 225 static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27,
225 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; 226 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
226 static constexpr std::int16_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 227 static constexpr std::int16_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2,
@@ -247,8 +248,25 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co
247 const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); 248 const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]);
248 if (in.failed() || distance > out.size()) return ZlibError::data; 249 if (in.failed() || distance > out.size()) return ZlibError::data;
249 if (out.size() > limit || length > limit - out.size()) return ZlibError::limit; 250 if (out.size() > limit || length > limit - out.size()) return ZlibError::limit;
250 const std::size_t from = out.size() - distance; 251 const std::size_t start = out.size();
251 for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); 252 if (!bulk) {
253 for (std::size_t i = 0; i < length; ++i) out.push_back(out[start - distance + i]);
254 continue;
255 }
256 out.resize(start + length);
257 auto* dest = out.data() + start;
258 if (distance == 1) {
259 std::fill_n(dest, length, dest[-1]);
260 } else {
261 // Overlapping matches repeat their first distance bytes. Each copy reads only completed output.
262 std::size_t copied = std::min(distance, length);
263 std::memcpy(dest, dest - distance, copied);
264 while (copied < length) {
265 const auto count = std::min(copied, length - copied);
266 std::memcpy(dest + copied, dest, count);
267 copied += count;
268 }
269 }
252 } 270 }
253} 271}
254 272
@@ -260,7 +278,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co
260// dictionary), `data` for the deflate data or a missing trailer, `checksum` for an Adler-32 mismatch, `limit` for 278// dictionary), `data` for the deflate data or a missing trailer, `checksum` for an Adler-32 mismatch, `limit` for
261// output beyond `limit`. Bytes after the Adler-32 trailer are not read. 279// output beyond `limit`. Bytes after the Adler-32 trailer are not read.
262inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint8_t>& out, 280inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint8_t>& out,
263 std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr) { 281 std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr, bool bulk = true) {
264 out.clear(); 282 out.clear();
265 const auto fail = [why](ZlibError reason) { 283 const auto fail = [why](ZlibError reason) {
266 if (why) *why = reason; 284 if (why) *why = reason;
@@ -303,7 +321,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
303 detail::build_huffman(t.second, lengths, 30); 321 detail::build_huffman(t.second, lengths, 30);
304 return t; 322 return t;
305 }(); 323 }();
306 if (const ZlibError e = detail::inflate_codes(reader, out, tables.first, tables.second, limit); e != ZlibError::none) 324 if (const ZlibError e = detail::inflate_codes(reader, out, tables.first, tables.second, limit, bulk); e != ZlibError::none)
307 return fail(e); 325 return fail(e);
308 } else if (type == 2) { // dynamic Huffman 326 } else if (type == 2) { // dynamic Huffman
309 const int literal_count = int(reader.bits(5)) + 257, distance_count = int(reader.bits(5)) + 1; 327 const int literal_count = int(reader.bits(5)) + 257, distance_count = int(reader.bits(5)) + 1;
@@ -340,7 +358,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
340 if (!detail::build_huffman(literal, lengths, literal_count) || 358 if (!detail::build_huffman(literal, lengths, literal_count) ||
341 !detail::build_huffman(distance, lengths + literal_count, distance_count)) 359 !detail::build_huffman(distance, lengths + literal_count, distance_count))
342 return fail(ZlibError::data); 360 return fail(ZlibError::data);
343 if (const ZlibError e = detail::inflate_codes(reader, out, literal, distance, limit); e != ZlibError::none) 361 if (const ZlibError e = detail::inflate_codes(reader, out, literal, distance, limit, bulk); e != ZlibError::none)
344 return fail(e); 362 return fail(e);
345 } else { 363 } else {
346 return fail(ZlibError::data); 364 return fail(ZlibError::data);
@@ -351,9 +369,23 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
351 const std::size_t at = 2 + reader.position(); 369 const std::size_t at = 2 + reader.position();
352 if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data); 370 if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data);
353 std::uint32_t a = 1, b = 0; 371 std::uint32_t a = 1, b = 0;
354 for (const std::uint8_t x : out) { 372 if (bulk) {
355 a = (a + x) % 65521; 373 // At most 5,552 bytes of 0xff fit in both 32-bit accumulators between reductions.
356 b = (b + a) % 65521; 374 for (std::span<const std::uint8_t> tail(out); !tail.empty();) {
375 const auto block = tail.first(std::min<std::size_t>(tail.size(), 5552));
376 for (const auto x : block) {
377 a += x;
378 b += a;
379 }
380 a %= 65521;
381 b %= 65521;
382 tail = tail.subspan(block.size());
383 }
384 } else {
385 for (const std::uint8_t x : out) {
386 a = (a + x) % 65521;
387 b = (b + a) % 65521;
388 }
357 } 389 }
358 const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) | 390 const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) |
359 (std::uint32_t(in[at + 2]) << 8) | in[at + 3]; 391 (std::uint32_t(in[at + 2]) << 8) | in[at + 3];
@@ -808,7 +840,8 @@ struct SignatureElement {
808 840
809struct ShaderEntry { 841struct ShaderEntry {
810 std::string name; 842 std::string name;
811 std::string stage; // "vs", "ps", "cs", "ms", "gs" 843 std::string spv_file; // optional "<prefix><spv>" filename when the index key is a hash
844 std::string stage; // "vs", "ps", "cs", "ms", "gs"
812 std::string fssm_sha256; 845 std::string fssm_sha256;
813 std::string fspx_code_sha256; // an FSPX program (docs/fspx.md): the SHA-256 of its kind-6 bytes 846 std::string fspx_code_sha256; // an FSPX program (docs/fspx.md): the SHA-256 of its kind-6 bytes
814 std::string fspx_state_sha256; // and of its kind-0 entry (dispatch state) 847 std::string fspx_state_sha256; // and of its kind-0 entry (dispatch state)
@@ -819,6 +852,7 @@ struct ShaderEntry {
819 // pipeline needs it at or under the device's maxComputeSharedMemorySize (32768 on some drivers). 852 // pipeline needs it at or under the device's maxComputeSharedMemorySize (32768 on some drivers).
820 std::uint32_t lds_bytes = 0; 853 std::uint32_t lds_bytes = 0;
821 bool uses_code_base = false; 854 bool uses_code_base = false;
855 bool code_base_known = false;
822 bool wave64 = false; 856 bool wave64 = false;
823 // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null, 857 // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null,
824 // as one translated with --wave64-emulate does, or has none. 858 // as one translated with --wave64-emulate does, or has none.
@@ -826,7 +860,14 @@ struct ShaderEntry {
826 // "workgroup" for a shader translated with --wave64-emulate: it uses no subgroup operation and is exact on any 860 // "workgroup" for a shader translated with --wave64-emulate: it uses no subgroup operation and is exact on any
827 // subgroup size. Empty for a native translation. 861 // subgroup size. Empty for a native translation.
828 std::string wave64_exchange; 862 std::string wave64_exchange;
863 // Wave64 VS/PS/GS only: the translator's partition-invariance tier (index.json `wave64_graphics`; docs/design.md,
864 // "Wave64 graphics"). A and B are exact when the wave is cut into two 32-lane halves, C is not. Empty for other
865 // stages or an index written without the analysis.
866 std::string wave64_graphics;
829 bool emulated() const { return wave64_exchange == "workgroup"; } 867 bool emulated() const { return wave64_exchange == "workgroup"; }
868 // Mesh shaders: the index's "root_window" is {"sgpr": 16, "dword": 8}, so the module reads its root arguments
869 // from the graphics window (push dword 8 = root dword 0, D3D-448 follow-up). False for one translated before it.
870 bool graphics_root_window = false;
830 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed 871 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed
831 std::vector<std::uint32_t> inputs; // pixel shaders: input locations declared 872 std::vector<std::uint32_t> inputs; // pixel shaders: input locations declared
832 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written 873 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written
@@ -841,18 +882,55 @@ struct ShaderEntry {
841 std::uint32_t max_primitives = 0; 882 std::uint32_t max_primitives = 0;
842}; 883};
843 884
885// Which descriptor-table hash finalizer the loaded modules probe with (descriptor_table.h). Each module's index.json
886// meta may carry `"descriptor_hash": "fnv1a_fmix32"`; an absent key means the old bare `"fnv1a"`. The runtime has one
887// table for all shaders, so it counts the kinds over every loaded module (the root index and each sub-index) and picks
888// the majority; a mixed library still works, because the minority's lookups simply miss to index 0.
889struct DescriptorHashCensus {
890 std::size_t fnv1a = 0;
891 std::size_t fnv1a_fmix32 = 0;
892 std::size_t total() const { return fnv1a + fnv1a_fmix32; }
893};
894
895// The kind most modules declare. A tie (or no modules) is fnv1a, the behaviour before the marker existed.
896inline DescriptorHashKind majority_descriptor_hash_kind(const DescriptorHashCensus& census) {
897 return census.fnv1a_fmix32 > census.fnv1a ? DescriptorHashKind::fnv1a_fmix32 : DescriptorHashKind::fnv1a;
898}
899
900// LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32 overrides the modules' majority. False when `value` is null, empty or not
901// one of the two kinds (an unrecognised value is ignored rather than failing startup).
902inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* kind) {
903 if (!value || !*value) return false;
904 if (std::strcmp(value, "fnv1a_fmix32") == 0) {
905 if (kind) *kind = DescriptorHashKind::fnv1a_fmix32;
906 return true;
907 }
908 if (std::strcmp(value, "fnv1a") == 0) {
909 if (kind) *kind = DescriptorHashKind::fnv1a;
910 return true;
911 }
912 return false;
913}
914
844class ShaderLibrary { 915class ShaderLibrary {
845public: 916public:
846 // Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each 917 // Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's DLLs and the
847 // when it is there: 918 // game executable, each when it is there:
848 // - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md); 919 // - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md);
920 // - <dir>/fspx_compute/index.json, the compute programs from shaders.rpf's pipeline library;
921 // - <dir>/fspx_gfx/index.json, the graphics programs from the same library;
849 // - <dir>/bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/<name>" and found by 922 // - <dir>/bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/<name>" and found by
850 // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md); 923 // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md);
924 // - <dir>/exe/index.json, game_scarlett_master.exe's own DXBC containers, entries named "exe/<name>" and found
925 // the same way (docs/embedded_shaders.md, "Retail executable");
851 // - <dir>/library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable 926 // - <dir>/library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable
852 // creates with slot 67; entries named "library/<name>" and found by fspx_code_sha256 and fspx_state_sha256 927 // creates with slot 67; entries named "library/<name>" and found by fspx_code_sha256 and fspx_state_sha256
853 // like the FSPX ones (docs/shader_library.md). 928 // like the FSPX ones (docs/shader_library.md).
854 // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders 929 // fspx_compute/ and library/ are two builds of the same slot-67 programs (make_game.py's library_shaders() writes
855 // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded. 930 // library/; fspx_compute/ is the set translated from every console-path miss): both go into the same FSPX lookup
931 // by kind-6 and kind-0 SHA-256, and fspx_compute/ is read first, so its entry is the one found when both hold a
932 // program. Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The
933 // sub-indexes are optional: a missing or unreadable index there leaves the main one and the other folders loaded.
856 bool load(const std::filesystem::path& dir, std::string* error = nullptr) { 934 bool load(const std::filesystem::path& dir, std::string* error = nullptr) {
857 const auto fail = [&](const std::string& why) { 935 const auto fail = [&](const std::string& why) {
858 if (error) *error = why; 936 if (error) *error = why;
@@ -870,7 +948,7 @@ public:
870 } catch (...) { 948 } catch (...) {
871 return fail("index.json could not be read"); 949 return fail("index.json could not be read");
872 } 950 }
873 for (const char* sub_folder : {"fspx", "bvh", "library"}) { 951 for (const char* sub_folder : {"fspx", "fspx_compute", "fspx_gfx", "bvh", "exe", "library"}) {
874 try { 952 try {
875 const auto ignore = [](const std::string&) { return false; }; 953 const auto ignore = [](const std::string&) { return false; };
876 const std::filesystem::path sub = folder / sub_folder; 954 const std::filesystem::path sub = folder / sub_folder;
@@ -882,17 +960,53 @@ public:
882 return true; 960 return true;
883 } 961 }
884 962
963 // Loads only the optional FSPX sub-indexes (<dir>/fspx/index.json and <dir>/fspx_gfx/index.json) without parsing
964 // the 26,565-entry main index.json, for fast stage/hash lookups in the Xbox device proxy.
965 bool load_fspx_only(const std::filesystem::path& dir) {
966 dir_ = dir;
967 entries_.clear();
968 fspx_entries_.clear();
969 count_ = 0;
970 fspx_count_ = 0;
971 fspx_compute_count_ = 0;
972 fspx_gfx_count_ = 0;
973 bvh_count_ = 0;
974 exe_count_ = 0;
975 descriptor_hash_census_ = {};
976 for (const char* folder : {"fspx", "fspx_gfx"}) {
977 try {
978 const auto ignore = [](const std::string&) { return false; };
979 const std::filesystem::path sub = dir / folder;
980 if (std::ifstream(sub / "index.json", std::ios::binary))
981 load_index(sub, std::string(folder) + "/", ignore);
982 } catch (...) {
983 }
984 }
985 return (fspx_count_ + fspx_gfx_count_) > 0;
986 }
987
885 bool loaded() const { return !dir_.empty(); } 988 bool loaded() const { return !dir_.empty(); }
886 // The folder load() read, made absolute; empty before. 989 // The folder load() read, made absolute; empty before.
887 const std::filesystem::path& directory() const { return dir_; } 990 const std::filesystem::path& directory() const { return dir_; }
888 std::size_t size() const { return count_; } 991 std::size_t size() const { return count_; }
992 // The descriptor-hash kinds the loaded modules declare, and the kind the majority of them probe with (fnv1a when
993 // they tie or none declares one). The device takes this once, before its descriptor table's first insert, unless
994 // LEONIDA_DESCRIPTOR_HASH names a kind.
995 const DescriptorHashCensus& descriptor_hash_census() const { return descriptor_hash_census_; }
996 DescriptorHashKind descriptor_hash_kind() const { return majority_descriptor_hash_kind(descriptor_hash_census_); }
889 // Entries loaded from <dir>/fspx/index.json and <dir>/library/index.json. A corpus of RPF containers never 997 // Entries loaded from <dir>/fspx/index.json and <dir>/library/index.json. A corpus of RPF containers never
890 // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached 998 // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached
891 // entries with size() must leave them out. 999 // entries with size() must leave them out.
892 std::size_t fspx_size() const { return fspx_count_; } 1000 std::size_t fspx_size() const { return fspx_count_; }
1001 std::size_t fspx_compute_size() const { return fspx_compute_count_; }
1002 // Entries loaded from <dir>/fspx_gfx/index.json (graphics FSPX programs from shaders.rpf's pipeline library).
1003 std::size_t fspx_gfx_size() const { return fspx_gfx_count_; }
893 // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes 1004 // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes
894 // their containers itself. 1005 // their containers itself.
895 std::size_t bvh_size() const { return bvh_count_; } 1006 std::size_t bvh_size() const { return bvh_count_; }
1007 // Entries loaded from <dir>/exe/index.json: game_scarlett_master.exe's inline containers, which no shader
1008 // archive holds.
1009 std::size_t exe_size() const { return exe_count_; }
896 1010
897 // The first entry for this program. Two containers can hold the same FSSM program with different input 1011 // The first entry for this program. Two containers can hold the same FSSM program with different input
898 // signatures; `candidates` returns all of them. 1012 // signatures; `candidates` returns all of them.
@@ -910,6 +1024,15 @@ public:
910 return lookup(fspx_entries_, stage, fspx_code_sha256); 1024 return lookup(fspx_entries_, stage, fspx_code_sha256);
911 } 1025 }
912 1026
1027 // Finds an FSPX program by its kind-6 SHA-256 across all stages so the stage comes from the index entry itself.
1028 const ShaderEntry* find_fspx_by_code(std::string_view fspx_code_sha256) const {
1029 for (std::string_view st : {"vs", "ps", "ms", "gs", "cs"}) {
1030 const auto all = fspx_candidates(st, fspx_code_sha256);
1031 if (!all.empty()) return all.front();
1032 }
1033 return nullptr;
1034 }
1035
913 // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time 1036 // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time
914 // lookup"): 1037 // lookup"):
915 // - FSSM: by fssm_sha256, as before; 1038 // - FSSM: by fssm_sha256, as before;
@@ -946,11 +1069,30 @@ public:
946 return all; 1069 return all;
947 } 1070 }
948 1071
1072 // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it.
1073 std::size_t spirv_bytes(const ShaderEntry& entry) const {
1074 std::error_code ec;
1075 auto path = dir_;
1076 path += "/" + entry.name + ".spv";
1077 auto size = std::filesystem::file_size(path, ec);
1078 if (ec && !entry.spv_file.empty()) {
1079 auto alt = dir_;
1080 alt += "/" + entry.spv_file;
1081 size = std::filesystem::file_size(alt, ec);
1082 }
1083 return ec ? 0 : static_cast<std::size_t>(size);
1084 }
1085
949 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. 1086 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V.
950 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { 1087 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const {
951 auto path = dir_; 1088 auto path = dir_;
952 path += "/" + entry.name + ".spv"; 1089 path += "/" + entry.name + ".spv";
953 std::ifstream file(path, std::ios::binary | std::ios::ate); 1090 std::ifstream file(path, std::ios::binary | std::ios::ate);
1091 if (!file && !entry.spv_file.empty()) {
1092 auto alt = dir_;
1093 alt += "/" + entry.spv_file;
1094 file.open(alt, std::ios::binary | std::ios::ate);
1095 }
954 return read_spirv_words(file, file.tellg()); 1096 return read_spirv_words(file, file.tellg());
955 } 1097 }
956 1098
@@ -999,7 +1141,11 @@ private:
999 fspx_entries_.clear(); 1141 fspx_entries_.clear();
1000 count_ = 0; 1142 count_ = 0;
1001 fspx_count_ = 0; 1143 fspx_count_ = 0;
1144 fspx_compute_count_ = 0;
1145 fspx_gfx_count_ = 0;
1002 bvh_count_ = 0; 1146 bvh_count_ = 0;
1147 exe_count_ = 0;
1148 descriptor_hash_census_ = {};
1003 } 1149 }
1004 for (const auto& [name, meta] : root.object) { 1150 for (const auto& [name, meta] : root.object) {
1005 const Json* hash = meta.find("fssm_sha256"); 1151 const Json* hash = meta.find("fssm_sha256");
@@ -1010,6 +1156,8 @@ private:
1010 if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue; 1156 if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue;
1011 ShaderEntry e; 1157 ShaderEntry e;
1012 e.name = prefix + name; 1158 e.name = prefix + name;
1159 if (const Json* spv = meta.find("spv"); spv && spv->kind == Json::Kind::string && !spv->string.empty())
1160 e.spv_file = prefix + spv->string;
1013 e.stage = stage->string; 1161 e.stage = stage->string;
1014 if (by_fssm) e.fssm_sha256 = hash->string; 1162 if (by_fssm) e.fssm_sha256 = hash->string;
1015 if (by_fspx) e.fspx_code_sha256 = code_hash->string; 1163 if (by_fspx) e.fspx_code_sha256 = code_hash->string;
@@ -1020,12 +1168,26 @@ private:
1020 e.lds_bytes = u32(meta.find("lds_bytes")); 1168 e.lds_bytes = u32(meta.find("lds_bytes"));
1021 if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array) 1169 if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array)
1022 for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); 1170 for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]);
1023 if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; 1171 // The paired FSPX translator emits uses_code_base only when true. Older
1172 // key-only indexes have no such contract; retain their program bytes.
1173 e.code_base_known = !e.fspx_state_sha256.empty();
1174 if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) {
1175 e.uses_code_base = c->boolean;
1176 e.code_base_known = true;
1177 }
1024 if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; 1178 if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean;
1025 if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) 1179 if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number)
1026 e.subgroup_size = u32(g); 1180 e.subgroup_size = u32(g);
1027 if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string) 1181 if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string)
1028 e.wave64_exchange = x->string; 1182 e.wave64_exchange = x->string;
1183 if (const Json* r = meta.find("root_window"); r && r->kind == Json::Kind::object) {
1184 const Json* sgpr = r->find("sgpr");
1185 const Json* dword = r->find("dword");
1186 e.graphics_root_window = sgpr && dword && sgpr->kind == Json::Kind::number &&
1187 dword->kind == Json::Kind::number && u32(sgpr) == 16 && u32(dword) == 8;
1188 }
1189 if (const Json* wg = meta.find("wave64_graphics"); wg && wg->kind == Json::Kind::string)
1190 e.wave64_graphics = wg->string;
1029 if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { 1191 if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) {
1030 for (const Json& item : s->array) { 1192 for (const Json& item : s->array) {
1031 SignatureElement element; 1193 SignatureElement element;
@@ -1072,10 +1234,20 @@ private:
1072 } 1234 }
1073 e.max_vertices = u32(meta.find("max_vertices")); 1235 e.max_vertices = u32(meta.find("max_vertices"));
1074 e.max_primitives = u32(meta.find("max_primitives")); 1236 e.max_primitives = u32(meta.find("max_primitives"));
1237 // Which finalizer this module's shader probes the descriptor table with (descriptor_table.h). Absent, or not
1238 // a kind this runtime knows, is the old bare FNV-1a.
1239 if (const Json* dh = meta.find("descriptor_hash");
1240 dh && dh->kind == Json::Kind::string && dh->string == "fnv1a_fmix32")
1241 ++descriptor_hash_census_.fnv1a_fmix32;
1242 else
1243 ++descriptor_hash_census_.fnv1a;
1075 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 1244 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
1076 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 1245 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
1077 if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; 1246 if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_;
1247 if (by_fspx && prefix == "fspx_compute/") ++fspx_compute_count_;
1248 if (by_fspx && prefix == "fspx_gfx/") ++fspx_gfx_count_;
1078 if (prefix == "bvh/") ++bvh_count_; 1249 if (prefix == "bvh/") ++bvh_count_;
1250 if (prefix == "exe/") ++exe_count_;
1079 ++count_; 1251 ++count_;
1080 } 1252 }
1081 return true; 1253 return true;
@@ -1084,10 +1256,14 @@ private:
1084 std::filesystem::path dir_; 1256 std::filesystem::path dir_;
1085 std::size_t count_ = 0; 1257 std::size_t count_ = 0;
1086 std::size_t fspx_count_ = 0; 1258 std::size_t fspx_count_ = 0;
1259 std::size_t fspx_compute_count_ = 0;
1260 std::size_t fspx_gfx_count_ = 0;
1087 std::size_t bvh_count_ = 0; 1261 std::size_t bvh_count_ = 0;
1262 std::size_t exe_count_ = 0;
1088 // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. 1263 // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order.
1089 Entries entries_; 1264 Entries entries_;
1090 Entries fspx_entries_; 1265 Entries fspx_entries_;
1266 DescriptorHashCensus descriptor_hash_census_;
1091}; 1267};
1092 1268
1093} // namespace leonida 1269} // namespace leonida
diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h
index c391b7e63..0241c4db8 100644
--- a/runtime/src/subgroup_size.h
+++ b/runtime/src/subgroup_size.h
@@ -61,6 +61,14 @@ inline VkShaderStageFlagBits subgroup_stage_bit(std::string_view stage) {
61 return VkShaderStageFlagBits(0); 61 return VkShaderStageFlagBits(0);
62} 62}
63 63
64// A wave64 VS/PS/GS that the translator's partition-invariance analysis (index.json `wave64_graphics`; docs/design.md,
65// "Wave64 graphics") puts in tier A or B: observable results do not change when the GPU cuts the wave into two 32-lane
66// halves, so the device's 32-wide size is exact for it. Tier C and entries without the analysis stay conservative.
67inline bool graphics_partition_invariant(const ShaderEntry& entry) {
68 if (entry.stage != "vs" && entry.stage != "ps" && entry.stage != "gs") return false;
69 return entry.wave64 && (entry.wave64_graphics == "A" || entry.wave64_graphics == "B");
70}
71
64enum class SubgroupOutcome { 72enum class SubgroupOutcome {
65 emulated, // --wave64-emulate: exact on any size, nothing is required 73 emulated, // --wave64-emulate: exact on any size, nothing is required
66 required, // the stage asks for `size` 74 required, // the stage asks for `size`
diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp
new file mode 100644
index 000000000..67188d908
--- /dev/null
+++ b/runtime/src/thread_stacks.cpp
@@ -0,0 +1,237 @@
1#include "thread_stacks.h"
2
3#include <windows.h>
4#include <tlhelp32.h>
5
6#include <algorithm>
7#include <array>
8#include <charconv>
9#include <chrono>
10#include <condition_variable>
11#include <cstdio>
12#include <mutex>
13#include <string>
14
15#include "../shims/shims.h"
16#include "../shims/startup_trace.h"
17
18namespace rt {
19namespace {
20
21using Clock = std::chrono::steady_clock;
22using GetDescription = HRESULT(WINAPI*)(HANDLE, PWSTR*);
23using QueryThread = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
24
25struct CopiedStack {
26 DWORD64 copy = 0; // Where the bytes are now.
27 DWORD64 original = 0; // Where they were in the thread: [original, original + size).
28 size_t size = 0;
29};
30
31// Suspended section: system calls and a copy only.
32bool copy_context_and_stack(HANDLE thread, CONTEXT& context, std::byte* buffer, CopiedStack& stack) {
33 if (SuspendThread(thread) == DWORD(-1)) return false;
34 context.ContextFlags = CONTEXT_FULL;
35 MEMORY_BASIC_INFORMATION region{};
36 bool copied = false;
37 if (GetThreadContext(thread, &context) &&
38 VirtualQuery(reinterpret_cast<void*>(context.Rsp), &region, sizeof(region)) &&
39 region.State == MEM_COMMIT && !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS))) {
40 // From RSP (rounded down to keep the 16-byte alignment the copy buffer also has) to the top of the committed
41 // run of stack pages, at most kMaxStackBytes.
42 stack.original = context.Rsp & ~DWORD64(15);
43 const DWORD64 top = reinterpret_cast<DWORD64>(region.BaseAddress) + region.RegionSize;
44 stack.size = static_cast<size_t>(std::min<DWORD64>(StackSampler::kMaxStackBytes, top - stack.original));
45 SIZE_T read = 0;
46 copied = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<void*>(stack.original), buffer, stack.size,
47 &read) && read == stack.size;
48 }
49 ResumeThread(thread);
50 stack.copy = reinterpret_cast<DWORD64>(buffer);
51 return copied;
52}
53
54// A frame's code can be unloaded after its thread resumes and a damaged stack can hand the unwinder a bad pointer:
55// both are access violations here, and end the walk.
56bool unwind_frame(CONTEXT& context) {
57 __try {
58 DWORD64 image_base = 0;
59 if (const auto* entry = RtlLookupFunctionEntry(context.Rip, &image_base, nullptr)) {
60 void* handler_data = nullptr;
61 DWORD64 establisher = 0;
62 RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, context.Rip, const_cast<PRUNTIME_FUNCTION>(entry),
63 &context, &handler_data, &establisher, nullptr);
64 } else {
65 // No function entry: a leaf (or a thunk without unwind data) that has not moved RSP.
66 context.Rip = *reinterpret_cast<const DWORD64*>(context.Rsp);
67 context.Rsp += sizeof(DWORD64);
68 }
69 } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR
70 ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
71 return false;
72 }
73 return true;
74}
75
76size_t walk_copy(CONTEXT& context, const CopiedStack& stack, std::uint64_t* frames) {
77 // An address in the copied range now names the same word in the copy.
78 const auto rebase = [&](DWORD64& address) {
79 if (address >= stack.original && address - stack.original < stack.size) address += stack.copy - stack.original;
80 };
81 const auto in_copy = [&](DWORD64 address) {
82 return address >= stack.copy && address - stack.copy + sizeof(DWORD64) <= stack.size;
83 };
84 size_t count = 0;
85 rebase(context.Rsp);
86 while (context.Rip && count < StackSampler::kMaxFrames) {
87 frames[count++] = context.Rip;
88 if (!in_copy(context.Rsp)) break;
89 const DWORD64 rsp = context.Rsp;
90 // Any nonvolatile register can be a frame pointer, including one just restored from the copy's bytes.
91 for (DWORD64* reg : {&context.Rbx, &context.Rbp, &context.Rsi, &context.Rdi,
92 &context.R12, &context.R13, &context.R14, &context.R15})
93 rebase(*reg);
94 if (!unwind_frame(context)) break;
95 rebase(context.Rsp); // A machine frame restores RSP from the copy as well.
96 if (context.Rsp <= rsp) break;
97 }
98 return count;
99}
100
101std::string thread_label(HANDLE thread, GetDescription describe, QueryThread query) {
102 if (describe) {
103 PWSTR description = nullptr;
104 if (SUCCEEDED(describe(thread, &description)) && description) {
105 std::string name = startup_trace::detail::utf8_from_wide(description, static_cast<int>(wcslen(description)));
106 LocalFree(description);
107 if (!name.empty()) return name;
108 }
109 }
110 constexpr int kWin32StartAddress = 9; // ThreadQuerySetWin32StartAddress
111 DWORD64 start = 0;
112 if (query && query(thread, kWin32StartAddress, &start, sizeof(start), nullptr) >= 0 && start)
113 return "start " + shims::module_offset(start);
114 return "start unknown";
115}
116
117struct ThreadTrace {
118 DWORD tid = 0;
119 std::string label;
120 std::array<std::uint64_t, StackSampler::kMaxFrames> frames{};
121 size_t count = 0;
122};
123
124void print_traces(unsigned at, const std::vector<ThreadTrace>& traces) {
125 std::string out = "[rt] stacks t=" + std::to_string(at) + ": " + std::to_string(traces.size()) + " threads\n";
126 for (auto it = traces.begin(); it != traces.end(); ++it) {
127 out += "[rt] stacks t=" + std::to_string(at) + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n";
128 const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) {
129 return it->count && it->count == earlier.count &&
130 std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin());
131 });
132 if (same != it) {
133 out += " same as thread " + std::to_string(same->tid) + "\n";
134 } else if (!it->count) {
135 out += " stack unavailable\n";
136 } else {
137 for (size_t i = 0; i < it->count; ++i)
138 out += " #" + std::to_string(i) + " " + shims::module_offset(it->frames[i]) + "\n";
139 }
140 }
141 std::fputs(out.c_str(), stderr);
142 std::fflush(stderr);
143}
144
145void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describe, QueryThread query) {
146 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
147 if (snapshot == INVALID_HANDLE_VALUE) {
148 std::fprintf(stderr, "[rt] stacks t=%u: thread list failed (error %lu)\n", at, GetLastError());
149 return;
150 }
151 std::vector<ThreadTrace> traces;
152 traces.reserve(512);
153 const DWORD pid = GetCurrentProcessId();
154 const DWORD self = GetCurrentThreadId();
155 THREADENTRY32 entry{};
156 entry.dwSize = sizeof(entry);
157 for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) {
158 entry.dwSize = sizeof(entry);
159 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue;
160 const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
161 FALSE, entry.th32ThreadID);
162 if (!thread) continue;
163 if (GetProcessIdOfThread(thread) == pid) { // The listed thread may have exited and its ID been reused.
164 ThreadTrace& trace = traces.emplace_back();
165 trace.tid = entry.th32ThreadID;
166 trace.label = thread_label(thread, describe, query); // Before sampling: it allocates.
167 trace.count = sampler.sample(thread, trace.frames.data());
168 }
169 CloseHandle(thread);
170 }
171 CloseHandle(snapshot);
172 print_traces(at, traces);
173}
174
175} // namespace
176
177StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite<std::byte[]>(kMaxStackBytes)) {}
178
179std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) {
180 CONTEXT context{};
181 CopiedStack stack;
182 if (!copy_context_and_stack(static_cast<HANDLE>(thread), context, stack_.get(), stack)) {
183 if (!context.Rip) return 0;
184 frames[0] = context.Rip; // The context without its stack: the innermost frame only.
185 return 1;
186 }
187 return walk_copy(context, stack, frames);
188}
189
190bool parse_stack_times(std::string_view text, std::vector<unsigned>& seconds) {
191 seconds.clear();
192 for (;;) {
193 const auto comma = text.find(',');
194 const auto token = text.substr(0, comma);
195 unsigned value = 0;
196 const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value);
197 if (token.empty() || error != std::errc{} || end != token.data() + token.size()) {
198 seconds.clear();
199 return false;
200 }
201 seconds.push_back(value);
202 if (comma == std::string_view::npos) break;
203 text.remove_prefix(comma + 1);
204 }
205 std::sort(seconds.begin(), seconds.end());
206 seconds.erase(std::unique(seconds.begin(), seconds.end()), seconds.end());
207 return true;
208}
209
210std::jthread start_thread_stacks() {
211 const auto start = Clock::now();
212 char spec[1024];
213 const DWORD length = GetEnvironmentVariableA("LEONIDA_STACKS", spec, sizeof(spec));
214 if (!length) return {};
215 std::vector<unsigned> times;
216 if (length >= sizeof(spec) || !parse_stack_times(std::string_view(spec, length), times)) {
217 std::fprintf(stderr, "[rt] LEONIDA_STACKS: expected comma-separated whole seconds\n");
218 return {};
219 }
220 return std::jthread([start, times = std::move(times)](std::stop_token stop) {
221 const auto describe = reinterpret_cast<GetDescription>(reinterpret_cast<void*>(
222 GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription")));
223 const auto query = reinterpret_cast<QueryThread>(reinterpret_cast<void*>(
224 GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
225 StackSampler sampler;
226 std::condition_variable_any wake;
227 std::mutex mutex;
228 std::unique_lock lock(mutex);
229 for (const unsigned at : times) {
230 wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; });
231 if (stop.stop_requested()) break;
232 snapshot_threads(at, sampler, describe, query);
233 }
234 });
235}
236
237} // namespace rt
diff --git a/runtime/src/thread_stacks.h b/runtime/src/thread_stacks.h
new file mode 100644
index 000000000..523c7b266
--- /dev/null
+++ b/runtime/src/thread_stacks.h
@@ -0,0 +1,38 @@
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <memory>
6#include <string_view>
7#include <thread>
8#include <vector>
9
10namespace rt {
11
12// One thread's call chain, taken without stopping the thread for longer than a context and stack copy.
13class StackSampler {
14public:
15 static constexpr std::size_t kMaxFrames = 40;
16 static constexpr std::size_t kMaxStackBytes = 8 * 1024 * 1024;
17
18 StackSampler(); // Allocates the stack copy once, so sample() allocates nothing.
19
20 // `thread` needs THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT. While it is suspended this makes system calls only
21 // (GetThreadContext, VirtualQuery, ReadProcessMemory): no heap, stdio or user-mode locks, which the suspended
22 // thread may hold. After ResumeThread it unwinds the copy with RtlLookupFunctionEntry/RtlVirtualUnwind, reading
23 // stack words from the copy rather than the live stack, which has moved on. Writes up to kMaxFrames addresses
24 // (the instruction pointer, then return addresses) and returns how many; 0 if the thread could not be sampled.
25 std::size_t sample(void* thread, std::uint64_t* frames);
26
27private:
28 std::unique_ptr<std::byte[]> stack_;
29};
30
31// Parses LEONIDA_STACKS: comma-separated whole seconds. Returns false (and leaves `seconds` empty) on bad text.
32bool parse_stack_times(std::string_view text, std::vector<unsigned>& seconds);
33
34// LEONIDA_STACKS: snapshots of every thread at the listed times since this call, printed to stderr. Destroy the
35// sampler before unmapping the title image.
36std::jthread start_thread_stacks();
37
38} // namespace rt
diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h
new file mode 100644
index 000000000..ddc21d218
--- /dev/null
+++ b/runtime/src/title_geometry_watch.h
@@ -0,0 +1,123 @@
1#pragma once
2
3#include "title_page_watch.h"
4#include <array>
5#include <vector>
6
7namespace leonida::geometry_writes {
8
9constexpr std::uintptr_t tile_size = 65536, page_size = 4096;
10using Aliases = void (*)(std::uintptr_t, std::vector<std::uintptr_t>&);
11inline std::atomic<Aliases> aliases{};
12
13struct Cell {
14 std::atomic<std::uint64_t> version{1}, mapping{1};
15 std::array<DWORD, tile_size / page_size> restore{};
16 unsigned refs = 0;
17};
18struct State {
19 std::mutex mutex;
20 host_heap::map<std::uintptr_t, Cell> cells;
21 std::atomic<std::uint64_t> serial{1};
22 std::atomic<std::size_t> count{0};
23};
24inline State& state() { static State s; return s; }
25
26inline Cell* acquire(std::uintptr_t va) {
27 auto& s = state();
28 std::lock_guard lock(s.mutex);
29 auto& c = s.cells[va];
30 ++c.refs;
31 s.count.store(s.cells.size(), std::memory_order_release);
32 return &c;
33}
34
35// Restore only protections this watch installed. A guest remap or explicit new protection supersedes them.
36inline DWORD read_only(DWORD protection) {
37 switch (protection & 255u) {
38 case PAGE_READWRITE: case PAGE_WRITECOPY: return (protection & ~255u) | PAGE_READONLY;
39 case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: return (protection & ~255u) | PAGE_EXECUTE_READ;
40 default: return 0;
41 }
42}
43inline void reopen(std::uintptr_t va, Cell& c) {
44 for (std::size_t i = 0; i < c.restore.size(); ++i) {
45 if (!c.restore[i]) continue;
46 void* p = reinterpret_cast<void*>(va + i * page_size);
47 MEMORY_BASIC_INFORMATION m{};
48 DWORD old{};
49 if (!VirtualQuery(p, &m, sizeof m)) continue;
50 if (m.State == MEM_COMMIT && m.Protect == read_only(c.restore[i]) &&
51 !VirtualProtect(p, page_size, c.restore[i], &old)) continue;
52 c.restore[i] = 0;
53 }
54}
55inline void release(std::uintptr_t va) {
56 auto& s = state();
57 std::lock_guard lock(s.mutex);
58 auto it = s.cells.find(va);
59 if (it != s.cells.end() && !--it->second.refs) {
60 reopen(va, it->second);
61 s.cells.erase(it);
62 s.count.store(s.cells.size(), std::memory_order_release);
63 }
64}
65enum class Event { write, open, fault, mapping, replaced };
66inline bool notify(std::uintptr_t begin, std::uintptr_t end, Event event) {
67 auto& s = state();
68 if (!s.count.load(std::memory_order_acquire) || end <= begin) return false;
69 std::lock_guard lock(s.mutex);
70 auto it = s.cells.lower_bound(begin & ~(tile_size - 1));
71 if (it == s.cells.end() || it->first >= end) return false;
72 const auto version = s.serial.load(std::memory_order_relaxed) + 1;
73 bool opened = false;
74 for (; it != s.cells.end() && it->first < end; ++it) {
75 auto& cell = it->second;
76 if (event == Event::open || event == Event::fault) {
77 reopen(it->first, cell);
78 if (event == Event::fault) {
79 MEMORY_BASIC_INFORMATION m{};
80 opened = VirtualQuery(reinterpret_cast<void*>(begin), &m, sizeof m) &&
81 m.State == MEM_COMMIT && !(m.Protect & PAGE_GUARD) && read_only(m.Protect);
82 }
83 }
84 if (event == Event::replaced) {
85 for (unsigned i = 0; i < cell.restore.size(); ++i) {
86 auto p = it->first + i * page_size;
87 if (p < end && p + page_size > begin) cell.restore[i] = 0;
88 }
89 }
90 if (event == Event::mapping || event == Event::replaced) cell.mapping.store(version, std::memory_order_release);
91 cell.version.store(version, std::memory_order_release);
92 }
93 s.serial.store(version, std::memory_order_release);
94 return opened;
95}
96
97// Arm under the same lock as the write-fault path. A kernel destination may only be guarded again after its pin ends.
98inline bool arm(std::uintptr_t va, Cell& c) {
99 auto& s = state();
100 // Querying an OVERLAPPED can fault into xmem. Never do it with the watch lock held.
101 const auto version = c.version.load(std::memory_order_acquire);
102 bool pinned = false;
103 kernel_writes::for_each_pin(va, va + tile_size, [&](auto, auto) { pinned = true; });
104 std::lock_guard lock(s.mutex);
105 if (pinned || version != c.version.load(std::memory_order_relaxed)) return false;
106 for (std::size_t i = 0; i < c.restore.size();) {
107 auto p = va + i * page_size;
108 MEMORY_BASIC_INFORMATION m{};
109 if (!VirtualQuery(reinterpret_cast<void*>(p), &m, sizeof m)) return false;
110 const auto end = (std::min)(va + tile_size, reinterpret_cast<std::uintptr_t>(m.BaseAddress) + m.RegionSize);
111 if (end <= p) return false;
112 const auto next = (end - va) / page_size;
113 const DWORD guarded = read_only(m.Protect);
114 if (m.State == MEM_COMMIT && !(m.Protect & PAGE_GUARD) && guarded) {
115 DWORD old{};
116 if (!VirtualProtect(reinterpret_cast<void*>(p), end - p, guarded, &old)) return false;
117 for (auto j = i; j < next; ++j) c.restore[j] = old;
118 }
119 i = next;
120 }
121 return true;
122}
123} // namespace leonida::geometry_writes
diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h
new file mode 100644
index 000000000..b83e71b7b
--- /dev/null
+++ b/runtime/src/title_page_watch.h
@@ -0,0 +1,700 @@
1#pragma once
2// What the D3D12 layer's slot-133 shadow buffers (ShadowPages in d3d12_vulkan_device.cpp) need from the rest of the
3// runtime to see every write to the title's pages.
4//
5// A shadow notices the title's writes by asking the kernel which pages were written, where xmem reserved them with
6// MEM_WRITE_WATCH (title_write_watch, below), and elsewhere by making the buffer's pages read-only between
7// submissions: a write faults, the layer's handler makes the page writable again and the page is copied at the next
8// submission. Two kinds of write don't fault there, and are reported here instead:
9//
10// 1. Aliases (title_page_aliases). xmem maps one physical page at as many VAs as the title asks
11// (XMemMapPhysicalPages): a write through one VA changes what the others read without touching them. xmem
12// reports each 64 KiB page mapped at more than one address; a shadow copies those at every submission.
13//
14// 2. Kernel writes (kernel_writes). A read-only page makes ReadFile fail with ERROR_NOACCESS instead of faulting
15// into a user-mode handler. The file shims (read_file and the rest, below) pin the destination before the kernel
16// writes it: the layer makes its pages writable and doesn't protect them again until the pin ends, when the
17// call returns or, for an overlapped read, once its OVERLAPPED says it completed. A read that still fails with
18// ERROR_NOACCESS is retried once after the destination is opened again and xmem has committed the physical pages
19// mapped there that wait for their first touch (they are reserved until then, and a kernel write does not fault
20// them in either: measured on Windows 11, the title's 258 MiB effect-database read failed this way forever).
21//
22// Any other host code that has the kernel write title memory (a DirectStorage queue that ReadFiles straight into
23// a request's destination, for one) does the same: kernel_writes::read_file instead of ::ReadFile, or
24// begin_write(destination, bytes, overlapped) before the call and end_write(id, pending) after it. A user-mode
25// copy into title memory needs nothing: it faults like the title's own writes.
26//
27// Successful title memory map changes also invalidate the shadows' cached protection state. The shadows' own
28// protection changes stay local to their trackers.
29//
30// The shadows themselves are brought up to date in one place, DeviceState::refresh_shadows in
31// d3d12_vulkan_device.cpp, which VulkanQueue::execute_now calls (VulkanContext::set_before_execute) before every
32// submission of command lists.
33//
34// Header-only, so the D3D12 layer, xmem and the file shims share one state in a process without linking each other.
35#include <windows.h>
36
37#include <algorithm>
38#include <atomic>
39#include <cstdint>
40#include <cstdio>
41#include <cstdlib>
42#include <functional>
43#include <map>
44#include <mutex>
45#include <new>
46#include <shared_mutex>
47#include <tuple>
48#include <unordered_set>
49#include <utility>
50#include <vector>
51
52// The runtime's own heap (host_heap) for the state the D3D12 layer's write-fault handler waits behind. A thread can take
53// a write fault on a guarded title page while it holds the process heap's lock: XMemAlloc is _aligned_malloc, so
54// HeapAlloc and HeapFree write block headers on the title's pages. Its handler then waits for the tracker's lock
55// (ShadowPages::reopen) and the list of trackers (g_shadow_pages_lock). So a thread that holds either of those, or any
56// lock such a thread waits for (the record and journal of title_write_watch, title_page_aliases, kernel_writes' pins),
57// must never wait for the process heap: it would wait for the faulting thread, which waits for it. Their containers
58// allocate here instead, from a heap the title never touches and on whose lock no thread faults.
59namespace leonida::host_heap {
60
61inline HANDLE handle() {
62 static const HANDLE heap = [] {
63 const HANDLE created = HeapCreate(0, 0, 0);
64 if (!created) // the process heap brings back the deadlock this heap avoids: write watching stays off
65 std::fprintf(stderr, "[rt] host heap: HeapCreate failed (%lu); write watching is off\n", GetLastError());
66 return created ? created : GetProcessHeap();
67 }();
68 return heap;
69}
70
71template <class T>
72struct Allocator {
73 using value_type = T;
74 Allocator() noexcept { handle(); } // created before any lock is taken
75 template <class U>
76 Allocator(const Allocator<U>&) noexcept {}
77 T* allocate(std::size_t n) {
78 if (n > std::size_t(-1) / sizeof(T)) throw std::bad_array_new_length();
79 if (void* p = HeapAlloc(handle(), 0, n * sizeof(T))) return static_cast<T*>(p);
80 throw std::bad_alloc();
81 }
82 void deallocate(T* p, std::size_t) noexcept { HeapFree(handle(), 0, p); }
83 template <class U>
84 bool operator==(const Allocator<U>&) const noexcept {
85 return true;
86 }
87};
88
89template <class T>
90using vector = std::vector<T, Allocator<T>>;
91template <class K, class V>
92using map = std::map<K, V, std::less<K>, Allocator<std::pair<const K, V>>>;
93
94} // namespace leonida::host_heap
95
96namespace leonida::title_memory_map {
97
98inline std::atomic<std::uint64_t> map_generation{0};
99
100inline std::uint64_t generation() { return map_generation.load(std::memory_order_acquire); }
101inline void changed() { map_generation.fetch_add(1, std::memory_order_release); }
102
103} // namespace leonida::title_memory_map
104
105namespace leonida::title_page_aliases {
106
107constexpr std::uintptr_t kPageSize = 0x10000;
108
109struct State {
110 std::shared_mutex mutex;
111 // 64 KiB-aligned VAs
112 std::unordered_set<std::uintptr_t, std::hash<std::uintptr_t>, std::equal_to<std::uintptr_t>,
113 host_heap::Allocator<std::uintptr_t>>
114 aliased;
115 std::atomic<std::uint64_t> generation{0};
116};
117
118inline State& state() {
119 static State s;
120 return s;
121}
122
123// The 64 KiB page at `va` (rounded down) shows a page that is also mapped elsewhere (true), or no longer does.
124inline void set(std::uintptr_t va, bool aliased) {
125 State& s = state();
126 va &= ~(kPageSize - 1);
127 std::unique_lock lock(s.mutex);
128 const bool changed = aliased ? s.aliased.insert(va).second : s.aliased.erase(va) != 0;
129 if (changed) s.generation.fetch_add(1, std::memory_order_release);
130}
131
132// Bumped by every change of set().
133inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); }
134
135// Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end).
136template<class F>
137void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) {
138 State& s = state();
139 std::shared_lock lock(s.mutex);
140 if (s.aliased.empty()) return;
141 for (std::uintptr_t va = begin & ~(kPageSize - 1); va < end; va += kPageSize)
142 if (s.aliased.count(va)) f(va);
143}
144
145} // namespace leonida::title_page_aliases
146
147// 3. GPU-only views (title_gpu_views). The title reserves some memory twice: a range the CPU maps physical pages into
148// and a GPU-only range of the same size (PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS) that the console's GPU page
149// tables map to the same pages, and it hands the GPU-only address to the GPU (the texture stream pool: slot-133
150// placements, slot-70 views, DirectStorage destinations; gfxres notes section 5). Nothing maps the GPU-only range
151// for the host CPU, so the D3D12 layer reads such memory at the CPU range's address: to_cpu. xmem pairs each
152// GPU-only reservation with the CPU-mappable reservation of the same size made just before it, as
153// five-star-recomp does (docs/gpu-resources.md "Addresses", XMemReservation.CpuView; GPL-3.0-or-later).
154namespace leonida::title_gpu_views {
155
156struct View {
157 std::uintptr_t gpu, cpu, size;
158};
159
160struct State {
161 std::shared_mutex mutex;
162 std::vector<View> views;
163 std::atomic<std::size_t> count{0};
164 std::uintptr_t last_cpu = 0, last_cpu_size = 0; // the last CPU-mappable reservation
165};
166
167inline State& state() {
168 static State s;
169 return s;
170}
171
172// xmem: a reservation the title made, GPU-only or not. Returns true when it paired a GPU-only one.
173inline bool note_reservation(std::uintptr_t base, std::uintptr_t size, bool gpu_only) {
174 State& s = state();
175 std::unique_lock lock(s.mutex);
176 if (!gpu_only) {
177 s.last_cpu = base;
178 s.last_cpu_size = size;
179 return false;
180 }
181 if (!s.last_cpu || s.last_cpu_size != size) return false;
182 s.views.push_back({base, s.last_cpu, size});
183 s.count.store(s.views.size(), std::memory_order_release);
184 s.last_cpu = s.last_cpu_size = 0;
185 return true;
186}
187
188// Where the CPU reads the memory a GPU address names: the paired CPU range for a GPU-only view, else the address.
189inline std::uintptr_t to_cpu(std::uintptr_t va, std::uintptr_t bytes = 1) {
190 State& s = state();
191 if (!s.count.load(std::memory_order_acquire)) return va;
192 std::shared_lock lock(s.mutex);
193 for (const View& v : s.views)
194 if (va >= v.gpu && va - v.gpu < v.size && bytes <= v.size - (va - v.gpu)) return va - v.gpu + v.cpu;
195 return va;
196}
197
198// The other address of memory in a paired range: the CPU view's address for a GPU-only one and the GPU-only
199// address for a CPU view's; 0 outside every pair.
200inline std::uintptr_t other_view(std::uintptr_t va) {
201 State& s = state();
202 if (!s.count.load(std::memory_order_acquire)) return 0;
203 std::shared_lock lock(s.mutex);
204 for (const View& v : s.views) {
205 if (va >= v.gpu && va - v.gpu < v.size) return va - v.gpu + v.cpu;
206 if (va >= v.cpu && va - v.cpu < v.size) return va - v.cpu + v.gpu;
207 }
208 return 0;
209}
210
211} // namespace leonida::title_gpu_views
212
213// 4. Texel writes (title_texel_writes). The title writes texels into its own texture memory through XG's
214// CopyIntoSubresource (xg_xs.cpp) and through the pointer Map gives it; the D3D12 layer fills a texture's image
215// from that memory again when told (Device::refresh_title_textures drains these ranges before a submission), so a
216// small update (a glyph in a font cache) is not left to a hash that samples the bytes.
217namespace leonida::title_texel_writes {
218
219struct State {
220 std::mutex mutex;
221 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> ranges; // [begin, end)
222 bool overflow = false; // too many to keep: check everything
223 std::atomic<bool> pending{false};
224};
225
226inline State& state() {
227 static State s;
228 return s;
229}
230
231inline void note(const void* begin, std::size_t bytes) {
232 if (!begin || !bytes) return;
233 State& s = state();
234 std::lock_guard lock(s.mutex);
235 const auto at = reinterpret_cast<std::uintptr_t>(begin);
236 if (s.ranges.size() < 4096) s.ranges.emplace_back(at, at + bytes);
237 else s.overflow = true;
238 s.pending.store(true, std::memory_order_release);
239}
240
241// The ranges noted since the last call; `overflow` says some were dropped.
242inline std::vector<std::pair<std::uintptr_t, std::uintptr_t>> take(bool& overflow) {
243 State& s = state();
244 overflow = false;
245 if (!s.pending.load(std::memory_order_acquire)) return {};
246 std::lock_guard lock(s.mutex);
247 overflow = std::exchange(s.overflow, false);
248 s.pending.store(false, std::memory_order_relaxed);
249 return std::exchange(s.ranges, {});
250}
251
252} // namespace leonida::title_texel_writes
253
254// 5. XG layouts by shape (title_xg_layouts). A texture the title locks and writes with the CPU through Map is laid out
255// as the XG computer the title made for it says (its lock computes the layout with XGCreateTextureComputer right
256// before it maps, gfxres notes section 5), which a slot-133 description (Layout 0) does not tell: measured, the
257// 2048x2048 and 1024x1024 A8 glyph caches are LINEAR (0x100) while XG's default for that description is 4KB_S.
258// xg_xs records the Layout word of every computer by the texture's shape; the D3D12 layer takes the latest one of
259// a mapped texture's shape when no slot-70 view has given it a layout.
260namespace leonida::title_xg_layouts {
261
262struct Shape {
263 std::uint32_t dimension, format, height, depth, mips;
264 std::uint64_t width;
265 bool operator<(const Shape& o) const {
266 return std::tie(dimension, format, width, height, depth, mips) <
267 std::tie(o.dimension, o.format, o.width, o.height, o.depth, o.mips);
268 }
269};
270
271struct State {
272 std::mutex mutex;
273 std::map<Shape, std::uint32_t> layouts;
274};
275
276inline State& state() {
277 static State s;
278 return s;
279}
280
281inline void note(const Shape& shape, std::uint32_t layout) {
282 State& s = state();
283 std::lock_guard lock(s.mutex);
284 if (s.layouts.size() < 65536 || s.layouts.count(shape)) s.layouts[shape] = layout;
285}
286
287// The Layout word of the latest computer of this shape, or false.
288inline bool find(const Shape& shape, std::uint32_t& layout) {
289 State& s = state();
290 std::lock_guard lock(s.mutex);
291 const auto it = s.layouts.find(shape);
292 if (it == s.layouts.end()) return false;
293 layout = it->second;
294 return true;
295}
296
297} // namespace leonida::title_xg_layouts
298
299// 6. Write-watched title memory (title_write_watch). xmem reserves the title's ordinary memory (the XMemVirtualAlloc
300// and VirtualAlloc reservations that are not placeholders or physical-page windows) with MEM_WRITE_WATCH, and the
301// kernel keeps a dirty bit per 4 KiB page there: GetWriteWatch with WRITE_WATCH_FLAG_RESET returns the pages
302// written since and clears them. A shadow over such pages asks the kernel instead of making them read-only: no
303// write fault, no VirtualProtect, and a kernel write (ReadFile) into them neither fails nor needs opening first.
304// Sections (xmem's physical-page views) can't be write-watched, and keep the read-only guard.
305//
306// Several shadows can cover one page (a console descriptor heap's mirror next to a slot-133 buffer, two devices),
307// and one asking clears the kernel's bits for all of them. So what each asking found is kept in a journal: per
308// page, the number of the last asking that found it written. A reader (a shadow's tracker) was written to since its
309// own last asking where a page's number is above it. As VIctory does (crates/victory-gpu/src/watch.rs,
310// GPL-3.0-or-later). A reservation is numbered the same way when it is recorded: a reader whose last asking is
311// older takes all of its pages as written. A reservation the title releases and reserves again at the same address
312// is then new to the shadows, though its pages are write-watched both before and after and the new one's kernel
313// bits are clear (what the old one's pages held is gone: they read as zeros now).
314//
315// LEONIDA_WRITE_WATCH=0 reserves without MEM_WRITE_WATCH: every shadow keeps the read-only guard, as before. Under
316// Wine that is the default (=1 turns write watching on).
317namespace leonida::title_write_watch {
318
319constexpr std::uintptr_t kPage = 0x1000; // the kernel's unit
320// The journal is pruned of what every reader has seen once it doubles. Past kMaxPages it forgets askings more than
321// kKeep old even if a reader hasn't seen them: that reader then takes all of its pages as written, once.
322constexpr std::size_t kMaxPages = std::size_t(1) << 18;
323constexpr std::uint64_t kKeep = std::uint64_t(1) << 16;
324
325// On by default on Windows; off under Wine, whose write watching was not measured here (LEONIDA_WRITE_WATCH=1 turns it
326// on there). Off with LEONIDA_WRITE_WATCH=0.
327inline bool enabled() {
328 static const bool on = [] {
329 char value[8] = {};
330 std::size_t length = 0;
331 if (host_heap::handle() == GetProcessHeap()) return false; // no private heap: see host_heap
332 if (getenv_s(&length, value, sizeof(value), "LEONIDA_WRITE_WATCH") == 0 && length > 1) return value[0] != '0';
333 const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
334 return !(ntdll && GetProcAddress(ntdll, "wine_get_version"));
335 }();
336 return on;
337}
338
339// A reservation made with MEM_WRITE_WATCH: its end, and the number it was recorded with (an asking's, see ask).
340struct Region {
341 std::uintptr_t end;
342 std::uint64_t born;
343};
344
345// The containers allocate from host_heap: the D3D12 layer takes these locks while it holds a tracker's lock, which its
346// write-fault handler waits for, and a faulting thread may hold the process heap's lock.
347struct State {
348 std::shared_mutex mutex; // regions
349 host_heap::map<std::uintptr_t, Region> regions; // base -> the reservation at base
350 std::atomic<std::uint64_t> generation{0}; // bumped by every change of regions
351 std::atomic<std::size_t> count{0}; // regions.size(), read without the lock
352
353 // The last number given to an asking (or to a recorded reservation, which takes one without the journal's lock).
354 std::atomic<std::uint64_t> asked{0};
355 std::mutex journal; // everything below
356 std::uint64_t floor = 0; // askings up to this one were forgotten before every reader saw them
357 host_heap::map<std::uintptr_t, std::uint64_t> written; // page address -> the last asking that found it written
358 std::size_t pruned_size = 0; // written.size() after the last pruning
359 std::uint64_t pruned_at = 0; // the asking of the last pruning
360 host_heap::map<std::uint64_t, std::uint64_t> readers; // reader -> its last asking
361 std::uint64_t next_reader = 1;
362 host_heap::vector<void*> found; // room for the kernel's answer
363 host_heap::vector<std::uint8_t> refusals; // per run of an asking: the kernel refused it
364};
365
366inline State& state() {
367 static State s;
368 return s;
369}
370
371// xmem: [base, base + size) was reserved with MEM_WRITE_WATCH for the shadows. A reservation the title asked to be
372// write-watched itself is not added: its bits are the title's. Every reader takes its pages as written at its next
373// asking (they are not the pages it copied, even at the same address).
374inline void add(std::uintptr_t base, std::uintptr_t size) {
375 if (!size) return;
376 State& s = state();
377 const std::uintptr_t end = base + ((size + kPage - 1) & ~(kPage - 1));
378 std::unique_lock lock(s.mutex);
379 // A reservation released without remove() overlapping the new one is gone.
380 auto it = s.regions.lower_bound(base);
381 if (it != s.regions.begin() && std::prev(it)->second.end > base) --it;
382 while (it != s.regions.end() && it->first < end) it = s.regions.erase(it);
383 // Numbered under the lock: an asking that finds the reservation took its own number later (see ask).
384 s.regions[base] = Region{end, s.asked.fetch_add(1, std::memory_order_acq_rel) + 1};
385 s.count.store(s.regions.size(), std::memory_order_release);
386 s.generation.fetch_add(1, std::memory_order_release);
387}
388
389// xmem: the reservation holding `address` was released.
390inline void remove(std::uintptr_t address) {
391 State& s = state();
392 if (!s.count.load(std::memory_order_acquire)) return;
393 std::unique_lock lock(s.mutex);
394 auto it = s.regions.upper_bound(address);
395 if (it == s.regions.begin() || (--it)->second.end <= address) return;
396 s.regions.erase(it);
397 s.count.store(s.regions.size(), std::memory_order_release);
398 s.generation.fetch_add(1, std::memory_order_release);
399}
400
401inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); }
402
403// Whether `address` is in a write-watched reservation.
404inline bool contains(std::uintptr_t address) {
405 State& s = state();
406 if (!s.count.load(std::memory_order_acquire)) return false;
407 std::shared_lock lock(s.mutex);
408 auto it = s.regions.upper_bound(address);
409 return it != s.regions.begin() && (--it)->second.end > address;
410}
411
412// The end of the write-watched reservation holding `address`, or 0.
413inline std::uintptr_t end_of(std::uintptr_t address) {
414 State& s = state();
415 if (!s.count.load(std::memory_order_acquire)) return 0;
416 std::shared_lock lock(s.mutex);
417 auto it = s.regions.upper_bound(address);
418 return it != s.regions.begin() && (--it)->second.end > address ? it->second.end : 0;
419}
420
421// Calls `f(from, to)` for each write-watched part of [begin, end): each inside one reservation.
422template <class F>
423void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) {
424 State& s = state();
425 if (!s.count.load(std::memory_order_acquire)) return;
426 std::shared_lock lock(s.mutex);
427 auto it = s.regions.upper_bound(begin);
428 if (it != s.regions.begin() && std::prev(it)->second.end > begin) --it;
429 for (; it != s.regions.end() && it->first < end; ++it) {
430 const std::uintptr_t from = (std::max)(it->first, begin), to = (std::min)(it->second.end, end);
431 if (from < to) f(from, to);
432 }
433}
434
435// xmem: [from, to) of a write-watched reservation changed with no write the kernel sees (decommitted, committed again,
436// reset): every reader takes its pages as written at its next asking. Past kKeep pages, every reader takes all of its
437// write-watched pages as written instead.
438inline void mark(std::uintptr_t from, std::uintptr_t to) {
439 from &= ~(kPage - 1);
440 to = (to + kPage - 1) & ~(kPage - 1);
441 if (from >= to || !contains(from)) return;
442 State& s = state();
443 std::lock_guard lock(s.journal);
444 const std::uint64_t now = s.asked.fetch_add(1, std::memory_order_acq_rel) + 1;
445 if ((to - from) / kPage > kKeep) {
446 s.floor = now;
447 return;
448 }
449 for (std::uintptr_t p = from; p < to; p += kPage) s.written[p] = now;
450}
451
452// A new reader, which has seen everything asked so far (its pages are not known yet: it copies them all first).
453inline std::uint64_t open_reader() {
454 State& s = state();
455 std::lock_guard lock(s.journal);
456 const std::uint64_t id = s.next_reader++;
457 s.readers[id] = s.asked.load(std::memory_order_acquire);
458 return id;
459}
460
461inline void close_reader(std::uint64_t reader) {
462 State& s = state();
463 std::lock_guard lock(s.journal);
464 s.readers.erase(reader);
465}
466
467// `reader` takes over what `other` has not seen yet (a tracker absorbing another's pages).
468inline void merge_reader(std::uint64_t reader, std::uint64_t other) {
469 State& s = state();
470 std::lock_guard lock(s.journal);
471 const auto a = s.readers.find(reader), b = s.readers.find(other);
472 if (a != s.readers.end() && b != s.readers.end()) a->second = (std::min)(a->second, b->second);
473}
474
475// When the reservation holding `address` was recorded (see ask), or 0 when no recorded one holds it.
476inline std::uint64_t born(std::uintptr_t address) {
477 State& s = state();
478 if (!s.count.load(std::memory_order_acquire)) return 0;
479 std::shared_lock lock(s.mutex);
480 auto it = s.regions.upper_bound(address);
481 return it != s.regions.begin() && (--it)->second.end > address ? it->second.born : 0;
482}
483
484// One asking for `reader`: the kernel's written pages of each run (4 KiB aligned, each inside one reservation from
485// for_each_in) are taken and cleared, then `dirty(from, to)` gets the pages of the runs written since the reader's
486// last asking, the kernel's answer now and the earlier askings of other readers alike, and all of a run whose
487// reservation was recorded since then (or is not recorded: reserved again, not added yet). `refused(from, to)` gets
488// a run the kernel refused (no longer write-watched: released), for which dirty is not called. Returns the asking's
489// number. `runs` is a vector of (from, to) pairs.
490template <class Runs, class Dirty, class Refused>
491std::uint64_t ask(std::uint64_t reader, const Runs& runs, Dirty&& dirty, Refused&& refused) {
492 State& s = state();
493 std::lock_guard lock(s.journal);
494 const auto me = s.readers.find(reader);
495 const std::uint64_t since = me != s.readers.end() ? me->second : 0;
496 const std::uint64_t now = s.asked.fetch_add(1, std::memory_order_acq_rel) + 1;
497 s.refusals.assign(runs.size(), 0);
498 for (std::size_t r = 0; r < runs.size(); ++r) {
499 const auto [from, to] = runs[r];
500 ULONG_PTR count = (to - from) / kPage;
501 if (s.found.size() < count) s.found.resize(count);
502 ULONG granularity = 0;
503 if (GetWriteWatch(WRITE_WATCH_FLAG_RESET, reinterpret_cast<void*>(from), to - from, s.found.data(), &count,
504 &granularity) != 0) {
505 s.refusals[r] = 1;
506 continue;
507 }
508 for (ULONG_PTR k = 0; k < count; ++k)
509 s.written[reinterpret_cast<std::uintptr_t>(s.found[k]) & ~(kPage - 1)] = now;
510 }
511 for (std::size_t r = 0; r < runs.size(); ++r) {
512 const auto [from, to] = runs[r];
513 if (s.refusals[r]) {
514 refused(from, to);
515 continue;
516 }
517 // Forgotten before this reader saw it, or a reservation new to it: all of it. Looked up after `now` was
518 // taken, so a reservation recorded later has a higher number and is all written at the next asking too.
519 const std::uint64_t reserved = born(from);
520 if (since < s.floor || !reserved || reserved > since) {
521 dirty(from, to);
522 continue;
523 }
524 std::uintptr_t run_from = 0, run_to = 0;
525 for (auto it = s.written.lower_bound(from); it != s.written.end() && it->first < to; ++it) {
526 if (it->second <= since) continue;
527 if (it->first != run_to) {
528 if (run_from != run_to) dirty(run_from, run_to);
529 run_from = it->first;
530 }
531 run_to = it->first + kPage;
532 }
533 if (run_from != run_to) dirty(run_from, run_to);
534 }
535 if (me != s.readers.end()) me->second = now;
536 // What every reader has seen goes, once the journal doubled or every kPruneEvery askings (a pruning that dropped
537 // little, readers being behind then, must not stop the next); past kMaxPages, what is more than kKeep askings old
538 // goes too.
539 constexpr std::uint64_t kPruneEvery = 256;
540 if (s.written.size() > 4096 && (s.written.size() > 2 * s.pruned_size || now - s.pruned_at >= kPruneEvery)) {
541 s.pruned_at = now;
542 std::uint64_t seen = now;
543 for (const auto& [id, last] : s.readers) seen = (std::min)(seen, last);
544 if (s.written.size() > kMaxPages && now > kKeep && seen < now - kKeep) {
545 seen = now - kKeep;
546 s.floor = (std::max)(s.floor, seen);
547 }
548 std::erase_if(s.written, [seen](const auto& entry) { return entry.second <= seen; });
549 s.pruned_size = s.written.size();
550 }
551 return now;
552}
553
554} // namespace leonida::title_write_watch
555
556namespace leonida::kernel_writes {
557
558// The layer's side: makes every watched page in [begin, end) writable. Set once the first shadow exists.
559using Opener = void (*)(std::uintptr_t begin, std::uintptr_t end);
560
561// xmem's side: commits the physical pages mapped in [address, address + bytes) that are still waiting for their first
562// touch (rt::xmem::commit_physical_range; pages xmem does not map are left as they are). gta6rt sets it at start.
563using Committer = bool (*)(const void* address, std::size_t bytes);
564
565struct Pin {
566 std::uintptr_t begin, end;
567 const OVERLAPPED* overlapped; // null: ends when the call returns
568 std::uint64_t id;
569};
570
571struct State {
572 std::atomic<Opener> opener{nullptr};
573 std::atomic<Committer> committer{nullptr};
574 std::mutex mutex;
575 host_heap::vector<Pin> pins; // host_heap: see there
576 std::uint64_t next_id = 1;
577 std::atomic<std::size_t> count{0}; // pins.size(), read without the lock
578};
579
580inline State& state() {
581 static State s;
582 return s;
583}
584
585inline void set_opener(Opener opener) { state().opener.store(opener, std::memory_order_release); }
586inline void set_committer(Committer committer) { state().committer.store(committer, std::memory_order_release); }
587
588// Whether an overlapped request is still in flight. Its OVERLAPPED is the title's and may be gone by now: a read that
589// faults counts as completed (the title doesn't free an OVERLAPPED it is still waiting on).
590inline bool overlapped_pending(const OVERLAPPED* overlapped) {
591 __try {
592 return overlapped->Internal == static_cast<ULONG_PTR>(STATUS_PENDING);
593 } __except (EXCEPTION_EXECUTE_HANDLER) {
594 return false;
595 }
596}
597
598// The pinned ranges overlapping [begin, end), for the layer's refresh. Overlapped pins whose request completed are
599// dropped first.
600template<class F>
601void for_each_pin(std::uintptr_t begin, std::uintptr_t end, F&& f) {
602 State& s = state();
603 if (!s.count.load(std::memory_order_acquire)) return;
604 std::lock_guard lock(s.mutex);
605 std::erase_if(s.pins, [](const Pin& pin) { return pin.overlapped && !overlapped_pending(pin.overlapped); });
606 s.count.store(s.pins.size(), std::memory_order_release);
607 for (const Pin& pin : s.pins)
608 if (pin.begin < end && begin < pin.end) f((std::max)(pin.begin, begin), (std::min)(pin.end, end));
609}
610
611// Before the kernel writes [buffer, buffer + bytes): pins the range (until end_write(), or until `overlapped` completes
612// when it is not null) and opens it. Returns the pin's id, 0 when nothing was pinned.
613inline std::uint64_t begin_write(const void* buffer, std::size_t bytes, const OVERLAPPED* overlapped) {
614 State& s = state();
615 const Opener opener = s.opener.load(std::memory_order_acquire);
616 if (!opener || !buffer || !bytes) return 0;
617 const auto begin = reinterpret_cast<std::uintptr_t>(buffer);
618 std::uint64_t id = 0;
619 {
620 std::lock_guard lock(s.mutex);
621 id = s.next_id++;
622 s.pins.push_back({begin, begin + bytes, overlapped, id});
623 s.count.store(s.pins.size(), std::memory_order_release);
624 }
625 // After the pin: a refresh that runs from here on leaves the range writable.
626 opener(begin, begin + bytes);
627 return id;
628}
629
630// The call is over: a synchronous pin ends. An overlapped pin whose request is still pending stays until it completes.
631inline void end_write(std::uint64_t id, bool pending) {
632 if (!id) return;
633 State& s = state();
634 std::lock_guard lock(s.mutex);
635 std::erase_if(s.pins, [id, pending](const Pin& pin) { return pin.id == id && !(pending && pin.overlapped); });
636 s.count.store(s.pins.size(), std::memory_order_release);
637}
638
639// Readies [buffer, buffer + bytes) for a retry after ERROR_NOACCESS: commits xmem's pages that wait for their first
640// touch (the kernel's write does not fault them in) and opens watched pages again. false: neither side is set.
641inline bool reopen(const void* buffer, std::size_t bytes) {
642 if (!buffer || !bytes) return false;
643 const State& s = state();
644 const Committer committer = s.committer.load(std::memory_order_acquire);
645 const Opener opener = s.opener.load(std::memory_order_acquire);
646 if (committer) committer(buffer, bytes);
647 if (opener) {
648 const auto begin = reinterpret_cast<std::uintptr_t>(buffer);
649 opener(begin, begin + bytes);
650 }
651 return committer || opener;
652}
653
654// The file shims' reads into title memory (file_system.cpp): ReadFile, ReadFileEx and ReadFileScatter with their
655// destination pinned and opened first, and retried once if it fails with ERROR_NOACCESS anyway (after committing
656// first-touch pages: the title retries such a read forever, `0x314200`, so the retry has to change something).
657inline BOOL read_file(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) {
658 const std::uint64_t pin = begin_write(buffer, bytes, overlapped);
659 BOOL ok = ::ReadFile(file, buffer, bytes, read, overlapped);
660 if (!ok && GetLastError() == ERROR_NOACCESS && reopen(buffer, bytes))
661 ok = ::ReadFile(file, buffer, bytes, read, overlapped);
662 const DWORD error = GetLastError();
663 end_write(pin, !ok && error == ERROR_IO_PENDING);
664 SetLastError(error);
665 return ok;
666}
667
668inline BOOL read_file_ex(HANDLE file, LPVOID buffer, DWORD bytes, LPOVERLAPPED overlapped,
669 LPOVERLAPPED_COMPLETION_ROUTINE routine) {
670 const std::uint64_t pin = begin_write(buffer, bytes, overlapped);
671 BOOL ok = ::ReadFileEx(file, buffer, bytes, overlapped, routine);
672 if (!ok && GetLastError() == ERROR_NOACCESS && reopen(buffer, bytes))
673 ok = ::ReadFileEx(file, buffer, bytes, overlapped, routine);
674 const DWORD error = GetLastError();
675 end_write(pin, bool(ok)); // queued: pending until the OVERLAPPED says otherwise
676 SetLastError(error);
677 return ok;
678}
679
680// Each segment is one system page.
681inline BOOL read_file_scatter(HANDLE file, FILE_SEGMENT_ELEMENT segments[], DWORD bytes, LPDWORD reserved,
682 LPOVERLAPPED overlapped) {
683 SYSTEM_INFO info{};
684 GetSystemInfo(&info);
685 std::vector<std::uint64_t> pins;
686 const DWORD count = segments ? (bytes + info.dwPageSize - 1) / info.dwPageSize : 0;
687 for (DWORD i = 0; i < count; ++i)
688 pins.push_back(begin_write(segments[i].Buffer, info.dwPageSize, overlapped));
689 BOOL ok = ::ReadFileScatter(file, segments, bytes, reserved, overlapped);
690 if (!ok && GetLastError() == ERROR_NOACCESS && count) {
691 for (DWORD i = 0; i < count; ++i) reopen(segments[i].Buffer, info.dwPageSize);
692 ok = ::ReadFileScatter(file, segments, bytes, reserved, overlapped);
693 }
694 const DWORD error = GetLastError();
695 for (const std::uint64_t pin : pins) end_write(pin, bool(ok) || error == ERROR_IO_PENDING);
696 SetLastError(error);
697 return ok;
698}
699
700} // namespace leonida::kernel_writes
diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h
new file mode 100644
index 000000000..d592029c2
--- /dev/null
+++ b/runtime/src/title_texture_memory.h
@@ -0,0 +1,58 @@
1#pragma once
2#include <windows.h>
3#include <cstddef>
4#include <cstdint>
5#include <limits>
6
7namespace leonida {
8
9// Keep negative probes until the title changes the map or a writer reports this footprint.
10class TextureReadability {
11public:
12 template<class Probe>
13 bool check(std::uint64_t generation, bool cache_failure, Probe probe) {
14 if (cache_failure && pending_ && !retry_ && generation_ == generation) return false;
15 generation_ = generation; // snapshot before the probe so a concurrent map change is noticed
16 retry_ = false;
17 pending_ = !probe();
18 return !pending_;
19 }
20 void defer() { pending_ = true; } // mapping disappeared between the probe and the read
21 void retry() { retry_ = true; }
22 bool pending() const { return pending_; }
23private:
24 std::uint64_t generation_ = 0;
25 bool pending_ = false, retry_ = false;
26};
27
28using TexturePageCommitter = bool (*)(const void*, std::size_t);
29
30// Check the whole footprint. A committed first page says nothing about a streamed mip farther on.
31inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) {
32 if (!base || !size || size > (std::numeric_limits<std::uintptr_t>::max)() - base) return false;
33 const auto end = base + size;
34 for (auto at = base; at < end;) {
35 MEMORY_BASIC_INFORMATION region{};
36 const auto* address = reinterpret_cast<const void*>(at);
37 if (!VirtualQuery(address, &region, sizeof(region))) return false;
38 // A persistent Map can name an xmem section whose physical pages commit on first touch.
39 // Only xmem may commit them. A bare reservation or an inaccessible page must still defer.
40 if (commit && region.State == MEM_RESERVE && region.Type == MEM_MAPPED) {
41 if (!commit(address, end - at) || !VirtualQuery(address, &region, sizeof(region))) return false;
42 }
43 if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return false;
44 switch (region.Protect & 0xff) {
45 case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY:
46 case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break;
47 default: return false;
48 }
49 const auto start = reinterpret_cast<std::uintptr_t>(region.BaseAddress);
50 if (at < start || at - start >= region.RegionSize) return false;
51 const auto available = region.RegionSize - (at - start);
52 if (available >= end - at) return true;
53 at += available;
54 }
55 return true;
56}
57
58} // namespace leonida
diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h
new file mode 100644
index 000000000..21a88d279
--- /dev/null
+++ b/runtime/src/title_texture_refresh.h
@@ -0,0 +1,45 @@
1#pragma once
2#include <algorithm>
3#include <cstdint>
4#include <utility>
5#include <vector>
6
7namespace leonida {
8
9using TitleWriteRanges = std::vector<std::pair<std::uintptr_t, std::uintptr_t>>;
10
11// Sorted, disjoint half-open intervals let each texture find its first possible writer by end address.
12inline void merge_title_writes(TitleWriteRanges& writes) {
13 std::sort(writes.begin(), writes.end());
14 std::size_t count = 0;
15 for (const auto [begin, end] : writes) {
16 if (begin >= end) continue;
17 if (count && begin <= writes[count - 1].second)
18 writes[count - 1].second = std::max(writes[count - 1].second, end);
19 else
20 writes[count++] = {begin, end};
21 }
22 writes.resize(count);
23}
24
25inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t begin, std::uintptr_t end) {
26 const auto it = std::upper_bound(writes.begin(), writes.end(), begin,
27 [](auto address, const auto& range) { return address < range.second; });
28 return begin < end && it != writes.end() && it->first < end;
29}
30
31// Poll unmarked textures in placement order. A time or byte limit resumes the next pass at
32// the following address. The cursor also survives insertion or removal between passes.
33template<class Registry, class Visit, class Exhausted>
34void poll_title_textures(Registry& textures, std::uint64_t& cursor, Visit visit, Exhausted exhausted) {
35 auto it = textures.lower_bound(cursor);
36 for (auto left = textures.size(); left; --left) {
37 if (it == textures.end()) it = textures.begin();
38 auto& [address, texture] = *it++;
39 cursor = address + 1;
40 if (!texture->mapped && !texture->stale) visit(*texture);
41 if (exhausted()) break; // advance at least one registry entry even if a deadline already passed
42 }
43}
44
45} // namespace leonida
diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h
new file mode 100644
index 000000000..6e97d7f1d
--- /dev/null
+++ b/runtime/src/title_va_alias.h
@@ -0,0 +1,318 @@
1#pragma once
2// Buffer addresses in the title's own memory and the console VA a translated shader reaches them by
3// (docs/d3d12_vulkan.md section 3.3, "Title-chosen addresses").
4//
5// A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The
6// layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them:
7// - device slot 133 places a buffer at the CPU address of the title's own pages (a user-mode Windows address, far above 4 GiB);
8// - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5).
9// Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is
10// therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset
11// when the copy is an arena range (a slot-133 shadow, or a window of the title's pages copied before every
12// submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133
13// buffer). Addresses that are not in the title's memory are passed through unchanged.
14//
15// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver
16// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the
17// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was
18// added to it, so it is tested without a GPU (title_va_alias_test).
19#include <algorithm>
20#include <array>
21#include <atomic>
22#include <cstddef>
23#include <cstdint>
24#include <iterator>
25#include <map>
26#include <mutex>
27#include <shared_mutex>
28#include <utility>
29#include <vector>
30
31namespace leonida {
32
33class TitleVaAliases {
34public:
35 // Where the layer saw the address, for the counters.
36 enum Kind : unsigned { root_view, created_view, table_view, vertex_view, index_view, kind_count };
37 static constexpr const char* kKindNames[kind_count] = {"root view", "created view", "table V#", "vertex view",
38 "index view"};
39
40 // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when
41 // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's).
42 using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va);
43 using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors);
44
45 // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one
46 // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range.
47 bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) {
48 if (!bytes || title_va > UINT64_MAX - bytes) return false;
49 std::unique_lock lock(mutex_);
50 erase_overlapping(title_va, title_va + bytes);
51 ranges_[title_va] = {title_va + bytes, shader_va};
52 count_.store(ranges_.size(), std::memory_order_release);
53 return true;
54 }
55
56 // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps
57 // its own entry).
58 void remove(std::uint64_t title_va, std::uint64_t shader_va) {
59 std::unique_lock lock(mutex_);
60 const auto it = ranges_.find(title_va);
61 if (it != ranges_.end() && it->second.shader_va == shader_va) ranges_.erase(it);
62 count_.store(ranges_.size(), std::memory_order_release);
63 }
64
65 // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged
66 // elsewhere. No copy is made here.
67 std::uint64_t shader_va(std::uint64_t va, std::uint64_t bytes = 1) const {
68 if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all
69 std::shared_lock lock(mutex_);
70 auto it = ranges_.upper_bound(va);
71 if (it == ranges_.begin()) return va;
72 --it;
73 if (va >= it->second.end || bytes > it->second.end - va) return va;
74 return it->second.shader_va + (va - it->first);
75 }
76
77 // Debug-only inverse lookup. V#s retain 48 bits, so an import below heap_base wraps.
78 bool source_of_vsharp(std::uint64_t base, std::uint64_t& title, std::uint64_t& available) const {
79 constexpr std::uint64_t mask = (1ull << 48) - 1;
80 std::shared_lock lock(mutex_);
81 for (const auto& [start, range] : ranges_) {
82 const auto delta = (base - range.shader_va) & mask;
83 if (delta >= range.end - start) continue;
84 title = start + delta;
85 available = range.end - title;
86 return true;
87 }
88 return false;
89 }
90
91 // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never
92 // replaces a range another buffer still uses.
93 void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const {
94 std::shared_lock lock(mutex_);
95 lo = 0;
96 hi = UINT64_MAX;
97 auto it = ranges_.upper_bound(va);
98 if (it != ranges_.end()) hi = it->first;
99 if (it != ranges_.begin()) lo = std::prev(it)->second.end;
100 }
101
102 // shader_va, and when `va` is in the title's memory with no copy yet, a copy made by the device's resolver.
103 // Counted by kind: translated, or in the title's memory and left as it was.
104 std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) {
105 if (!va) return va;
106 std::uint64_t to = shader_va(va);
107 if (to != va) {
108 translated_[kind].fetch_add(1, std::memory_order_relaxed);
109 return to;
110 }
111 Resolver resolver;
112 void* context;
113 {
114 std::lock_guard lock(hook_mutex_);
115 resolver = resolver_;
116 context = hook_context_;
117 }
118 if (!resolver || !resolver(context, va, bytes, to)) return va;
119 (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed);
120 return to;
121 }
122
123 // Counts an address that the layer resolves through its buffer index instead (vertex and index views): only
124 // whether it is in a title range.
125 void note(std::uint64_t va, Kind kind) {
126 if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed);
127 }
128
129 // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares
130 // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps).
131 void scan_table(std::uint64_t table_va, std::uint32_t descriptors) {
132 TableScanner scanner;
133 void* context;
134 {
135 std::lock_guard lock(hook_mutex_);
136 scanner = scanner_;
137 context = hook_context_;
138 }
139 if (scanner) scanner(context, table_va, descriptors);
140 }
141
142 // The scan's cost, per ExecuteCommandLists that had tables to scan.
143 void note_scan(std::uint64_t nanoseconds) {
144 scans_.fetch_add(1, std::memory_order_relaxed);
145 scan_ns_.fetch_add(nanoseconds, std::memory_order_relaxed);
146 std::uint64_t seen = scan_max_ns_.load(std::memory_order_relaxed);
147 while (nanoseconds > seen && !scan_max_ns_.compare_exchange_weak(seen, nanoseconds)) {
148 }
149 }
150 std::uint64_t scans() const { return scans_.load(std::memory_order_relaxed); }
151 std::uint64_t scan_ns() const { return scan_ns_.load(std::memory_order_relaxed); }
152 std::uint64_t scan_max_ns() const { return scan_max_ns_.load(std::memory_order_relaxed); }
153
154 // The title's own memory, as the xmem shims hand it out (XMemAlloc, XMemVirtualAlloc, the title's VirtualAlloc):
155 // only an address in one of these ranges gets a copy. A base anywhere else (the runtime's own heap, a host DLL)
156 // is left as it was and counted.
157 void add_title_memory(std::uint64_t base, std::uint64_t bytes) {
158 if (!base || !bytes || base > UINT64_MAX - bytes) return;
159 std::uint64_t begin = base, end = base + bytes;
160 std::unique_lock lock(memory_mutex_);
161 // A commit inside a reserved range, or two that overlap, are one range.
162 auto it = memory_.upper_bound(begin);
163 if (it != memory_.begin() && std::prev(it)->second > begin) --it;
164 while (it != memory_.end() && it->first < end) {
165 begin = std::min(begin, it->first);
166 end = std::max(end, it->second);
167 it = memory_.erase(it);
168 }
169 memory_[begin] = end;
170 }
171 void remove_title_memory(std::uint64_t base) {
172 std::unique_lock lock(memory_mutex_);
173 memory_.erase(base);
174 }
175 // LOCAL DIAGNOSTIC (mem probe): every title range, [begin, end), in address order.
176 std::vector<std::pair<std::uint64_t, std::uint64_t>> title_memory_ranges() const {
177 std::shared_lock lock(memory_mutex_);
178 return {memory_.begin(), memory_.end()};
179 }
180 // The title range that holds `va`: [lo, hi). False when none does.
181 bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const {
182 std::shared_lock lock(memory_mutex_);
183 auto it = memory_.upper_bound(va);
184 if (it == memory_.begin()) return false;
185 --it;
186 if (va >= it->second) return false;
187 lo = it->first;
188 hi = it->second;
189 return true;
190 }
191
192 // A title that gives a descriptor heap its own backing memory (__XMemAllocationHooks__) writes descriptors there
193 // itself, while shaders read the layer's heap. The layer that keeps that mapping registers a source: before a
194 // bound table is scanned, it copies the slots the title wrote in its own memory over the layer's copy
195 // ([real, real + bytes) is the layer heap's CPU memory). Returns how many slots it copied.
196 using DescriptorSource = std::uint64_t (*)(void* context, std::uint8_t* real, std::size_t bytes);
197 void set_descriptor_source(void* context, DescriptorSource source) {
198 std::lock_guard lock(hook_mutex_);
199 source_context_ = context;
200 source_ = source;
201 }
202 void pull_descriptors(std::uint8_t* real, std::size_t bytes) {
203 DescriptorSource source;
204 void* context;
205 {
206 std::lock_guard lock(hook_mutex_);
207 source = source_;
208 context = source_context_;
209 }
210 if (source) pulled_.fetch_add(source(context, real, bytes), std::memory_order_relaxed);
211 }
212 std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); }
213
214 // The end of the first title range that overlaps [lo, hi), or 0 when none does. The GPU address arena keeps its
215 // own allocations out of these ranges, so one number is never both an arena address and a title address.
216 std::uint64_t title_overlap_end(std::uint64_t lo, std::uint64_t hi) const {
217 std::shared_lock lock(memory_mutex_);
218 auto it = memory_.upper_bound(lo);
219 if (it != memory_.begin() && std::prev(it)->second > lo) return std::prev(it)->second;
220 if (it != memory_.end() && it->first < hi) return it->second;
221 return 0;
222 }
223
224 // A vertex or index buffer view at `va`. On the console every page of the title's memory is GPU memory, so a view
225 // may name any address: the retail title binds vertex data that lives in its own CPU heap, with no D3D12 resource
226 // over it. When `va` is in the title's memory the device's maker makes sure a buffer covers it (found with a
227 // debugger: the address a draw could not resolve was a field of a vertex-buffer object in the title's heap,
228 // docs/re/answers.md).
229 using BufferMaker = void (*)(void* context, std::uint64_t va, std::uint64_t bytes);
230 void set_buffer_maker(void* context, BufferMaker maker) {
231 std::lock_guard lock(hook_mutex_);
232 maker_context_ = context;
233 maker_ = maker;
234 }
235 void clear_buffer_maker(void* context) {
236 std::lock_guard lock(hook_mutex_);
237 if (maker_context_ != context) return;
238 maker_context_ = nullptr;
239 maker_ = nullptr;
240 }
241 void want_buffer(std::uint64_t va, std::uint64_t bytes) {
242 if (!va) return;
243 std::uint64_t lo = 0, hi = 0;
244 if (!title_memory(va, lo, hi)) return;
245 BufferMaker maker;
246 void* context;
247 {
248 std::lock_guard lock(hook_mutex_);
249 maker = maker_;
250 context = maker_context_;
251 }
252 if (maker) maker(context, va, bytes);
253 }
254
255 // The first device to register keeps the hooks until it clears them.
256 void set_hooks(void* context, Resolver resolver, TableScanner scanner) {
257 std::lock_guard lock(hook_mutex_);
258 if (hook_context_) return;
259 hook_context_ = context;
260 resolver_ = resolver;
261 scanner_ = scanner;
262 }
263 void clear_hooks(void* context) {
264 std::lock_guard lock(hook_mutex_);
265 if (hook_context_ != context) return;
266 hook_context_ = nullptr;
267 resolver_ = nullptr;
268 scanner_ = nullptr;
269 }
270 // The resolver alone, for a device that scans its descriptor tables itself.
271 void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); }
272 void clear_resolver(void* context) { clear_hooks(context); }
273
274 std::size_t size() const { return count_.load(std::memory_order_acquire); }
275 std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); }
276 std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); }
277
278private:
279 struct Range {
280 std::uint64_t end; // exclusive
281 std::uint64_t shader_va; // what the range's first byte becomes
282 };
283
284 void erase_overlapping(std::uint64_t begin, std::uint64_t end) {
285 auto it = ranges_.lower_bound(begin);
286 if (it != ranges_.begin()) {
287 auto previous = std::prev(it);
288 if (previous->second.end > begin) it = previous;
289 }
290 while (it != ranges_.end() && it->first < end) it = ranges_.erase(it);
291 }
292
293 mutable std::shared_mutex mutex_;
294 std::map<std::uint64_t, Range> ranges_; // by title VA
295 std::atomic<std::size_t> count_{0};
296 std::mutex hook_mutex_;
297 void* hook_context_ = nullptr;
298 void* maker_context_ = nullptr;
299 BufferMaker maker_ = nullptr;
300 Resolver resolver_ = nullptr;
301 TableScanner scanner_ = nullptr;
302 void* source_context_ = nullptr;
303 DescriptorSource source_ = nullptr;
304 std::atomic<std::uint64_t> pulled_{0};
305 std::array<std::atomic<std::uint64_t>, kind_count> translated_{};
306 std::array<std::atomic<std::uint64_t>, kind_count> untranslated_{};
307 std::atomic<std::uint64_t> scans_{0}, scan_ns_{0}, scan_max_ns_{0};
308 mutable std::shared_mutex memory_mutex_;
309 std::map<std::uint64_t, std::uint64_t> memory_; // the title's memory: base -> end
310};
311
312// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers.
313inline TitleVaAliases& title_va_aliases() {
314 static TitleVaAliases aliases;
315 return aliases;
316}
317
318} // namespace leonida
diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp
index ab234cbd9..6cf5e70ae 100644
--- a/runtime/src/tls_host.cpp
+++ b/runtime/src/tls_host.cpp
@@ -5,6 +5,12 @@
5// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves 5// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves
6// and restores the helper's own block, so the helper's CRT TLS state is not disturbed. 6// and restores the helper's own block, so the helper's CRT TLS state is not disturbed.
7// 7//
8// One more clone, leonida_tls_host_<pid>_home.dll, is made at process start by reserve_tls_index0: its TLS directory
9// is pointed at gta6rt_tls_home_template below, filled with a copy of the runtime EXE's template, and the runtime EXE
10// moves its TLS from index 0 (which Windows gave it) to that clone's index, so a mapped executable can take index 0.
11// That clone stays loaded until the process ends, and its slot then holds the runtime's live TLS, so nothing in this
12// DLL may read or write its own TLS (gta6rt_tls_host_keep is never called).
13//
8// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that 14// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that
9// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers 15// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers
10// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back 16// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back
@@ -26,6 +32,13 @@ void* volatile g_thread_event = nullptr;
26// the linker without making DllMain touch TLS during thread attach/detach. 32// the linker without making DllMain touch TLS during thread attach/detach.
27extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; } 33extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; }
28 34
35// The home clone's TLS template (pe_loader.cpp, make_home_clone_image): zeros here, the runtime EXE's template in the
36// clone's file. 16 KiB: gta6rt.exe's own TLS template was 1398 bytes when measured; the loader refuses the move when
37// the EXE's TLS does not fit. Each thread gets a block of the EXE's size, not of this array's. Clones of this DLL for
38// mapped DLLs keep the 514-byte TLS directory and do not use the array.
39extern "C" __declspec(dllexport) const unsigned char gta6rt_tls_home_template[16384] = {};
40extern "C" __declspec(dllexport) const unsigned int gta6rt_tls_home_template_size = sizeof(gta6rt_tls_home_template);
41
29// Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and 42// Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and
30// DLL_THREAD_DETACH; nullptr stops the calls. 43// DLL_THREAD_DETACH; nullptr stops the calls.
31extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) { 44extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) {
diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h
index ea65caa2d..8f2dd61f8 100644
--- a/runtime/src/vulkan13_features.h
+++ b/runtime/src/vulkan13_features.h
@@ -32,6 +32,8 @@ public:
32 Vulkan13Features& operator=(const Vulkan13Features&) = delete; 32 Vulkan13Features& operator=(const Vulkan13Features&) = delete;
33 33
34 bool core = false; // a Vulkan 1.3 device: the features are core 34 bool core = false; // a Vulkan 1.3 device: the features are core
35 bool pipeline_cache_control = false;
36 bool enable_pipeline_cache_control = false;
35 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering 37 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering
36 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 38 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2
37 // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device. 39 // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device.
@@ -45,6 +47,7 @@ public:
45 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, 47 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2,
46 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { 48 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) {
47 core = api_version >= VK_API_VERSION_1_3; 49 core = api_version >= VK_API_VERSION_1_3;
50 pipeline_cache_control=false;enable_pipeline_cache_control=false;
48 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; 51 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false;
49 extended_dynamic_state = false; 52 extended_dynamic_state = false;
50 if (!features2) return; 53 if (!features2) return;
@@ -53,6 +56,7 @@ public:
53 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13}; 56 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13};
54 features2(physical, &query); 57 features2(physical, &query);
55 dynamic_rendering = f13.dynamicRendering == VK_TRUE; 58 dynamic_rendering = f13.dynamicRendering == VK_TRUE;
59 pipeline_cache_control = f13.pipelineCreationCacheControl == VK_TRUE;
56 synchronization2 = f13.synchronization2 == VK_TRUE; 60 synchronization2 = f13.synchronization2 == VK_TRUE;
57 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; 61 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE;
58 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; 62 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE;
@@ -98,6 +102,7 @@ public:
98 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). 102 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them).
99 void choose(const Vulkan13Features& from) { 103 void choose(const Vulkan13Features& from) {
100 core = from.core; 104 core = from.core;
105 pipeline_cache_control=from.pipeline_cache_control;enable_pipeline_cache_control=false;
101 dynamic_rendering = from.dynamic_rendering; 106 dynamic_rendering = from.dynamic_rendering;
102 synchronization2 = from.synchronization2; 107 synchronization2 = from.synchronization2;
103 subgroup_size_control = from.subgroup_size_control; 108 subgroup_size_control = from.subgroup_size_control;
@@ -111,6 +116,7 @@ public:
111 if (core) { 116 if (core) {
112 enable13_.pNext = chain; 117 enable13_.pNext = chain;
113 enable13_.dynamicRendering = VK_TRUE; 118 enable13_.dynamicRendering = VK_TRUE;
119 enable13_.pipelineCreationCacheControl = pipeline_cache_control && enable_pipeline_cache_control ? VK_TRUE : VK_FALSE;
114 enable13_.synchronization2 = VK_TRUE; 120 enable13_.synchronization2 = VK_TRUE;
115 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; 121 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE;
116 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; 122 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE;
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index ab6786a51..9652fd51b 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1,4 +1,5 @@
1#pragma once 1#pragma once
2#include "vulkan_gpu_labels.h"
2 3
3// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, 4// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker,
4// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in 5// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in
@@ -11,17 +12,20 @@
11#endif 12#endif
12#include "binary_occlusion_spirv.h" 13#include "binary_occlusion_spirv.h"
13#include "buffer_va_index.h" 14#include "buffer_va_index.h"
15#include "image_memory.h"
14#include "occlusion_sum_spirv.h" 16#include "occlusion_sum_spirv.h"
15#include "queue_holds.h" 17#include "queue_holds.h"
16#include "retire_tickets.h" 18#include "retire_tickets.h"
17#include "statistics_sum_spirv.h" 19#include "statistics_sum_spirv.h"
18#include "vulkan13_features.h" 20#include "vulkan13_features.h"
19#include "vulkan_depth24.h" 21#include "vulkan_depth24.h"
22#include "vulkan_title_image_pool.h"
20#include "vulkan_indirect_dispatch_count.h" 23#include "vulkan_indirect_dispatch_count.h"
21#include "vulkan_scratch.h" 24#include "vulkan_scratch.h"
22#include "vulkan_replay.h" 25#include "vulkan_replay.h"
23#include "queue_families.h" 26#include "queue_families.h"
24#include "resource_tiling.h" 27#include "resource_tiling.h"
28#include "pipeline_profile.h"
25#include "xdxr_build.h" 29#include "xdxr_build.h"
26 30
27#include <algorithm> 31#include <algorithm>
@@ -46,6 +50,15 @@
46 50
47namespace leonida { 51namespace leonida {
48 52
53// Which check of the queue's replay refused a batch ("ExecuteCommandLists failed: unsupported"), by source line,
54// the first time each one does. The batch is then not submitted at all.
55inline ReplayResult queue_unsupported(int line) {
56 static std::atomic<bool> seen[4096];
57 if (line < 0 || line >= 4096 || !seen[line].exchange(true, std::memory_order_relaxed))
58 std::fprintf(stderr, "[rt] d3d12: queue replay refused a batch at vulkan_backend.h:%d\n", line);
59 return ReplayResult::unsupported;
60}
61
49// A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes. 62// A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes.
50// Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame. 63// Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame.
51struct KhrInstanceStage { 64struct KhrInstanceStage {
@@ -85,7 +98,7 @@ struct VulkanDeviceFunctions {
85 X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \ 98 X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \
86 X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ 99 X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \
87 X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ 100 X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \
88 X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ 101 X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) X(vkCmdBlitImage) \
89 X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \ 102 X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \
90 X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \ 103 X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \
91 X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \ 104 X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \
@@ -105,7 +118,7 @@ struct VulkanDeviceFunctions {
105 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 118 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
106 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 119 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
107 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 120 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
108 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ 121 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \
109 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ 122 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \
110 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 123 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
111 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 124 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)
@@ -426,6 +439,7 @@ private:
426}; 439};
427 440
428struct SparseResource; 441struct SparseResource;
442using ImageMemory = ImageMemoryPool<VkDeviceMemory>;
429 443
430// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. 444// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore.
431class DeferredDeletionQueue { 445class DeferredDeletionQueue {
@@ -435,8 +449,10 @@ public:
435 image_view, 449 image_view,
436 image, 450 image,
437 sparse_resource, 451 sparse_resource,
452 pooled_title_image,
438 buffer, 453 buffer,
439 device_memory, 454 device_memory,
455 image_memory, // an ImageMemory::Range*, deleted: its bytes go back to their block
440 acceleration_structure, 456 acceleration_structure,
441 framebuffer, 457 framebuffer,
442 }; 458 };
@@ -512,6 +528,9 @@ public:
512 case Kind::image: 528 case Kind::image:
513 vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); 529 vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr);
514 break; 530 break;
531 case Kind::pooled_title_image:
532 delete reinterpret_cast<PooledTitleImage*>(item.handle);
533 break;
515 case Kind::sparse_resource: 534 case Kind::sparse_resource:
516 // Releases the resource and its page backing together after outstanding submissions. 535 // Releases the resource and its page backing together after outstanding submissions.
517 delete reinterpret_cast<std::shared_ptr<SparseResource>*>(item.handle); 536 delete reinterpret_cast<std::shared_ptr<SparseResource>*>(item.handle);
@@ -522,6 +541,9 @@ public:
522 case Kind::device_memory: 541 case Kind::device_memory:
523 vk.vkFreeMemory(device, reinterpret_cast<VkDeviceMemory>(item.handle), nullptr); 542 vk.vkFreeMemory(device, reinterpret_cast<VkDeviceMemory>(item.handle), nullptr);
524 break; 543 break;
544 case Kind::image_memory:
545 delete reinterpret_cast<ImageMemory::Range*>(item.handle);
546 break;
525 case Kind::acceleration_structure: 547 case Kind::acceleration_structure:
526 if (vk.vkDestroyAccelerationStructureKHR) 548 if (vk.vkDestroyAccelerationStructureKHR)
527 vk.vkDestroyAccelerationStructureKHR( 549 vk.vkDestroyAccelerationStructureKHR(
@@ -550,6 +572,22 @@ private:
550 void* bindless_release_user_ = nullptr; 572 void* bindless_release_user_ = nullptr;
551}; 573};
552 574
575// Sets a device's lost flag and says so once, on stderr, at the moment it is first seen. From then on every fence of
576// the device reads UINT64_MAX and device calls return DXGI_ERROR_DEVICE_REMOVED, so a title takes its own
577// device-removed path (on the retail boot an int3 at game_scarlett_master.exe+0x2474606, reached from its frame wait
578// reading a fence's completed value as ~0); without this line that later stop is the first sign of the loss.
579// True when this call set the flag. device_lost_reports counts the lines said in this process (for tests).
580inline std::atomic<unsigned> device_lost_reports{0};
581inline bool set_device_lost(std::atomic<bool>& flag, const char* where) noexcept {
582 if (flag.exchange(true, std::memory_order_acq_rel)) return false;
583 device_lost_reports.fetch_add(1, std::memory_order_relaxed);
584 std::fprintf(stderr,
585 "[rt] vulkan: the device was lost (%s); its fences now read UINT64_MAX and device calls return "
586 "DXGI_ERROR_DEVICE_REMOVED\n",
587 where);
588 return true;
589}
590
553// Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT). 591// Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT).
554// Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0 592// Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0
555// wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true. 593// wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true.
@@ -601,6 +639,8 @@ public:
601 FenceWaitDispatcher(const FenceWaitDispatcher&) = delete; 639 FenceWaitDispatcher(const FenceWaitDispatcher&) = delete;
602 FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete; 640 FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete;
603 641
642 void set_device_fault(DeviceFaultDiagnostics* diagnostics) { diagnostics_ = diagnostics; }
643
604 void set_signal_event_fn(SignalEventFn fn) { 644 void set_signal_event_fn(SignalEventFn fn) {
605 std::lock_guard lock(mutex_); 645 std::lock_guard lock(mutex_);
606 signal_event_ = fn; 646 signal_event_ = fn;
@@ -777,7 +817,8 @@ private:
777 VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 817 VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
778 si.semaphore = wakeup_sem_; 818 si.semaphore = wakeup_sem_;
779 si.value = next; 819 si.value = next;
780 vk_.vkSignalSemaphore(device_, &si); 820 DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkSignalSemaphore(device_, &si),
821 "vkSignalSemaphore (fence wakeup)");
781 } 822 }
782 823
783 void run() { 824 void run() {
@@ -814,7 +855,8 @@ private:
814 // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes 855 // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes
815 // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the 856 // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the
816 // same wait; completions still wake it at once through the ANY wait. 857 // same wait; completions still wake it at once through the ANY wait.
817 const VkResult res = vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs); 858 const VkResult res = DeviceFaultDiagnostics::observe(
859 diagnostics_, vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs), "vkWaitSemaphores (fence dispatcher)");
818 860
819 lock.lock(); 861 lock.lock();
820 waiting_ = false; 862 waiting_ = false;
@@ -822,7 +864,7 @@ private:
822 epoch_cv_.notify_all(); 864 epoch_cv_.notify_all();
823 865
824 if (res == VK_ERROR_DEVICE_LOST || device_lost_.load(std::memory_order_acquire)) { 866 if (res == VK_ERROR_DEVICE_LOST || device_lost_.load(std::memory_order_acquire)) {
825 device_lost_.store(true, std::memory_order_release); 867 set_device_lost(device_lost_, "vkWaitSemaphores in the fence dispatcher returned VK_ERROR_DEVICE_LOST");
826 std::vector<Entry> drained = std::move(pending_); 868 std::vector<Entry> drained = std::move(pending_);
827 pending_.clear(); 869 pending_.clear();
828 dispatch_outside_lock(lock, drained, signal_event_); 870 dispatch_outside_lock(lock, drained, signal_event_);
@@ -835,7 +877,9 @@ private:
835 std::size_t write = 0; 877 std::size_t write = 0;
836 for (std::size_t i = 0; i < pending_.size(); ++i) { 878 for (std::size_t i = 0; i < pending_.size(); ++i) {
837 std::uint64_t done = 0; 879 std::uint64_t done = 0;
838 const VkResult cr = vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done); 880 const VkResult cr = DeviceFaultDiagnostics::observe(
881 diagnostics_, vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done),
882 "vkGetSemaphoreCounterValue (fence dispatcher)");
839 if (cr == VK_ERROR_DEVICE_LOST) { 883 if (cr == VK_ERROR_DEVICE_LOST) {
840 lost = true; 884 lost = true;
841 for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j])); 885 for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j]));
@@ -852,7 +896,8 @@ private:
852 pending_.resize(write); 896 pending_.resize(write);
853 for (Entry& e : pending_) ready.push_back(std::move(e)); 897 for (Entry& e : pending_) ready.push_back(std::move(e));
854 pending_.clear(); 898 pending_.clear();
855 device_lost_.store(true, std::memory_order_release); 899 set_device_lost(device_lost_,
900 "vkGetSemaphoreCounterValue in the fence dispatcher returned VK_ERROR_DEVICE_LOST");
856 dispatch_outside_lock(lock, ready, signal_event_); 901 dispatch_outside_lock(lock, ready, signal_event_);
857 return; 902 return;
858 } 903 }
@@ -867,6 +912,7 @@ private:
867 VkDevice device_; 912 VkDevice device_;
868 const VulkanDeviceFunctions& vk_; 913 const VulkanDeviceFunctions& vk_;
869 std::atomic<bool>& device_lost_; 914 std::atomic<bool>& device_lost_;
915 DeviceFaultDiagnostics* diagnostics_ = nullptr; // configured before the dispatcher starts
870 SignalEventFn signal_event_ = nullptr; 916 SignalEventFn signal_event_ = nullptr;
871 VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; 917 VkSemaphore wakeup_sem_ = VK_NULL_HANDLE;
872 std::uint64_t wakeup_val_ = 0; 918 std::uint64_t wakeup_val_ = 0;
@@ -948,6 +994,9 @@ public:
948 bool conditional_rendering = false, bool ray_tracing = false, bool xdxr = false) 994 bool conditional_rendering = false, bool ray_tracing = false, bool xdxr = false)
949 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { 995 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) {
950 loaded_ = vk.load(get, device); 996 loaded_ = vk.load(get, device);
997 if (loaded_ && gpu_labels_.initialize(device, get)) {
998 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); };
999 }
951 replay_.pipeline_barrier = vk.vkCmdPipelineBarrier; 1000 replay_.pipeline_barrier = vk.vkCmdPipelineBarrier;
952 replay_.clear_color_image = vk.vkCmdClearColorImage; 1001 replay_.clear_color_image = vk.vkCmdClearColorImage;
953 replay_.clear_depth_stencil_image = vk.vkCmdClearDepthStencilImage; 1002 replay_.clear_depth_stencil_image = vk.vkCmdClearDepthStencilImage;
@@ -959,6 +1008,7 @@ public:
959 replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage; 1008 replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage;
960 replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; 1009 replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer;
961 replay_.copy_image = vk.vkCmdCopyImage; 1010 replay_.copy_image = vk.vkCmdCopyImage;
1011 replay_.blit_image = vk.vkCmdBlitImage;
962 replay_.resolve_image = vk.vkCmdResolveImage; 1012 replay_.resolve_image = vk.vkCmdResolveImage;
963 replay_.fill_buffer = vk.vkCmdFillBuffer; 1013 replay_.fill_buffer = vk.vkCmdFillBuffer;
964 replay_.update_buffer = vk.vkCmdUpdateBuffer; 1014 replay_.update_buffer = vk.vkCmdUpdateBuffer;
@@ -1106,6 +1156,8 @@ public:
1106 } 1156 }
1107 1157
1108 ~VulkanContext() { 1158 ~VulkanContext() {
1159 progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away
1160 gpu_labels_.stop(device_);
1109 fence_dispatcher_.reset(); 1161 fence_dispatcher_.reset();
1110 deletion_queue_.drain(UINT64_MAX, device_, vk); 1162 deletion_queue_.drain(UINT64_MAX, device_, vk);
1111 for (const auto& [key, framebuffer] : resolve_framebuffers_) 1163 for (const auto& [key, framebuffer] : resolve_framebuffers_)
@@ -1118,6 +1170,22 @@ public:
1118 VulkanContext& operator=(const VulkanContext&) = delete; 1170 VulkanContext& operator=(const VulkanContext&) = delete;
1119 1171
1120 bool loaded() const { return loaded_; } 1172 bool loaded() const { return loaded_; }
1173
1174 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) {
1175 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled);
1176 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get());
1177 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); });
1178 }
1179
1180 void add_diagnostic_queue(VkQueue queue) {
1181 if (device_fault_) device_fault_->add_queue(queue);
1182 }
1183
1184 DeviceFaultDiagnostics* device_fault() const { return device_fault_.get(); }
1185
1186 VkResult observe_result(VkResult result, const char* operation) const noexcept {
1187 return DeviceFaultDiagnostics::observe(device_fault_.get(), result, operation);
1188 }
1121 void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, 1189 void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
1122 VkDeviceSize max_range, std::uint32_t family) { 1190 VkDeviceSize max_range, std::uint32_t family) {
1123 std::unique_lock lock(resource_mutex_); 1191 std::unique_lock lock(resource_mutex_);
@@ -1136,6 +1204,13 @@ public:
1136 std::unique_lock lock(resource_mutex_); 1204 std::unique_lock lock(resource_mutex_);
1137 counted_dispatch_ = std::make_unique<IndirectDispatchCounter>(get, device_, memory, limits); 1205 counted_dispatch_ = std::make_unique<IndirectDispatchCounter>(get, device_, memory, limits);
1138 } 1206 }
1207 // Indexed quad lists are drawn from triangle indices a compute pass writes into the copy scratch
1208 // (quad_index_expand.h). Call only with bufferDeviceAddress enabled and after an enable_copy_scratch whose chunks
1209 // have INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage on memory allocated with a device address.
1210 void configure_quad_indices(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) {
1211 std::unique_lock lock(resource_mutex_);
1212 quad_indices_ = std::make_unique<QuadIndexExpander>(get, device_, limits);
1213 }
1139 VkDevice device() const { return device_; } 1214 VkDevice device() const { return device_; }
1140 1215
1141 // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets 1216 // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets
@@ -1155,6 +1230,11 @@ public:
1155 std::unique_lock lock(resource_mutex_); 1230 std::unique_lock lock(resource_mutex_);
1156 set_resource_locked(id, binding); 1231 set_resource_locked(id, binding);
1157 } 1232 }
1233 // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches).
1234 bool knows_buffer_va(std::uint64_t va, std::uint64_t bytes = 1) {
1235 std::shared_lock lock(resource_mutex_);
1236 return buffer_vas_.covers(va, bytes);
1237 }
1158 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { 1238 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) {
1159 std::unique_lock rlock(resource_mutex_); 1239 std::unique_lock rlock(resource_mutex_);
1160 set_resource_locked(id, binding); 1240 set_resource_locked(id, binding);
@@ -1216,6 +1296,7 @@ public:
1216 } 1296 }
1217 { 1297 {
1218 std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled 1298 std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled
1299 storage_pending_.erase(id);
1219 std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); 1300 std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; });
1220 } 1301 }
1221 if (img) { 1302 if (img) {
@@ -1293,6 +1374,32 @@ public:
1293 replay_.depth_range_unrestricted = enabled; 1374 replay_.depth_range_unrestricted = enabled;
1294 } 1375 }
1295 1376
1377 struct GeometryUpload {
1378 std::uint64_t source{}, size{};
1379 VkBuffer buffer{};
1380 VkDeviceSize offset{};
1381 std::shared_ptr<void> owner;
1382 };
1383 using GeometryProvider = std::function<bool(std::uint64_t,std::uint64_t,GeometryUpload&)>;
1384 void set_geometry_provider(GeometryProvider provider) {
1385 std::unique_lock lock(resource_mutex_);
1386 geometry_provider_=std::move(provider);
1387 }
1388
1389 // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory).
1390 void set_title_memory(std::function<bool(std::uint64_t, std::uint64_t, VkBuffer&, VkDeviceSize&)> copy) {
1391 std::unique_lock lock(resource_mutex_);
1392 replay_.title_memory = std::move(copy);
1393 }
1394
1395 // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices).
1396 void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) {
1397 std::unique_lock lock(resource_mutex_);
1398 replay_.quad_indices = buffer;
1399 replay_.quad_indices_offset = offset;
1400 replay_.quad_index_count = count;
1401 }
1402
1296 // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. 1403 // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears.
1297 void set_color_attachment_format(std::function<bool(VkFormat)> check) { 1404 void set_color_attachment_format(std::function<bool(VkFormat)> check) {
1298 std::unique_lock lock(resource_mutex_); 1405 std::unique_lock lock(resource_mutex_);
@@ -1304,24 +1411,77 @@ public:
1304 } 1411 }
1305 1412
1306 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1413 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1307 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline) { 1414 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1308 std::unique_lock lock(resource_mutex_); 1415 std::unique_lock lock(resource_mutex_);
1309 pipelines_[id] = pipeline; 1416 pipelines_[id] = pipeline;
1417 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1310 } 1418 }
1311 void remove_pipeline(std::uintptr_t id) { 1419 void remove_pipeline(std::uintptr_t id) {
1312 std::unique_lock lock(resource_mutex_); 1420 std::unique_lock lock(resource_mutex_);
1313 pipelines_.erase(id); 1421 pipelines_.erase(id);
1314 graphics_pipelines_.erase(id); 1422 graphics_pipelines_.erase(id);
1423 if (device_fault_) device_fault_->pipeline_names.erase(id);
1315 } 1424 }
1316 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline) { 1425 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1426 const CheckpointShaders* shaders = nullptr) {
1317 std::unique_lock lock(resource_mutex_); 1427 std::unique_lock lock(resource_mutex_);
1318 graphics_pipelines_[id] = pipeline; 1428 graphics_pipelines_[id] = pipeline;
1429 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1319 } 1430 }
1320 // Configure before queue creation, when the selected queue family supports compute. 1431 // Configure before queue creation, when the selected queue family supports compute.
1321 void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { 1432 void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) {
1322 occlusion_resolve_memory_ = memory; 1433 occlusion_resolve_memory_ = memory;
1323 } 1434 }
1324 1435
1436 struct HostTextureStats { std::uint64_t copies = 0, waits = 0; };
1437 HostTextureStats host_texture_stats() {
1438 std::lock_guard lock(submit_mutex_);
1439 return host_texture_stats_;
1440 }
1441
1442 // CPU writes to a title texture have no application fence. Prevent another queue from
1443 // claiming a new layout or submitting work between the completion check and the host copy.
1444 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues.
1445 template<class Copy>
1446 VkResult write_host_texture(ResourceId id, std::uint32_t subresource, Copy&& copy) {
1447 std::lock_guard layout_lock(tracker_mutex_);
1448 std::lock_guard queue_lock(submit_mutex_);
1449 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY;
1450 if (image_work_pending_) {
1451 ++host_texture_stats_.waits;
1452 const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)");
1453 if (result != VK_SUCCESS) return result;
1454 image_work_pending_ = false;
1455 }
1456 if (!copy()) return VK_ERROR_UNKNOWN;
1457 ++host_texture_stats_.copies;
1458 return VK_SUCCESS;
1459 }
1460
1461 // A complete CPU-side replacement of these color subresources. Serialize with replay and
1462 // present while recording the old layouts, finishing prior reads and publishing the copy.
1463 template<class Copy>
1464 VkResult write_staged_title_image(ResourceId id, const VkImageSubresourceRange& range, Copy&& copy) {
1465 std::lock_guard layout_lock(tracker_mutex_);
1466 std::lock_guard queue_lock(submit_mutex_);
1467 LayoutPieces pieces;
1468 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN;
1469 if (image_work_pending_) {
1470 const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)");
1471 if (r != VK_SUCCESS) return r;
1472 image_work_pending_ = false;
1473 }
1474 const auto r = observe_result(copy(replay_, pieces), "title staging upload");
1475 if (r == VK_SUCCESS) {
1476 for (const auto& p : pieces)
1477 if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) tracker_.set(id, p.range, VK_IMAGE_LAYOUT_GENERAL);
1478 }
1479 return r;
1480 }
1481
1482 // Present and probe submissions have their own fences, outside the queue retirement timelines.
1483 void note_image_work_locked() { image_work_pending_ = true; }
1484
1325 // For tests and traces. 1485 // For tests and traces.
1326 VkImageLayout layout(ResourceId id, std::uint32_t subresource) { 1486 VkImageLayout layout(ResourceId id, std::uint32_t subresource) {
1327 std::lock_guard lock(tracker_mutex_); 1487 std::lock_guard lock(tracker_mutex_);
@@ -1333,6 +1493,23 @@ public:
1333 return resources_.find(id) != resources_.end(); 1493 return resources_.find(id) != resources_.end();
1334 } 1494 }
1335 1495
1496 // The registered buffer whose VA range holds `va`, preferring one that holds [va, va + bytes) as buffer_at does: its
1497 // ID, first VA and size in bytes. False when none does, or when `acquire(id)` returns false. `acquire` runs with
1498 // the registry locked, so the resource cannot finish being removed under it: it takes the caller's reference
1499 // (Resource's destructor removes its entry first, which waits for this lock). Used where a console call names a
1500 // buffer by VA only (Xbox device slot 70).
1501 template<class Acquire>
1502 bool buffer_resource_at(std::uint64_t va, std::uint64_t bytes, ResourceId& id, std::uint64_t& start,
1503 std::uint64_t& size, Acquire&& acquire) {
1504 std::shared_lock lock(resource_mutex_);
1505 BufferVaIndex<ResourceId>::Hit hit{};
1506 if (!buffer_vas_.find(va, hit, bytes) || !acquire(hit.id)) return false;
1507 id = hit.id;
1508 start = hit.start;
1509 size = hit.size;
1510 return true;
1511 }
1512
1336 bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } 1513 bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; }
1337 bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } 1514 bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; }
1338 1515
@@ -1407,6 +1584,56 @@ public:
1407 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) 1584 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h)
1408 // and records what the set needs first. When it fails, nothing of that call is executed. 1585 // and records what the set needs first. When it fails, nothing of that call is executed.
1409 void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } 1586 void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; }
1587 void set_graphics_family(std::uint32_t family) { graphics_family_ = family; }
1588 void set_compute_copy_aspects(std::function<VkImageAspectFlags(VkFormat)> check) {
1589 replay_.compute_copy_aspects = std::move(check);
1590 }
1591
1592 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1593 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1594 // Set once, before the first queue exists.
1595 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1596
1597 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues.
1598 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of
1599 // Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b, GPL-3.0.)
1600 using TableScanner = std::function<void(std::uint64_t, std::uint32_t)>;
1601 void set_table_scanner(TableScanner scan) { table_scanner_ = std::move(scan); }
1602 void set_cpu_texture_publisher(std::function<bool()> f) { cpu_texture_publisher_ = std::move(f); }
1603 bool publish_cpu_textures() const { return !cpu_texture_publisher_ || cpu_texture_publisher_(); }
1604 void set_sample_table_resolver(std::function<bool(std::uint64_t,std::uint32_t)> f) { sample_table_resolver_ = std::move(f); }
1605 bool prepare_sample_table(std::uint64_t address, std::uint32_t count) const {
1606 return !sample_table_resolver_ || sample_table_resolver_(address,count);
1607 }
1608 // False when this context has no scanner of its own.
1609 bool scan_table(std::uint64_t va, std::uint32_t descriptors) const {
1610 if (!table_scanner_) return false;
1611 table_scanner_(va, descriptors);
1612 return true;
1613 }
1614
1615 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1616 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1617 // Set once, before the first queue exists.
1618 using InputProbe = std::function<void(std::span<const CommandList* const>, std::uint64_t, const char*)>;
1619 void set_input_probe(InputProbe probe) { input_probe_ = std::move(probe); }
1620 bool diagnostic_buffer(std::uint64_t va, std::uint64_t& host, std::uint64_t& room) {
1621 std::shared_lock lock(resource_mutex_);
1622 BufferVaIndex<ResourceId>::Hit hit{};
1623 if (!buffer_vas_.find(va, hit)) return false;
1624 const auto* b = resolve(hit.id);
1625 if (!b || va - b->va >= b->size) return false;
1626 const auto offset = va - b->va;
1627 host = b->host ? reinterpret_cast<std::uint64_t>(b->host + offset) : 0;
1628 room = b->size - offset;
1629 return true;
1630 }
1631 const char* diagnostic_compute_name(std::uintptr_t id) {
1632 std::shared_lock lock(resource_mutex_);
1633 if (!device_fault_) return nullptr;
1634 const auto it = device_fault_->pipeline_names.find(id);
1635 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
1636 }
1410 1637
1411 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1638 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1412 std::unique_lock lock(resource_mutex_); 1639 std::unique_lock lock(resource_mutex_);
@@ -1418,7 +1645,8 @@ public:
1418 void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, 1645 void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate,
1419 std::uint64_t max_storage_range = 1u << 27) { 1646 std::uint64_t max_storage_range = 1u << 27) {
1420 std::unique_lock lock(resource_mutex_); 1647 std::unique_lock lock(resource_mutex_);
1421 depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); 1648 depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range,
1649 device_fault_.get());
1422 if (!depth24_->loaded()) { 1650 if (!depth24_->loaded()) {
1423 depth24_.reset(); 1651 depth24_.reset();
1424 return; 1652 return;
@@ -1430,10 +1658,13 @@ public:
1430 } 1658 }
1431 1659
1432 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from 1660 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from
1433 // `allocate`. Without this such a copy is refused as unsupported. 1661 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer
1434 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { 1662 // usage, for configure_quad_indices.
1663 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate,
1664 VkBufferUsageFlags extra_usage = 0, std::vector<std::uint32_t> families = {}) {
1435 std::unique_lock lock(resource_mutex_); 1665 std::unique_lock lock(resource_mutex_);
1436 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate)); 1666 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage, std::move(families),
1667 device_fault_.get());
1437 if (!scratch_->loaded()) scratch_.reset(); 1668 if (!scratch_->loaded()) scratch_.reset();
1438 } 1669 }
1439 1670
@@ -1497,7 +1728,8 @@ public:
1497 wait.semaphoreCount = std::uint32_t(semaphores.size()); 1728 wait.semaphoreCount = std::uint32_t(semaphores.size());
1498 wait.pSemaphores = semaphores.data(); 1729 wait.pSemaphores = semaphores.data();
1499 wait.pValues = values.data(); 1730 wait.pValues = values.data();
1500 vk.vkWaitSemaphores(device_, &wait, UINT64_MAX); // outside submit_mutex_: a signal may need it 1731 // Outside submit_mutex_: a signal may need it.
1732 observe_result(vk.vkWaitSemaphores(device_, &wait, UINT64_MAX), "vkWaitSemaphores (retirement)");
1501 } 1733 }
1502 return completed_retire_ticket(); 1734 return completed_retire_ticket();
1503 } 1735 }
@@ -1515,7 +1747,8 @@ public:
1515 if (is_device_lost()) return 0; 1747 if (is_device_lost()) return 0;
1516 ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { 1748 ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) {
1517 std::uint64_t done = 0; 1749 std::uint64_t done = 0;
1518 const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); 1750 const VkResult result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done),
1751 "vkGetSemaphoreCounterValue (retirement)");
1519 if (result == VK_ERROR_DEVICE_LOST) lost = true; 1752 if (result == VK_ERROR_DEVICE_LOST) lost = true;
1520 return result == VK_SUCCESS && done >= value; 1753 return result == VK_SUCCESS && done >= value;
1521 }); 1754 });
@@ -1536,6 +1769,7 @@ public:
1536 void record_submit_locked(VkSemaphore progress, std::uint64_t value) { 1769 void record_submit_locked(VkSemaphore progress, std::uint64_t value) {
1537 const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; 1770 const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1;
1538 retire_tickets_.record(ticket, progress, value); 1771 retire_tickets_.record(ticket, progress, value);
1772 note_image_work_locked();
1539 } 1773 }
1540 void retire_queue_idle_locked(VkSemaphore progress) { 1774 void retire_queue_idle_locked(VkSemaphore progress) {
1541 retire_tickets_.queue_idle(progress); 1775 retire_tickets_.queue_idle(progress);
@@ -1546,8 +1780,8 @@ public:
1546 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 1780 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
1547 std::mutex& submit_mutex() { return submit_mutex_; } 1781 std::mutex& submit_mutex() { return submit_mutex_; }
1548 1782
1549 void mark_device_lost() noexcept { 1783 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept {
1550 device_lost_.store(true, std::memory_order_release); 1784 set_device_lost(device_lost_, where);
1551 if (fence_dispatcher_) { 1785 if (fence_dispatcher_) {
1552 try { 1786 try {
1553 fence_dispatcher_->notify_device_lost(); 1787 fence_dispatcher_->notify_device_lost();
@@ -1605,7 +1839,14 @@ private:
1605 1839
1606 const ResourceBinding* resolve(ResourceId id) const { 1840 const ResourceBinding* resolve(ResourceId id) const {
1607 const auto it = resources_.find(id); 1841 const auto it = resources_.find(id);
1608 return it == resources_.end() ? nullptr : &it->second; 1842 if (it == resources_.end()) return nullptr;
1843 const auto& binding = it->second;
1844 if (auto* memory = binding.deferred_memory; memory && !memory->ensure()) return nullptr;
1845 // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind.
1846 if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr;
1847 if (auto* seen = binding.replay_seen; seen && !seen->load(std::memory_order_relaxed))
1848 seen->store(true, std::memory_order_relaxed);
1849 return &binding;
1609 } 1850 }
1610 1851
1611 // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. 1852 // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe.
@@ -1693,6 +1934,52 @@ private:
1693 return framebuffer; 1934 return framebuffer;
1694 } 1935 }
1695 1936
1937 std::uint64_t poll_retirement_locked(VkResult& result) {
1938 return retire_tickets_.completed([&](VkSemaphore semaphore, std::uint64_t value) {
1939 std::uint64_t done = 0;
1940 result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done),
1941 "vkGetSemaphoreCounterValue (retirement)");
1942 return result == VK_SUCCESS && done >= value;
1943 });
1944 }
1945
1946 void watch_queue_progress(std::stop_token stop) {
1947 using Watch = SubmissionProgressWatch;
1948 Watch watch;
1949 std::uint64_t retired = 0;
1950 std::mutex timer_mutex;
1951 std::condition_variable_any timer;
1952 std::unique_lock timer_lock(timer_mutex);
1953 while (!stop.stop_requested()) {
1954 timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; });
1955 if (stop.stop_requested() || is_device_lost()) break;
1956 auto state = Watch::State::submit_lock_busy;
1957 VkResult result = VK_SUCCESS;
1958 std::uint64_t submitted;
1959 {
1960 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait
1961 // blocked inside the driver can hold this mutex indefinitely.
1962 std::unique_lock lock(submit_mutex_, std::try_to_lock);
1963 submitted = submitted_retire_ticket();
1964 if (lock.owns_lock()) {
1965 if (is_device_lost()) break;
1966 retired = poll_retirement_locked(result);
1967 state = retired < submitted ? Watch::State::pending : Watch::State::idle;
1968 }
1969 }
1970 if (result == VK_ERROR_DEVICE_LOST) {
1971 mark_device_lost();
1972 break;
1973 }
1974 // A failed counter query does not measure GPU progress.
1975 if (result != VK_SUCCESS) state = Watch::State::idle;
1976 if (watch.sample(state, retired, Watch::Clock::now()))
1977 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced"
1978 : "could not sample the submit lock",
1979 submitted, retired);
1980 }
1981 }
1982
1696 VkDevice device_; 1983 VkDevice device_;
1697 bool loaded_ = false; 1984 bool loaded_ = false;
1698 bool ray_tracing_ = false; 1985 bool ray_tracing_ = false;
@@ -1702,9 +1989,13 @@ private:
1702 alignas(64) std::mutex tracker_mutex_; 1989 alignas(64) std::mutex tracker_mutex_;
1703 alignas(64) std::mutex views_mutex_; 1990 alignas(64) std::mutex views_mutex_;
1704 alignas(64) std::mutex submit_mutex_; 1991 alignas(64) std::mutex submit_mutex_;
1992 bool image_work_pending_ = false; // under submit_mutex_
1993 HostTextureStats host_texture_stats_; // under submit_mutex_
1705 RetireTickets<VkSemaphore> retire_tickets_; 1994 RetireTickets<VkSemaphore> retire_tickets_;
1706 std::atomic<std::uint64_t> submitted_ticket_{0}; 1995 std::atomic<std::uint64_t> submitted_ticket_{0};
1707 DeferredDeletionQueue deletion_queue_; 1996 DeferredDeletionQueue deletion_queue_;
1997 std::unique_ptr<DeviceFaultDiagnostics> device_fault_;
1998 std::jthread progress_watch_;
1708 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; 1999 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_;
1709 QueueHolds<VkSemaphore> holds_; 2000 QueueHolds<VkSemaphore> holds_;
1710 std::unordered_map<ResourceId, ResourceBinding> resources_; 2001 std::unordered_map<ResourceId, ResourceBinding> resources_;
@@ -1732,6 +2023,12 @@ private:
1732 std::map<std::tuple<VkFormat, std::uint32_t, VkImageLayout, VkImageLayout, VkResolveModeFlagBits>, VkRenderPass> 2023 std::map<std::tuple<VkFormat, std::uint32_t, VkImageLayout, VkImageLayout, VkResolveModeFlagBits>, VkRenderPass>
1733 resolve_passes_; 2024 resolve_passes_;
1734 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; 2025 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_;
2026 std::function<void()> before_execute_;
2027 InputProbe input_probe_;
2028 TableScanner table_scanner_;
2029 GeometryProvider geometry_provider_;
2030 std::function<bool(std::uint64_t,std::uint32_t)> sample_table_resolver_;
2031 std::function<bool()> cpu_texture_publisher_;
1735 std::function<bool(VkCommandBuffer)> bindless_prepare_; 2032 std::function<bool(VkCommandBuffer)> bindless_prepare_;
1736 std::function<VkDescriptorSet()> bindless_current_; 2033 std::function<VkDescriptorSet()> bindless_current_;
1737 bool bindless_upload_pending_ = false; // tracker_mutex_ 2034 bool bindless_upload_pending_ = false; // tracker_mutex_
@@ -1747,12 +2044,15 @@ private:
1747 double timestamp_period_ = 0; 2044 double timestamp_period_ = 0;
1748 bool order_timestamp_copies_ = false; 2045 bool order_timestamp_copies_ = false;
1749 VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; 2046 VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{};
2047 label::Completions gpu_labels_;
1750 ReplayFunctions replay_; 2048 ReplayFunctions replay_;
1751 std::unique_ptr<PredicateReducer> predicate_reducer_; 2049 std::unique_ptr<PredicateReducer> predicate_reducer_;
1752 std::unique_ptr<PredicatedBufferCopier> predicated_copier_; 2050 std::unique_ptr<PredicatedBufferCopier> predicated_copier_;
1753 std::unique_ptr<IndirectDispatchCounter> counted_dispatch_; 2051 std::unique_ptr<IndirectDispatchCounter> counted_dispatch_;
2052 std::unique_ptr<QuadIndexExpander> quad_indices_;
1754 std::uint32_t predicate_family_ = UINT32_MAX; 2053 std::uint32_t predicate_family_ = UINT32_MAX;
1755 std::uint32_t transfer_only_family_ = UINT32_MAX; 2054 std::uint32_t transfer_only_family_ = UINT32_MAX;
2055 std::uint32_t graphics_family_ = UINT32_MAX;
1756 DebugLabelFunctions labels_; 2056 DebugLabelFunctions labels_;
1757}; 2057};
1758#ifdef _MSC_VER 2058#ifdef _MSC_VER
@@ -1784,7 +2084,8 @@ public:
1784 std::uint64_t completed() const { 2084 std::uint64_t completed() const {
1785 if (context_.is_device_lost()) return UINT64_MAX; 2085 if (context_.is_device_lost()) return UINT64_MAX;
1786 std::uint64_t value = 0; 2086 std::uint64_t value = 0;
1787 const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); 2087 const VkResult result = context_.observe_result(
2088 context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value), "vkGetSemaphoreCounterValue");
1788 if (result == VK_ERROR_DEVICE_LOST) { 2089 if (result == VK_ERROR_DEVICE_LOST) {
1789 context_.mark_device_lost(); 2090 context_.mark_device_lost();
1790 return UINT64_MAX; 2091 return UINT64_MAX;
@@ -1800,13 +2101,15 @@ public:
1800 // it marks the context lost on a query error and prevents the dispatcher from waking. 2101 // it marks the context lost on a query error and prevents the dispatcher from waking.
1801 if (context_.is_device_lost()) return false; 2102 if (context_.is_device_lost()) return false;
1802 std::uint64_t current = 0; 2103 std::uint64_t current = 0;
1803 if (context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &current) == VK_SUCCESS && 2104 if (context_.observe_result(context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &current),
2105 "vkGetSemaphoreCounterValue") == VK_SUCCESS &&
1804 value <= current) 2106 value <= current)
1805 return false; 2107 return false;
1806 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 2108 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
1807 info.semaphore = semaphore_; 2109 info.semaphore = semaphore_;
1808 info.value = value; 2110 info.value = value;
1809 const VkResult result = context_.vk.vkSignalSemaphore(context_.device(), &info); 2111 const VkResult result = context_.observe_result(context_.vk.vkSignalSemaphore(context_.device(), &info),
2112 "vkSignalSemaphore");
1810 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 2113 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
1811 if (result != VK_SUCCESS) return false; 2114 if (result != VK_SUCCESS) return false;
1812 context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now 2115 context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now
@@ -1820,7 +2123,8 @@ public:
1820 info.semaphoreCount = 1; 2123 info.semaphoreCount = 1;
1821 info.pSemaphores = &semaphore_; 2124 info.pSemaphores = &semaphore_;
1822 info.pValues = &value; 2125 info.pValues = &value;
1823 const VkResult result = context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns); 2126 const VkResult result = context_.observe_result(
2127 context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns), "vkWaitSemaphores");
1824 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 2128 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
1825 return result == VK_SUCCESS; 2129 return result == VK_SUCCESS;
1826 } 2130 }
@@ -1893,7 +2197,7 @@ public:
1893 if (queue_) { 2197 if (queue_) {
1894 std::lock_guard lock(context_.submit_mutex()); 2198 std::lock_guard lock(context_.submit_mutex());
1895 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 2199 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
1896 const VkResult idle_result = vk.vkQueueWaitIdle(queue_); 2200 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle");
1897 if (idle_result == VK_SUCCESS) { 2201 if (idle_result == VK_SUCCESS) {
1898 if (progress_) context_.retire_queue_idle_locked(progress_); 2202 if (progress_) context_.retire_queue_idle_locked(progress_);
1899 } else { 2203 } else {
@@ -2014,18 +2318,21 @@ public:
2014 using PinFn = std::function<std::shared_ptr<void>()>; 2318 using PinFn = std::function<std::shared_ptr<void>()>;
2015 2319
2016 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { 2320 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) {
2321 auto* diagnostics = context_.device_fault();
2322 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0;
2017 ReplayResult result = ReplayResult::success; 2323 ReplayResult result = ReplayResult::success;
2018 bool held = false; 2324 bool held = false;
2019 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released 2325 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released
2020 { 2326 {
2021 std::lock_guard state(state_mutex_); 2327 std::lock_guard state(state_mutex_);
2022 if (!must_hold()) { 2328 if (!must_hold()) {
2023 result = execute_now(lists); 2329 result = execute_now(lists, execute_call);
2024 } else if (context_.is_device_lost()) { 2330 } else if (context_.is_device_lost()) {
2025 result = ReplayResult::unsupported; 2331 result = queue_unsupported(__LINE__);
2026 } else { 2332 } else {
2027 Deferred op; 2333 Deferred op;
2028 op.kind = Deferred::Kind::batch; 2334 op.kind = Deferred::Kind::batch;
2335 op.execute_call = execute_call;
2029 op.lists.reserve(lists.size()); 2336 op.lists.reserve(lists.size());
2030 for (const CommandList* list : lists) op.lists.push_back(*list); 2337 for (const CommandList* list : lists) op.lists.push_back(*list);
2031 if (pin) op.pins.push_back(pin()); 2338 if (pin) op.pins.push_back(pin());
@@ -2104,7 +2411,7 @@ public:
2104 2411
2105 bool idle() { 2412 bool idle() {
2106 std::lock_guard lock(context_.submit_mutex()); 2413 std::lock_guard lock(context_.submit_mutex());
2107 return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; 2414 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS;
2108 } 2415 }
2109 2416
2110private: 2417private:
@@ -2190,11 +2497,11 @@ private:
2190 !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || 2497 !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory ||
2191 !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || 2498 !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at ||
2192 !build.instance_count) 2499 !build.instance_count)
2193 return ReplayResult::unsupported; 2500 return queue_unsupported(__LINE__);
2194 const std::uint64_t bytes = 8ull * build.instance_count; 2501 const std::uint64_t bytes = 8ull * build.instance_count;
2195 const std::uint8_t* guest = nullptr; 2502 const std::uint8_t* guest = nullptr;
2196 const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); 2503 const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest);
2197 if (status == HostReadStatus::not_cpu_written) return ReplayResult::unsupported; 2504 if (status == HostReadStatus::not_cpu_written) return queue_unsupported(__LINE__);
2198 if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; 2505 if (status != HostReadStatus::ok) return ReplayResult::invalid_copy;
2199 2506
2200 KhrInstanceStage stage{}; 2507 KhrInstanceStage stage{};
@@ -2217,7 +2524,7 @@ private:
2217 info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | 2524 info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
2218 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; 2525 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
2219 if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) 2526 if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS)
2220 return ReplayResult::unsupported; 2527 return queue_unsupported(__LINE__);
2221 VkMemoryRequirements requirements{}; 2528 VkMemoryRequirements requirements{};
2222 funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); 2529 funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements);
2223 const auto& memory = context_.occlusion_resolve_memory_; 2530 const auto& memory = context_.occlusion_resolve_memory_;
@@ -2233,7 +2540,7 @@ private:
2233 } 2540 }
2234 if (type == memory.memoryTypeCount) { 2541 if (type == memory.memoryTypeCount) {
2235 discard(); 2542 discard();
2236 return ReplayResult::unsupported; 2543 return queue_unsupported(__LINE__);
2237 } 2544 }
2238 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; 2545 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
2239 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; 2546 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
@@ -2243,7 +2550,7 @@ private:
2243 if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || 2550 if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS ||
2244 funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { 2551 funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) {
2245 discard(); 2552 discard();
2246 return ReplayResult::unsupported; 2553 return queue_unsupported(__LINE__);
2247 } 2554 }
2248 stage.size = bytes; 2555 stage.size = bytes;
2249 } 2556 }
@@ -2251,7 +2558,7 @@ private:
2251 void* mapped = nullptr; 2558 void* mapped = nullptr;
2252 if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { 2559 if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) {
2253 discard(); 2560 discard();
2254 return ReplayResult::unsupported; 2561 return queue_unsupported(__LINE__);
2255 } 2562 }
2256 // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. 2563 // Validate and translate in one pass straight into the staging buffer; no second vector of addresses.
2257 for (std::uint32_t i = 0; i < build.instance_count; ++i) { 2564 for (std::uint32_t i = 0; i < build.instance_count; ++i) {
@@ -2277,21 +2584,25 @@ private:
2277 stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); 2584 stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address);
2278 if (!stage.address) { 2585 if (!stage.address) {
2279 discard(); 2586 discard();
2280 return ReplayResult::unsupported; 2587 return queue_unsupported(__LINE__);
2281 } 2588 }
2282 stages.push_back(std::move(stage)); 2589 stages.push_back(std::move(stage));
2283 address = stages.back().address; 2590 address = stages.back().address;
2284 return ReplayResult::success; 2591 return ReplayResult::success;
2285 } 2592 }
2286 2593
2287 ReplayResult execute_now(std::span<const CommandList* const> lists) { 2594 ReplayResult execute_now(std::span<const CommandList* const> lists, std::uint64_t execute_call) {
2288 if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; 2595 if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__);
2596 if (context_.before_execute_) context_.before_execute_();
2597 if (context_.input_probe_)
2598 context_.input_probe_(lists, execute_call, kind_ == QueueKind::direct ? "direct" :
2599 kind_ == QueueKind::compute ? "compute" : "copy");
2289 if (kind_ != QueueKind::direct) 2600 if (kind_ != QueueKind::direct)
2290 for (const auto* list : lists) 2601 for (const auto* list : lists)
2291 for (const auto& command : list->commands()) 2602 for (const auto& command : list->commands())
2292 if (std::holds_alternative<ClearRenderTarget>(command) || 2603 if (std::holds_alternative<ClearRenderTarget>(command) ||
2293 std::holds_alternative<ClearDepthStencil>(command)) 2604 std::holds_alternative<ClearDepthStencil>(command))
2294 return ReplayResult::unsupported; 2605 return queue_unsupported(__LINE__);
2295 VkCommandBuffer command_buffer = VK_NULL_HANDLE; 2606 VkCommandBuffer command_buffer = VK_NULL_HANDLE;
2296 struct KhrGuard { 2607 struct KhrGuard {
2297 VulkanQueue* queue; 2608 VulkanQueue* queue;
@@ -2337,6 +2648,25 @@ private:
2337 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 2648 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2338 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 2649 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2339 ReplayFunctions replay = context_.replay_; 2650 ReplayFunctions replay = context_.replay_;
2651 unsigned mesh_draws = 0;
2652 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2653 std::vector<VulkanContext::GeometryUpload> geometry;
2654 if (context_.geometry_provider_) {
2655 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2656 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2657 for (const auto& upload : geometry) {
2658 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2659 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2660 return true;
2661 }
2662 VulkanContext::GeometryUpload upload;
2663 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2664 buffer=upload.buffer;offset=upload.offset;
2665 geometry.push_back(std::move(upload));
2666 return true;
2667 };
2668 }
2669 replay.graphics_family = family_ == context_.graphics_family_;
2340 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy 2670 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2341 : kind_ == QueueKind::compute ? detail::queue_stages_compute 2671 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2342 : 0; 2672 : 0;
@@ -2359,12 +2689,12 @@ private:
2359 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 2689 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2360 if (captures) { 2690 if (captures) {
2361 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 2691 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
2362 return ReplayResult::unsupported; 2692 return queue_unsupported(__LINE__);
2363 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 2693 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
2364 // retaining main's resource -> tracker -> submit lock order through emit and submission. 2694 // retaining main's resource -> tracker -> submit lock order through emit and submission.
2365 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2695 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2366 batch = context_.predicate_reducer_->batch(captures); 2696 batch = context_.predicate_reducer_->batch(captures);
2367 if (!batch) return ReplayResult::unsupported; 2697 if (!batch) return queue_unsupported(__LINE__);
2368 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 2698 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
2369 return batch->prepare(buffer, offset, out); 2699 return batch->prepare(buffer, offset, out);
2370 }; 2700 };
@@ -2407,6 +2737,19 @@ private:
2407 context_.counted_dispatch_->emit(cb, job); 2737 context_.counted_dispatch_->emit(cb, job);
2408 }; 2738 };
2409 } 2739 }
2740 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
2741 replay.prepare_quad_indices = [this, &tracker_lock](
2742 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
2743 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
2744 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
2745 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2746 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
2747 scratch_offset, out);
2748 };
2749 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
2750 context_.quad_indices_->emit(cb, job);
2751 };
2752 }
2410 if (context_.depth24_ && !transfer_only) { 2753 if (context_.depth24_ && !transfer_only) {
2411 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, 2754 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
2412 std::vector<Depth24Job>& parts) { 2755 std::vector<Depth24Job>& parts) {
@@ -2449,7 +2792,7 @@ private:
2449 if (result != ReplayResult::success) return result; 2792 if (result != ReplayResult::success) return result;
2450 if (prepared[i].segment_count > UINT32_MAX - segments || 2793 if (prepared[i].segment_count > UINT32_MAX - segments ||
2451 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 2794 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
2452 return ReplayResult::unsupported; 2795 return queue_unsupported(__LINE__);
2453 segments += prepared[i].segment_count; 2796 segments += prepared[i].segment_count;
2454 statistics_segments += prepared[i].statistics_segment_count; 2797 statistics_segments += prepared[i].statistics_segment_count;
2455 has_queries = has_queries || !prepared[i].queries.empty(); 2798 has_queries = has_queries || !prepared[i].queries.empty();
@@ -2469,12 +2812,12 @@ private:
2469 return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS; 2812 return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS;
2470 }; 2813 };
2471 std::shared_ptr<OcclusionSegmentPool> physical, statistics; 2814 std::shared_ptr<OcclusionSegmentPool> physical, statistics;
2472 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; 2815 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return queue_unsupported(__LINE__);
2473 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before 2816 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before
2474 // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). 2817 // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then).
2475 if (statistics_segments && can_resolve_occlusion) { 2818 if (statistics_segments && can_resolve_occlusion) {
2476 if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) 2819 if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics))
2477 return ReplayResult::unsupported; 2820 return queue_unsupported(__LINE__);
2478 for (const auto& list : prepared) 2821 for (const auto& list : prepared)
2479 statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), 2822 statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(),
2480 list.statistics_mesh.end()); 2823 list.statistics_mesh.end());
@@ -2489,7 +2832,7 @@ private:
2489 info.pipelineStatistics = kMeshStatisticsFlags; 2832 info.pipelineStatistics = kMeshStatisticsFlags;
2490 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != 2833 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) !=
2491 VK_SUCCESS) 2834 VK_SUCCESS)
2492 return ReplayResult::unsupported; 2835 return queue_unsupported(__LINE__);
2493 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, 2836 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type,
2494 // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, 2837 // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature,
2495 // or the clipping field of a mesh segment stays 0. 2838 // or the clipping field of a mesh segment stays 0.
@@ -2499,7 +2842,7 @@ private:
2499 primitives.queryCount = statistics_segments; 2842 primitives.queryCount = statistics_segments;
2500 if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, 2843 if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr,
2501 &statistics->primitives_pool) != VK_SUCCESS) 2844 &statistics->primitives_pool) != VK_SUCCESS)
2502 return ReplayResult::unsupported; 2845 return queue_unsupported(__LINE__);
2503 } 2846 }
2504 } 2847 }
2505 } 2848 }
@@ -2519,16 +2862,16 @@ private:
2519 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) { 2862 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) {
2520 if (!occlusion_resolve_) { 2863 if (!occlusion_resolve_) {
2521 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); 2864 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device());
2522 if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; 2865 if (!helper->initialize(occlusion_memory)) return queue_unsupported(__LINE__);
2523 occlusion_resolve_ = std::move(helper); 2866 occlusion_resolve_ = std::move(helper);
2524 } 2867 }
2525 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum, 2868 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum,
2526 queries.needs_sum_binary)) 2869 queries.needs_sum_binary))
2527 return ReplayResult::unsupported; 2870 return queue_unsupported(__LINE__);
2528 } 2871 }
2529 2872
2530 CommandSlot* slot = acquire(); 2873 CommandSlot* slot = acquire();
2531 if (!slot) return ReplayResult::unsupported; 2874 if (!slot) return queue_unsupported(__LINE__);
2532 slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused 2875 slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused
2533 khr_guard.stages.clear(); 2876 khr_guard.stages.clear();
2534 slot->khr_as_queries = std::move(khr_guard.as_queries); 2877 slot->khr_as_queries = std::move(khr_guard.as_queries);
@@ -2557,9 +2900,11 @@ private:
2557 }; 2900 };
2558 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 2901 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
2559 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; 2902 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
2560 if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { 2903 context_.gpu_labels_.begin_record(command_buffer);
2904 if (context_.observe_result(context_.vk.vkBeginCommandBuffer(command_buffer, &begin),
2905 "vkBeginCommandBuffer") != VK_SUCCESS) {
2561 discard(); 2906 discard();
2562 return ReplayResult::unsupported; 2907 return queue_unsupported(__LINE__);
2563 } 2908 }
2564 // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the 2909 // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the
2565 // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier: 2910 // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier:
@@ -2575,7 +2920,8 @@ private:
2575 } 2920 }
2576 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2921 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2577 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 2922 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
2578 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 2923 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
2924 "vkEndCommandBuffer") == VK_SUCCESS;
2579 resource_lock.unlock(); 2925 resource_lock.unlock();
2580 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 2926 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
2581 if (!submitted) discard(); 2927 if (!submitted) discard();
@@ -2589,7 +2935,7 @@ private:
2589 } 2935 }
2590 if (bindless_commit) bindless_commit(submitted); 2936 if (bindless_commit) bindless_commit(submitted);
2591 tracker_lock.unlock(); 2937 tracker_lock.unlock();
2592 return ReplayResult::unsupported; 2938 return queue_unsupported(__LINE__);
2593 } 2939 }
2594 replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; 2940 replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE;
2595 const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); 2941 const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false);
@@ -2612,8 +2958,7 @@ private:
2612 storage_init_seen_ = context_.storage_init_version_; 2958 storage_init_seen_ = context_.storage_init_version_;
2613 } 2959 }
2614 // The set this submission binds may be a new generation whose table another queue's submission uploads: 2960 // The set this submission binds may be a new generation whose table another queue's submission uploads:
2615 // wait for that one, as for the storage images (the table's buffers are used by one queue family only: 2961 // wait for that one, as for the storage images. The table and fallback images share the device's families.
2616 // every D3D12 queue of the device is made in info.queue_family).
2617 if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && 2962 if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ &&
2618 context_.bindless_upload_version_ != bindless_upload_seen_) { 2963 context_.bindless_upload_version_ != bindless_upload_seen_) {
2619 waits_.push_back(context_.bindless_upload_semaphore_); 2964 waits_.push_back(context_.bindless_upload_semaphore_);
@@ -2644,9 +2989,23 @@ private:
2644 bool wrote_readback = false; 2989 bool wrote_readback = false;
2645 VkPipelineStageFlags2 readback_stages = 0; 2990 VkPipelineStageFlags2 readback_stages = 0;
2646 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 2991 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
2992 CheckpointSubmission diagnostics;
2993 PFN_vkCmdSetCheckpointNV checkpoint = nullptr;
2994 if (execute_call) {
2995 auto& fault = *context_.device_fault();
2996 checkpoint = fault.checkpoint_command();
2997 const char* queue_kind = kind_ == QueueKind::direct ? "direct" :
2998 kind_ == QueueKind::compute ? "compute" : "copy";
2999 diagnostics = fault.begin_submission(execute_call, queue_, queue_kind, lists.size());
3000 }
2647 for (std::size_t i = 0; i < lists.size(); ++i) { 3001 for (std::size_t i = 0; i < lists.size(); ++i) {
2648 const auto& list = prepared[i]; 3002 const auto& list = prepared[i];
2649 emit(list, command_buffer, replay, &next_tracker, &open_labels); 3003 if (execute_call && i < diagnostics.lists.size()) {
3004 const CheckpointRecorder recorder{checkpoint, diagnostics, context_.device_fault()->pipeline_names, i};
3005 emit_commands<true>(list, command_buffer, replay, &next_tracker, &open_labels, &recorder);
3006 } else {
3007 emit(list, command_buffer, replay, &next_tracker, &open_labels);
3008 }
2650 wrote_readback |= list.wrote_readback; 3009 wrote_readback |= list.wrote_readback;
2651 readback_stages |= list.readback_src_stages; 3010 readback_stages |= list.readback_src_stages;
2652 } 3011 }
@@ -2681,14 +3040,19 @@ private:
2681 0, 1, &host, 0, nullptr, 0, nullptr); 3040 0, 1, &host, 0, nullptr, 0, nullptr);
2682 } 3041 }
2683 } 3042 }
2684 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 3043 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3044 "vkEndCommandBuffer") == VK_SUCCESS;
2685 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3045 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held
2686 const bool wait_previous = ordered_timestamps && submitted_; 3046 const bool wait_previous = ordered_timestamps && submitted_;
2687 if (wait_previous) { 3047 if (wait_previous) {
2688 waits_.push_back(progress_); 3048 waits_.push_back(progress_);
2689 wait_values_.push_back(submitted_); 3049 wait_values_.push_back(submitted_);
2690 } 3050 }
2691 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3051 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0,
3052 execute_call ? &diagnostics : nullptr);
3053 if (mesh_draws)
3054 std::fprintf(stderr, "[rt] pso-mesh unix_ms=%lld draws=%u submitted=%d\n",
3055 pipeline_profile::unix_ms(), mesh_draws, int(submitted));
2692 if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { 3056 if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) {
2693 // not initialized after all: try again with the next submission 3057 // not initialized after all: try again with the next submission
2694 std::lock_guard lock(context_.storage_mutex_); 3058 std::lock_guard lock(context_.storage_mutex_);
@@ -2720,6 +3084,7 @@ private:
2720 slot->counted_dispatch = std::move(counted_batch); 3084 slot->counted_dispatch = std::move(counted_batch);
2721 queries.commit(); 3085 queries.commit();
2722 slot->segments = std::move(queries.retained); 3086 slot->segments = std::move(queries.retained);
3087 slot->geometry = std::move(geometry);
2723 } else { 3088 } else {
2724 discard(); 3089 discard();
2725 } 3090 }
@@ -2735,7 +3100,7 @@ private:
2735 // the queue (it keeps a single upload obligation). 3100 // the queue (it keeps a single upload obligation).
2736 if (bindless_commit) bindless_commit(submitted); 3101 if (bindless_commit) bindless_commit(submitted);
2737 tracker_lock.unlock(); 3102 tracker_lock.unlock();
2738 return submitted ? ReplayResult::success : ReplayResult::unsupported; 3103 return submitted ? ReplayResult::success : queue_unsupported(__LINE__);
2739 } 3104 }
2740 3105
2741 void marker_now(DebugMarker::Kind kind, const char* label) { 3106 void marker_now(DebugMarker::Kind kind, const char* label) {
@@ -2763,6 +3128,7 @@ private:
2763 enum class Kind : std::uint8_t { batch, signal, marker }; 3128 enum class Kind : std::uint8_t { batch, signal, marker };
2764 Kind kind = Kind::batch; 3129 Kind kind = Kind::batch;
2765 std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues 3130 std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues
3131 std::uint64_t execute_call = 0; // original ExecuteCommandLists call for a held batch
2766 std::vector<VkSemaphore> waits; 3132 std::vector<VkSemaphore> waits;
2767 std::vector<std::uint64_t> wait_values; 3133 std::vector<std::uint64_t> wait_values;
2768 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call 3134 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call
@@ -2847,7 +3213,7 @@ private:
2847 for (const CommandList& list : op.lists) lists.push_back(&list); 3213 for (const CommandList& list : op.lists) lists.push_back(&list);
2848 // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until 3214 // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until
2849 // the batch has been recorded and then, with the fences, until its submission has completed (below). 3215 // the batch has been recorded and then, with the fences, until its submission has completed (below).
2850 const ReplayResult result = execute_now(lists); 3216 const ReplayResult result = execute_now(lists, op.execute_call);
2851 if (result != ReplayResult::success) { 3217 if (result != ReplayResult::success) {
2852 int none = static_cast<int>(ReplayResult::success); 3218 int none = static_cast<int>(ReplayResult::success);
2853 held_failure_.compare_exchange_strong(none, static_cast<int>(result)); 3219 held_failure_.compare_exchange_strong(none, static_cast<int>(result));
@@ -2954,6 +3320,7 @@ private:
2954 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 3320 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
2955 std::vector<KhrInstanceStage> khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime 3321 std::vector<KhrInstanceStage> khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime
2956 std::vector<KhrAsQueryPool> khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime 3322 std::vector<KhrAsQueryPool> khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime
3323 std::vector<VulkanContext::GeometryUpload> geometry;
2957 }; 3324 };
2958 3325
2959 struct PendingBindings { 3326 struct PendingBindings {
@@ -2976,6 +3343,7 @@ private:
2976 auto& vk = context_.vk; 3343 auto& vk = context_.vk;
2977 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 3344 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
2978 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; 3345 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
3346 context_.gpu_labels_.begin_record(command_buffer);
2979 if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { 3347 if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) {
2980 slot->ticket = 0; 3348 slot->ticket = 0;
2981 return false; 3349 return false;
@@ -3071,7 +3439,8 @@ private:
3071 pending_bindings_.push_back(std::move(pending)); 3439 pending_bindings_.push_back(std::move(pending));
3072 { 3440 {
3073 std::lock_guard lock(context_.submit_mutex()); 3441 std::lock_guard lock(context_.submit_mutex());
3074 const auto result = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE); 3442 const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE),
3443 "vkQueueBindSparse");
3075 if (result != VK_SUCCESS) { 3444 if (result != VK_SUCCESS) {
3076 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 3445 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3077 pending_bindings_.pop_back(); 3446 pending_bindings_.pop_back();
@@ -3093,7 +3462,8 @@ private:
3093 std::uint64_t completed() const { 3462 std::uint64_t completed() const {
3094 if (context_.is_device_lost()) return 0; 3463 if (context_.is_device_lost()) return 0;
3095 std::uint64_t done = 0; 3464 std::uint64_t done = 0;
3096 const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); 3465 const VkResult result = context_.observe_result(
3466 context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done), "vkGetSemaphoreCounterValue");
3097 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 3467 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3098 // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. 3468 // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket.
3099 return result == VK_SUCCESS ? done : 0; 3469 return result == VK_SUCCESS ? done : 0;
@@ -3114,6 +3484,7 @@ private:
3114 for (auto& slot : buffers_) { 3484 for (auto& slot : buffers_) {
3115 if (slot.ticket > done) continue; 3485 if (slot.ticket > done) continue;
3116 slot.segments.clear(); 3486 slot.segments.clear();
3487 slot.geometry.clear();
3117 recycle_khr_stages(slot.khr_instances); 3488 recycle_khr_stages(slot.khr_instances);
3118 recycle_khr_as_queries(slot.khr_as_queries); 3489 recycle_khr_as_queries(slot.khr_as_queries);
3119 for (VkEvent event : slot.events) 3490 for (VkEvent event : slot.events)
@@ -3161,7 +3532,8 @@ private:
3161 info.semaphoreCount = 1; 3532 info.semaphoreCount = 1;
3162 info.pSemaphores = &progress_; 3533 info.pSemaphores = &progress_;
3163 info.pValues = &oldest; 3534 info.pValues = &oldest;
3164 return context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs); 3535 return context_.observe_result(context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs),
3536 "vkWaitSemaphores (queue progress)");
3165 } 3537 }
3166 3538
3167 CommandSlot* acquire() { 3539 CommandSlot* acquire() {
@@ -3201,7 +3573,8 @@ private:
3201 return event; 3573 return event;
3202 } 3574 }
3203 3575
3204 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { 3576 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value,
3577 CheckpointSubmission* diagnostics = nullptr) {
3205 if (context_.is_device_lost()) return false; 3578 if (context_.is_device_lost()) return false;
3206 const std::uint64_t ticket = submitted_ + 1; 3579 const std::uint64_t ticket = submitted_ + 1;
3207 if (last_sparse_) { 3580 if (last_sparse_) {
@@ -3250,7 +3623,12 @@ private:
3250 submit.pCommandBuffers = &command_buffer; 3623 submit.pCommandBuffers = &command_buffer;
3251 submit.signalSemaphoreCount = signal_count; 3624 submit.signalSemaphoreCount = signal_count;
3252 submit.pSignalSemaphores = signals; 3625 submit.pSignalSemaphores = signals;
3253 res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); 3626 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss.
3627 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics));
3628 const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer);
3629 res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence),
3630 "vkQueueSubmit");
3631 context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS);
3254 if (res == VK_SUCCESS) { 3632 if (res == VK_SUCCESS) {
3255 context_.record_submit_locked(progress_, ticket); 3633 context_.record_submit_locked(progress_, ticket);
3256 if (signals_fence) context_.holds().signaled(fence, value); 3634 if (signals_fence) context_.holds().signaled(fence, value);
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index cb5b61f65..589cadffd 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -8,11 +8,13 @@
8// 2 the descriptor hash table 1 7 3D r32ui storage images 256 8// 2 the descriptor hash table 1 7 3D r32ui storage images 256
9// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: 9// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each:
10// 4 2D r32ui storage images 1024 storage images by component class 10// 4 2D r32ui storage images 1024 storage images by component class
11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. 11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the first four STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint.
12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). 12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs).
13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. 13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes.
14// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays 14// bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4).
15// from the device's limits instead; the shaders declare runtime arrays, so any count works for them. 15// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the sampled arrays of every
16// single-sample dimension, the samplers and the storage arrays from the device's limits instead; the shaders declare
17// runtime arrays, so any count works for them.
16// 18//
17// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in 19// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in
18// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage 20// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage
@@ -37,12 +39,22 @@
37// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped 39// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped
38// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush. 40// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush.
39// 41//
42// When device-local memory runs out (a title that fills VRAM), a new generation's table goes to HOST_VISIBLE memory
43// instead: slower lookups beat no table. Released generations are kept as spares (at most max_spares) and reused,
44// pool and buffers, by the next replacing flush, so steady churn allocates nothing. If a generation still cannot be
45// made, flush() rewrites the current table in place when every submission that could read it is done, and otherwise
46// degrades: the descriptors are written, the table keeps its last uploaded contents (keys added since find the
47// fallback, index 0; keys rebound since keep their previous index, whose views stay alive; removed indices are not
48// given out again meanwhile) and the change waits for a later flush. A flush never fails the submission for want of
49// memory (last_flush_degraded(), degraded_flushes()).
50//
40// Not thread-safe: the owner serialises calls. 51// Not thread-safe: the owner serialises calls.
41 52
42#ifndef VK_NO_PROTOTYPES 53#ifndef VK_NO_PROTOTYPES
43#define VK_NO_PROTOTYPES 54#define VK_NO_PROTOTYPES
44#endif 55#endif
45#include "descriptor_table.h" 56#include "descriptor_table.h"
57#include "queue_families.h"
46 58
47#include <vulkan/vulkan.h> 59#include <vulkan/vulkan.h>
48 60
@@ -52,12 +64,13 @@
52#include <cstring> 64#include <cstring>
53#include <functional> 65#include <functional>
54#include <unordered_map> 66#include <unordered_map>
67#include <utility>
55#include <vector> 68#include <vector>
56 69
57namespace leonida { 70namespace leonida {
58 71
59// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. 72// The first five dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers.
60enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; 73enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_1d_array, dim_2d_ms, dim_2d_ms_array };
61 74
62// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the 75// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the
63// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). 76// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only).
@@ -70,7 +83,7 @@ struct StorageViews {
70}; 83};
71 84
72namespace bindless { 85namespace bindless {
73inline constexpr std::uint32_t binding_count = 26; 86inline constexpr std::uint32_t binding_count = 29;
74constexpr std::array<std::uint32_t, binding_count> default_counts(); 87constexpr std::array<std::uint32_t, binding_count> default_counts();
75} // namespace bindless 88} // namespace bindless
76 89
@@ -94,10 +107,12 @@ struct Binding {
94inline constexpr std::uint32_t table_binding = 2; 107inline constexpr std::uint32_t table_binding = 2;
95inline constexpr std::uint32_t sampler_binding = 1; 108inline constexpr std::uint32_t sampler_binding = 1;
96inline constexpr std::uint32_t first_ms_binding = 20; 109inline constexpr std::uint32_t first_ms_binding = 20;
110inline constexpr std::uint32_t ms_binding_count = 6;
111inline constexpr std::uint32_t first_1d_array_storage_binding = first_ms_binding + ms_binding_count;
97inline constexpr std::uint32_t no_binding = 0xffffffffu; 112inline constexpr std::uint32_t no_binding = 0xffffffffu;
98 113
99// Indexed by binding number. 114// Indexed by binding number. Keep the literal extent for tools/spirv_metal_set0.py.
100inline constexpr std::array<Binding, 26> bindings = {{ 115inline constexpr std::array<Binding, 29> bindings = {{
101 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, 116 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024},
102 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, 117 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024},
103 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 118 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
@@ -111,6 +126,8 @@ inline constexpr std::array<Binding, 26> bindings = {{
111 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 126 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
112 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 127 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
113 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 128 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
129 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
130 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
114}}; 131}};
115 132
116static_assert(bindings.size() == binding_count); 133static_assert(bindings.size() == binding_count);
@@ -121,8 +138,12 @@ constexpr std::array<std::uint32_t, binding_count> default_counts() {
121 return counts; 138 return counts;
122} 139}
123 140
141constexpr bool ms_binding(std::uint32_t binding) {
142 return binding >= first_ms_binding && binding < first_ms_binding + ms_binding_count;
143}
144
124constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { 145constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) {
125 return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; 146 return !ms_binding(binding) || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT;
126} 147}
127 148
128// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose 149// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose
@@ -131,7 +152,8 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl
131 std::uint32_t resource_limit) { 152 std::uint32_t resource_limit) {
132 const auto& counts = features.counts; 153 const auto& counts = features.counts;
133 std::uint32_t sampled = 0, total = 0; 154 std::uint32_t sampled = 0, total = 0;
134 for (std::uint32_t b = 0; b < first_ms_binding; ++b) { 155 for (std::uint32_t b = 0; b < binding_count; ++b) {
156 if (ms_binding(b)) continue;
135 if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; 157 if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b];
136 if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; 158 if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b];
137 } 159 }
@@ -153,12 +175,13 @@ constexpr bool multisampled(ImageDimension dimension) {
153} 175}
154 176
155constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { 177constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) {
156 constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; 178 constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, no_binding, first_ms_binding, first_ms_binding + 1};
157 return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); 179 return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0);
158} 180}
159 181
160// component_class: 0 = float, 1 = uint, 2 = sint. 182// component_class: 0 = float, 1 = uint, 2 = sint.
161constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { 183constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) {
184 if (dimension == ImageDimension::dim_1d_array) return first_1d_array_storage_binding + component_class;
162 return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; 185 return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class;
163} 186}
164 187
@@ -196,8 +219,13 @@ struct SetLayout {
196}; 219};
197 220
198// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then 221// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then
199// 3-6 MiB (93793 descriptors on an RTX 5070). 222// 5-10 MiB with 153697 descriptors when all MS classes and array bindings reach their limits (an RTX 5070).
200inline constexpr std::uint32_t max_2d_images = 65536; 223inline constexpr std::uint32_t max_2d_images = 65536;
224// The other single-sample dimensions: a title streams far more cube maps and texture arrays (and 1D lookup
225// textures) than the 1024 and 256 of the defaults, each distinct T# of one taking its own index.
226inline constexpr std::uint32_t max_2d_array_images = 16384;
227inline constexpr std::uint32_t max_3d_images = 4096;
228inline constexpr std::uint32_t max_1d_images = 4096;
201inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images 229inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images
202// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can 230// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can
203// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. 231// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set.
@@ -212,10 +240,12 @@ inline constexpr std::uint32_t growth_headroom = 64;
212// standalone samplers do not, though they count in an update-after-bind pool. 240// standalone samplers do not, though they count in an update-after-bind pool.
213// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. 241// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images.
214// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). 242// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off).
215// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says 243// 3. Growth towards the maximums above, in the same order, then the 2D-array, 3D and 1D images, within
216// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. 244// maxPerSetDescriptors. That limit only says what is sure to work (vkGetDescriptorSetLayoutSupport may allow
217// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a 245// more), so it never shrinks step 1.
218// storage view an index past the sampled array. The other bindings keep their default counts. 246// A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never
247// gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256.
248// The other bindings keep their default counts.
219// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: 249// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument:
220// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports 250// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports
221// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. 251// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors.
@@ -243,15 +273,24 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
243 auto& counts = features.counts; 273 auto& counts = features.counts;
244 counts = default_counts(); 274 counts = default_counts();
245 std::uint32_t images = 1, samplers = 1, storage = 1; 275 std::uint32_t images = 1, samplers = 1, storage = 1;
276 std::uint32_t arrays = counts[sampled_binding(ImageDimension::dim_2d_array)];
277 std::uint32_t volumes = counts[sampled_binding(ImageDimension::dim_3d)];
278 std::uint32_t lines = counts[sampled_binding(ImageDimension::dim_1d)];
246 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only 279 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only
247 // take descriptors away. 280 // take descriptors away.
248 const auto apply = [&](bool final) { 281 const auto apply = [&](bool final) {
249 counts[sampled_binding(ImageDimension::dim_2d)] = images; 282 counts[sampled_binding(ImageDimension::dim_2d)] = images;
283 counts[sampled_binding(ImageDimension::dim_2d_array)] = arrays;
284 counts[sampled_binding(ImageDimension::dim_3d)] = volumes;
285 counts[sampled_binding(ImageDimension::dim_1d)] = lines;
250 counts[sampler_binding] = samplers; 286 counts[sampler_binding] = samplers;
251 for (std::uint32_t d = 0; d < 4; ++d) { 287 for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) {
252 const auto dimension = ImageDimension(d); 288 const auto dimension = ImageDimension(d);
289 const auto sampled_at = sampled_binding(dimension);
290 const auto capacity = sampled_at == no_binding ? bindings[storage_binding(dimension, 0)].count
291 : counts[sampled_at];
253 const bool capped = final || dimension != ImageDimension::dim_2d; 292 const bool capped = final || dimension != ImageDimension::dim_2d;
254 const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; 293 const std::uint32_t held = capped ? std::min(storage, capacity) : storage;
255 for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; 294 for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held;
256 if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; 295 if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held;
257 } 296 }
@@ -305,6 +344,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
305 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); 344 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit);
306 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); 345 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit);
307 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); 346 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit);
347 grow(arrays, std::max(arrays, max_2d_array_images), growth_headroom, set_limit);
348 grow(volumes, std::max(volumes, max_3d_images), growth_headroom, set_limit);
349 grow(lines, std::max(lines, max_1d_images), growth_headroom, set_limit);
308 apply(true); 350 apply(true);
309 return full; 351 return full;
310} 352}
@@ -313,14 +355,20 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
313 355
314class BindlessSet { 356class BindlessSet {
315public: 357public:
358 // `descriptor_hash` is the finalizer the shaders of this device probe the table with (descriptor_table.h); it is
359 // handed to the table before its first key is inserted, so every insert, lookup and rehash agrees with them.
316 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, 360 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
317 BindlessFeatures features = {}) 361 BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a,
318 : device_(device), memory_(memory), features_(features) { 362 std::vector<std::uint32_t> families = {})
363 : device_(device), memory_(memory), features_(features), families_(std::move(families)),
364 table_(64, descriptor_hash) {
319 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); 365 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill();
320 } 366 }
321 367
322 ~BindlessSet() { 368 ~BindlessSet() {
323 release_retired(); 369 release_retired();
370 for (Generation& spare : spares_) destroy(spare);
371 spares_.clear();
324 destroy(table_buffers_); 372 destroy(table_buffers_);
325 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); 373 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr);
326 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); 374 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr);
@@ -342,7 +390,8 @@ public:
342 // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those 390 // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those
343 // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. 391 // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers.
344 std::uint32_t image_capacity(ImageDimension dimension) const { 392 std::uint32_t image_capacity(ImageDimension dimension) const {
345 return features_.counts[bindless::sampled_binding(dimension)]; 393 const auto binding = bindless::sampled_binding(dimension);
394 return binding == bindless::no_binding ? storage_capacity(dimension) : features_.counts[binding];
346 } 395 }
347 std::uint32_t storage_capacity(ImageDimension dimension) const { 396 std::uint32_t storage_capacity(ImageDimension dimension) const {
348 return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; 397 return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)];
@@ -401,6 +450,7 @@ public:
401 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, 450 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout,
402 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 451 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) {
403 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; 452 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui;
453 if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0;
404 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; 454 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0;
405 auto& used = image_used_[std::uint32_t(dimension)]; 455 auto& used = image_used_[std::uint32_t(dimension)];
406 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); 456 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension));
@@ -414,16 +464,20 @@ public:
414 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, 464 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout,
415 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 465 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) {
416 const auto& used = image_used_[std::uint32_t(dimension)]; 466 const auto& used = image_used_[std::uint32_t(dimension)];
417 if (index && index < used.size() && used[index]) 467 if (index && index < used.size() && used[index] == in_use)
418 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); 468 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class);
419 } 469 }
420 470
421 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. 471 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first.
472 // While the table has changes the GPU's copy lacks (an erased key may still name the index there), the index is
473 // held until a flush has brought the table up to date (one that did not degrade), so that no new image answers
474 // that key; otherwise it is free at once.
422 void remove_image(ImageDimension dimension, std::uint32_t index) { 475 void remove_image(ImageDimension dimension, std::uint32_t index) {
423 auto& used = image_used_[std::uint32_t(dimension)]; 476 auto& used = image_used_[std::uint32_t(dimension)];
424 if (!index || index >= used.size() || !used[index]) return; 477 if (!index || index >= used.size() || used[index] != in_use) return;
425 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); 478 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0);
426 used[index] = 0; 479 used[index] = table_dirty_ ? held : 0;
480 if (table_dirty_) held_images_.push_back({dimension, index});
427 } 481 }
428 482
429 // 0 when the sampler array is full. 483 // 0 when the sampler array is full.
@@ -434,9 +488,10 @@ public:
434 } 488 }
435 489
436 void remove_sampler(std::uint32_t index) { 490 void remove_sampler(std::uint32_t index) {
437 if (!index || index >= sampler_used_.size() || !sampler_used_[index]) return; 491 if (!index || index >= sampler_used_.size() || sampler_used_[index] != in_use) return;
438 write_sampler(index, fallback_sampler_); 492 write_sampler(index, fallback_sampler_);
439 sampler_used_[index] = 0; 493 sampler_used_[index] = table_dirty_ ? held : 0;
494 if (table_dirty_) held_samplers_.push_back(index);
440 } 495 }
441 496
442 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders 497 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders
@@ -479,7 +534,10 @@ public:
479 void table_upload_result(bool submitted) { 534 void table_upload_result(bool submitted) {
480 if (!upload_in_flight_) return; 535 if (!upload_in_flight_) return;
481 upload_in_flight_ = false; 536 upload_in_flight_ = false;
482 if (submitted) return; 537 if (submitted) {
538 table_on_gpu_ = true; // the current buffers hold a table the GPU was given
539 return;
540 }
483 table_dirty_ = true; 541 table_dirty_ = true;
484 force_full_upload_ = true; 542 force_full_upload_ = true;
485 } 543 }
@@ -488,17 +546,42 @@ public:
488 // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table 546 // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table
489 // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire 547 // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire
490 // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired() 548 // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired()
491 // compares with what has completed. False when the new generation cannot be made: the set then still has the 549 // compares with what has completed.
492 // table as of the last flush. 550 // When the new generation cannot be made (no memory for its buffers or descriptor pool) and `completed_ticket` is
493 bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0) { 551 // given, it is asked what has completed: the generations retired up to there are released (to the spares) and
552 // the generation is tried again; when everything up to `retire_ticket` is done, nothing reads the current table
553 // and it is rewritten in place if it is large enough. Failing both, the flush degrades instead of failing: the
554 // descriptors are written in place, as on a flush that does not replace the table (add_image writes new indices,
555 // which no key of the GPU's table reaches; remove_image writes the fallback, and the index stays held until a
556 // flush that does not degrade), the table keeps what it had, and its changes wait for a later flush
557 // (last_flush_degraded()). False only without a command buffer, when nothing can be recorded.
558 bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0,
559 const std::function<std::uint64_t()>& completed_ticket = {}) {
560 if (!command_buffer) return false;
494 bool replaced = false; 561 bool replaced = false;
495 bool written = true; 562 bool written = true;
496 const bool must_replace = flush_replaces_table(); 563 const bool must_replace = flush_replaces_table();
564 last_flush_degraded_ = false;
497 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced); 565 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced);
566 if (!written && must_replace && completed_ticket) {
567 const std::uint64_t completed = completed_ticket();
568 if (!retired_.empty()) {
569 release_retired(completed);
570 written = upload_table(command_buffer, retire_ticket, replaced);
571 }
572 if (!written && completed >= retire_ticket) written = rewrite_table_in_place(command_buffer);
573 }
498 last_flush_replaced_ = replaced; 574 last_flush_replaced_ = replaced;
499 // The new generation could not be made: the current set is the one running work reads, so its descriptors are 575 // Degrading keeps what the current buffers hold, so only once they hold a table that reached the queue: a
500 // not written in place either. The pending writes and the table's changes stay for the next flush. 576 // first flush under full memory, or one after a failed submission of the only upload, has nothing on the GPU
501 if (!written && must_replace) return false; 577 // (word 0 is the probe mask) and refuses as before (review of #64).
578 if (!written && must_replace && !table_on_gpu_) return false;
579 if (!written && must_replace) {
580 // The current set is the one running work reads, and the table's changes may move or rebind live keys:
581 // they stay for a later flush, and keys added since find the fallback until then.
582 ++degraded_flushes_;
583 last_flush_degraded_ = true;
584 }
502 for (const Pending& pending : pending_) { 585 for (const Pending& pending : pending_) {
503 if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue; 586 if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue;
504 shadow_[pending.binding][pending.index] = pending.info; 587 shadow_[pending.binding][pending.index] = pending.info;
@@ -521,17 +604,29 @@ public:
521 } 604 }
522 pending_.clear(); 605 pending_.clear();
523 pending_slots_.clear(); 606 pending_slots_.clear();
524 return written; 607 if (!last_flush_degraded_) {
608 // The table this flush leaves on the GPU names no removed index any more: they can be given out again.
609 for (const auto& [dimension, index] : held_images_) image_used_[std::uint32_t(dimension)][index] = 0;
610 for (const std::uint32_t index : held_samplers_) sampler_used_[index] = 0;
611 held_images_.clear();
612 held_samplers_.clear();
613 }
614 return true;
525 } 615 }
526 616
527 // Frees the generations (table buffers and descriptor set) that flush() retired with a ticket up to `completed`. 617 // Releases the generations (table buffers and descriptor set) that flush() retired with a ticket up to
528 // The default frees all of them: when nothing submitted before the last flush() still runs. 618 // `completed`: up to max_spares of them, large enough for the table, are kept for the next replacing flush to
619 // reuse; the others are freed. The default releases all of them: when nothing submitted before the last flush()
620 // still runs.
529 void release_retired(std::uint64_t completed = UINT64_MAX) { 621 void release_retired(std::uint64_t completed = UINT64_MAX) {
530 std::size_t kept = 0; 622 std::size_t kept = 0;
531 for (auto& generation : retired_) { 623 for (auto& generation : retired_) {
532 if (generation.ticket <= completed) { 624 if (generation.ticket <= completed) {
533 destroy(generation.buffers); 625 if (spares_.size() < max_spares && generation.pool && generation.buffers.staging.mapped &&
534 if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); 626 generation.buffers.table.size >= table_.size_bytes())
627 spares_.push_back(generation);
628 else
629 destroy(generation);
535 } else { 630 } else {
536 retired_[kept++] = generation; 631 retired_[kept++] = generation;
537 } 632 }
@@ -548,11 +643,32 @@ public:
548 std::uint64_t generations_made() const { return generations_made_; } 643 std::uint64_t generations_made() const { return generations_made_; }
549 std::size_t retired_count() const { return retired_.size(); } 644 std::size_t retired_count() const { return retired_.size(); }
550 645
646 // Released generations kept for reuse, and how many replacing flushes reused one instead of allocating. One: the
647 // current generation and a spare are the two a replacing flush has at its peak anyway (the new one, and the one
648 // retired until its work completes), and a grown table can be large (64 MiB at a million slots).
649 static constexpr std::size_t max_spares = 1;
650 std::size_t spare_count() const { return spares_.size(); }
651 std::uint64_t spares_reused() const { return spares_reused_; }
652 // Flushes that could not make the generation they needed and kept the previous table (see flush()), and whether
653 // the last one did; flushes that rewrote the table in place instead, every submission being done.
654 std::uint64_t degraded_flushes() const { return degraded_flushes_; }
655 bool last_flush_degraded() const { return last_flush_degraded_; }
656 std::uint64_t in_place_rewrites() const { return in_place_rewrites_; }
657 // Table buffers placed in HOST_VISIBLE memory because the DEVICE_LOCAL allocation failed.
658 std::uint64_t table_host_fallbacks() const { return table_host_fallbacks_; }
659 // What the last generation that could not be made failed to get: "table buffer", "staging buffer" or
660 // "descriptor set" (nullptr before any failure), and the Vulkan result of that call.
661 const char* last_failure() const { return last_failure_; }
662 VkResult last_failure_result() const { return last_failure_result_; }
663 // Bytes of the current table buffer (the table grows by doubling its slots: size_bytes() of table()).
664 std::size_t table_buffer_bytes() const { return table_buffers_.table.size; }
665
551private: 666private:
552 struct Functions { 667 struct Functions {
553#define LEONIDA_BINDLESS_FUNCTIONS(X) \ 668#define LEONIDA_BINDLESS_FUNCTIONS(X) \
554 X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ 669 X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \
555 X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) \ 670 X(vkDestroyDescriptorPool) X(vkResetDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \
671 X(vkCreateBuffer) \
556 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ 672 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \
557 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ 673 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \
558 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ 674 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \
@@ -583,6 +699,7 @@ private:
583 VkDeviceMemory memory = VK_NULL_HANDLE; 699 VkDeviceMemory memory = VK_NULL_HANDLE;
584 void* mapped = nullptr; 700 void* mapped = nullptr;
585 std::size_t size = 0; 701 std::size_t size = 0;
702 bool device_local = false; // the memory is DEVICE_LOCAL
586 }; 703 };
587 704
588 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes. 705 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes.
@@ -591,13 +708,23 @@ private:
591 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT 708 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT
592 }; 709 };
593 710
711 struct Generation { // what a replaced table leaves for release_retired()
712 TableBuffers buffers;
713 VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set
714 VkDescriptorSet set = VK_NULL_HANDLE;
715 std::uint64_t ticket = 0;
716 };
717
594 struct Pending { 718 struct Pending {
595 std::uint32_t binding; 719 std::uint32_t binding;
596 std::uint32_t index; 720 std::uint32_t index;
597 VkDescriptorImageInfo info; 721 VkDescriptorImageInfo info;
598 }; 722 };
599 723
600 static constexpr std::uint32_t dimensions = 6, classes = 3; 724 static constexpr std::uint32_t dimensions = 7, classes = 3;
725 // image_used_ and sampler_used_: 0 free, in_use, or held (removed while the table was dirty: free after the next
726 // flush that does not degrade).
727 static constexpr std::uint8_t in_use = 1, held = 2;
601 728
602 // The first free index in [begin, end), marked used; 0 when there is none. 729 // The first free index in [begin, end), marked used; 0 when there is none.
603 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) { 730 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) {
@@ -645,21 +772,35 @@ private:
645 pool_info.maxSets = 1; 772 pool_info.maxSets = 1;
646 pool_info.poolSizeCount = pool_size_count_; 773 pool_info.poolSizeCount = pool_size_count_;
647 pool_info.pPoolSizes = pool_sizes_.data(); 774 pool_info.pPoolSizes = pool_sizes_.data();
648 if (vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool) != VK_SUCCESS) { 775 if (const VkResult result = vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool);
776 result != VK_SUCCESS) {
649 pool = VK_NULL_HANDLE; 777 pool = VK_NULL_HANDLE;
778 note_failure("descriptor set", result);
650 return false; 779 return false;
651 } 780 }
781 if (allocate_set(pool, set)) return true;
782 vk_.vkDestroyDescriptorPool(device_, pool, nullptr);
783 pool = VK_NULL_HANDLE;
784 return false;
785 }
786
787 bool allocate_set(VkDescriptorPool pool, VkDescriptorSet& set) const {
652 VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; 788 VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
653 set_info.descriptorPool = pool; 789 set_info.descriptorPool = pool;
654 set_info.descriptorSetCount = 1; 790 set_info.descriptorSetCount = 1;
655 set_info.pSetLayouts = &layout_; 791 set_info.pSetLayouts = &layout_;
656 if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set) == VK_SUCCESS) return true; 792 const VkResult result = vk_.vkAllocateDescriptorSets(device_, &set_info, &set);
657 vk_.vkDestroyDescriptorPool(device_, pool, nullptr); 793 if (result == VK_SUCCESS) return true;
658 pool = VK_NULL_HANDLE;
659 set = VK_NULL_HANDLE; 794 set = VK_NULL_HANDLE;
795 note_failure("descriptor set", result);
660 return false; 796 return false;
661 } 797 }
662 798
799 void note_failure(const char* what, VkResult result) const {
800 last_failure_ = what;
801 last_failure_result_ = result;
802 }
803
663 // Writes every descriptor written so far (the shadow) into the current set, one update per run of written 804 // Writes every descriptor written so far (the shadow) into the current set, one update per run of written
664 // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows. 805 // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows.
665 void write_shadow() const { 806 void write_shadow() const {
@@ -695,10 +836,11 @@ private:
695 constexpr std::uint32_t ms_type = 3; 836 constexpr std::uint32_t ms_type = 3;
696 constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; 837 constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT};
697 // dimension -> (index into types, view type) 838 // dimension -> (index into types, view type)
698 constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; 839 constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, 2, ms_type, ms_type};
699 constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 840 constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY,
700 VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, 841 VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D,
701 VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; 842 VK_IMAGE_VIEW_TYPE_1D_ARRAY,
843 VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY};
702 for (std::uint32_t t = 0; t < std::size(types); ++t) { 844 for (std::uint32_t t = 0; t < std::size(types); ++t) {
703 for (std::uint32_t c = 0; c < classes; ++c) { 845 for (std::uint32_t c = 0; c < classes; ++c) {
704 if (t == ms_type && !supports_ms_class(c)) continue; 846 if (t == ms_type && !supports_ms_class(c)) continue;
@@ -713,6 +855,7 @@ private:
713 if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; 855 if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
714 if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; 856 if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
715 FallbackImage& image = fallback_images_[t * classes + c]; 857 FallbackImage& image = fallback_images_[t * classes + c];
858 share_across_queue_families(info, families_);
716 if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; 859 if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false;
717 VkMemoryRequirements requirements{}; 860 VkMemoryRequirements requirements{};
718 vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); 861 vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements);
@@ -737,8 +880,9 @@ private:
737 VkImageView view = VK_NULL_HANDLE; 880 VkImageView view = VK_NULL_HANDLE;
738 if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; 881 if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false;
739 fallback_views_.push_back(view); 882 fallback_views_.push_back(view);
740 if (c == 0 || bindless::multisampled(dimension)) 883 const auto sampled_at = bindless::sampled_binding(dimension, c);
741 fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; 884 if (sampled_at != bindless::no_binding && (c == 0 || bindless::multisampled(dimension)))
885 fallback_by_binding_[sampled_at] = view;
742 const auto storage_at = bindless::storage_binding(dimension, c); 886 const auto storage_at = bindless::storage_binding(dimension, c);
743 if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; 887 if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view;
744 const auto r32ui_at = bindless::r32ui_binding(dimension); 888 const auto r32ui_at = bindless::r32ui_binding(dimension);
@@ -753,36 +897,54 @@ private:
753 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; 897 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS;
754 } 898 }
755 899
756 bool create(TableBuffer& out, std::size_t bytes, bool device_local, bool* got_device_local = nullptr) const { 900 // device_local: the table (DEVICE_LOCAL, else HOST_VISIBLE when the device has no such type or that heap is out
901 // of memory); otherwise the mapped staging buffer (HOST_VISIBLE | HOST_COHERENT).
902 bool create(TableBuffer& out, std::size_t bytes, bool device_local) {
903 constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
904 const char* what = device_local ? "table buffer" : "staging buffer";
757 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 905 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
758 info.size = bytes; 906 info.size = bytes;
759 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | 907 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
760 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); 908 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
761 TableBuffer made; 909 TableBuffer made;
762 made.size = bytes; 910 made.size = bytes;
763 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; 911 share_across_queue_families(info, families_);
912 if (const VkResult result = vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer); result != VK_SUCCESS) {
913 made.buffer = VK_NULL_HANDLE;
914 note_failure(what, result);
915 return false;
916 }
764 VkMemoryRequirements requirements{}; 917 VkMemoryRequirements requirements{};
765 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); 918 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements);
766 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; 919 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
767 allocation.allocationSize = requirements.size; 920 allocation.allocationSize = requirements.size;
768 allocation.memoryTypeIndex = 921 const auto allocate = [&](std::uint32_t type) {
769 device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) 922 if (type == 0xffffffffu) return VK_ERROR_OUT_OF_DEVICE_MEMORY;
770 : memory_type(requirements.memoryTypeBits, 923 allocation.memoryTypeIndex = type;
771 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 924 const VkResult result = vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory);
772 if (device_local && allocation.memoryTypeIndex == 0xffffffffu) 925 if (result != VK_SUCCESS) made.memory = VK_NULL_HANDLE;
773 allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, 926 return result;
774 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | 927 };
775 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 928 const std::uint32_t local = device_local
776 if (got_device_local) 929 ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
777 *got_device_local = allocation.memoryTypeIndex != 0xffffffffu && 930 : 0xffffffffu;
778 (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags & 931 VkResult result = device_local ? allocate(local) : allocate(memory_type(requirements.memoryTypeBits, host));
932 if (result != VK_SUCCESS && device_local) {
933 const std::uint32_t fallback = memory_type(requirements.memoryTypeBits, host);
934 if (fallback != local) {
935 result = allocate(fallback);
936 if (result == VK_SUCCESS && local != 0xffffffffu) ++table_host_fallbacks_;
937 }
938 }
939 if (result == VK_SUCCESS) {
940 made.device_local = (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags &
779 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; 941 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0;
780 bool ready = allocation.memoryTypeIndex != 0xffffffffu && 942 result = vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0);
781 vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && 943 }
782 vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS; 944 if (result == VK_SUCCESS && !device_local)
783 if (ready && !device_local) 945 result = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped);
784 ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; 946 if (result != VK_SUCCESS) {
785 if (!ready) { 947 note_failure(what, result);
786 destroy(made); 948 destroy(made);
787 return false; 949 return false;
788 } 950 }
@@ -801,17 +963,55 @@ private:
801 destroy(buffers.table); 963 destroy(buffers.table);
802 } 964 }
803 965
966 void destroy(Generation& generation) const {
967 destroy(generation.buffers);
968 if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); // frees the set
969 generation.pool = VK_NULL_HANDLE;
970 generation.set = VK_NULL_HANDLE;
971 }
972
973 // A generation for a table of `bytes`: a spare when one is large enough (its pool reset for a fresh set), else
974 // new buffers and a new pool. Spares too small for the table are freed: the table never shrinks.
975 bool make_generation(std::size_t bytes, TableBuffers& buffers, VkDescriptorPool& pool, VkDescriptorSet& set) {
976 std::size_t kept = 0;
977 bool found = false;
978 for (Generation& spare : spares_) {
979 if (spare.buffers.table.size < bytes || spare.buffers.staging.size < bytes) {
980 destroy(spare);
981 continue;
982 }
983 if (!found && vk_.vkResetDescriptorPool(device_, spare.pool, 0) == VK_SUCCESS &&
984 allocate_set(spare.pool, set)) {
985 buffers = spare.buffers;
986 pool = spare.pool;
987 found = true;
988 ++spares_reused_;
989 continue;
990 }
991 spares_[kept++] = spare;
992 }
993 spares_.resize(kept);
994 if (found) return true;
995 TableBuffers made;
996 if (!create(made.table, bytes, true) || !create(made.staging, bytes, false) || !make_set(pool, set)) {
997 destroy(made);
998 return false;
999 }
1000 buffers = made;
1001 return true;
1002 }
1003
804 bool create_table_buffers() { 1004 bool create_table_buffers() {
805 const std::size_t bytes = table_.size_bytes(); 1005 const std::size_t bytes = table_.size_bytes();
806 TableBuffers made; 1006 TableBuffers made;
807 bool device_local = false; 1007 if (!create(made.table, bytes, true) || !create(made.staging, bytes, false)) {
808 if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) {
809 destroy(made); 1008 destroy(made);
810 return false; 1009 return false;
811 } 1010 }
812 table_buffers_ = made; 1011 table_buffers_ = made;
813 table_device_local_ = device_local; 1012 table_device_local_ = made.table.device_local;
814 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it 1013 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it
1014 table_on_gpu_ = false;
815 table_dirty_ = existing_entries_changed_ = false; 1015 table_dirty_ = existing_entries_changed_ = false;
816 return true; 1016 return true;
817 } 1017 }
@@ -829,15 +1029,11 @@ private:
829 TableBuffers larger; 1029 TableBuffers larger;
830 VkDescriptorPool pool = VK_NULL_HANDLE; 1030 VkDescriptorPool pool = VK_NULL_HANDLE;
831 VkDescriptorSet set = VK_NULL_HANDLE; 1031 VkDescriptorSet set = VK_NULL_HANDLE;
832 bool device_local = false; 1032 if (!make_generation(bytes, larger, pool, set)) return false;
833 if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false) || 1033 table_device_local_ = larger.table.device_local;
834 !make_set(pool, set)) {
835 destroy(larger);
836 return false;
837 }
838 table_device_local_ = device_local;
839 retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); 1034 retired_.push_back({table_buffers_, pool_, set_, retire_ticket});
840 table_buffers_ = larger; 1035 table_buffers_ = larger;
1036 table_on_gpu_ = false; // until this generation's upload is submitted (table_upload_result)
841 pool_ = pool; 1037 pool_ = pool;
842 set_ = set; 1038 set_ = set;
843 write_table_binding(table_buffers_.table.buffer); 1039 write_table_binding(table_buffers_.table.buffer);
@@ -893,6 +1089,25 @@ private:
893 return true; 1089 return true;
894 } 1090 }
895 1091
1092 // The whole table into the current generation's buffers, for a flush whose new generation could not be made,
1093 // once every submission that could read the current table is done (flush()). False when the table outgrew them.
1094 bool rewrite_table_in_place(VkCommandBuffer command_buffer) {
1095 const std::size_t bytes = table_.size_bytes();
1096 if (bytes > table_buffers_.table.size || bytes > table_buffers_.staging.size || !table_buffers_.staging.mapped)
1097 return false;
1098 table_.take_changes(); // all of it goes
1099 // Nothing still runs that copies from the staging buffer or reads the table.
1100 table_.write_to_buffer(table_buffers_.staging.mapped);
1101 copy_table_range(command_buffer, 0, bytes);
1102 record_table_barrier(command_buffer);
1103 upload_in_flight_ = true;
1104 table_dirty_ = existing_entries_changed_ = false;
1105 table_uploaded_ = true;
1106 force_full_upload_ = false;
1107 ++in_place_rewrites_;
1108 return true;
1109 }
1110
896 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging 1111 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging
897 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy. 1112 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy.
898 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data, 1113 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data,
@@ -998,8 +1213,9 @@ private:
998 return; 1213 return;
999 } 1214 }
1000 const std::uint32_t sampled_at = bindless::sampled_binding(dimension); 1215 const std::uint32_t sampled_at = bindless::sampled_binding(dimension);
1001 queue(sampled_at, index, 1216 if (sampled_at != bindless::no_binding)
1002 sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); 1217 queue(sampled_at, index,
1218 sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at));
1003 const auto store = [&](std::uint32_t binding, VkImageView view) { 1219 const auto store = [&](std::uint32_t binding, VkImageView view) {
1004 if (binding == bindless::no_binding || index >= features_.counts[binding]) return; 1220 if (binding == bindless::no_binding || index >= features_.counts[binding]) return;
1005 queue(binding, index, 1221 queue(binding, index,
@@ -1014,6 +1230,7 @@ private:
1014 VkDevice device_; 1230 VkDevice device_;
1015 VkPhysicalDeviceMemoryProperties memory_; 1231 VkPhysicalDeviceMemoryProperties memory_;
1016 BindlessFeatures features_; 1232 BindlessFeatures features_;
1233 std::vector<std::uint32_t> families_;
1017 Functions vk_; 1234 Functions vk_;
1018 bool ok_ = false; 1235 bool ok_ = false;
1019 VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; 1236 VkDescriptorSetLayout layout_ = VK_NULL_HANDLE;
@@ -1026,25 +1243,30 @@ private:
1026 bool fallbacks_ready_ = false; 1243 bool fallbacks_ready_ = false;
1027 std::array<std::vector<std::uint8_t>, dimensions> image_used_; 1244 std::array<std::vector<std::uint8_t>, dimensions> image_used_;
1028 std::vector<std::uint8_t> sampler_used_; 1245 std::vector<std::uint8_t> sampler_used_;
1246 std::vector<std::pair<ImageDimension, std::uint32_t>> held_images_; // removed, not yet free (remove_image)
1247 std::vector<std::uint32_t> held_samplers_;
1029 std::vector<Pending> pending_; 1248 std::vector<Pending> pending_;
1030 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_ 1249 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_
1031 DescriptorTable table_{64}; 1250 DescriptorTable table_; // 64 slots, and the device's hash kind, from the constructor
1032 TableBuffers table_buffers_; 1251 TableBuffers table_buffers_;
1033 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table 1252 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table
1253 bool table_on_gpu_ = false; // an upload into the current table buffers reached the queue (degrading is safe)
1034 bool table_device_local_ = false; 1254 bool table_device_local_ = false;
1035 bool table_dirty_ = false; // the table differs from the buffer 1255 bool table_dirty_ = false; // the table differs from the buffer
1036 bool existing_entries_changed_ = false; // ... and not only by entries added 1256 bool existing_entries_changed_ = false; // ... and not only by entries added
1037 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue 1257 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue
1038 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush 1258 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush
1039 struct Generation { // what a replaced table leaves for release_retired()
1040 TableBuffers buffers;
1041 VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set
1042 VkDescriptorSet set = VK_NULL_HANDLE;
1043 std::uint64_t ticket = 0;
1044 };
1045 std::vector<Generation> retired_; 1259 std::vector<Generation> retired_;
1260 std::vector<Generation> spares_; // released generations kept for reuse (release_retired)
1046 std::uint64_t generations_made_ = 0; 1261 std::uint64_t generations_made_ = 0;
1047 bool last_flush_replaced_ = false; 1262 bool last_flush_replaced_ = false;
1263 bool last_flush_degraded_ = false;
1264 std::uint64_t spares_reused_ = 0;
1265 std::uint64_t degraded_flushes_ = 0;
1266 std::uint64_t in_place_rewrites_ = 0;
1267 std::uint64_t table_host_fallbacks_ = 0;
1268 mutable const char* last_failure_ = nullptr;
1269 mutable VkResult last_failure_result_ = VK_SUCCESS;
1048 std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{}; 1270 std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{};
1049 std::uint32_t pool_size_count_ = 0; 1271 std::uint32_t pool_size_count_ = 0;
1050 // Every descriptor written to the set (the table's binding aside), to fill the next generation's set. 1272 // Every descriptor written to the set (the table's binding aside), to fill the next generation's set.
diff --git a/runtime/src/vulkan_depth24.h b/runtime/src/vulkan_depth24.h
index 988b79d9f..a46177dd4 100644
--- a/runtime/src/vulkan_depth24.h
+++ b/runtime/src/vulkan_depth24.h
@@ -12,6 +12,8 @@
12#endif 12#endif
13#include <vulkan/vulkan.h> 13#include <vulkan/vulkan.h>
14 14
15#include "vulkan_device_fault.h"
16
15#include <algorithm> 17#include <algorithm>
16#include <cstdint> 18#include <cstdint>
17#include <functional> 19#include <functional>
@@ -29,14 +31,15 @@ public:
29 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>; 31 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>;
30 32
31 // `max_range`: the device's maxStorageBufferRange; a copy is split into dispatches that stay inside it. 33 // `max_range`: the device's maxStorageBufferRange; a copy is split into dispatches that stay inside it.
32 Depth24Converter(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, std::uint64_t max_range = 1u << 27) 34 Depth24Converter(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate,
33 : device_(device), allocate_(std::move(allocate)), max_range_(max_range) { 35 std::uint64_t max_range = 1u << 27, DeviceFaultDiagnostics* diagnostics = nullptr)
36 : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), max_range_(max_range) {
34 loaded_ = vk_.load(get, device); 37 loaded_ = vk_.load(get, device);
35 } 38 }
36 39
37 ~Depth24Converter() { 40 ~Depth24Converter() {
38 if (!loaded_) return; 41 if (!loaded_) return;
39 vk_.vkDeviceWaitIdle(device_); 42 DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle");
40 release(current_); 43 release(current_);
41 for (auto& batch : retired_) release(batch); 44 for (auto& batch : retired_) release(batch);
42 for (auto& chunk : spare_) destroy(chunk); 45 for (auto& chunk : spare_) destroy(chunk);
@@ -146,7 +149,9 @@ public:
146 if (retired_[i].ticket != 0) { 149 if (retired_[i].ticket != 0) {
147 std::uint64_t done = 0; 150 std::uint64_t done = 0;
148 if (!retired_[i].timeline || 151 if (!retired_[i].timeline ||
149 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS || 152 DeviceFaultDiagnostics::observe(diagnostics_,
153 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done),
154 "vkGetSemaphoreCounterValue (scratch)") != VK_SUCCESS ||
150 done < retired_[i].ticket) { 155 done < retired_[i].ticket) {
151 ++i; 156 ++i;
152 continue; 157 continue;
@@ -354,6 +359,7 @@ private:
354 } 359 }
355 360
356 VkDevice device_; 361 VkDevice device_;
362 DeviceFaultDiagnostics* diagnostics_;
357 Allocate allocate_; 363 Allocate allocate_;
358 std::uint64_t max_range_; 364 std::uint64_t max_range_;
359 Functions vk_; 365 Functions vk_;
diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h
new file mode 100644
index 000000000..f51edb360
--- /dev/null
+++ b/runtime/src/vulkan_device_fault.h
@@ -0,0 +1,429 @@
1#pragma once
2
3#include <vulkan/vulkan.h>
4
5#include <algorithm>
6#include <array>
7#include <atomic>
8#include <chrono>
9#include <cinttypes>
10#include <cstddef>
11#include <cstdint>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <mutex>
16#include <span>
17#include <unordered_map>
18#include <utility>
19#include <vector>
20
21namespace leonida {
22
23struct DeviceFaultExtensions {
24 bool fault = false;
25 bool checkpoints = false;
26 bool diagnostics_config = false;
27};
28
29// Owns the feature structures until vkCreateDevice returns.
30struct DeviceFaultFeatures {
31 VkPhysicalDeviceFaultFeaturesEXT fault{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT};
32 VkPhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics{
33 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV};
34 VkDeviceDiagnosticsConfigCreateInfoNV config{VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV};
35
36 DeviceFaultExtensions enable(VkPhysicalDevice physical, PFN_vkGetPhysicalDeviceFeatures2 query,
37 std::span<const VkExtensionProperties> advertised,
38 std::vector<const char*>& extensions, VkDeviceCreateInfo& device) {
39 const auto has = [&](const char* name) {
40 return std::any_of(advertised.begin(), advertised.end(), [name](const auto& ext) {
41 return std::strcmp(ext.extensionName, name) == 0;
42 });
43 };
44 const bool has_fault = has(VK_EXT_DEVICE_FAULT_EXTENSION_NAME);
45 const bool has_config = has(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
46 if (has_fault || has_config) {
47 diagnostics.pNext = nullptr;
48 fault.pNext = has_config ? &diagnostics : nullptr;
49 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
50 features.pNext = has_fault ? static_cast<void*>(&fault) : static_cast<void*>(&diagnostics);
51 query(physical, &features);
52 }
53 const DeviceFaultExtensions enabled{has_fault && fault.deviceFault == VK_TRUE,
54 has(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME),
55 has_config && diagnostics.diagnosticsConfig == VK_TRUE};
56 if (enabled.fault) {
57 extensions.push_back(VK_EXT_DEVICE_FAULT_EXTENSION_NAME);
58 fault.pNext = const_cast<void*>(device.pNext);
59 device.pNext = &fault;
60 }
61 if (enabled.checkpoints) extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME);
62 if (enabled.diagnostics_config) {
63 extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
64 diagnostics.pNext = const_cast<void*>(device.pNext);
65 config.pNext = &diagnostics;
66 config.flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV |
67 VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV |
68 VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV;
69 device.pNext = &config;
70 }
71 return enabled;
72 }
73};
74
75enum class CheckpointKind : std::uint8_t { draw = 1, dispatch, copy, resolve, clear };
76
77struct CheckpointMarker {
78 static constexpr std::uint32_t max_list = 0xff;
79 static constexpr std::uint32_t max_command = 0x1ffff;
80 static constexpr std::uint64_t tag = 0xa;
81
82 std::uint32_t submission = 0;
83 std::uint32_t list = 0;
84 std::uint32_t command = 0;
85 CheckpointKind kind{};
86
87 // Vulkan treats the value as an opaque pointer. The runtime never dereferences it.
88 static constexpr std::uintptr_t encode(std::uint32_t submission, std::size_t list, std::size_t command,
89 CheckpointKind kind) {
90 if (sizeof(void*) < 8 || !submission || list > max_list || command > max_command) return 0;
91 return static_cast<std::uintptr_t>((tag << 60) | (std::uint64_t{submission} << 28) |
92 (std::uint64_t{list} << 20) | (std::uint64_t{command} << 3) |
93 static_cast<std::uint8_t>(kind));
94 }
95
96 static constexpr CheckpointMarker decode(std::uintptr_t marker) {
97 const std::uint64_t bits = marker;
98 const auto kind = static_cast<CheckpointKind>(bits & 7);
99 if ((bits >> 60) != tag || kind < CheckpointKind::draw || kind > CheckpointKind::clear) return {};
100 return {static_cast<std::uint32_t>(bits >> 28), static_cast<std::uint32_t>((bits >> 20) & max_list),
101 static_cast<std::uint32_t>((bits >> 3) & max_command), kind};
102 }
103
104 const char* kind_name() const {
105 switch (kind) {
106 case CheckpointKind::draw: return "draw";
107 case CheckpointKind::dispatch: return "dispatch";
108 case CheckpointKind::copy: return "copy";
109 case CheckpointKind::resolve: return "resolve";
110 case CheckpointKind::clear: return "clear";
111 default: return "unknown";
112 }
113 }
114};
115
116using CheckpointShaders = std::array<const char*, 3>; // Immutable ShaderLibrary names, valid until context teardown.
117
118struct CheckpointPipeline {
119 VkPipeline handle = VK_NULL_HANDLE;
120 std::uintptr_t id = 0;
121 CheckpointShaders shaders{};
122};
123
124struct CheckpointList {
125 struct ShaderChange {
126 std::uint32_t command;
127 CheckpointPipeline pipeline;
128 };
129 std::vector<ShaderChange> shaders;
130};
131
132// CPU record of work handed to vkQueueSubmit. A driver checkpoint can identify which
133// entry it reached; on drivers without checkpoints these remain submitted candidates.
134struct CheckpointDispatch {
135 std::uint64_t execute_call;
136 VkQueue queue;
137 const char* queue_kind;
138 std::size_t list, command;
139 const char* shader;
140 std::array<std::uint32_t, 3> groups;
141 std::uintptr_t argument_buffer, count_buffer;
142 std::uint64_t argument_offset, count_offset;
143 std::uint32_t max_count, stride;
144 std::array<std::uint32_t, 32> roots;
145 bool indirect;
146};
147
148struct CheckpointSubmission {
149 std::uint32_t sequence = 0;
150 std::uint64_t execute_call = 0;
151 VkQueue queue = VK_NULL_HANDLE;
152 const char* queue_kind = nullptr;
153 std::size_t list_count = 0;
154 std::vector<CheckpointList> lists;
155 std::vector<CheckpointDispatch> dispatches;
156 std::size_t dispatch_count = 0;
157 static constexpr std::size_t dispatch_limit = 64;
158
159 void append_dispatch(CheckpointDispatch d) {
160 if (dispatches.size() < dispatch_limit) dispatches.push_back(d);
161 else dispatches[dispatch_count % dispatch_limit] = d;
162 ++dispatch_count;
163 }
164};
165
166struct CheckpointRecorder {
167 PFN_vkCmdSetCheckpointNV set;
168 CheckpointSubmission& submission;
169 const std::unordered_map<std::uintptr_t, CheckpointShaders>& pipeline_names;
170 std::size_t list;
171
172 void record(VkCommandBuffer buffer, std::size_t command, CheckpointKind kind,
173 VkPipeline pipeline = VK_NULL_HANDLE, std::uintptr_t id = 0) const {
174 if (!set) return;
175 const auto marker = CheckpointMarker::encode(submission.sequence, list, command, kind);
176 if (!marker) return;
177 if (kind == CheckpointKind::draw || kind == CheckpointKind::dispatch) {
178 auto& shaders = submission.lists[list].shaders;
179 if (shaders.empty() || shaders.back().pipeline.handle != pipeline || shaders.back().pipeline.id != id) {
180 const auto names = pipeline_names.find(id);
181 shaders.push_back({static_cast<std::uint32_t>(command),
182 {pipeline, id, names != pipeline_names.end() ? names->second : CheckpointShaders{}}});
183 }
184 }
185 set(buffer, reinterpret_cast<const void*>(marker));
186 }
187
188 void dispatch(VkCommandBuffer buffer, std::size_t command, VkPipeline pipeline, std::uintptr_t id,
189 const std::array<std::uint32_t, 32>& roots, std::array<std::uint32_t, 3> groups,
190 bool indirect = false, std::uintptr_t args = 0, std::uint64_t offset = 0,
191 std::uintptr_t count = 0, std::uint64_t count_offset = 0,
192 std::uint32_t max_count = 0, std::uint32_t stride = 0) const {
193 const auto names = pipeline_names.find(id);
194 submission.append_dispatch({submission.execute_call, submission.queue, submission.queue_kind, list, command,
195 names != pipeline_names.end() ? names->second[0] : nullptr, groups, args, count,
196 offset, count_offset, max_count, stride, roots, indirect});
197 record(buffer, command, CheckpointKind::dispatch, pipeline, id);
198 }
199};
200
201// A D3D fence may stay unsignalled by design. Only queue retirement tickets represent
202// work that actually reached vkQueueSubmit.
203class SubmissionProgressWatch {
204public:
205 using Clock = std::chrono::steady_clock;
206 enum class State { idle, pending, submit_lock_busy };
207
208 bool sample(State state, std::uint64_t retired, Clock::time_point now) {
209 if (state == State::idle || state != state_ || retired != retired_) {
210 state_ = state;
211 retired_ = retired;
212 since_ = now;
213 reported_ = false;
214 return false;
215 }
216 if (reported_ || now - since_ < std::chrono::seconds(15)) return false;
217 reported_ = true;
218 return true;
219 }
220
221private:
222 State state_ = State::idle;
223 std::uint64_t retired_ = 0;
224 Clock::time_point since_{};
225 bool reported_ = false;
226};
227
228class DeviceFaultDiagnostics {
229public:
230 DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled)
231 : device_(device) {
232#define LEONIDA_FAULT_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name))
233 if (enabled.fault) LEONIDA_FAULT_LOAD(vkGetDeviceFaultInfoEXT);
234 if (enabled.checkpoints) {
235 LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV);
236 LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV);
237 }
238#undef LEONIDA_FAULT_LOAD
239 std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n",
240 vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable",
241 enabled.diagnostics_config ? "on" : "unavailable");
242 }
243
244 PFN_vkCmdSetCheckpointNV checkpoint_command() const {
245 return sizeof(void*) >= 8 && vkGetQueueCheckpointDataNV ? vkCmdSetCheckpointNV : nullptr;
246 }
247
248 void add_queue(VkQueue queue) {
249 if (!queue || !vkGetQueueCheckpointDataNV) return;
250 std::lock_guard lock(mutex_);
251 if (std::find(queues_.begin(), queues_.end(), queue) == queues_.end()) queues_.push_back(queue);
252 }
253
254 std::uint64_t next_execute_call() { return ++execute_calls_; }
255
256 // Accessed under the context's resource lock. Reports read the names copied into the ring instead.
257 std::unordered_map<std::uintptr_t, CheckpointShaders> pipeline_names;
258
259 // Called under the context's tracker lock, in replay order.
260 CheckpointSubmission begin_submission(std::uint64_t call, VkQueue queue, const char* kind, std::size_t lists) {
261 if (!++sequence_) ++sequence_; // 0 is reserved for invalid markers
262 return {sequence_, call, queue, kind, lists,
263 std::vector<CheckpointList>(std::min(lists, std::size_t{CheckpointMarker::max_list} + 1))};
264 }
265
266 void publish(CheckpointSubmission&& submission) {
267 std::lock_guard lock(mutex_);
268 for (std::size_t i = submission.dispatch_count - submission.dispatches.size(); i < submission.dispatch_count; ++i)
269 dispatches_[dispatch_count_++ % dispatches_.size()] = submission.dispatches[i % submission.dispatch_limit];
270 submission.dispatches.clear();
271 recent_[submission.sequence % recent_.size()] = std::move(submission);
272 }
273
274 static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept {
275 if (result == VK_ERROR_DEVICE_LOST && diagnostics) diagnostics->report(operation);
276 return result;
277 }
278
279 void report_stall(const char* reason, std::uint64_t submitted, std::uint64_t retired) {
280 std::fprintf(stderr, "[rt] device-stall: %s for 15 s; submitted ticket %" PRIu64
281 ", last observed retired ticket %" PRIu64 "\n", reason, submitted, retired);
282 // NV checkpoints and EXT fault data require a lost device. The CPU ring is valid at any time.
283 dump_dispatches();
284 }
285
286private:
287 void dump_dispatches() {
288 std::lock_guard lock(mutex_);
289 const auto n = std::min(dispatch_count_, dispatches_.size());
290 for (std::size_t i = dispatch_count_ - n; i < dispatch_count_; ++i) {
291 const auto& d = dispatches_[i % dispatches_.size()];
292 std::fprintf(stderr, "[rt] device-fault: submitted dispatch seq=%zu execute=%" PRIu64
293 " queue=%p (%s) list=%zu command=%zu shader=%s ", i + 1, d.execute_call,
294 static_cast<void*>(d.queue), d.queue_kind, d.list, d.command, d.shader ? d.shader : "-");
295 if (d.indirect)
296 std::fprintf(stderr, "indirect args=0x%" PRIxPTR "+0x%" PRIx64 " count=0x%" PRIxPTR
297 "+0x%" PRIx64 " max=%u stride=%u", d.argument_buffer, d.argument_offset,
298 d.count_buffer, d.count_offset, d.max_count, d.stride);
299 else std::fprintf(stderr, "groups=%u,%u,%u", d.groups[0], d.groups[1], d.groups[2]);
300 if (include_roots_) {
301 std::fputs(" roots=", stderr);
302 for (auto word : d.roots) std::fprintf(stderr, "%08x ", word);
303 }
304 std::fputc('\n', stderr);
305 }
306 }
307
308 void report(const char* operation) noexcept {
309 if (reported_.exchange(true, std::memory_order_relaxed)) return;
310 std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation);
311 dump_dispatches();
312 try {
313 if (vkGetDeviceFaultInfoEXT) report_fault();
314 } catch (...) {
315 std::fprintf(stderr, "[rt] device-fault: fault info collection failed\n");
316 }
317 try {
318 std::lock_guard lock(mutex_);
319 for (VkQueue queue : queues_) report_queue(queue);
320 } catch (...) {
321 std::fprintf(stderr, "[rt] device-fault: checkpoint collection failed\n");
322 }
323 }
324
325 void report_fault() const {
326 VkDeviceFaultCountsEXT counts{VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT};
327 VkResult result = vkGetDeviceFaultInfoEXT(device_, &counts, nullptr);
328 if (result != VK_SUCCESS) {
329 std::fprintf(stderr, "[rt] device-fault: vkGetDeviceFaultInfoEXT counts failed (%d)\n", int(result));
330 return;
331 }
332 std::fprintf(stderr, "[rt] device-fault: vendor binary size %" PRIu64 " bytes\n", counts.vendorBinarySize);
333 std::vector<VkDeviceFaultAddressInfoEXT> addresses(counts.addressInfoCount);
334 std::vector<VkDeviceFaultVendorInfoEXT> vendors(counts.vendorInfoCount);
335 std::vector<std::byte> binary;
336 // Keep collecting addresses and vendor records if the crash binary cannot be allocated.
337 try {
338 if (counts.vendorBinarySize <= binary.max_size())
339 binary.resize(static_cast<std::size_t>(counts.vendorBinarySize));
340 } catch (...) {
341 }
342 counts.vendorBinarySize = binary.size();
343 VkDeviceFaultInfoEXT fault{VK_STRUCTURE_TYPE_DEVICE_FAULT_INFO_EXT};
344 fault.pAddressInfos = addresses.data();
345 fault.pVendorInfos = vendors.data();
346 fault.pVendorBinaryData = binary.data();
347 result = vkGetDeviceFaultInfoEXT(device_, &counts, &fault);
348 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
349 std::fprintf(stderr, "[rt] device-fault: vkGetDeviceFaultInfoEXT data failed (%d)\n", int(result));
350 return;
351 }
352 std::fprintf(stderr, "[rt] device-fault: description: %.*s%s\n", int(sizeof(fault.description)),
353 fault.description, result == VK_INCOMPLETE ? " (partial report)" : "");
354 for (std::size_t i = 0; i < counts.addressInfoCount; ++i) {
355 const auto& address = addresses[i];
356 std::fprintf(stderr, "[rt] device-fault: address[%zu] type=%d address=0x%" PRIx64
357 " precision=%" PRIu64 "\n",
358 i, int(address.addressType), address.reportedAddress, address.addressPrecision);
359 }
360 for (std::size_t i = 0; i < counts.vendorInfoCount; ++i) {
361 const auto& vendor = vendors[i];
362 std::fprintf(stderr, "[rt] device-fault: vendor[%zu] %.*s code=0x%" PRIx64 " data=0x%" PRIx64 "\n",
363 i, int(sizeof(vendor.description)), vendor.description, vendor.vendorFaultCode,
364 vendor.vendorFaultData);
365 }
366 }
367
368 void report_queue(VkQueue queue) const {
369 std::uint32_t count = 0;
370 vkGetQueueCheckpointDataNV(queue, &count, nullptr);
371 std::vector<VkCheckpointDataNV> data(count, {VK_STRUCTURE_TYPE_CHECKPOINT_DATA_NV});
372 if (count) vkGetQueueCheckpointDataNV(queue, &count, data.data());
373 std::fprintf(stderr, "[rt] device-fault: queue %p checkpoints=%u\n", static_cast<void*>(queue), count);
374 for (std::uint32_t i = 0; i < count; ++i) {
375 const auto& checkpoint = data[i];
376 const auto stage = static_cast<std::uint64_t>(checkpoint.stage);
377 const auto marker = CheckpointMarker::decode(reinterpret_cast<std::uintptr_t>(checkpoint.pCheckpointMarker));
378 if (!marker.submission) {
379 std::fprintf(stderr, "[rt] device-fault: stage=0x%" PRIx64 " marker=%p (unrecognized)\n",
380 stage, checkpoint.pCheckpointMarker);
381 continue;
382 }
383 std::fprintf(stderr, "[rt] device-fault: stage=0x%" PRIx64 " submission=%u list=%u command=%u kind=%s\n",
384 stage, marker.submission, marker.list, marker.command, marker.kind_name());
385 const auto& entry = recent_[marker.submission % recent_.size()];
386 if (entry.sequence != marker.submission || entry.queue != queue || marker.list >= entry.lists.size()) {
387 std::fprintf(stderr, "[rt] device-fault: submission metadata unavailable\n");
388 continue;
389 }
390 std::fprintf(stderr, "[rt] device-fault: ExecuteCommandLists #%" PRIu64 " queue=%p (%s) lists=%zu\n",
391 entry.execute_call, static_cast<void*>(entry.queue), entry.queue_kind, entry.list_count);
392 const auto& shaders = entry.lists[marker.list].shaders;
393 const auto next = std::upper_bound(shaders.begin(), shaders.end(), marker.command,
394 [](auto command, const auto& change) { return command < change.command; });
395 if (next != shaders.begin()) {
396 const auto& pipeline = (next - 1)->pipeline;
397 std::fprintf(stderr, "[rt] device-fault: last shader pipeline=0x%" PRIx64 " shaders=%s %s %s\n",
398 pipeline_handle(pipeline.handle), pipeline.shaders[0] ? pipeline.shaders[0] : "-",
399 pipeline.shaders[1] ? pipeline.shaders[1] : "-",
400 pipeline.shaders[2] ? pipeline.shaders[2] : "-");
401 }
402 }
403 }
404
405 template<typename Handle>
406 static std::uint64_t pipeline_handle(Handle handle) {
407 if constexpr (VK_USE_64_BIT_PTR_DEFINES) return reinterpret_cast<std::uintptr_t>(handle);
408 else return handle;
409 }
410
411 VkDevice device_;
412 PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr;
413 PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr;
414 PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr;
415 std::atomic<bool> reported_{false};
416 std::atomic<std::uint64_t> execute_calls_{0};
417 std::uint32_t sequence_ = 0;
418 std::mutex mutex_; // leaf lock, guards queues_ and recent_
419 std::vector<VkQueue> queues_;
420 const bool include_roots_ = [] {
421 const char* value = std::getenv("LEONIDA_DEVICE_FAULT_ROOTS");
422 return value && !std::strcmp(value, "1");
423 }();
424 std::array<CheckpointDispatch, CheckpointSubmission::dispatch_limit> dispatches_{};
425 std::size_t dispatch_count_ = 0;
426 std::array<CheckpointSubmission, 64> recent_;
427};
428
429} // namespace leonida
diff --git a/runtime/src/vulkan_gpu_labels.h b/runtime/src/vulkan_gpu_labels.h
new file mode 100644
index 000000000..32590cc39
--- /dev/null
+++ b/runtime/src/vulkan_gpu_labels.h
@@ -0,0 +1,299 @@
1#pragma once
2#include "gpu_label_memory.h"
3#include <vulkan/vulkan.h>
4#include <algorithm>
5#include <atomic>
6#include <chrono>
7#include <condition_variable>
8#include <cstdio>
9#include <cstdlib>
10#include <memory>
11#include <mutex>
12#include <thread>
13#include <unordered_map>
14#include <utility>
15#include <vector>
16#ifdef _WIN32
17#ifndef NOMINMAX
18#define NOMINMAX
19#endif
20#include <windows.h>
21#include "title_page_watch.h"
22#endif
23
24namespace leonida::label {
25inline bool enabled() {
26 static const bool active = [] {
27 const char *v = std::getenv("LEONIDA_GPU_LABELS");
28 return v && v[0] == '1';
29 }();
30 return active;
31}
32// Stores a completed label into the title's memory: only into a committed, private, writable page of the allocation
33// the label was captured in, and only while that allocation's generation is the captured one (Memory::publish).
34//
35// A page the D3D12 layer watches for the title's writes is read-only while it waits (title_page_watch.h), and it is
36// writable as far as the title knows. Such a page is announced and opened the way a kernel write is
37// (kernel_writes::begin_write), so the label reaches it and the layer copies the page again; a page that stays
38// read-only after that is the title's own doing and the label is dropped, as before. Called with no shadow lock held.
39inline bool store_value(const Target &target, std::uint64_t value) {
40#ifdef _WIN32
41 return memory().publish(target, [&](std::uintptr_t address, unsigned width, std::uintptr_t allocation_base) {
42 MEMORY_BASIC_INFORMATION mbi{};
43 const auto in_allocation = [&] {
44 return VirtualQuery(reinterpret_cast<const void *>(address), &mbi, sizeof(mbi)) && mbi.State == MEM_COMMIT &&
45 mbi.Type == MEM_PRIVATE && reinterpret_cast<std::uintptr_t>(mbi.AllocationBase) == allocation_base &&
46 !(mbi.Protect & PAGE_GUARD);
47 };
48 if (!in_allocation()) return false;
49 std::uint64_t pin = 0;
50 if ((mbi.Protect & 0xff) == PAGE_READONLY) {
51 pin = kernel_writes::begin_write(reinterpret_cast<const void *>(address), width, nullptr);
52 if (!pin || !in_allocation()) {
53 kernel_writes::end_write(pin, false);
54 return false;
55 }
56 }
57 const auto begin = reinterpret_cast<std::uintptr_t>(mbi.BaseAddress);
58 const bool writable = (mbi.Protect & 0xff) == PAGE_READWRITE || (mbi.Protect & 0xff) == PAGE_WRITECOPY;
59 const bool inside = address >= begin && address - begin <= mbi.RegionSize &&
60 mbi.RegionSize - (address - begin) >= width;
61 if (writable && inside) {
62 if (width == 4)
63 InterlockedExchange(reinterpret_cast<volatile LONG *>(address), static_cast<LONG>(value));
64 else
65 InterlockedExchange64(reinterpret_cast<volatile LONG64 *>(address), static_cast<LONG64>(value));
66 }
67 kernel_writes::end_write(pin, false);
68 return writable && inside;
69 });
70#else
71 (void)target;
72 (void)value;
73 return false;
74#endif
75}
76
77// Each submitted Vulkan command buffer owns a fence and its query slots until the GPU finishes it.
78// The CPU destination is a generation-checked title data allocation. No guest pointer is a GPU command destination.
79class Completions {
80 static constexpr unsigned per_pool = 64;
81 struct Batch {
82 VkFence fence{};
83 std::vector<VkQueryPool> pools;
84 std::vector<Write> labels;
85 };
86 std::mutex mutex_;
87 std::condition_variable changed_;
88 bool closing_ = false;
89 std::thread worker_;
90 VkDevice device_{};
91 std::unordered_map<VkCommandBuffer, std::unique_ptr<Batch>> recording_;
92 std::vector<std::unique_ptr<Batch>> pending_;
93 std::vector<VkQueryPool> idle_pools_;
94 std::vector<VkFence> idle_fences_;
95 PFN_vkCreateQueryPool create_pool_{};
96 PFN_vkDestroyQueryPool destroy_pool_{};
97 PFN_vkCmdResetQueryPool reset_query_{};
98 PFN_vkCmdWriteTimestamp timestamp_{};
99 PFN_vkGetQueryPoolResults results_{};
100 PFN_vkCreateFence create_fence_{};
101 PFN_vkDestroyFence destroy_fence_{};
102 PFN_vkGetFenceStatus fence_status_{};
103 PFN_vkResetFences reset_fences_{};
104 PFN_vkDeviceWaitIdle device_idle_{};
105 std::uint64_t expired_ = 0, errors_ = 0;
106 VkQueryPool pool() {
107 if (!idle_pools_.empty()) {
108 auto h = idle_pools_.back();
109 idle_pools_.pop_back();
110 return h;
111 }
112 VkQueryPoolCreateInfo c{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
113 c.queryType = VK_QUERY_TYPE_TIMESTAMP;
114 c.queryCount = per_pool;
115 VkQueryPool p{};
116 return create_pool_(device_, &c, nullptr, &p) == VK_SUCCESS ? p : VK_NULL_HANDLE;
117 }
118 VkFence fence() {
119 if (!idle_fences_.empty()) {
120 auto f = idle_fences_.back();
121 idle_fences_.pop_back();
122 if (reset_fences_(device_, 1, &f) == VK_SUCCESS) return f;
123 destroy_fence_(device_, f, nullptr);
124 }
125 VkFenceCreateInfo c{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
126 VkFence f{};
127 return create_fence_(device_, &c, nullptr, &f) == VK_SUCCESS ? f : VK_NULL_HANDLE;
128 }
129 void recycle(Batch &b) {
130 for (auto p : b.pools)
131 idle_pools_.push_back(p);
132 if (b.fence) idle_fences_.push_back(b.fence);
133 }
134 static bool store(const Target &target, std::uint64_t value) { return store_value(target, value); }
135 void publish(const Batch &batch) {
136 for (std::size_t i = 0; i < batch.labels.size(); ++i) {
137 const Write &op = batch.labels[i];
138 std::uint64_t value = op.value;
139 if (op.clock == 1) {
140 if (results_(device_, batch.pools[i / per_pool], static_cast<unsigned>(i % per_pool), 1, sizeof(value),
141 &value, sizeof(value), VK_QUERY_RESULT_64_BIT) != VK_SUCCESS) {
142 ++errors_;
143 continue;
144 }
145 } else if (op.clock == 2) {
146#ifdef _WIN32
147 LARGE_INTEGER qpc{};
148 if (!QueryPerformanceCounter(&qpc)) {
149 ++errors_;
150 continue;
151 }
152 value = static_cast<std::uint64_t>(qpc.QuadPart);
153#else
154 ++errors_;
155 continue;
156#endif
157 }
158 if (!store(op.target, value)) ++expired_;
159 }
160 }
161 void run() {
162 std::unique_lock lock(mutex_);
163 for (;;) {
164 if (pending_.empty() && !closing_) changed_.wait(lock, [&] { return closing_ || !pending_.empty(); });
165 for (auto i = pending_.begin(); i != pending_.end();) {
166 auto &b = **i;
167 const auto status = fence_status_(device_, b.fence);
168 if (status == VK_NOT_READY && !closing_) {
169 ++i;
170 continue;
171 }
172 if (status == VK_SUCCESS)
173 publish(b);
174 else
175 ++errors_;
176 recycle(b);
177 i = pending_.erase(i);
178 }
179 if (closing_) return;
180 if (!pending_.empty()) changed_.wait_for(lock, std::chrono::milliseconds(1));
181 }
182 }
183
184 public:
185 ~Completions() { stop(device_); }
186
187 bool initialize(VkDevice dev, PFN_vkGetDeviceProcAddr get) {
188 if (!enabled() || !dev || !get) return false;
189 std::lock_guard lock(mutex_);
190 if (device_) return device_ == dev;
191#define LABEL_FN(name) reinterpret_cast<PFN_##name>(get(dev, #name))
192 create_pool_ = LABEL_FN(vkCreateQueryPool);
193 destroy_pool_ = LABEL_FN(vkDestroyQueryPool);
194 reset_query_ = LABEL_FN(vkCmdResetQueryPool);
195 timestamp_ = LABEL_FN(vkCmdWriteTimestamp);
196 results_ = LABEL_FN(vkGetQueryPoolResults);
197 create_fence_ = LABEL_FN(vkCreateFence);
198 destroy_fence_ = LABEL_FN(vkDestroyFence);
199 fence_status_ = LABEL_FN(vkGetFenceStatus);
200 reset_fences_ = LABEL_FN(vkResetFences);
201 device_idle_ = LABEL_FN(vkDeviceWaitIdle);
202#undef LABEL_FN
203 if (!create_pool_ || !destroy_pool_ || !reset_query_ || !timestamp_ || !results_ || !create_fence_ ||
204 !destroy_fence_ || !fence_status_ || !reset_fences_ || !device_idle_)
205 return false;
206 device_ = dev;
207 closing_ = false;
208 worker_ = std::thread([this] { run(); });
209 return true;
210 }
211 void begin_record(VkCommandBuffer cb) {
212 if (!enabled()) return;
213 std::lock_guard lock(mutex_);
214 auto i = recording_.find(cb);
215 if (i != recording_.end()) {
216 recycle(*i->second);
217 recording_.erase(i);
218 }
219 }
220 void record(VkCommandBuffer cb, const Write &op) {
221 if (!enabled()) return;
222 std::lock_guard lock(mutex_);
223 if (!device_ || closing_) {
224 ++errors_;
225 return;
226 }
227 auto &slot = recording_[cb];
228 if (!slot) {
229 slot = std::make_unique<Batch>();
230 slot->fence = fence();
231 }
232 if (!slot->fence) {
233 ++errors_;
234 return;
235 }
236 const auto i = slot->labels.size();
237 const auto j = static_cast<unsigned>(i % per_pool);
238 if (!j) {
239 auto p = pool();
240 if (!p) {
241 ++errors_;
242 return;
243 }
244 slot->pools.push_back(p);
245 }
246 auto p = slot->pools[i / per_pool];
247 reset_query_(cb, p, j, 1);
248 timestamp_(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, p, j);
249 slot->labels.push_back(op);
250 }
251 VkFence submit_fence(VkCommandBuffer cb) {
252 if (!enabled() || !cb) return VK_NULL_HANDLE;
253 std::lock_guard lock(mutex_);
254 auto i = recording_.find(cb);
255 return i == recording_.end() ? VK_NULL_HANDLE : i->second->fence;
256 }
257 void submitted(VkCommandBuffer cb, bool ok) {
258 if (!enabled() || !cb) return;
259 std::lock_guard lock(mutex_);
260 auto i = recording_.find(cb);
261 if (i == recording_.end()) return;
262 if (ok && i->second->fence) {
263 pending_.push_back(std::move(i->second));
264 changed_.notify_one();
265 } else
266 recycle(*i->second);
267 recording_.erase(i);
268 }
269 void stop(VkDevice dev) {
270 {
271 std::lock_guard lock(mutex_);
272 if (!dev || device_ != dev) return;
273 }
274 device_idle_(dev);
275 {
276 std::lock_guard lock(mutex_);
277 closing_ = true;
278 changed_.notify_all();
279 }
280 if (worker_.joinable()) worker_.join();
281 std::lock_guard lock(mutex_);
282 for (auto &pair : recording_)
283 recycle(*pair.second);
284 recording_.clear();
285 for (auto f : idle_fences_)
286 destroy_fence_(dev, f, nullptr);
287 idle_fences_.clear();
288 for (auto p : idle_pools_)
289 destroy_pool_(dev, p, nullptr);
290 idle_pools_.clear();
291 if (errors_) {
292 std::fprintf(stderr, "[rt] d3d12: %llu GPU label operations failed, %llu destinations expired\n",
293 static_cast<unsigned long long>(errors_), static_cast<unsigned long long>(expired_));
294 }
295 expired_ = errors_ = 0;
296 device_ = VK_NULL_HANDLE;
297 }
298};
299} // namespace leonida::label
diff --git a/runtime/src/vulkan_graphics_shader_modules.h b/runtime/src/vulkan_graphics_shader_modules.h
new file mode 100644
index 000000000..f3f7ef742
--- /dev/null
+++ b/runtime/src/vulkan_graphics_shader_modules.h
@@ -0,0 +1,65 @@
1#pragma once
2
3#include <vulkan/vulkan.h>
4#include <algorithm>
5#include <cstdint>
6#include <memory>
7#include <mutex>
8#include <span>
9#include <unordered_map>
10#include <vector>
11
12namespace leonida {
13class GraphicsShaderModules {
14 public:
15 struct Module {
16 VkDevice device;
17 PFN_vkDestroyShaderModule destroy;
18 std::vector<std::uint32_t> words;
19 VkShaderModule handle = VK_NULL_HANDLE;
20 Module(VkDevice d, PFN_vkDestroyShaderModule fn, std::span<const std::uint32_t> input)
21 : device(d), destroy(fn), words(input.begin(), input.end()) {}
22 ~Module() {
23 if (handle) destroy(device, handle, nullptr);
24 }
25 };
26 using Reference = std::shared_ptr<const Module>;
27 Reference acquire(VkDevice device, PFN_vkCreateShaderModule create, PFN_vkDestroyShaderModule destroy,
28 std::span<const std::uint32_t> words) {
29 if (words.empty()) return {};
30 std::uint64_t hash = 14695981039346656037ull;
31 for (std::uint32_t word : words)
32 hash = (hash ^ word) * 1099511628211ull;
33 {
34 std::lock_guard lock(mutex_);
35 if (auto found = find_locked(hash, words)) return found;
36 }
37 auto result = std::make_shared<Module>(device, destroy, words);
38 VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
39 info.pCode = words.data();
40 info.codeSize = words.size_bytes();
41 if (create(device, &info, nullptr, &result->handle) != VK_SUCCESS) {
42 result->handle = VK_NULL_HANDLE;
43 return {};
44 }
45 std::lock_guard lock(mutex_);
46 if (auto found = find_locked(hash, words)) return found;
47 if ((++created_ % 1024) == 0) std::erase_if(modules_, [](const auto &entry) { return entry.second.expired(); });
48 modules_.emplace(hash, result);
49 return result;
50 }
51
52 private:
53 Reference find_locked(std::uint64_t hash, std::span<const std::uint32_t> words) {
54 const auto [first, last] = modules_.equal_range(hash);
55 for (auto i = first; i != last; ++i)
56 if (auto live = i->second.lock();
57 live && std::equal(words.begin(), words.end(), live->words.begin(), live->words.end()))
58 return live;
59 return {};
60 }
61 std::mutex mutex_;
62 std::unordered_multimap<std::uint64_t, std::weak_ptr<const Module>> modules_;
63 std::uint64_t created_ = 0;
64};
65} // namespace leonida
diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h
index 08c764d33..a818ce205 100644
--- a/runtime/src/vulkan_memory.h
+++ b/runtime/src/vulkan_memory.h
@@ -56,6 +56,12 @@ inline std::vector<std::uint32_t> memory_type_order(const VkPhysicalDeviceMemory
56 return order; 56 return order;
57} 57}
58 58
59// The size of the blocks that textures share (image_memory.h): 64 MiB, or a sixteenth of a small heap, such as the BAR
60// window of a GPU without Resizable BAR. A texture larger than an eighth of a block has its own allocation.
61inline VkDeviceSize image_block_bytes(VkDeviceSize heap) {
62 return std::min<VkDeviceSize>(VkDeviceSize(64) << 20, heap / 16) & ~VkDeviceSize(0xffff);
63}
64
59// D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap 65// D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap
60// buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible 66// buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible
61// allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this. 67// allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this.
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 97c365b5f..f01167cf4 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -27,6 +27,9 @@
27 27
28#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h" 29#include "vulkan_present_compose.h"
30#include "fsdraw_probe.h" // LOCAL DIAGNOSTIC
31#include "local_diagnostics.h"
32#include "present_dump.h"
30 33
31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 34// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 35#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -185,6 +188,11 @@ public:
185 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit)); 188 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit));
186 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n", 189 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n",
187 capture_every_, capture_limit_, capture_dir_.c_str()); 190 capture_every_, capture_limit_, capture_dir_.c_str());
191 // LOCAL DIAGNOSTIC: LEONIDA_CAPTURE_SOURCE=1 also reads back the presented source texture itself.
192 if (const char* source = std::getenv("LEONIDA_CAPTURE_SOURCE"); source && *source && *source != '0') {
193 probe_source_ = true;
194 std::fprintf(stderr, "[rt] present-probe: source capture on\n");
195 }
188 } 196 }
189 ok_ = recreate(true, false); 197 ok_ = recreate(true, false);
190 if (!ok_ && capture_to_disk_) { 198 if (!ok_ && capture_to_disk_) {
@@ -204,7 +212,7 @@ public:
204 const VkDevice device = context_.device(); 212 const VkDevice device = context_.device();
205 { 213 {
206 std::lock_guard lock(context_.submit_mutex()); 214 std::lock_guard lock(context_.submit_mutex());
207 vk.vkQueueWaitIdle(queue_); 215 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
208 // A WSI layer may perform a device-wide idle while destroying the swapchain. 216 // A WSI layer may perform a device-wide idle while destroying the swapchain.
209 // Keep that implicit idle serialized with submits from every context queue. 217 // Keep that implicit idle serialized with submits from every context queue.
210 release(swapchain_); 218 release(swapchain_);
@@ -219,6 +227,7 @@ public:
219 if (frame.done) vkDestroyFence_(device, frame.done, nullptr); 227 if (frame.done) vkDestroyFence_(device, frame.done, nullptr);
220 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); 228 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr);
221 } 229 }
230 if (probe_fence_) vkDestroyFence_(device, probe_fence_, nullptr); // LOCAL DIAGNOSTIC
222 if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); 231 if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr);
223 if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); 232 if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr);
224 } 233 }
@@ -340,6 +349,7 @@ public:
340 bool enable_capture() { 349 bool enable_capture() {
341 std::lock_guard lock(present_mutex_); 350 std::lock_guard lock(present_mutex_);
342 if (!ok_) return false; 351 if (!ok_) return false;
352 splash_capture_only_ = false;
343 capture_ = true; 353 capture_ = true;
344 stale_ = true; 354 stale_ = true;
345 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { 355 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
@@ -349,6 +359,9 @@ public:
349 return true; 359 return true;
350 } 360 }
351 361
362 // Present the shell image immediately. Keep it on screen until the window has a non-black title frame.
363 bool present_splash(ResourceId source, std::shared_ptr<void> owner);
364
352 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). 365 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order).
353 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present 366 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present
354 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next 367 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next
@@ -357,7 +370,8 @@ public:
357 std::lock_guard lock(present_mutex_); 370 std::lock_guard lock(present_mutex_);
358 if (!capture_ || !capture_ptr_ || !captured_) return false; 371 if (!capture_ || !capture_ptr_ || !captured_) return false;
359 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; 372 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()];
360 if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS) 373 if (context_.observe_result(vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX),
374 "vkWaitForFences (present readback)") != VK_SUCCESS)
361 return false; 375 return false;
362 pixels.assign(capture_ptr_, capture_ptr_ + std::size_t(captured_extent_.width) * captured_extent_.height * 4); 376 pixels.assign(capture_ptr_, capture_ptr_ + std::size_t(captured_extent_.width) * captured_extent_.height * 4);
363 if (extent) *extent = captured_extent_; 377 if (extent) *extent = captured_extent_;
@@ -393,6 +407,9 @@ public:
393 if (source_rect) pending.rect = *source_rect; 407 if (source_rect) pending.rect = *source_rect;
394 if (planes) pending.planes = *planes; 408 if (planes) pending.planes = *planes;
395 deferred_.push_back(pending); 409 deferred_.push_back(pending);
410 if (const std::uint64_t n = ++probe_deferred_; local_diagnostics() && (n <= 8 || n % 600 == 0))
411 std::fprintf(stderr, "[rt] present-probe: present #%llu queued behind held work (%zu queued)\n",
412 static_cast<unsigned long long>(n), deferred_.size());
396 last_tore_ = false; 413 last_tore_ = false;
397 context_.holds().after_held(this, [this] { run_deferred(); }); 414 context_.holds().after_held(this, [this] { run_deferred(); });
398 return VK_SUCCESS; 415 return VK_SUCCESS;
@@ -455,6 +472,7 @@ private:
455 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 472 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
456 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { 473 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
457 last_tore_ = false; 474 last_tore_ = false;
475 probe_path(binding, source, planes); // LOCAL DIAGNOSTIC
458 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 476 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
459 if (surface_lost_) { // the window's display went away under a presented swapchain 477 if (surface_lost_) { // the window's display went away under a presented swapchain
460 // Try to make a new surface for the same window (the hwnd is retained by the factory's callback). 478 // Try to make a new surface for the same window (the hwnd is retained by the factory's callback).
@@ -478,7 +496,7 @@ private:
478 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) { 496 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) {
479 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed 497 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed
480 // recreate is tried again at the next present. 498 // recreate is tried again at the next present.
481 if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR; 499 if (!recreate_for_present(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR;
482 } 500 }
483 if (!swapchain_) { // minimised: try again next frame 501 if (!swapchain_) { // minimised: try again next frame
484 stale_ = true; 502 stale_ = true;
@@ -492,7 +510,9 @@ private:
492 auto& vk = context_.vk; 510 auto& vk = context_.vk;
493 const VkDevice device = context_.device(); 511 const VkDevice device = context_.device();
494 Frame& frame = frames_[frame_index_ % frames_.size()]; 512 Frame& frame = frames_[frame_index_ % frames_.size()];
495 if (const VkResult waited = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); waited != VK_SUCCESS) 513 if (const VkResult waited = context_.observe_result(
514 vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)");
515 waited != VK_SUCCESS)
496 return stop(waited); 516 return stop(waited);
497 // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride. 517 // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride.
498 if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r); 518 if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r);
@@ -500,7 +520,7 @@ private:
500 std::uint32_t image = 0; 520 std::uint32_t image = 0;
501 VkResult acquired = acquire(frame.acquired, &image); 521 VkResult acquired = acquire(frame.acquired, &image);
502 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 522 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
503 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; 523 if (!recreate_for_present(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
504 if (!swapchain_) { // minimised since the last present: skipped, as above 524 if (!swapchain_) { // minimised since the last present: skipped, as above
505 captured_ = false; 525 captured_ = false;
506 return VK_SUCCESS; 526 return VK_SUCCESS;
@@ -571,7 +591,8 @@ private:
571 plane_rollbacks[i].layout); 591 plane_rollbacks[i].layout);
572 }; 592 };
573 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 593 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
574 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { 594 if (const VkResult reset = context_.observe_result(vkResetFences_(device, 1, &frame.done),
595 "vkResetFences (present)"); reset != VK_SUCCESS) {
575 rollback(); 596 rollback();
576 return stop(reset); 597 return stop(reset);
577 } 598 }
@@ -603,22 +624,49 @@ private:
603 const bool tearing = false; 624 const bool tearing = false;
604 (void)tear; 625 (void)tear;
605#endif 626#endif
627 const bool inspect = splash_owner_ && capture_ptr_;
628 bool show_title = false;
629 if (inspect) {
630 submit_info.signalSemaphoreCount = 0; // signal ready only after choosing the image the window will show
631 if (!tracker_lock.owns_lock()) tracker_lock.lock();
632 }
606 VkResult submitted, result = VK_SUCCESS; 633 VkResult submitted, result = VK_SUCCESS;
607 { 634 {
608 std::lock_guard lock(context_.submit_mutex()); 635 std::lock_guard lock(context_.submit_mutex());
609 submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); 636 submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done),
637 "vkQueueSubmit (present)");
638 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
610 if (submitted != VK_SUCCESS) rollback(); 639 if (submitted != VK_SUCCESS) rollback();
611 // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission 640 if (submitted == VK_SUCCESS && inspect) {
612 // order without holding tracker_mutex_ across vkQueuePresentKHR. 641 result = finish_startup_frame(frame, image, show_title);
642 if (result != VK_SUCCESS) return stop(result);
643 }
613 if (tracker_lock.owns_lock()) tracker_lock.unlock(); 644 if (tracker_lock.owns_lock()) tracker_lock.unlock();
614 if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present); 645 if (submitted == VK_SUCCESS)
646 result = context_.observe_result(vkQueuePresentKHR_(queue_, &present), "vkQueuePresentKHR");
647 }
648 if (show_title && (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)) {
649 splash_owner_.reset();
650 if (splash_capture_only_) {
651 splash_capture_only_ = false;
652 capture_ = false;
653 release_capture();
654 }
615 } 655 }
616 if (submitted != VK_SUCCESS) return give_back(frame, submitted); 656 if (submitted != VK_SUCCESS) return give_back(frame, submitted);
617 ++frame_index_; 657 ++frame_index_;
618 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain 658 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain
619 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 659 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
620 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 660 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
621 ++presented_; 661 const auto shown = ++presented_;
662 if (dump_.due(shown - 1)) {
663 // Presentation is already queued and the queue/tracker locks are released. A sampled frame
664 // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker.
665 if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS)
666 dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_));
667 else
668 dump_.disable("present dump fence wait failed");
669 }
622 if (planes) ++composed_; 670 if (planes) ++composed_;
623 if (tearing) { 671 if (tearing) {
624 last_tore_ = true; 672 last_tore_ = true;
@@ -648,6 +696,310 @@ private:
648 } 696 }
649 697
650private: 698private:
699 // ---- LOCAL DIAGNOSTIC (not for upstream): which path each present takes, and the source texture's contents ----
700 bool probe_source_ = false;
701 std::uint64_t probe_calls_ = 0, probe_blit_ = 0, probe_compose_ = 0, probe_blank_ = 0, probe_unresolved_ = 0;
702 std::atomic<std::uint64_t> probe_deferred_{0};
703 int probe_written_ = 0;
704 VkCommandBuffer probe_commands_ = VK_NULL_HANDLE;
705 VkFence probe_fence_ = VK_NULL_HANDLE;
706
707 static float probe_half(std::uint16_t h) {
708 const std::uint32_t sign = (h >> 15) & 1, exponent = (h >> 10) & 0x1f, mantissa = h & 0x3ff;
709 float v;
710 if (exponent == 0) v = std::ldexp(float(mantissa), -24);
711 else if (exponent == 31) v = mantissa ? 0.0f : 65504.0f; // NaN reads as 0, inf as the largest half
712 else v = std::ldexp(float(mantissa | 0x400), int(exponent) - 25);
713 return sign ? -v : v;
714 }
715 static float probe_uf11(std::uint32_t bits, int mantissa_bits) { // B10G11R11 channels (5-bit exponent)
716 const std::uint32_t exponent = (bits >> mantissa_bits) & 0x1f, mantissa = bits & ((1u << mantissa_bits) - 1);
717 if (exponent == 0) return std::ldexp(float(mantissa), -14 - mantissa_bits);
718 if (exponent == 31) return 65504.0f;
719 return std::ldexp(float(mantissa | (1u << mantissa_bits)), int(exponent) - 15 - mantissa_bits);
720 }
721 // RGB in 0..1 (float formats unclamped) of one texel; false for a format this probe does not decode.
722 static bool probe_decode(VkFormat format, const std::uint8_t* t, float rgb[3]) {
723 switch (format) {
724 case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB:
725 rgb[0] = t[2] / 255.0f; rgb[1] = t[1] / 255.0f; rgb[2] = t[0] / 255.0f; return true;
726 case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB:
727 rgb[0] = t[0] / 255.0f; rgb[1] = t[1] / 255.0f; rgb[2] = t[2] / 255.0f; return true;
728 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: {
729 std::uint32_t w; std::memcpy(&w, t, 4);
730 const float lo = (w & 0x3ff) / 1023.0f, mid = ((w >> 10) & 0x3ff) / 1023.0f, hi = ((w >> 20) & 0x3ff) / 1023.0f;
731 const bool bgra = format == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
732 rgb[0] = bgra ? hi : lo; rgb[1] = mid; rgb[2] = bgra ? lo : hi; return true;
733 }
734 case VK_FORMAT_R16G16B16A16_SFLOAT: {
735 std::uint16_t h[3]; std::memcpy(h, t, 6);
736 for (int i = 0; i < 3; ++i) rgb[i] = probe_half(h[i]);
737 return true;
738 }
739 case VK_FORMAT_R16G16B16A16_UNORM: {
740 std::uint16_t h[3]; std::memcpy(h, t, 6);
741 for (int i = 0; i < 3; ++i) rgb[i] = h[i] / 65535.0f;
742 return true;
743 }
744 case VK_FORMAT_B10G11R11_UFLOAT_PACK32: {
745 std::uint32_t w; std::memcpy(&w, t, 4);
746 rgb[0] = probe_uf11(w & 0x7ff, 6); rgb[1] = probe_uf11((w >> 11) & 0x7ff, 6); rgb[2] = probe_uf11(w >> 22, 5);
747 return true;
748 }
749 case VK_FORMAT_R32G32B32A32_SFLOAT:
750 std::memcpy(rgb, t, 12); return true;
751 default:
752 return false;
753 }
754 }
755
756 // Called at the top of submit_now(), so after any held work it was queued behind.
757 void probe_path(const ResourceBinding* binding, ResourceId source, const PresentPlanes* planes) {
758 const std::uint64_t n = ++probe_calls_;
759 const char* path = planes ? "present_planes(compose)" : binding ? "present(blit)" : "present_blank";
760 (planes ? probe_compose_ : binding ? probe_blit_ : probe_blank_)++;
761 const ResourceId id = planes ? planes->plane[0].source : binding ? source : ResourceId{};
762 ResourceBinding found{};
763 bool resolved = false;
764 if (id) {
765 std::shared_lock lock(context_.resource_mutex_);
766 if (const ResourceBinding* b = context_.resolve(id)) {
767 found = *b;
768 resolved = true;
769 }
770 }
771 if (id && !resolved) ++probe_unresolved_;
772 if (local_diagnostics() && (n <= 6 || n % 600 == 0))
773 std::fprintf(stderr,
774 "[rt] present-probe: submit #%llu path %s source 0x%llx resolved %d image %p format %d %ux%u "
775 "mips %u layers %u samples %u sampled %d (blit %llu compose %llu blank %llu unresolved %llu)\n",
776 static_cast<unsigned long long>(n), path, static_cast<unsigned long long>(id), int(resolved),
777 reinterpret_cast<void*>(found.image), int(found.format), found.width, found.height,
778 found.mip_levels, found.array_layers, found.samples, int(found.sampled),
779 static_cast<unsigned long long>(probe_blit_), static_cast<unsigned long long>(probe_compose_),
780 static_cast<unsigned long long>(probe_blank_), static_cast<unsigned long long>(probe_unresolved_));
781 // The same frames the swapchain capture takes: the one presented_ becomes when this present is shown.
782 if (probe_source_ && resolved && found.image && probe_written_ < capture_limit_ &&
783 presented_ % std::uint64_t(capture_every_) == 0)
784 {
785 probe_read_source(id, presented_ + 1, path);
786 // LOCAL DIAGNOSTIC (fsdraw): the render targets of the frame's fullscreen draws, read back with it.
787 for (const std::uint64_t target : fsdraw::targets())
788 if (target != id) probe_read_source(target, presented_ + 1, "fullscreen-draw target", "target");
789 }
790 }
791
792 // Copies mip 0, layer 0 of `id` to host memory on the presenter's queue (waited for), logs and writes it.
793 void probe_read_source(ResourceId id, std::uint64_t number, const char* path, const char* prefix = "source") {
794 const bool is_source = std::strcmp(prefix, "source") == 0;
795 auto& vk = context_.vk;
796 const VkDevice device = context_.device();
797 const ReplayFunctions& fn = context_.replay_;
798 if (!probe_commands_) {
799 VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
800 allocate.commandPool = pool_;
801 allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
802 allocate.commandBufferCount = 1;
803 VkFenceCreateInfo fence{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
804 if (vk.vkAllocateCommandBuffers(device, &allocate, &probe_commands_) != VK_SUCCESS ||
805 vkCreateFence_(device, &fence, nullptr, &probe_fence_) != VK_SUCCESS) {
806 std::fprintf(stderr, "[rt] present-probe: cannot make the readback command buffer\n");
807 probe_source_ = false;
808 return;
809 }
810 }
811 std::shared_lock resource_lock(context_.resource_mutex_);
812 const ResourceBinding* found = context_.resolve(id);
813 if (!found || !found->image) return;
814 const ResourceBinding binding = *found;
815 const BlockFormat bf = block_format(binding.format, VK_IMAGE_ASPECT_COLOR_BIT);
816 // Held only while the copy is recorded (fsdraw: holding them through the wait, the slow host reads and the
817 // file write stalled every resource creation and the boot ran out of memory).
818 std::unique_lock tracker_lock(context_.tracker_mutex_);
819 const bool tracked = context_.tracker_.tracked(id);
820 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
821 const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL);
822 LayoutPieces pieces = detail::current(&context_.tracker_, id, range, common);
823 const VkImageLayout layout = pieces.empty() ? VK_IMAGE_LAYOUT_UNDEFINED : pieces[0].layout;
824 std::fprintf(stderr,
825 "[rt] present-probe: %s frame %llu via %s: id 0x%llx format %d %ux%u mips %u layers %u samples %u "
826 "texel bytes %u tracked %d layout %d\n",
827 prefix, static_cast<unsigned long long>(number), path, static_cast<unsigned long long>(id),
828 int(binding.format), binding.width, binding.height, binding.mip_levels, binding.array_layers,
829 binding.samples, bf.bytes, int(tracked), int(layout));
830 if (layout == VK_IMAGE_LAYOUT_UNDEFINED) {
831 std::fprintf(stderr, "[rt] present-probe: %s frame %llu is UNDEFINED in the tracker: no tracked GPU "
832 "operation ever wrote it (the present zero-fills it)\n",
833 prefix, static_cast<unsigned long long>(number));
834 if (is_source) ++probe_written_;
835 return;
836 }
837 if (binding.samples > 1 || bf.block != 1 || !bf.bytes) {
838 std::fprintf(stderr, "[rt] present-probe: %s format %d not read back\n", prefix, int(binding.format));
839 return;
840 }
841 const VkDeviceSize size = VkDeviceSize(binding.width) * binding.height * bf.bytes;
842 VkBuffer buffer = VK_NULL_HANDLE;
843 VkDeviceMemory memory = VK_NULL_HANDLE;
844 void* mapped = nullptr;
845 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
846 info.size = size;
847 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
848 if (vk.vkCreateBuffer(device, &info, nullptr, &buffer) != VK_SUCCESS) return;
849 VkMemoryRequirements requirements{};
850 vk.vkGetBufferMemoryRequirements(device, buffer, &requirements);
851 VkPhysicalDeviceMemoryProperties props{};
852 vkGetPhysicalDeviceMemoryProperties_(physical_, &props);
853 constexpr VkMemoryPropertyFlags wanted = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
854 std::uint32_t type = UINT32_MAX;
855 // Host-cached system memory first (fsdraw): a resizable-BAR type is uncached for host reads.
856 for (int pass = 0; pass < 2 && type == UINT32_MAX; ++pass)
857 for (std::uint32_t i = 0; i < props.memoryTypeCount; ++i) {
858 const VkMemoryPropertyFlags f = props.memoryTypes[i].propertyFlags;
859 const bool cached = (f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) && !(f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
860 if ((requirements.memoryTypeBits & (1u << i)) && (f & wanted) == wanted && (pass || cached)) {
861 type = i;
862 break;
863 }
864 }
865 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
866 allocate.allocationSize = requirements.size;
867 allocate.memoryTypeIndex = type;
868 const auto cleanup = [&] {
869 if (memory) vk.vkFreeMemory(device, memory, nullptr);
870 if (buffer) vk.vkDestroyBuffer(device, buffer, nullptr);
871 };
872 if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &memory) != VK_SUCCESS ||
873 vk.vkBindBufferMemory(device, buffer, memory, 0) != VK_SUCCESS ||
874 vk.vkMapMemory(device, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) {
875 cleanup();
876 return;
877 }
878 VkCommandBuffer commands = probe_commands_;
879 vk.vkResetCommandBuffer(commands, 0);
880 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
881 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
882 vk.vkBeginCommandBuffer(commands, &begin);
883 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
884 for (const auto& piece : pieces)
885 detail::image_barrier(fn, commands, binding, piece.range, piece.layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
886 any, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_READ_BIT,
887 VK_PIPELINE_STAGE_TRANSFER_BIT);
888 VkBufferImageCopy copy{};
889 copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
890 copy.imageExtent = {binding.width, binding.height, 1};
891 fn.copy_image_to_buffer(commands, binding.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1, &copy);
892 for (const auto& piece : pieces)
893 detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, piece.layout,
894 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any,
895 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
896 VkBufferMemoryBarrier to_host{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
897 to_host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
898 to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
899 to_host.srcQueueFamilyIndex = to_host.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
900 to_host.buffer = buffer;
901 to_host.size = VK_WHOLE_SIZE;
902 fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, nullptr, 1,
903 &to_host, 0, nullptr);
904 vk.vkEndCommandBuffer(commands);
905 tracker_lock.unlock();
906 resource_lock.unlock();
907 vkResetFences_(device, 1, &probe_fence_);
908 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO};
909 submit_info.commandBufferCount = 1;
910 submit_info.pCommandBuffers = &commands;
911 VkResult submitted;
912 {
913 std::lock_guard lock(context_.submit_mutex());
914 submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, probe_fence_),
915 "vkQueueSubmit (present probe)");
916 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
917 }
918 if (submitted != VK_SUCCESS ||
919 context_.observe_result(vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 5'000'000'000ull),
920 "vkWaitForFences (present probe)") != VK_SUCCESS) {
921 std::fprintf(stderr, "[rt] present-probe: readback submit/wait failed (%d)\n", int(submitted));
922 cleanup();
923 return;
924 }
925 const std::size_t texels = std::size_t(binding.width) * binding.height;
926 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
927 std::vector<std::uint8_t> rgb(texels * 3);
928 double sum[3] = {0, 0, 0};
929 float peak = 0.0f;
930 std::size_t nonzero = 0;
931 bool decoded = true;
932 for (std::size_t i = 0; i < texels && decoded; ++i) {
933 float c[3];
934 if (!probe_decode(binding.format, bytes + i * bf.bytes, c)) {
935 decoded = false;
936 break;
937 }
938 bool any_set = false;
939 for (int k = 0; k < 3; ++k) {
940 sum[k] += c[k];
941 peak = std::max(peak, c[k]);
942 if (c[k] != 0.0f) any_set = true;
943 rgb[i * 3 + k] = std::uint8_t(std::clamp(c[k], 0.0f, 1.0f) * 255.0f + 0.5f);
944 }
945 nonzero += any_set;
946 }
947 // Raw bytes too: a format the probe cannot decode still says whether anything was written.
948 std::size_t raw_nonzero = 0;
949 std::size_t first_nonzero = SIZE_MAX;
950 for (std::size_t i = 0; i < std::size_t(size); ++i)
951 if (bytes[i]) {
952 if (first_nonzero == SIZE_MAX) first_nonzero = i;
953 ++raw_nonzero;
954 }
955 { // LOCAL DIAGNOSTIC (fsdraw): raw texels at the centre and at the first non-zero byte
956 const std::size_t centre = (std::size_t(binding.height / 2) * binding.width + binding.width / 2) * bf.bytes;
957 std::string c, f;
958 char b[8];
959 for (std::uint32_t k = 0; k < bf.bytes && k < 16; ++k) {
960 std::snprintf(b, sizeof b, "%02x", bytes[centre + k]);
961 c += b;
962 }
963 if (first_nonzero != SIZE_MAX) {
964 const std::size_t t = first_nonzero / bf.bytes * bf.bytes;
965 for (std::uint32_t k = 0; k < bf.bytes && k < 16; ++k) {
966 std::snprintf(b, sizeof b, "%02x", bytes[t + k]);
967 f += b;
968 }
969 }
970 std::fprintf(stderr, "[rt] present-probe: %s frame %llu raw centre texel %s first non-zero texel %lld (%s)\n",
971 prefix, static_cast<unsigned long long>(number), c.c_str(),
972 first_nonzero == SIZE_MAX ? -1ll : static_cast<long long>(first_nonzero / bf.bytes), f.c_str());
973 }
974 cleanup();
975 const double scale = 255.0 / double(texels);
976 std::fprintf(stderr,
977 "[rt] present-probe: %s frame %llu mean rgb %.2f %.2f %.2f (0..255 scale) peak %.3f nonzero "
978 "texels %zu of %zu, nonzero bytes %zu of %llu%s\n",
979 prefix, static_cast<unsigned long long>(number), sum[0] * scale, sum[1] * scale, sum[2] * scale, peak,
980 nonzero, texels, raw_nonzero, static_cast<unsigned long long>(size),
981 decoded ? "" : " (format not decoded)");
982 std::string dir = capture_dir_;
983 if (dir.back() != '/' && dir.back() != '\\') dir += '/';
984 if (decoded && (is_source || nonzero)) {
985 char name[64];
986 std::snprintf(name, sizeof name, "%s_%05llu.ppm", prefix, static_cast<unsigned long long>(number));
987 std::ofstream file(dir + name, std::ios::binary | std::ios::trunc);
988 if (file) {
989 file << "P6\n" << binding.width << ' ' << binding.height << "\n255\n";
990 file.write(reinterpret_cast<const char*>(rgb.data()), std::streamsize(rgb.size()));
991 }
992 }
993 std::ofstream index(dir + "source_index.txt", std::ios::app);
994 if (index)
995 index << prefix << " frame " << number << " id 0x" << std::hex << id << std::dec << " path " << path << " format " << int(binding.format) << " extent "
996 << binding.width << 'x' << binding.height << " layout " << int(layout) << " mean rgb " << std::fixed
997 << std::setprecision(2) << sum[0] * scale << ' ' << sum[1] * scale << ' ' << sum[2] * scale
998 << " nonzero texels " << nonzero << " nonzero bytes " << raw_nonzero << '\n';
999 if (is_source) ++probe_written_;
1000 }
1001 // ---- end LOCAL DIAGNOSTIC ----
1002
651 struct Frame { 1003 struct Frame {
652 VkCommandBuffer commands = VK_NULL_HANDLE; 1004 VkCommandBuffer commands = VK_NULL_HANDLE;
653 VkFence done = VK_NULL_HANDLE; 1005 VkFence done = VK_NULL_HANDLE;
@@ -655,6 +1007,9 @@ private:
655 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused 1007 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
656 }; 1008 };
657 1009
1010 bool recreate_for_present(bool vsync, bool srgb, bool hdr);
1011 VkResult finish_startup_frame(Frame& frame, std::uint32_t image, bool& show_title);
1012
658 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 1013 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
659 bool presentable(ResourceId source) { 1014 bool presentable(ResourceId source) {
660 std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h) 1015 std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h)
@@ -667,7 +1022,8 @@ private:
667 // present, which gives back the image that was never presented. Returns `failure`, the error to report. 1022 // present, which gives back the image that was never presented. Returns `failure`, the error to report.
668 VkResult give_back(Frame& frame, VkResult failure) { 1023 VkResult give_back(Frame& frame, VkResult failure) {
669 const VkDevice device = context_.device(); 1024 const VkDevice device = context_.device();
670 if (vkResetFences_(device, 1, &frame.done) != VK_SUCCESS) return stop(failure); 1025 if (context_.observe_result(vkResetFences_(device, 1, &frame.done), "vkResetFences (present)") != VK_SUCCESS)
1026 return stop(failure);
671 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; 1027 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
672 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; 1028 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO};
673 submit_info.waitSemaphoreCount = 1; 1029 submit_info.waitSemaphoreCount = 1;
@@ -676,7 +1032,8 @@ private:
676 VkResult submitted; 1032 VkResult submitted;
677 { 1033 {
678 std::lock_guard lock(context_.submit_mutex()); 1034 std::lock_guard lock(context_.submit_mutex());
679 submitted = context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); 1035 submitted = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done),
1036 "vkQueueSubmit (return present image)");
680 } 1037 }
681 if (submitted != VK_SUCCESS) return stop(failure); 1038 if (submitted != VK_SUCCESS) return stop(failure);
682 stale_ = true; 1039 stale_ = true;
@@ -707,7 +1064,8 @@ private:
707 const VkDevice device = context_.device(); 1064 const VkDevice device = context_.device();
708 { 1065 {
709 std::lock_guard lock(context_.submit_mutex()); 1066 std::lock_guard lock(context_.submit_mutex());
710 vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use 1067 // The old swapchain's images and semaphores may still be in use.
1068 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
711 release(swapchain_); 1069 release(swapchain_);
712 } 1070 }
713 swapchain_ = VK_NULL_HANDLE; 1071 swapchain_ = VK_NULL_HANDLE;
@@ -796,7 +1154,8 @@ private:
796 return true; 1154 return true;
797 { 1155 {
798 std::lock_guard lock(context_.submit_mutex()); 1156 std::lock_guard lock(context_.submit_mutex());
799 context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use 1157 // The old target may still be in use.
1158 context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
800 } 1159 }
801 bool changed = false; 1160 bool changed = false;
802 return composer_->ensure_target(extent_, changed); 1161 return composer_->ensure_target(extent_, changed);
@@ -921,8 +1280,9 @@ private:
921 1280
922 VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) { 1281 VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) {
923 for (;;) { 1282 for (;;) {
924 const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, 1283 const VkResult result = context_.observe_result(
925 VK_NULL_HANDLE, image); 1284 vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, VK_NULL_HANDLE, image),
1285 "vkAcquireNextImageKHR");
926 if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; 1286 if (result != VK_TIMEOUT && result != VK_NOT_READY) return result;
927 if (should_abort()) return VK_NOT_READY; 1287 if (should_abort()) return VK_NOT_READY;
928 } 1288 }
@@ -953,7 +1313,7 @@ private:
953 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 1313 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
954 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; 1314 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
955 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; 1315 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT;
956 if (capture_ && capture_buffer_) { 1316 if (capture_buffer_ && (capture_ || dump_.due(presented_))) {
957 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy 1317 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy
958 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. 1318 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC.
959 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; 1319 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
@@ -980,6 +1340,10 @@ private:
980 copy.imageExtent = {extent_.width, extent_.height, 1}; 1340 copy.imageExtent = {extent_.width, extent_.height, 1};
981 fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, 1341 fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1,
982 &copy); 1342 &copy);
1343 auto to_host = capture_waw;
1344 to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
1345 fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
1346 0, nullptr, 1, &to_host, 0, nullptr);
983 layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; 1347 layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
984 access = VK_ACCESS_TRANSFER_READ_BIT; 1348 access = VK_ACCESS_TRANSFER_READ_BIT;
985 } 1349 }
@@ -992,7 +1356,7 @@ private:
992 release_capture(); 1356 release_capture();
993 auto& vk = context_.vk; 1357 auto& vk = context_.vk;
994 const VkDevice device = context_.device(); 1358 const VkDevice device = context_.device();
995 capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; 1359 capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_);
996 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 1360 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
997 info.size = capture_size_; 1361 info.size = capture_size_;
998 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; 1362 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
@@ -1050,7 +1414,8 @@ private:
1050 1414
1051 VkResult finish_pending_capture() { 1415 VkResult finish_pending_capture() {
1052 if (!pending_capture_) return VK_SUCCESS; 1416 if (!pending_capture_) return VK_SUCCESS;
1053 const VkResult waited = vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX); 1417 const VkResult waited = context_.observe_result(
1418 vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX), "vkWaitForFences (capture)");
1054 pending_capture_ = VK_NULL_HANDLE; 1419 pending_capture_ = VK_NULL_HANDLE;
1055 if (waited == VK_SUCCESS) write_capture(); 1420 if (waited == VK_SUCCESS) write_capture();
1056 return waited; 1421 return waited;
@@ -1145,7 +1510,8 @@ private:
1145 const VkDevice device = context_.device(); 1510 const VkDevice device = context_.device();
1146 { 1511 {
1147 std::lock_guard lock(context_.submit_mutex()); 1512 std::lock_guard lock(context_.submit_mutex());
1148 vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use 1513 // The old swapchain's images and semaphores may still be in use.
1514 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1149 } 1515 }
1150 if (finish_pending_capture() != VK_SUCCESS) return false; 1516 if (finish_pending_capture() != VK_SUCCESS) return false;
1151 stale_ = true; // until this succeeds 1517 stale_ = true; // until this succeeds
@@ -1180,7 +1546,9 @@ private:
1180 return true; 1546 return true;
1181 } 1547 }
1182 VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; 1548 VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1183 if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; 1549 if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT))
1550 dump_.disable("surface does not support swapchain readback");
1551 if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
1184 if ((caps.supportedUsageFlags & usage) != usage) return false; 1552 if ((caps.supportedUsageFlags & usage) != usage) return false;
1185 // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain 1553 // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain
1186 // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it 1554 // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it
@@ -1288,7 +1656,8 @@ private:
1288 swapchain_ = VK_NULL_HANDLE; 1656 swapchain_ = VK_NULL_HANDLE;
1289 info.oldSwapchain = old; 1657 info.oldSwapchain = old;
1290 VkSwapchainKHR fresh = VK_NULL_HANDLE; 1658 VkSwapchainKHR fresh = VK_NULL_HANDLE;
1291 const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); 1659 const VkResult created = context_.observe_result(vkCreateSwapchainKHR_(device, &info, nullptr, &fresh),
1660 "vkCreateSwapchainKHR");
1292 { 1661 {
1293 std::lock_guard lock(context_.submit_mutex()); 1662 std::lock_guard lock(context_.submit_mutex());
1294 release(old); // retired by the creation attempt, whether or not it succeeded 1663 release(old); // retired by the creation attempt, whether or not it succeeded
@@ -1324,13 +1693,14 @@ private:
1324 extent_ = extent; 1693 extent_ = extent;
1325 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; 1694 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height;
1326 hdr_active_ = chose_hdr; 1695 hdr_active_ = chose_hdr;
1327 if (capture_) { 1696 dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT;
1328 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1697 if (capture_ || dump_.enabled()) {
1329 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1698 const auto stride = present_dump::texel_size(format_);
1330 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || 1699 if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel
1331 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || 1700 if (!stride || !make_capture_buffer()) {
1332 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; 1701 dump_.disable("cannot read back this swapchain format or allocate its capture buffer");
1333 if (!four_bytes || !make_capture_buffer()) return false; 1702 if (capture_) return false;
1703 }
1334 } 1704 }
1335 vsync_ = vsync; 1705 vsync_ = vsync;
1336 swapchain_srgb_ = srgb; 1706 swapchain_srgb_ = srgb;
@@ -1440,7 +1810,13 @@ private:
1440 bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created 1810 bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created
1441 std::map<VkFormat, VkFormatFeatureFlags> features_; 1811 std::map<VkFormat, VkFormatFeatureFlags> features_;
1442 bool warned_srgb_ = false; 1812 bool warned_srgb_ = false;
1813 std::shared_ptr<void> splash_owner_;
1814 ResourceBinding splash_binding_{};
1815 ResourceId splash_source_{};
1816 bool splash_capture_only_ = false;
1443 bool capture_ = false; 1817 bool capture_ = false;
1818 present_dump::PresentDump dump_;
1819 bool dump_pq_ = false;
1444 VkBuffer capture_buffer_ = VK_NULL_HANDLE; 1820 VkBuffer capture_buffer_ = VK_NULL_HANDLE;
1445 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; 1821 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE;
1446 VkDeviceSize capture_size_ = 0; 1822 VkDeviceSize capture_size_ = 0;
@@ -1479,3 +1855,5 @@ private:
1479}; 1855};
1480 1856
1481} // namespace leonida 1857} // namespace leonida
1858
1859#include "vulkan_present_splash.h"
diff --git a/runtime/src/vulkan_present_splash.h b/runtime/src/vulkan_present_splash.h
new file mode 100644
index 000000000..9dd94a313
--- /dev/null
+++ b/runtime/src/vulkan_present_splash.h
@@ -0,0 +1,63 @@
1#pragma once
2
3#include "vulkan_present.h"
4
5namespace leonida {
6
7inline bool VulkanPresenter::present_splash(ResourceId source, std::shared_ptr<void> owner) {
8 std::lock_guard lock(present_mutex_);
9 if (!deferred_.empty() || context_.holds().any_held()) return false;
10 {
11 std::shared_lock resources(context_.resource_mutex_);
12 const auto* binding = context_.resolve(source);
13 if (!binding || !binding->image) return false;
14 splash_binding_ = *binding;
15 }
16 if (!capture_) splash_capture_only_ = enable_capture();
17 const auto before = presented();
18 if (present(source, true) != VK_SUCCESS || presented() == before) return false;
19 const Frame& frame = frames_[(frame_index_ - 1) % frames_.size()];
20 if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS ||
21 finish_pending_capture() != VK_SUCCESS) return false;
22 if (capture_ptr_) {
23 splash_source_ = source;
24 splash_owner_ = std::move(owner);
25 }
26 return true;
27}
28
29// A changed surface or colour format may not support readback. Keep the title able to present on it.
30inline bool VulkanPresenter::recreate_for_present(bool vsync, bool srgb, bool hdr) {
31 if (recreate(vsync, srgb, hdr)) return true;
32 if (!splash_capture_only_) return false;
33 splash_owner_.reset();
34 splash_capture_only_ = false;
35 capture_ = false;
36 return recreate(vsync, srgb, hdr);
37}
38
39// Called only during the launch handoff, with the tracker and queue locked. Check the composed pixels so a
40// transparent overlay or a clear with nonzero alpha cannot dismiss the splash. Later black frames are genuine.
41inline VkResult VulkanPresenter::finish_startup_frame(Frame& frame, std::uint32_t image, bool& show_title) {
42 const VkDevice device = context_.device();
43 VkResult result = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX);
44 if (result != VK_SUCCESS) return result;
45 const bool ten_bit = format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
46 const std::uint32_t rgb = ten_bit ? 0x3fffffffu : 0xffffffu;
47 const auto* pixels = reinterpret_cast<const std::uint32_t*>(capture_ptr_);
48 const auto count = std::size_t(extent_.width) * extent_.height;
49 show_title = std::any_of(pixels, pixels + count, [rgb](auto pixel) { return (pixel & rgb) != 0; });
50 VkSubmitInfo ready{VK_STRUCTURE_TYPE_SUBMIT_INFO};
51 ready.signalSemaphoreCount = 1;
52 ready.pSignalSemaphores = &ready_[image];
53 if (show_title) return context_.vk.vkQueueSubmit(queue_, 1, &ready, VK_NULL_HANDLE);
54 // The acquire was consumed and the title commands finished. Overwrite the same image before presenting it.
55 record(frame.commands, splash_binding_, splash_source_, image, nullptr);
56 result = vkResetFences_(device, 1, &frame.done);
57 if (result != VK_SUCCESS) return result;
58 ready.commandBufferCount = 1;
59 ready.pCommandBuffers = &frame.commands;
60 return context_.vk.vkQueueSubmit(queue_, 1, &ready, frame.done);
61}
62
63} // namespace leonida
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 619d53827..2fef87194 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -1,4 +1,7 @@
1#pragma once 1#pragma once
2#include <atomic>
3#include <cfloat>
4#include <cstdlib>
2 5
3#include "resource_tiling.h" 6#include "resource_tiling.h"
4 7
@@ -31,7 +34,11 @@
31// A list that needs a missing function fails with ReplayResult::unsupported before anything is written. 34// A list that needs a missing function fails with ReplayResult::unsupported before anything is written.
32 35
33#include "command_list.h" 36#include "command_list.h"
37#include "deferred_image_binding.h"
38#include "vulkan_device_fault.h"
34#include "depth24.h" 39#include "depth24.h"
40#include "quad_index_expand.h"
41#include "rect_list_geometry.h"
35#include "uav_clear.h" 42#include "uav_clear.h"
36 43
37#include <vulkan/vulkan.h> 44#include <vulkan/vulkan.h>
@@ -41,8 +48,11 @@
41 48
42#include <algorithm> 49#include <algorithm>
43#include <array> 50#include <array>
51#include <atomic>
44#include <cmath> 52#include <cmath>
45#include <cstdint> 53#include <cstdint>
54#include <cstdio>
55#include <cstdlib>
46#include <functional> 56#include <functional>
47#include <limits> 57#include <limits>
48#include <map> 58#include <map>
@@ -97,6 +107,15 @@ struct ResourceBinding {
97 bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it 107 bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it
98 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush 108 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush
99 bool sparse_buffer = false; 109 bool sparse_buffer = false;
110 DeferredImageBinding* deferred_memory = nullptr; // Owned by the placed resource until it leaves the context.
111 std::atomic<bool>* replay_seen = nullptr; // Optional census of placed image use under the resource lock.
112 bool xbox_depth16_stencil8=false;
113 bool rgba4_render_fallback=false;
114 // The two independently addressable storage images of an Xbox depth/stencil UAV.
115 ResourceId depth_uav = 0, stencil_uav = 0;
116 void* residency_owner = nullptr;
117 bool (*ensure_residency)(void*) = nullptr;
118 ResourceId depth_conversion = 0; // R32_FLOAT transfer image for a widened Xbox D16+S8 attachment
100}; 119};
101 120
102struct VulkanAccess { 121struct VulkanAccess {
@@ -465,11 +484,16 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
465 case VK_FORMAT_R16_SINT: 484 case VK_FORMAT_R16_SINT:
466 case VK_FORMAT_A4R4G4B4_UNORM_PACK16: 485 case VK_FORMAT_A4R4G4B4_UNORM_PACK16:
467 case VK_FORMAT_R4G4B4A4_UNORM_PACK16: 486 case VK_FORMAT_R4G4B4A4_UNORM_PACK16:
487 case VK_FORMAT_D16_UNORM_S8_UINT:
468 case VK_FORMAT_D16_UNORM: return {2, 1}; 488 case VK_FORMAT_D16_UNORM: return {2, 1};
469 case VK_FORMAT_R8_UNORM: 489 case VK_FORMAT_R8_UNORM:
470 case VK_FORMAT_R8_SNORM: 490 case VK_FORMAT_R8_SNORM:
471 case VK_FORMAT_R8_UINT: 491 case VK_FORMAT_R8_UINT:
472 case VK_FORMAT_R8_SINT: return {1, 1}; 492 case VK_FORMAT_R8_SINT:
493#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
494 case VK_FORMAT_A8_UNORM_KHR: // an A8_UNORM render target (VulkanDeviceInfo::a8_render_target)
495#endif
496 return {1, 1};
473 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: 497 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
474 case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: 498 case VK_FORMAT_BC1_RGBA_SRGB_BLOCK:
475 case VK_FORMAT_BC4_UNORM_BLOCK: 499 case VK_FORMAT_BC4_UNORM_BLOCK:
@@ -504,6 +528,21 @@ inline bool two_planes(const ResourceBinding& resource) {
504// R32_FLOAT/UINT/SINT (R32_TYPELESS) and D16_UNORM with R16_FLOAT/UNORM/SNORM/UINT/SINT (R16_TYPELESS). Single-sampled, single-plane depth only: D24 and D32 with stencil have two planes, and a D24 528// R32_FLOAT/UINT/SINT (R32_TYPELESS) and D16_UNORM with R16_FLOAT/UNORM/SNORM/UINT/SINT (R16_TYPELESS). Single-sampled, single-plane depth only: D24 and D32 with stencil have two planes, and a D24
505// stored as D32 would need the depth24 conversion. Vulkan's vkCmdCopyImage refuses mismatched aspects, so the replay 529// stored as D32 would need the depth24 conversion. Vulkan's vkCmdCopyImage refuses mismatched aspects, so the replay
506// stages these through a buffer. 530// stages these through a buffer.
531// An A8_UNORM texture is a VK_FORMAT_A8_UNORM_KHR image when it is a render target (VulkanDeviceInfo::
532// a8_render_target) and an R8_UNORM image otherwise; D3D12 copies between the two as between any two A8_UNORM
533// textures. Vulkan puts A8 in a compatibility class of its own, so vkCmdCopyImage refuses the pair
534// (VUID-vkCmdCopyImage-srcImage-01548) although both have one byte per texel: the replay stages it through a buffer,
535// as it does a depth <-> colour pair.
536inline bool a8_mixed_backing(VkFormat a, VkFormat b) {
537#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
538 return a != b && (a == VK_FORMAT_A8_UNORM_KHR || b == VK_FORMAT_A8_UNORM_KHR);
539#else
540 (void)a;
541 (void)b;
542 return false;
543#endif
544}
545
507inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { 546inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) {
508 const auto family = [](VkFormat format) -> int { 547 const auto family = [](VkFormat format) -> int {
509 switch (format) { 548 switch (format) {
@@ -759,6 +798,12 @@ struct ComputePipeline {
759 VkPipelineLayout layout = VK_NULL_HANDLE; 798 VkPipelineLayout layout = VK_NULL_HANDLE;
760 std::uint64_t code_base = 0; 799 std::uint64_t code_base = 0;
761 VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none 800 VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none
801 // A pipeline built on first use: with `pipeline` null, `build(build_context)` returns the handle (building it if
802 // nobody has yet), or null when it cannot be built. Null `build`: `pipeline` is final.
803 VkPipeline (*build)(void*) = nullptr;
804 void* build_context = nullptr;
805 bool async_build = false; // a null handle may be waiting for the compile worker
806 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped
762}; 807};
763 808
764// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it 809// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it
@@ -781,8 +826,12 @@ struct GraphicsPipeline {
781 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth 826 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth
782 // and stencil. Null when it cannot be built. 827 // and stencil. Null when it cannot be built.
783 static constexpr std::uint32_t unbound_depth = 1u << 8; 828 static constexpr std::uint32_t unbound_depth = 1u << 8;
784 std::function<VkPipeline(std::uint32_t unbound)> variant; 829 static constexpr std::uint32_t rectangle_stage = 1u << 9;
830 // IA topology requiring a fourth-corner geometry stage. Zero when the PSO already contains the stage.
831 std::uint32_t rectangle_variant_topology = 0;
832 std::function<VkPipeline(std::uint32_t flags)> variant;
785 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 833 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
834 bool async_build = false;
786}; 835};
787 836
788// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 837// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -811,7 +860,63 @@ enum class ReplayResult {
811 unsupported 860 unsupported
812}; 861};
813 862
863// LOCAL DIAGNOSTIC: which check called a resource unresolved, by source line, logged at the 1st, 2nd, 4th, 8th...
864// time it fires (a list that fails this way is not submitted at all, so the first lines name what stops rendering).
865// LEONIDA_STRICT_REPLAY=1: an unresolvable draw or dispatch fails its list again instead of being dropped. Read with
866// the C runtime, not the Win32 API: this header is built into tests without windows.h too.
867inline bool strict_replay() {
868 static const bool strict = [] {
869#ifdef _WIN32
870 char value[2]{};
871 std::size_t length = 0;
872 return getenv_s(&length, value, sizeof value, "LEONIDA_STRICT_REPLAY") == 0 && length == 2 && value[0] == '1';
873#else
874 const char* value = std::getenv("LEONIDA_STRICT_REPLAY");
875 return value && value[0] == '1' && !value[1];
876#endif
877 }();
878 return strict;
879}
880
881inline bool order_buffer_copies() {
882 static const bool enabled = [] {
883#ifdef _WIN32
884 char value[2]{};
885 std::size_t length = 0;
886 return getenv_s(&length, value, sizeof value, "LEONIDA_ORDER_BUFFER_COPIES") != 0 || length != 2 || value[0] != '0';
887#else
888 const char* value = std::getenv("LEONIDA_ORDER_BUFFER_COPIES");
889 return !value || value[0] != '0' || value[1];
890#endif
891 }();
892 return enabled;
893}
894
895inline ReplayResult unresolved_at(int line) {
896 static std::atomic<unsigned> seen[8192];
897 if (line >= 0 && line < 8192) {
898 const unsigned count = seen[line].fetch_add(1, std::memory_order_relaxed) + 1;
899 if ((count & (count - 1)) == 0)
900 std::fprintf(stderr, "[rt] replay: unresolved resource at vulkan_replay.h:%d (x%u)\n", line, count);
901 }
902 return ReplayResult::unresolved_resource;
903}
904
905// LOCAL DIAGNOSTIC, as unresolved_at: which check called a command list unsupported (the whole list is then not
906// submitted: "ExecuteCommandLists failed: unsupported"), by source line, at the 1st, 2nd, 4th, 8th... time.
907inline ReplayResult unsupported_at(int line) {
908 static std::atomic<unsigned> seen[8192];
909 if (line >= 0 && line < 8192) {
910 const unsigned count = seen[line].fetch_add(1, std::memory_order_relaxed) + 1;
911 if ((count & (count - 1)) == 0)
912 std::fprintf(stderr, "[rt] replay: unsupported at vulkan_replay.h:%d (x%u)\n", line, count);
913 }
914 return ReplayResult::unsupported;
915}
916
917
814struct ReplayFunctions { 918struct ReplayFunctions {
919 std::function<void(VkCommandBuffer, const label::Write&)> gpu_label;
815 // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current 920 // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current
816 // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. 921 // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's.
817 VkDescriptorSet bindless_set = VK_NULL_HANDLE; 922 VkDescriptorSet bindless_set = VK_NULL_HANDLE;
@@ -822,6 +927,9 @@ struct ReplayFunctions {
822 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. 927 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported.
823 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers 928 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers
824 VkPipelineStageFlags2 queue_stages = 0; 929 VkPipelineStageFlags2 queue_stages = 0;
930 bool graphics_family = true;
931 // Aspects with maintenance10 depth/stencil transfer support on a dedicated compute family.
932 std::function<VkImageAspectFlags(VkFormat)> compute_copy_aspects;
825 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears 933 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears
826 PFN_vkCmdEndRendering end_rendering = nullptr; 934 PFN_vkCmdEndRendering end_rendering = nullptr;
827 PFN_vkCmdClearAttachments clear_attachments = nullptr; 935 PFN_vkCmdClearAttachments clear_attachments = nullptr;
@@ -829,6 +937,7 @@ struct ReplayFunctions {
829 PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr; 937 PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr;
830 PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; 938 PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr;
831 PFN_vkCmdCopyImage copy_image = nullptr; 939 PFN_vkCmdCopyImage copy_image = nullptr;
940 PFN_vkCmdBlitImage blit_image = nullptr;
832 PFN_vkCmdResolveImage resolve_image = nullptr; // resolves 941 PFN_vkCmdResolveImage resolve_image = nullptr; // resolves
833 PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer 942 PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer
834 PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears 943 PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears
@@ -866,6 +975,7 @@ struct ReplayFunctions {
866 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; 975 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr;
867 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; 976 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr;
868 PFN_vkCmdDraw draw = nullptr; 977 PFN_vkCmdDraw draw = nullptr;
978 unsigned* mesh_draw_count = nullptr; // opt-in count for this submission
869 PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported 979 PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported
870 PFN_vkCmdDrawIndexed draw_indexed = nullptr; 980 PFN_vkCmdDrawIndexed draw_indexed = nullptr;
871 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline; 981 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline;
@@ -873,6 +983,10 @@ struct ReplayFunctions {
873 // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all 983 // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all
874 // of it. 984 // of it.
875 std::function<bool(std::uint64_t va, std::uint64_t& size, VkBuffer&, VkDeviceSize&)> buffer_at; 985 std::function<bool(std::uint64_t va, std::uint64_t& size, VkBuffer&, VkDeviceSize&)> buffer_at;
986 // A vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console
987 // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false
988 // when the range is not readable host memory.
989 std::function<bool(std::uint64_t va, std::uint64_t size, VkBuffer&, VkDeviceSize&)> title_memory;
876 // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small 990 // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small
877 // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. 991 // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build.
878 std::function<HostReadStatus(std::uint64_t va, std::uint64_t bytes, const std::uint8_t*&)> host_at; 992 std::function<HostReadStatus(std::uint64_t va, std::uint64_t bytes, const std::uint8_t*&)> host_at;
@@ -880,6 +994,10 @@ struct ReplayFunctions {
880 VkBuffer zero_buffer = VK_NULL_HANDLE; 994 VkBuffer zero_buffer = VK_NULL_HANDLE;
881 VkDeviceSize zero_offset = 0; 995 VkDeviceSize zero_offset = 0;
882 VkDeviceSize zero_size = 0; 996 VkDeviceSize zero_size = 0;
997 // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad.
998 VkBuffer quad_indices = VK_NULL_HANDLE;
999 VkDeviceSize quad_indices_offset = 0;
1000 std::uint32_t quad_index_count = 0;
883 std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) 1001 std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33)
884 // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. 1002 // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering.
885 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 1003 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
@@ -912,6 +1030,14 @@ struct ReplayFunctions {
912 std::function<bool(VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t, 1030 std::function<bool(VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t,
913 CountedDispatch&)> prepare_counted_dispatch; 1031 CountedDispatch&)> prepare_counted_dispatch;
914 std::function<void(VkCommandBuffer, const CountedDispatch&)> emit_counted_dispatch; 1032 std::function<void(VkCommandBuffer, const CountedDispatch&)> emit_counted_dispatch;
1033 // An indexed quad list draws from triangle-list indices that a compute prepass writes from the application's
1034 // index buffer (quad_index_expand.h): the index buffer and the offset of the draw's first index, the index type,
1035 // how many indices from there the view holds, the quads, and QuadIndexExpander::bytes(quads) of `copy_scratch`.
1036 // That scratch must be usable as an index buffer and through its device address. Without both such a draw is
1037 // unsupported.
1038 std::function<bool(VkBuffer, VkDeviceSize, VkIndexType, std::uint64_t, std::uint32_t, VkBuffer, VkDeviceSize,
1039 QuadIndexExpansion&)> prepare_quad_indices;
1040 std::function<void(VkCommandBuffer, const QuadIndexExpansion&)> emit_quad_indices;
915 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. 1041 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure.
916 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; 1042 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr;
917 // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan 1043 // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan
@@ -955,7 +1081,8 @@ struct ReplayFunctions {
955 std::function<bool(Depth24Job&, std::vector<Depth24Job>&)> depth24_prepare; // whole copy in, dispatches out 1081 std::function<bool(Depth24Job&, std::vector<Depth24Job>&)> depth24_prepare; // whole copy in, dispatches out
956 std::function<void(VkCommandBuffer, const Depth24Job&)> depth24_run; 1082 std::function<void(VkCommandBuffer, const Depth24Job&)> depth24_run;
957 // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour 1083 // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour
958 // copies go through it, image to buffer to image. Without it such a copy is unsupported. 1084 // copies go through it, image to buffer to image. Without it such a copy is unsupported. The expanded indices of
1085 // an indexed quad list are written there too (prepare_quad_indices).
959 std::function<bool(VkDeviceSize bytes, VkBuffer&, VkDeviceSize&)> copy_scratch; 1086 std::function<bool(VkDeviceSize bytes, VkBuffer&, VkDeviceSize&)> copy_scratch;
960 // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. 1087 // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run.
961 std::function<QueryPool*(QueryHeapId)> query_pool; 1088 std::function<QueryPool*(QueryHeapId)> query_pool;
@@ -1041,6 +1168,7 @@ struct Prepared {
1041 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. 1168 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination.
1042 VkBuffer staged = VK_NULL_HANDLE; 1169 VkBuffer staged = VK_NULL_HANDLE;
1043 std::vector<VkBufferImageCopy> staged_reads, staged_writes; 1170 std::vector<VkBufferImageCopy> staged_reads, staged_writes;
1171 VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue
1044 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard 1172 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard
1045 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands 1173 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands
1046 VkDeviceSize write_offset = 0; 1174 VkDeviceSize write_offset = 0;
@@ -1052,6 +1180,8 @@ struct Prepared {
1052 QueryPool* queries = nullptr; // query commands: the heap 1180 QueryPool* queries = nullptr; // query commands: the heap
1053 ComputePipeline pipeline; // dispatches 1181 ComputePipeline pipeline; // dispatches
1054 std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws 1182 std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws
1183 std::uint32_t depth_uav_copy = UINT32_MAX;
1184 bool order_depth_uav = false;
1055 VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; 1185 VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE;
1056 VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly 1186 VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly
1057 std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write 1187 std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write
@@ -1059,6 +1189,26 @@ struct Prepared {
1059 std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR 1189 std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR
1060}; 1190};
1061 1191
1192struct DepthUavCopy {
1193 std::array<ResourceBinding, 2> storage;
1194 ResourceBinding conversion{};
1195 VkBuffer scratch;
1196 VkDeviceSize offset;
1197 bool to_storage;
1198};
1199
1200inline bool texture_uav_layout(std::uint32_t layout) {
1201 return layout == d3d12_layout::unordered_access || layout == d3d12_layout::direct_queue_unordered_access ||
1202 layout == d3d12_layout::compute_queue_unordered_access;
1203}
1204
1205inline bool unsupported_depth_uav_access(std::uint32_t layout, std::uint32_t access) {
1206 // A queue-specific COMMON layout permits implicit storage writes. Generic COMMON permits only
1207 // sampling and copies, even when the access scope is COMMON (zero).
1208 return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common ||
1209 (layout == d3d12_layout::common && (access & d3d12_access::unordered_access));
1210}
1211
1062inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT 1212inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT
1063 1213
1064// What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every 1214// What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every
@@ -1080,12 +1230,18 @@ struct PreparedDraw {
1080 std::vector<VkDeviceSize> vertex_offsets, vertex_sizes, vertex_strides; 1230 std::vector<VkDeviceSize> vertex_offsets, vertex_sizes, vertex_strides;
1081 VkBuffer index_buffer = VK_NULL_HANDLE; 1231 VkBuffer index_buffer = VK_NULL_HANDLE;
1082 VkDeviceSize index_offset = 0; 1232 VkDeviceSize index_offset = 0;
1233 VkDeviceSize index_size = 0; // the bytes of the index buffer view inside its buffer; 0 with no index buffer
1083 VkIndexType index_type = VK_INDEX_TYPE_UINT16; 1234 VkIndexType index_type = VK_INDEX_TYPE_UINT16;
1235 QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead
1084 VkExtent2D area{}; 1236 VkExtent2D area{};
1085 std::uint32_t layers = 1; // the fewest layers any bound attachment view has 1237 std::uint32_t layers = 1; // the fewest layers any bound attachment view has
1238 // The draw is dropped at emit: its pipeline, a vertex buffer or its index buffer could not be resolved (see
1239 // skip_unresolved in prepare).
1240 bool skipped = false;
1086 1241
1087 // Back to a new draw's state, keeping the vectors' storage. 1242 // Back to a new draw's state, keeping the vectors' storage.
1088 void reset() { 1243 void reset() {
1244 skipped = false;
1089 graphics = nullptr; 1245 graphics = nullptr;
1090 pipeline = VK_NULL_HANDLE; 1246 pipeline = VK_NULL_HANDLE;
1091 colors.clear(); 1247 colors.clear();
@@ -1096,7 +1252,9 @@ struct PreparedDraw {
1096 vertex_strides.clear(); 1252 vertex_strides.clear();
1097 index_buffer = VK_NULL_HANDLE; 1253 index_buffer = VK_NULL_HANDLE;
1098 index_offset = 0; 1254 index_offset = 0;
1255 index_size = 0;
1099 index_type = VK_INDEX_TYPE_UINT16; 1256 index_type = VK_INDEX_TYPE_UINT16;
1257 quad_indices = {};
1100 area = {}; 1258 area = {};
1101 layers = 1; 1259 layers = 1;
1102 } 1260 }
@@ -1172,6 +1330,9 @@ inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearC
1172 case VK_FORMAT_R8G8_UNORM: 1330 case VK_FORMAT_R8G8_UNORM:
1173 case VK_FORMAT_R8G8B8A8_UNORM: 1331 case VK_FORMAT_R8G8B8A8_UNORM:
1174 case VK_FORMAT_B8G8R8A8_UNORM: is_integer = false; unorm = {255, 255, 255, 255}; break; 1332 case VK_FORMAT_B8G8R8A8_UNORM: is_integer = false; unorm = {255, 255, 255, 255}; break;
1333#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
1334 case VK_FORMAT_A8_UNORM_KHR: is_integer = false; unorm = {0, 0, 0, 255}; break; // alpha only
1335#endif
1175 case VK_FORMAT_R8G8B8A8_SRGB: 1336 case VK_FORMAT_R8G8B8A8_SRGB:
1176 case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels go through the sRGB curve on the GPU 1337 case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels go through the sRGB curve on the GPU
1177 is_integer = false; 1338 is_integer = false;
@@ -1370,14 +1531,12 @@ inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const V
1370 return out; 1531 return out;
1371} 1532}
1372 1533
1373// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page 1534// Copies zeroes from the device's zero page or transfer scratch. A buffer can initialize block-compressed
1374// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids 1535// images and, with maintenance10, a depth or stencil aspect on a compute-only queue where a clear is illegal.
1375// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set 1536inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command_buffer,
1376// (D3D-220). 1537 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1377inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer, 1538 VkImageAspectFlags aspect, VkImageLayout dst_layout) {
1378 const ResourceBinding& resource, const VkImageSubresourceRange& range, 1539 const BlockFormat fmt = block_format(resource.format, aspect);
1379 VkImageLayout dst_layout) {
1380 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1381 if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; 1540 if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false;
1382 const std::uint32_t mip_begin = range.baseMipLevel; 1541 const std::uint32_t mip_begin = range.baseMipLevel;
1383 const std::uint32_t mip_end = 1542 const std::uint32_t mip_end =
@@ -1411,7 +1570,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1411 VkDeviceSize zero_off = 0; 1570 VkDeviceSize zero_off = 0;
1412 VkDeviceSize zero_cap = 0; 1571 VkDeviceSize zero_cap = 0;
1413 if (vk.zero_buffer && vk.zero_size >= fmt.bytes) { 1572 if (vk.zero_buffer && vk.zero_size >= fmt.bytes) {
1414 const VkDeviceSize align = fmt.bytes; 1573 const VkDeviceSize align = std::max<VkDeviceSize>(4, fmt.bytes);
1415 const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align; 1574 const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align;
1416 if (vk.zero_size >= pad + fmt.bytes) { 1575 if (vk.zero_size >= pad + fmt.bytes) {
1417 zero_buf = vk.zero_buffer; 1576 zero_buf = vk.zero_buffer;
@@ -1420,20 +1579,23 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1420 } 1579 }
1421 } 1580 }
1422 if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { 1581 if (!zero_buf && vk.copy_scratch && vk.fill_buffer) {
1423 // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer). 1582 // vkCmdFillBuffer requires 4-byte aligned dstOffset and size (VUID-vkCmdFillBuffer-dstOffset-00024 /
1424 const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes; 1583 // -size-00028), while vkCmdCopyBufferToImage requires fmt.bytes alignment (1, 2, 4, 8, or 16).
1584 // Uncompressed 1B/2B color formats reach this path on copy-only queues (!can_clear).
1585 const VkDeviceSize align = std::max<VkDeviceSize>(4, fmt.bytes);
1586 const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align;
1425 VkBuffer scratch = VK_NULL_HANDLE; 1587 VkBuffer scratch = VK_NULL_HANDLE;
1426 VkDeviceSize offset = 0; 1588 VkDeviceSize offset = 0;
1427 if (vk.copy_scratch(fill_bytes, scratch, offset)) { 1589 if (vk.copy_scratch(fill_bytes, scratch, offset)) {
1428 const VkDeviceSize align = fmt.bytes;
1429 const VkDeviceSize pad = (align - (offset % align)) % align; 1590 const VkDeviceSize pad = (align - (offset % align)) % align;
1430 if (fill_bytes >= pad + fmt.bytes) { 1591 const VkDeviceSize usable = fill_bytes > pad ? ((fill_bytes - pad) / align) * align : 0;
1431 vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0); 1592 if (usable >= fmt.bytes) {
1593 vk.fill_buffer(command_buffer, scratch, offset + pad, usable, 0);
1432 memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 1594 memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1433 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); 1595 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1434 zero_buf = scratch; 1596 zero_buf = scratch;
1435 zero_off = offset + pad; 1597 zero_off = offset + pad;
1436 zero_cap = fill_bytes - pad; 1598 zero_cap = usable;
1437 } 1599 }
1438 } 1600 }
1439 } 1601 }
@@ -1450,7 +1612,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1450 layer_count <= zero_cap / (slice_bytes * mip_d)) { 1612 layer_count <= zero_cap / (slice_bytes * mip_d)) {
1451 VkBufferImageCopy r{}; 1613 VkBufferImageCopy r{};
1452 r.bufferOffset = zero_off; 1614 r.bufferOffset = zero_off;
1453 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count}; 1615 r.imageSubresource = {aspect, mip, layer_begin, layer_count};
1454 r.imageExtent = {ext.width, ext.height, mip_d}; 1616 r.imageExtent = {ext.width, ext.height, mip_d};
1455 regions.push_back(r); 1617 regions.push_back(r);
1456 continue; 1618 continue;
@@ -1463,7 +1625,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1463 for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) { 1625 for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) {
1464 VkBufferImageCopy r{}; 1626 VkBufferImageCopy r{};
1465 r.bufferOffset = zero_off; 1627 r.bufferOffset = zero_off;
1466 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; 1628 r.imageSubresource = {aspect, mip, layer, 1};
1467 r.imageOffset = {0, 0, std::int32_t(z)}; 1629 r.imageOffset = {0, 0, std::int32_t(z)};
1468 r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)}; 1630 r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)};
1469 regions.push_back(r); 1631 regions.push_back(r);
@@ -1477,7 +1639,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1477 const std::uint32_t eh = std::min<std::uint32_t>(rows_per_copy * fmt.block, ext.height - oy); 1639 const std::uint32_t eh = std::min<std::uint32_t>(rows_per_copy * fmt.block, ext.height - oy);
1478 VkBufferImageCopy r{}; 1640 VkBufferImageCopy r{};
1479 r.bufferOffset = zero_off; 1641 r.bufferOffset = zero_off;
1480 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; 1642 r.imageSubresource = {aspect, mip, layer, 1};
1481 r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)}; 1643 r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)};
1482 r.imageExtent = {ext.width, eh, 1}; 1644 r.imageExtent = {ext.width, eh, 1};
1483 regions.push_back(r); 1645 regions.push_back(r);
@@ -1496,7 +1658,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1496 std::min<std::uint32_t>(cols_per_copy * fmt.block, ext.width - ox); 1658 std::min<std::uint32_t>(cols_per_copy * fmt.block, ext.width - ox);
1497 VkBufferImageCopy r{}; 1659 VkBufferImageCopy r{};
1498 r.bufferOffset = zero_off; 1660 r.bufferOffset = zero_off;
1499 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; 1661 r.imageSubresource = {aspect, mip, layer, 1};
1500 r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)}; 1662 r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)};
1501 r.imageExtent = {ew, eh, 1}; 1663 r.imageExtent = {ew, eh, 1};
1502 regions.push_back(r); 1664 regions.push_back(r);
@@ -1512,6 +1674,14 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1512 return true; 1674 return true;
1513} 1675}
1514 1676
1677// The colour aspect of a block-compressed image: Vulkan forbids vkCmdClearColorImage on BC formats, yet D3D12
1678// committed resources start zeroed unless CREATE_NOT_ZEROED is set (D3D-220).
1679inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer,
1680 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1681 VkImageLayout dst_layout) {
1682 return zero_image_aspect(vk, command_buffer, resource, range, VK_IMAGE_ASPECT_COLOR_BIT, dst_layout);
1683}
1684
1515// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed, 1685// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed,
1516// so each such piece is zero-filled (clear for uncompressed images, zero-buffer copy for block-compressed formats 1686// so each such piece is zero-filled (clear for uncompressed images, zero-buffer copy for block-compressed formats
1517// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run 1687// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run
@@ -1523,12 +1693,15 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
1523 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1693 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
1524 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); 1694 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1525 const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; 1695 const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT;
1526 const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color); 1696 const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color) ||
1527 const bool compressed = fmt.block > 1 || (!can_clear && color); 1697 (resource.depth_uav && vk.graphics_family);
1528 if (resource.not_zeroed || (!can_clear && !color)) { 1698 const bool compute_depth = !color && resource.depth_uav && !vk.graphics_family &&
1699 (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && vk.compute_copy_aspects &&
1700 (vk.compute_copy_aspects(resource.format) & piece.range.aspectMask) == piece.range.aspectMask;
1701 if (resource.not_zeroed || (!can_clear && !color && !compute_depth)) {
1529 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 1702 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1530 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1703 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1531 } else if (compressed) { 1704 } else if (fmt.block > 1 || !can_clear) {
1532 const bool can_zero = 1705 const bool can_zero =
1533 vk.copy_buffer_to_image && 1706 vk.copy_buffer_to_image &&
1534 ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer)); 1707 ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer));
@@ -1537,7 +1710,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
1537 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, 1710 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
1538 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, 1711 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
1539 VK_PIPELINE_STAGE_TRANSFER_BIT); 1712 VK_PIPELINE_STAGE_TRANSFER_BIT);
1540 const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); 1713 bool zeroed = true;
1714 for (auto aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT})
1715 if (piece.range.aspectMask & aspect)
1716 zeroed &= zero_image_aspect(vk, command_buffer, resource, piece.range, aspect, dst);
1541 image_barrier(vk, command_buffer, resource, piece.range, dst, layout, 1717 image_barrier(vk, command_buffer, resource, piece.range, dst, layout,
1542 zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, 1718 zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0,
1543 zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, 1719 zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory,
@@ -1602,7 +1778,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear,
1602 const std::uint64_t size = std::min(view.size, p.binding.size - view.offset); 1778 const std::uint64_t size = std::min(view.size, p.binding.size - view.offset);
1603 if (view.format) { 1779 if (view.format) {
1604 if (!uav_clear::encode(VkFormat(view.format), clear.is_float, clear.values, p.element)) 1780 if (!uav_clear::encode(VkFormat(view.format), clear.is_float, clear.values, p.element))
1605 return ReplayResult::unsupported; 1781 return unsupported_at(__LINE__);
1606 if (view.element_size != p.element.size) return ReplayResult::invalid_clear; 1782 if (view.element_size != p.element.size) return ReplayResult::invalid_clear;
1607 } else { 1783 } else {
1608 p.element = uav_clear::raw_element(clear.values); 1784 p.element = uav_clear::raw_element(clear.values);
@@ -1616,7 +1792,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear,
1616 offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset 1792 offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset
1617 if (offset % std::min(e, 4u)) return ReplayResult::unsupported; 1793 if (offset % std::min(e, 4u)) return ReplayResult::unsupported;
1618 if (e > 4 && bytes % 4) { 1794 if (e > 4 && bytes % 4) {
1619 return ReplayResult::unsupported; 1795 return unsupported_at(__LINE__);
1620 } 1796 }
1621 p.fills.push_back({offset, bytes}); 1797 p.fills.push_back({offset, bytes});
1622 return ReplayResult::success; 1798 return ReplayResult::success;
@@ -1824,7 +2000,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1824 const BlockFormat format = copy_block_format(image, range.aspectMask); 2000 const BlockFormat format = copy_block_format(image, range.aspectMask);
1825 // A 12-byte texel does not divide D3D12's 256-byte pitches; an rgb96 copy hands Vulkan the scratch buffer of 2001 // A 12-byte texel does not divide D3D12's 256-byte pitches; an rgb96 copy hands Vulkan the scratch buffer of
1826 // the repack, never this pitch, and the pass reads the footprint in words. 2002 // the repack, never this pitch, and the pass reads the footprint in words.
1827 if (!format.bytes || placed.row_pitch % (image.rgb96 ? 4 : format.bytes)) return ReplayResult::unsupported; 2003 if (!format.bytes || placed.row_pitch % (image.rgb96 ? 4 : format.bytes)) return unsupported_at(__LINE__);
1828 const VkExtent2D mip = mip_extent(image, range.baseMipLevel); 2004 const VkExtent2D mip = mip_extent(image, range.baseMipLevel);
1829 const auto mip_depth = std::max(1u, image.depth >> range.baseMipLevel); 2005 const auto mip_depth = std::max(1u, image.depth >> range.baseMipLevel);
1830 // The box is in the source's coordinates: the footprint for an upload, the texture for a readback. 2006 // The box is in the source's coordinates: the footprint for an upload, the texture for a readback.
@@ -1857,7 +2033,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1857 // Vulkan wants a buffer offset that is a multiple of the texel size (VUID-vkCmdCopyBufferToImage-dstImage-07975), 2033 // Vulkan wants a buffer offset that is a multiple of the texel size (VUID-vkCmdCopyBufferToImage-dstImage-07975),
1858 // which D3D12's 512-byte placement does not give a 12-byte texel: one more reason an rgb96 copy is repacked. 2034 // which D3D12's 512-byte placement does not give a 12-byte texel: one more reason an rgb96 copy is repacked.
1859 const std::uint32_t alignment = (range.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : format.bytes; 2035 const std::uint32_t alignment = (range.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : format.bytes;
1860 if (offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; 2036 if (offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__);
1861 const std::uint64_t rows = (std::uint64_t(h) + format.block - 1) / format.block; 2037 const std::uint64_t rows = (std::uint64_t(h) + format.block - 1) / format.block;
1862 const std::uint64_t row_bytes = (std::uint64_t(w) + format.block - 1) / format.block * format.bytes; 2038 const std::uint64_t row_bytes = (std::uint64_t(w) + format.block - 1) / format.block * format.bytes;
1863 if (!rows || !row_bytes || !within(std::uint64_t(placed_x / format.block) * format.bytes, row_bytes, placed.row_pitch) || 2039 if (!rows || !row_bytes || !within(std::uint64_t(placed_x / format.block) * format.bytes, row_bytes, placed.row_pitch) ||
@@ -1866,7 +2042,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1866 return ReplayResult::invalid_copy; 2042 return ReplayResult::invalid_copy;
1867 if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy; 2043 if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy;
1868 const VkDeviceSize backing_offset = buffer.buffer_offset + offset; 2044 const VkDeviceSize backing_offset = buffer.buffer_offset + offset;
1869 if (backing_offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; 2045 if (backing_offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__);
1870 VkBufferImageCopy region{}; 2046 VkBufferImageCopy region{};
1871 region.bufferOffset = backing_offset; 2047 region.bufferOffset = backing_offset;
1872 region.bufferRowLength = placed.row_pitch / format.bytes * format.block; 2048 region.bufferRowLength = placed.row_pitch / format.bytes * format.block;
@@ -1875,7 +2051,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1875 region.imageOffset = {std::int32_t(texture_x), std::int32_t(texture_y), std::int32_t(texture_z)}; 2051 region.imageOffset = {std::int32_t(texture_x), std::int32_t(texture_y), std::int32_t(texture_z)};
1876 region.imageExtent = {w, h, depth}; 2052 region.imageExtent = {w, h, depth};
1877 if (image.rgb96) { // the repack's scratch replaces this buffer in the copy; these are for the pass 2053 if (image.rgb96) { // the repack's scratch replaces this buffer in the copy; these are for the pass
1878 if (placed.row_pitch / 4 > UINT32_MAX || slice_pitch / 4 > UINT32_MAX) return ReplayResult::unsupported; 2054 if (placed.row_pitch / 4 > UINT32_MAX || slice_pitch / 4 > UINT32_MAX) return unsupported_at(__LINE__);
1879 p.rgb96_row_words = std::uint32_t(placed.row_pitch / 4); 2055 p.rgb96_row_words = std::uint32_t(placed.row_pitch / 4);
1880 p.rgb96_slice_words = std::uint32_t(slice_pitch / 4); 2056 p.rgb96_slice_words = std::uint32_t(slice_pitch / 4);
1881 region.bufferRowLength = 0; 2057 region.bufferRowLength = 0;
@@ -2006,15 +2182,15 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared&
2006 } else if (from.width != to.width || from.height != to.height) { 2182 } else if (from.width != to.width || from.height != to.height) {
2007 return ReplayResult::invalid_copy; 2183 return ReplayResult::invalid_copy;
2008 } 2184 }
2009 if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return ReplayResult::unsupported; 2185 if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return unsupported_at(__LINE__);
2010 const auto& region = resolve.region; 2186 const auto& region = resolve.region;
2011 if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { 2187 if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
2012 if (region && region->mode != d3d12_resolve_mode::average) return ReplayResult::unsupported; 2188 if (region && region->mode != d3d12_resolve_mode::average) return unsupported_at(__LINE__);
2013 } else { 2189 } else {
2014 // A rendering scope resolves each pixel in place, so the destination offset must be the source's. 2190 // A rendering scope resolves each pixel in place, so the destination offset must be the source's.
2015 if (!region || dst_offset.x != src_offset.x || dst_offset.y != src_offset.y || 2191 if (!region || dst_offset.x != src_offset.x || dst_offset.y != src_offset.y ||
2016 (region->mode == d3d12_resolve_mode::average && src.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT)) 2192 (region->mode == d3d12_resolve_mode::average && src.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT))
2017 return ReplayResult::unsupported; 2193 return unsupported_at(__LINE__);
2018 p.resolve_mode = region->mode == d3d12_resolve_mode::minimum ? VK_RESOLVE_MODE_MIN_BIT 2194 p.resolve_mode = region->mode == d3d12_resolve_mode::minimum ? VK_RESOLVE_MODE_MIN_BIT
2019 : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT 2195 : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT
2020 : VK_RESOLVE_MODE_AVERAGE_BIT; 2196 : VK_RESOLVE_MODE_AVERAGE_BIT;
@@ -2058,7 +2234,7 @@ inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p)
2058 VkDeviceSize base = 0; 2234 VkDeviceSize base = 0;
2059 if (!texel || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch || 2235 if (!texel || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch ||
2060 !vk.copy_scratch(total, p.staged, base)) 2236 !vk.copy_scratch(total, p.staged, base))
2061 return ReplayResult::unsupported; 2237 return unsupported_at(__LINE__);
2062 for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base; 2238 for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base;
2063 return ReplayResult::success; 2239 return ReplayResult::success;
2064} 2240}
@@ -2123,6 +2299,77 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const
2123 } 2299 }
2124} 2300}
2125 2301
2302// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer
2303// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device
2304// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL.
2305inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy,
2306 VkImageLayout parent_layout, LayoutTracker* tracker) {
2307 constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
2308 constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT;
2309 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2310 const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT;
2311 const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT;
2312 const auto parent_range = planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts);
2313 image_barrier(vk, cb, p.binding, parent_range, parent_layout, VK_IMAGE_LAYOUT_GENERAL,
2314 any, all, parent_access, transfer);
2315 auto color = p.range;
2316 color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2317 for (unsigned plane = 0; plane < copy.storage.size(); ++plane) {
2318 const ResourceBinding& child = copy.storage[plane];
2319 if (!child.image) continue;
2320 const ResourceId child_id = plane ? p.binding.stencil_uav : p.binding.depth_uav;
2321 auto pieces = current(tracker, child_id, color, VK_IMAGE_LAYOUT_GENERAL);
2322 if (!copy.to_storage) initialize(vk, cb, child, child_id, pieces, VK_IMAGE_LAYOUT_GENERAL, tracker);
2323 for (const auto& piece : pieces)
2324 image_barrier(vk, cb, child, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL,
2325 piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, child_access, transfer);
2326 if (tracker) tracker->set(child_id, color, VK_IMAGE_LAYOUT_GENERAL);
2327 VkBufferImageCopy parent_region{};
2328 parent_region.bufferOffset = copy.offset;
2329 const VkImageAspectFlags aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT;
2330 parent_region.imageSubresource = {aspect, p.range.baseMipLevel, p.range.baseArrayLayer, p.range.layerCount};
2331 parent_region.imageExtent = {p.binding.width, p.binding.height, 1};
2332 VkBufferImageCopy child_region = parent_region;
2333 child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2334 // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier.
2335 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer);
2336 // A D32 depth aspect and R32_FLOAT colour carry the same bits through transfer scratch. The
2337 // intermediate colour image permits a real normalized blit between R32_FLOAT and R16_UNORM;
2338 // shaders see the latter's exact bits through an R16_UINT view.
2339 const bool convert = plane == 0 && copy.conversion.image;
2340 const VkImage colour = convert ? copy.conversion.image : child.image;
2341 VkImageBlit blit{};
2342 if (convert) {
2343 const auto id = p.binding.depth_conversion;
2344 const auto previous = current(tracker, id, color, VK_IMAGE_LAYOUT_UNDEFINED);
2345 for (const auto& piece : previous)
2346 image_barrier(vk, cb, copy.conversion, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL,
2347 piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all,
2348 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, transfer);
2349 if (tracker) tracker->set(id, color, VK_IMAGE_LAYOUT_GENERAL);
2350 blit.srcSubresource = blit.dstSubresource = child_region.imageSubresource;
2351 blit.srcOffsets[1] = blit.dstOffsets[1] = {int32_t(p.binding.width), int32_t(p.binding.height), 1};
2352 if (!copy.to_storage) {
2353 vk.blit_image(cb, child.image, VK_IMAGE_LAYOUT_GENERAL, colour, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
2354 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2355 }
2356 }
2357 vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : colour, VK_IMAGE_LAYOUT_GENERAL,
2358 copy.scratch, 1, copy.to_storage ? &parent_region : &child_region);
2359 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2360 vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? colour : p.binding.image, VK_IMAGE_LAYOUT_GENERAL,
2361 1, copy.to_storage ? &child_region : &parent_region);
2362 if (convert && copy.to_storage) {
2363 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2364 vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
2365 }
2366 image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
2367 child_access, transfer, any, all);
2368 }
2369 image_barrier(vk, cb, p.binding, parent_range, VK_IMAGE_LAYOUT_GENERAL, parent_layout,
2370 parent_access, transfer, any, all);
2371}
2372
2126} // namespace detail 2373} // namespace detail
2127 2374
2128namespace detail { 2375namespace detail {
@@ -2136,15 +2383,16 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2136 !vk.set_primitive_topology || !vk.set_primitive_restart_enable || !vk.set_stencil_reference || 2383 !vk.set_primitive_topology || !vk.set_primitive_restart_enable || !vk.set_stencil_reference ||
2137 !vk.set_blend_constants || !vk.draw || 2384 !vk.set_blend_constants || !vk.draw ||
2138 !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) 2385 !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants)
2139 return ReplayResult::unsupported; 2386 return unsupported_at(__LINE__);
2140 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); 2387 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline);
2141 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 2388 // A null pipeline with a variant builder is one built at its first draw: variant 0 (all slots bound).
2389 if (!pipeline || (!pipeline->pipeline && !pipeline->variant)) return unresolved_at(__LINE__);
2142 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; 2390 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw;
2143 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; 2391 if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__);
2144 if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) 2392 if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count))
2145 return ReplayResult::unsupported; 2393 return unsupported_at(__LINE__);
2146 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 2394 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__);
2147 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; 2395 if (pipeline->color_formats.size() > max_render_targets) return unsupported_at(__LINE__);
2148 p.graphics = pipeline; 2396 p.graphics = pipeline;
2149 p.pipeline = pipeline->pipeline; 2397 p.pipeline = pipeline->pipeline;
2150 p.area = {UINT32_MAX, UINT32_MAX}; 2398 p.area = {UINT32_MAX, UINT32_MAX};
@@ -2161,7 +2409,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2161 const TargetView& target = draw.views->render_targets[slot]; 2409 const TargetView& target = draw.views->render_targets[slot];
2162 if (!target.resource) continue; 2410 if (!target.resource) continue;
2163 const ResourceBinding* binding = resolve(target.resource); 2411 const ResourceBinding* binding = resolve(target.resource);
2164 if (!binding) return ReplayResult::unresolved_resource; 2412 if (!binding) return unresolved_at(__LINE__);
2165 auto& a = p.colors[slot]; 2413 auto& a = p.colors[slot];
2166 a.binding = *binding; 2414 a.binding = *binding;
2167 a.id = target.resource; 2415 a.id = target.resource;
@@ -2173,12 +2421,12 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2173 ResourceBinding viewed = a.binding; 2421 ResourceBinding viewed = a.binding;
2174 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot]; 2422 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot];
2175 a.view = vk.image_view(viewed, a.range); 2423 a.view = vk.image_view(viewed, a.range);
2176 if (!a.view) return ReplayResult::unsupported; 2424 if (!a.view) return unsupported_at(__LINE__);
2177 shrink(a.binding, target, a.range); 2425 shrink(a.binding, target, a.range);
2178 } 2426 }
2179 if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { 2427 if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) {
2180 const ResourceBinding* binding = resolve(draw.depth.resource); 2428 const ResourceBinding* binding = resolve(draw.depth.resource);
2181 if (!binding) return ReplayResult::unresolved_resource; 2429 if (!binding) return unresolved_at(__LINE__);
2182 auto& a = p.depth; 2430 auto& a = p.depth;
2183 a.binding = *binding; 2431 a.binding = *binding;
2184 a.id = draw.depth.resource; 2432 a.id = draw.depth.resource;
@@ -2188,7 +2436,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2188 ResourceBinding viewed = a.binding; 2436 ResourceBinding viewed = a.binding;
2189 viewed.format = pipeline->depth_format; 2437 viewed.format = pipeline->depth_format;
2190 a.view = vk.image_view(viewed, a.range); 2438 a.view = vk.image_view(viewed, a.range);
2191 if (!a.view) return ReplayResult::unsupported; 2439 if (!a.view) return unsupported_at(__LINE__);
2192 shrink(a.binding, draw.depth, a.range); 2440 shrink(a.binding, draw.depth, a.range);
2193 } 2441 }
2194 if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering 2442 if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering
@@ -2208,12 +2456,18 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2208 // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is 2456 // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is
2209 // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments. 2457 // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments.
2210 std::uint32_t unbound = 0; 2458 std::uint32_t unbound = 0;
2459 if (pipeline->rectangle_variant_topology && draw.topology == pipeline->rectangle_variant_topology)
2460 unbound |= GraphicsPipeline::rectangle_stage;
2211 for (std::size_t slot = 0; slot < p.colors.size(); ++slot) 2461 for (std::size_t slot = 0; slot < p.colors.size(); ++slot)
2212 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; 2462 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot;
2213 if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; 2463 if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth;
2214 if (unbound) { 2464 if (unbound || !p.pipeline) {
2215 p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; 2465 p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE;
2216 if (!p.pipeline) return ReplayResult::unsupported; 2466 if (!p.pipeline && pipeline->async_build && !strict_replay()) {
2467 p.skipped = true;
2468 return ReplayResult::success;
2469 }
2470 if (!p.pipeline) return unsupported_at(__LINE__);
2217 } 2471 }
2218 2472
2219 // An unbound vertex-buffer slot reads zeros, as in D3D12: the zero page with stride 0. Per-instance slots with 2473 // An unbound vertex-buffer slot reads zeros, as in D3D12: the zero page with stride 0. Per-instance slots with
@@ -2227,7 +2481,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2227 const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && 2481 const bool bound = draw.views && slot < draw.views->vertex_buffers.size() &&
2228 draw.views->vertex_buffers[slot].va; 2482 draw.views->vertex_buffers[slot].va;
2229 if (!bound) { 2483 if (!bound) {
2230 if (!vk.zero_buffer) return ReplayResult::unresolved_resource; 2484 if (!vk.zero_buffer) return unresolved_at(__LINE__);
2231 p.vertex_buffers[slot] = vk.zero_buffer; 2485 p.vertex_buffers[slot] = vk.zero_buffer;
2232 p.vertex_offsets[slot] = vk.zero_offset; 2486 p.vertex_offsets[slot] = vk.zero_offset;
2233 p.vertex_sizes[slot] = vk.zero_size; 2487 p.vertex_sizes[slot] = vk.zero_size;
@@ -2236,28 +2490,74 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2236 } 2490 }
2237 const VertexBufferView& view = draw.views->vertex_buffers[slot]; 2491 const VertexBufferView& view = draw.views->vertex_buffers[slot];
2238 std::uint64_t size = view.size; 2492 std::uint64_t size = view.size;
2239 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) 2493 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) {
2240 return ReplayResult::unresolved_resource; 2494 size = view.size;
2495 if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) {
2496 static std::atomic<unsigned> logged{0}; // LOCAL DIAGNOSTIC: where the unresolved vertex data lives
2497 if (logged.fetch_add(1, std::memory_order_relaxed) < 24)
2498 std::fprintf(stderr, "[rt] replay: vertex buffer slot %u va 0x%llx size %llu stride %u names no buffer\n",
2499 slot, static_cast<unsigned long long>(view.va),
2500 static_cast<unsigned long long>(view.size), unsigned(view.stride));
2501 return unresolved_at(__LINE__);
2502 }
2503 }
2241 p.vertex_sizes[slot] = size; 2504 p.vertex_sizes[slot] = size;
2242 p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; 2505 p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride;
2243 } 2506 }
2507 // A non-indexed quad list is drawn from the shared triangle index buffer (emit).
2508 if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices)
2509 return unresolved_at(__LINE__);
2244 if (draw.indexed) { 2510 if (draw.indexed) {
2245 if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; 2511 if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16;
2246 else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; 2512 else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32;
2247 else if (draw.index.va) return ReplayResult::unsupported; 2513 else if (draw.index.va) return unsupported_at(__LINE__);
2248 if (!draw.index.va) { // no index buffer: every index reads 0 2514 if (!draw.index.va) { // no index buffer: every index reads 0
2249 if (!vk.zero_buffer) return ReplayResult::unresolved_resource; 2515 if (!vk.zero_buffer) return unresolved_at(__LINE__);
2250 p.index_buffer = vk.zero_buffer; 2516 p.index_buffer = vk.zero_buffer;
2251 p.index_offset = vk.zero_offset; 2517 p.index_offset = vk.zero_offset;
2252 } else { 2518 } else {
2253 std::uint64_t size = draw.index.size; 2519 std::uint64_t size = draw.index.size;
2254 if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) 2520 if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) {
2255 return ReplayResult::unresolved_resource; 2521 size = draw.index.size;
2522 if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) {
2523 static std::atomic<unsigned> logged{0}; // LOCAL DIAGNOSTIC
2524 if (logged.fetch_add(1, std::memory_order_relaxed) < 24)
2525 std::fprintf(stderr, "[rt] replay: index buffer va 0x%llx size %llu names no buffer\n",
2526 static_cast<unsigned long long>(draw.index.va),
2527 static_cast<unsigned long long>(draw.index.size));
2528 return unresolved_at(__LINE__);
2529 }
2530 }
2531 p.index_size = size;
2256 } 2532 }
2257 } 2533 }
2258 return ReplayResult::success; 2534 return ReplayResult::success;
2259} 2535}
2260 2536
2537// An indexed quad list (D3D_PRIMITIVE_TOPOLOGY 19): the scratch and the compute job that turn the application's
2538// indices into triangle-list indices (quad_index_expand.h). `p` is the draw as prepare_draw left it. A draw of
2539// fewer than four indices has no quad and needs nothing.
2540inline ReplayResult prepare_quad_indices(const Draw& draw, const ReplayFunctions& vk, PreparedDraw& p) {
2541 const std::uint32_t quads = draw.count / 4;
2542 if (!quads) return ReplayResult::success;
2543 if (!vk.prepare_quad_indices || !vk.emit_quad_indices || !vk.copy_scratch ||
2544 quads > QuadIndexExpander::max_quads)
2545 return ReplayResult::unsupported;
2546 // The indices from the draw's first one that the view holds; the pass reads the rest as 0, like D3D12. With no
2547 // index buffer (the zero page) that is all of them.
2548 const std::uint32_t index_bytes = p.index_type == VK_INDEX_TYPE_UINT16 ? 2 : 4;
2549 const std::uint64_t in_view = p.index_size / index_bytes;
2550 const std::uint64_t readable = in_view > draw.first ? in_view - draw.first : 0;
2551 const VkDeviceSize first = readable ? p.index_offset + VkDeviceSize(draw.first) * index_bytes : p.index_offset;
2552 VkBuffer scratch = VK_NULL_HANDLE;
2553 VkDeviceSize scratch_offset = 0;
2554 if (!vk.copy_scratch(QuadIndexExpander::bytes(quads), scratch, scratch_offset) ||
2555 !vk.prepare_quad_indices(p.index_buffer, first, p.index_type, readable, quads, scratch, scratch_offset,
2556 p.quad_indices))
2557 return ReplayResult::unsupported;
2558 return ReplayResult::success;
2559}
2560
2261inline bool strip_topology(VkPrimitiveTopology topology) { 2561inline bool strip_topology(VkPrimitiveTopology topology) {
2262 return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || 2562 return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP ||
2263 topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY || 2563 topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY ||
@@ -2275,6 +2575,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) {
2275 case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; 2575 case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY;
2276 case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; 2576 case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY;
2277 case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; 2577 case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY;
2578 // Rectangles draw as triangle lists through a geometry stage, quads as triangle lists through indices: the
2579 // shared ones for a non-indexed draw, the application's own, expanded, for an indexed one (emit).
2580 case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
2581 case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
2278 default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; 2582 default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
2279 } 2583 }
2280} 2584}
@@ -2332,6 +2636,7 @@ public:
2332 // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the 2636 // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the
2333 // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws. 2637 // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws.
2334 std::vector<detail::PreparedDraw> draws; 2638 std::vector<detail::PreparedDraw> draws;
2639 std::vector<detail::DepthUavCopy> depth_uav_copies;
2335 std::size_t draw_count = 0; 2640 std::size_t draw_count = 0;
2336 std::vector<detail::PreparedQuery> queries; 2641 std::vector<detail::PreparedQuery> queries;
2337 VkQueryPool segment_pool = VK_NULL_HANDLE; 2642 VkQueryPool segment_pool = VK_NULL_HANDLE;
@@ -2391,6 +2696,17 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2391 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; 2696 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query;
2392} 2697}
2393 2698
2699// True for a command that records a compute dispatch of the layer's own before the application's work: a predicate
2700// capture, a predicated copy, a depth24 or rgb96 conversion, the count clamp of an ExecuteIndirect dispatch, or the
2701// index expansion of an indexed quad list (which is also a draw).
2702inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) {
2703 const auto& p = out.commands[i];
2704 if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect)
2705 return true;
2706 return std::holds_alternative<Draw>(out.list->commands()[i]) && p.draw < out.draws.size() &&
2707 out.draws[p.draw].quad_indices.buffer;
2708}
2709
2394// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and 2710// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and
2395// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements 2711// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements
2396// depend on heap state at planning time, so every non-timestamp resolve splits conservatively. 2712// depend on heap state at planning time, so every non-timestamp resolve splits conservatively.
@@ -2426,8 +2742,7 @@ inline void plan_statistics_segments(PreparedList& out) {
2426 const auto commands = out.list->commands(); 2742 const auto commands = out.list->commands();
2427 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2743 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2428 auto& p = out.commands[i]; 2744 auto& p = out.commands[i];
2429 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || 2745 if (begin && has_helper_dispatch(out, i)) {
2430 p.counted_dispatch.indirect)) {
2431 inner.push_back({&p.statistics_end, &p.statistics_begin, -1}); 2746 inner.push_back({&p.statistics_end, &p.statistics_begin, -1});
2432 splits = true; 2747 splits = true;
2433 } 2748 }
@@ -2512,13 +2827,12 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2512 query = &out.queries[next_query++]; 2827 query = &out.queries[next_query++];
2513 if (!query) { 2828 if (!query) {
2514 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical 2829 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical
2515 // segment before it and open a new one after, the way resolves do. 2830 // segment before it and open a new one after, the way resolves do. An indexed quad list is a helper and
2516 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || 2831 // a draw: the new segment is the one its draw runs in, and its kind is recorded below.
2517 p.counted_dispatch.indirect)) { 2832 if (!active.empty() && has_helper_dispatch(out, i)) {
2518 p.statistics_end = current; 2833 p.statistics_end = current;
2519 current = open(); 2834 current = open();
2520 p.statistics_begin = current; 2835 p.statistics_begin = current;
2521 continue;
2522 } 2836 }
2523 // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291). 2837 // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291).
2524 int draw = -1; 2838 int draw = -1;
@@ -2610,6 +2924,13 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun
2610 }, 2924 },
2611 command); 2925 command);
2612 if (missing(id, p.binding, p.range)) return true; 2926 if (missing(id, p.binding, p.range)) return true;
2927 if (p.depth_uav_copy != UINT32_MAX) {
2928 const auto& copy = prepared.depth_uav_copies[p.depth_uav_copy];
2929 auto color = p.range;
2930 color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2931 if (!copy.to_storage && (missing(p.binding.depth_uav, copy.storage[0], color) ||
2932 missing(p.binding.stencil_uav, copy.storage[1], color))) return true;
2933 }
2613 } 2934 }
2614 return false; 2935 return false;
2615} 2936}
@@ -2627,6 +2948,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2627 out.list = &list; 2948 out.list = &list;
2628 out.commands.assign(commands.size(), {}); 2949 out.commands.assign(commands.size(), {});
2629 out.draw_count = 0; 2950 out.draw_count = 0;
2951 out.depth_uav_copies.clear();
2630 out.queries.clear(); 2952 out.queries.clear();
2631 out.segment_pool = VK_NULL_HANDLE; 2953 out.segment_pool = VK_NULL_HANDLE;
2632 out.segment_base = out.segment_count = 0; 2954 out.segment_base = out.segment_count = 0;
@@ -2657,6 +2979,60 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2657 out.wrote_readback = false; 2979 out.wrote_readback = false;
2658 out.readback_src_stages = 0; 2980 out.readback_src_stages = 0;
2659 2981
2982 // Successive plane transfers use the same transient range and order their buffer accesses in emit().
2983 VkBuffer plane_scratch = VK_NULL_HANDLE;
2984 VkDeviceSize plane_capacity = 0, plane_offset = 0;
2985 const auto prepare_depth_uav = [&](detail::Prepared& p, bool before, bool after) {
2986 if (!p.binding.depth_uav && !p.binding.stencil_uav) return ReplayResult::success;
2987 if (before == after) {
2988 p.order_depth_uav = after;
2989 return ReplayResult::success;
2990 }
2991 if (!vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch)
2992 return ReplayResult::unsupported;
2993 if (!vk.graphics_family) {
2994 // Coupled layouts can also need to zero-initialize the sibling plane on first use.
2995 const auto aspects = detail::planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts).aspectMask;
2996 if (!(vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) || !vk.compute_copy_aspects ||
2997 (vk.compute_copy_aspects(p.binding.format) & aspects) != aspects)
2998 return ReplayResult::unsupported;
2999 }
3000 if (p.range.baseMipLevel || p.range.levelCount != 1) return ReplayResult::unsupported;
3001 detail::DepthUavCopy copy{};
3002 if (p.binding.depth_conversion && (p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT)) {
3003 if (!vk.graphics_family || !vk.blit_image) return ReplayResult::unsupported;
3004 const auto* middle = resolve(p.binding.depth_conversion);
3005 if (!middle || !middle->image) return ReplayResult::unresolved_resource;
3006 copy.conversion = *middle;
3007 }
3008 const ResourceId ids[] = {p.binding.depth_uav, p.binding.stencil_uav};
3009 for (unsigned plane = 0; plane < 2; ++plane) {
3010 const auto aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT;
3011 if (!(p.range.aspectMask & aspect)) continue;
3012 const auto* child = resolve(ids[plane]);
3013 if (!child || !child->image) return ReplayResult::unresolved_resource;
3014 copy.storage[plane] = *child;
3015 }
3016 const VkDeviceSize texels = VkDeviceSize(p.binding.width) * p.binding.height;
3017 const auto largest_aspect = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? VK_IMAGE_ASPECT_DEPTH_BIT :
3018 VK_IMAGE_ASPECT_STENCIL_BIT;
3019 const VkDeviceSize bytes_per_texel = block_format(p.binding.format, largest_aspect).bytes;
3020 if (!texels || !bytes_per_texel || texels > UINT64_MAX / bytes_per_texel / p.range.layerCount)
3021 return ReplayResult::unsupported;
3022 const VkDeviceSize bytes = texels * bytes_per_texel * p.range.layerCount;
3023 if (bytes > plane_capacity) {
3024 if (!vk.copy_scratch(bytes, plane_scratch, plane_offset) || !plane_scratch || plane_offset % 4)
3025 return ReplayResult::unsupported;
3026 plane_capacity = bytes;
3027 }
3028 copy.scratch = plane_scratch;
3029 copy.offset = plane_offset;
3030 copy.to_storage = after;
3031 p.depth_uav_copy = static_cast<std::uint32_t>(out.depth_uav_copies.size());
3032 out.depth_uav_copies.push_back(copy);
3033 return ReplayResult::success;
3034 };
3035
2660 for (std::size_t i = 0; i < commands.size(); ++i) { 3036 for (std::size_t i = 0; i < commands.size(); ++i) {
2661 const auto& command = commands[i]; 3037 const auto& command = commands[i];
2662 auto& p = out.commands[i]; 3038 auto& p = out.commands[i];
@@ -2667,7 +3043,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2667 }; 3043 };
2668 const auto rect_view = [&](std::span<const Rect> rects, const TargetView& target, VkImageAspectFlags view_aspects) { 3044 const auto rect_view = [&](std::span<const Rect> rects, const TargetView& target, VkImageAspectFlags view_aspects) {
2669 if (rects.empty()) return ReplayResult::success; 3045 if (rects.empty()) return ReplayResult::success;
2670 if (!rendering) return ReplayResult::unsupported; 3046 if (!rendering) return unsupported_at(__LINE__);
2671 detail::clip(rects, detail::mip_extent(p.binding, target.mip), target.layer_count, p.rects); 3047 detail::clip(rects, detail::mip_extent(p.binding, target.mip), target.layer_count, p.rects);
2672 if (p.rects.empty()) { 3048 if (p.rects.empty()) {
2673 p.skip = true; 3049 p.skip = true;
@@ -2687,24 +3063,39 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2687 }; 3063 };
2688 3064
2689 if (const auto* transition = std::get_if<TransitionBarrier>(&command)) { 3065 if (const auto* transition = std::get_if<TransitionBarrier>(&command)) {
2690 if (!bind(transition->resource)) return ReplayResult::unresolved_resource; 3066 if (!bind(transition->resource)) return unresolved_at(__LINE__);
2691 if (p.binding.image == VK_NULL_HANDLE) { 3067 if (p.binding.image == VK_NULL_HANDLE) {
2692 if (transition->subresource != 0 && transition->subresource != all_subresources) 3068 if (transition->subresource != 0 && transition->subresource != all_subresources)
2693 return ReplayResult::invalid_subresource; 3069 return ReplayResult::invalid_subresource;
2694 } else if (!image_range(p.binding, transition->subresource, p.range)) { 3070 } else if (!image_range(p.binding, transition->subresource, p.range)) {
2695 return ReplayResult::invalid_subresource; 3071 return ReplayResult::invalid_subresource;
2696 } 3072 }
3073 const auto result = prepare_depth_uav(p, transition->before & d3d12_state::unordered_access,
3074 transition->after & d3d12_state::unordered_access);
3075 if (result != ReplayResult::success) return result;
2697 } else if (std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command)) { 3076 } else if (std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command)) {
2698 if (!vk.pipeline_barrier2) return ReplayResult::unsupported; 3077 if (!vk.pipeline_barrier2) return unsupported_at(__LINE__);
2699 if (const auto* buffer_barrier = std::get_if<BufferBarrier>(&command)) 3078 if (const auto* buffer_barrier = std::get_if<BufferBarrier>(&command))
2700 if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; 3079 if (!bind(buffer_barrier->resource)) return unresolved_at(__LINE__);
2701 } else if (const auto* texture = std::get_if<TextureBarrier>(&command)) { 3080 } else if (const auto* texture = std::get_if<TextureBarrier>(&command)) {
2702 if (!vk.pipeline_barrier2) return ReplayResult::unsupported; 3081 if (!vk.pipeline_barrier2) return unsupported_at(__LINE__);
2703 if (!bind(texture->resource)) return ReplayResult::unresolved_resource; 3082 if (!bind(texture->resource)) return unresolved_at(__LINE__);
2704 if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) 3083 if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range))
2705 return ReplayResult::invalid_subresource; 3084 return ReplayResult::invalid_subresource;
3085 // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the
3086 // parent after only a global barrier. Bindless shaders need no per-resource bind command, so
3087 // there is no observable ownership transition at which to synchronize the two images.
3088 if (p.binding.depth_uav &&
3089 (detail::unsupported_depth_uav_access(texture->layout_before, texture->access_before) ||
3090 detail::unsupported_depth_uav_access(texture->layout_after, texture->access_after)))
3091 return ReplayResult::unsupported;
3092 if (!(texture->flags & texture_barrier_discard) && texture->layout_before != d3d12_layout::undefined) {
3093 const auto result = prepare_depth_uav(p, detail::texture_uav_layout(texture->layout_before),
3094 detail::texture_uav_layout(texture->layout_after));
3095 if (result != ReplayResult::success) return result;
3096 }
2706 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { 3097 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
2707 if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; 3098 if (!bind(color_clear->target.resource)) return unresolved_at(__LINE__);
2708 if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; 3099 if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear;
2709 if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) 3100 if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range))
2710 return ReplayResult::invalid_subresource; 3101 return ReplayResult::invalid_subresource;
@@ -2724,9 +3115,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2724 VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; 3115 VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r;
2725 } else if (const auto r = rect_view(clear_rects(color_clear->rects), color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT); 3116 } else if (const auto r = rect_view(clear_rects(color_clear->rects), color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT);
2726 r != ReplayResult::success) return r; 3117 r != ReplayResult::success) return r;
2727 if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; 3118 if (!p.skip && p.rects.empty() && !vk.clear_color_image) return unsupported_at(__LINE__);
2728 } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { 3119 } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) {
2729 if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; 3120 if (!bind(depth_clear->target.resource)) return unresolved_at(__LINE__);
2730 VkImageAspectFlags aspects = 0; 3121 VkImageAspectFlags aspects = 0;
2731 if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; 3122 if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2732 if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; 3123 if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
@@ -2743,12 +3134,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2743 if (const auto r = rect_view(clear_rects(depth_clear->rects), depth_clear->target, p.binding.aspects); 3134 if (const auto r = rect_view(clear_rects(depth_clear->rects), depth_clear->target, p.binding.aspects);
2744 r != ReplayResult::success) 3135 r != ReplayResult::success)
2745 return r; 3136 return r;
2746 if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; 3137 if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return unsupported_at(__LINE__);
2747 } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { 3138 } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) {
2748 const UavView& view = uav->view; 3139 const UavView& view = uav->view;
2749 if (!bind(view.resource)) return ReplayResult::unresolved_resource; 3140 if (!bind(view.resource)) return unresolved_at(__LINE__);
2750 if (view.buffer) { 3141 if (view.buffer) {
2751 if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; 3142 if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return unsupported_at(__LINE__);
2752 if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands 3143 if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands
2753 if (const auto r = detail::prepare_buffer_uav_clear(*uav, p); r != ReplayResult::success) return r; 3144 if (const auto r = detail::prepare_buffer_uav_clear(*uav, p); r != ReplayResult::success) return r;
2754 const bool short_fill = std::any_of(p.fills.begin(), p.fills.end(), [&](const auto& fill) { 3145 const bool short_fill = std::any_of(p.fills.begin(), p.fills.end(), [&](const auto& fill) {
@@ -2757,7 +3148,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2757 if (short_fill && (!vk.copy_scratch || 3148 if (short_fill && (!vk.copy_scratch ||
2758 !vk.copy_scratch(8, p.fill_scratch, p.fill_scratch_offset) || !p.fill_scratch || 3149 !vk.copy_scratch(8, p.fill_scratch, p.fill_scratch_offset) || !p.fill_scratch ||
2759 p.fill_scratch_offset % 4 || p.fill_scratch_offset > UINT64_MAX - 8)) 3150 p.fill_scratch_offset % 4 || p.fill_scratch_offset > UINT64_MAX - 8))
2760 return ReplayResult::unsupported; 3151 return unsupported_at(__LINE__);
2761 if (!p.skip && !p.fills.empty() && p.binding.host_readable) { 3152 if (!p.skip && !p.fills.empty() && p.binding.host_readable) {
2762 out.wrote_readback = true; 3153 out.wrote_readback = true;
2763 out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; 3154 out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT;
@@ -2775,22 +3166,57 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2775 // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the 3166 // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the
2776 // bit-exact R32_UINT backing path. 3167 // bit-exact R32_UINT backing path.
2777 const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; 3168 const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format;
3169 const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 &&
3170 p.binding.format == VK_FORMAT_R32_UINT;
2778 if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) 3171 if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element))
2779 return ReplayResult::unsupported; 3172 return unsupported_at(__LINE__);
2780 const auto* image_layout = uav_clear::layout(p.binding.format); 3173 const auto* image_layout = uav_clear::layout(p.binding.format);
2781 if (!image_layout || image_layout->bytes != p.element.size) 3174 if (!image_layout || image_layout->bytes != p.element.size)
2782 return ReplayResult::unsupported; 3175 return unsupported_at(__LINE__);
2783 const bool attachment = p.binding.color_attachment && !p.binding.volume; 3176 // The UAV attachment path supports 1D-array and 2D-array views. Keep 3D clears on the transfer
3177 // path and retain the exact-format restriction for 1D/3D UAVs below.
3178 const bool attachment = p.binding.color_attachment && !p.binding.volume &&
3179 (!view.exact_clear_format || p.binding.line);
2784 const bool view_attachable = vk.color_attachment_format 3180 const bool view_attachable = vk.color_attachment_format
2785 ? vk.color_attachment_format(view_format) 3181 ? vk.color_attachment_format(view_format)
2786 : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; 3182 : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32;
2787 const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; 3183 const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5;
3184 if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5)
3185 return ReplayResult::unsupported;
2788 const VkFormat clear_format = reinterpret ? view_format : p.binding.format; 3186 const VkFormat clear_format = reinterpret ? view_format : p.binding.format;
2789 if (!uav_clear::decode(clear_format, p.element, p.clear_color)) 3187 if (!uav_clear::decode(clear_format, p.element, p.clear_color))
2790 return ReplayResult::unsupported; 3188 return unsupported_at(__LINE__);
2791 if (reinterpret) p.clear_format = view_format; 3189 if (reinterpret) p.clear_format = view_format;
3190 // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render.
3191 // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear.
3192 if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) &&
3193 (!uav->rects.empty() || reinterpret || predicated)) {
3194 if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image ||
3195 (p.element.size != 1 && p.element.size != 2 && p.element.size != 4))
3196 return ReplayResult::unsupported;
3197 const auto rects = uav->rects.empty() ? std::span<const Rect>(&whole_view, 1) :
3198 std::span<const Rect>(uav->rects);
3199 detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects);
3200 if (p.rects.empty()) { p.skip = true; continue; }
3201 for (const auto& rect : p.rects) {
3202 VkBufferImageCopy region{};
3203 region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count};
3204 region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0};
3205 region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1};
3206 const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height;
3207 const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size;
3208 if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported;
3209 p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3));
3210 p.staged_writes.push_back(region);
3211 }
3212 VkDeviceSize offset = 0;
3213 if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4)
3214 return ReplayResult::unsupported;
3215 for (auto& region : p.staged_writes) region.bufferOffset = offset;
3216 continue;
3217 }
2792 if (!uav->rects.empty() && !attachment) 3218 if (!uav->rects.empty() && !attachment)
2793 return ReplayResult::unsupported; 3219 return unsupported_at(__LINE__);
2794 // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as 3220 // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as
2795 // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted. 3221 // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted.
2796 if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies; 3222 if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies;
@@ -2799,14 +3225,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2799 : attachment ? clear_rects(uav->rects) : std::span<const Rect>(uav->rects); 3225 : attachment ? clear_rects(uav->rects) : std::span<const Rect>(uav->rects);
2800 if (const auto r = rect_view(rects, target, VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) 3226 if (const auto r = rect_view(rects, target, VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success)
2801 return r; 3227 return r;
2802 if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; 3228 if (!p.skip && p.rects.empty() && !vk.clear_color_image) return unsupported_at(__LINE__);
2803 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || 3229 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) ||
2804 std::holds_alternative<CopyResource>(command)) { 3230 std::holds_alternative<CopyResource>(command)) {
2805 if (!copies) return ReplayResult::unsupported; 3231 if (!copies) return unsupported_at(__LINE__);
2806 if (predicated && !std::holds_alternative<CopyBuffer>(command)) ++out.unpredicated_copies; 3232 if (predicated && !std::holds_alternative<CopyBuffer>(command)) ++out.unpredicated_copies;
2807 const auto [dst_id, src_id] = copy_ids(command); 3233 const auto [dst_id, src_id] = copy_ids(command);
2808 const ResourceBinding* source = resolve(src_id); 3234 const ResourceBinding* source = resolve(src_id);
2809 if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; 3235 if (!bind(dst_id) || !source) return unresolved_at(__LINE__);
2810 p.source = *source; 3236 p.source = *source;
2811 ReplayResult result = ReplayResult::success; 3237 ReplayResult result = ReplayResult::success;
2812 if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { 3238 if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) {
@@ -2830,7 +3256,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2830 if (predicated) { 3256 if (predicated) {
2831 if ((statistics_active && !statistics_helpers) || !vk.prepare_predicated_copy || !vk.emit_predicated_copy || 3257 if ((statistics_active && !statistics_helpers) || !vk.prepare_predicated_copy || !vk.emit_predicated_copy ||
2832 !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy)) 3258 !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy))
2833 return ReplayResult::unsupported; 3259 return unsupported_at(__LINE__);
2834 } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); 3260 } else p.buffer_copies.push_back({src, dst, buffer_copy->size});
2835 } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { 3261 } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) {
2836 result = detail::prepare_texture_copy(*texture_copy, p); 3262 result = detail::prepare_texture_copy(*texture_copy, p);
@@ -2858,15 +3284,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2858 (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes; 3284 (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes;
2859 if (alignment > 1 && region.bufferOffset % alignment && 3285 if (alignment > 1 && region.bufferOffset % alignment &&
2860 !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) 3286 !detail::stage_unaligned_tile(vk, p, image, fmt, upload))
2861 return ReplayResult::unsupported; 3287 return unsupported_at(__LINE__);
2862 } 3288 }
3289 // A B4G4R4A4 target stored as RGBA8 moves 4-byte texels in a footprint copy, not packed 16-bit ones.
3290 // The copy is made all the same, as the retail boot was measured with it;
3291 // LEONIDA_RGBA4_COPY_REFUSE=1 refuses it instead.
3292 static const bool refuse_rgba4_copy = [] {
3293 const char* v = std::getenv("LEONIDA_RGBA4_COPY_REFUSE");
3294 return v && *v == '1';
3295 }();
3296 if (result == ReplayResult::success && image.rgba4_render_fallback && refuse_rgba4_copy)
3297 return ReplayResult::unsupported;
3298 if(result==ReplayResult::success && image.xbox_depth16_stencil8 && image.format!=VK_FORMAT_D16_UNORM_S8_UINT &&
3299 !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask==VK_IMAGE_ASPECT_DEPTH_BIT) return ReplayResult::unsupported;
2863 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && 3300 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2864 !p.buffer_image_copies.empty() && 3301 !p.buffer_image_copies.empty() &&
2865 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; 3302 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
2866 const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 && 3303 const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 &&
2867 !p.buffer_image_copies.empty(); 3304 !p.buffer_image_copies.empty();
2868 // Without a segment pool, refuse before allocating conversion scratch/descriptors. 3305 // Without a segment pool, refuse before allocating conversion scratch/descriptors.
2869 if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported; 3306 if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return unsupported_at(__LINE__);
2870 if (depth24_footprint) { 3307 if (depth24_footprint) {
2871 const VkBufferImageCopy& region = p.buffer_image_copies[0]; 3308 const VkBufferImageCopy& region = p.buffer_image_copies[0];
2872 const ResourceBinding& buffer = upload ? p.source : p.binding; 3309 const ResourceBinding& buffer = upload ? p.source : p.binding;
@@ -2880,7 +3317,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2880 job.slices = region.imageExtent.depth; 3317 job.slices = region.imageExtent.depth;
2881 job.app_row_words = region.bufferRowLength ? region.bufferRowLength : job.width; 3318 job.app_row_words = region.bufferRowLength ? region.bufferRowLength : job.width;
2882 job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); 3319 job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height);
2883 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; 3320 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return unsupported_at(__LINE__);
2884 p.has_depth24 = true; 3321 p.has_depth24 = true;
2885 } else if (rgb96_footprint) { 3322 } else if (rgb96_footprint) {
2886 // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. 3323 // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch.
@@ -2897,16 +3334,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2897 job.slices = region.imageExtent.depth; 3334 job.slices = region.imageExtent.depth;
2898 job.app_row_words = p.rgb96_row_words; 3335 job.app_row_words = p.rgb96_row_words;
2899 job.app_slice_words = p.rgb96_slice_words; 3336 job.app_slice_words = p.rgb96_slice_words;
2900 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; 3337 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return unsupported_at(__LINE__);
2901 p.has_depth24 = true; 3338 p.has_depth24 = true;
2902 } 3339 }
2903 } else { 3340 } else {
2904 result = detail::prepare_resource_copy(p); 3341 result = detail::prepare_resource_copy(p);
2905 } 3342 }
2906 if (result == ReplayResult::success && !p.image_copies.empty() && 3343 if (result == ReplayResult::success && !p.image_copies.empty() &&
2907 p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask) { 3344 (p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask ||
3345 a8_mixed_backing(p.source.format, p.binding.format))) {
2908 // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, 3346 // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image,
2909 // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. 3347 // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. The two
3348 // backings of A8_UNORM take the same route: one byte per texel on both sides, but Vulkan does not
3349 // count VK_FORMAT_A8_UNORM_KHR as size-compatible with R8_UNORM (VUID-vkCmdCopyImage-srcImage-01548).
2910 const std::uint32_t texel = 3350 const std::uint32_t texel =
2911 block_format(p.source.format, p.image_copies[0].srcSubresource.aspectMask).bytes; 3351 block_format(p.source.format, p.image_copies[0].srcSubresource.aspectMask).bytes;
2912 VkDeviceSize total = 0; 3352 VkDeviceSize total = 0;
@@ -2918,7 +3358,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2918 } 3358 }
2919 VkDeviceSize base = 0; 3359 VkDeviceSize base = 0;
2920 if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base)) 3360 if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base))
2921 return ReplayResult::unsupported; 3361 return unsupported_at(__LINE__);
2922 for (std::size_t r = 0; r < p.image_copies.size(); ++r) { 3362 for (std::size_t r = 0; r < p.image_copies.size(); ++r) {
2923 const VkImageCopy& c = p.image_copies[r]; 3363 const VkImageCopy& c = p.image_copies[r];
2924 VkBufferImageCopy region{}; 3364 VkBufferImageCopy region{};
@@ -2942,18 +3382,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2942 ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; 3382 ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT;
2943 } 3383 }
2944 } else if (const auto* resolve_command = std::get_if<ResolveSubresource>(&command)) { 3384 } else if (const auto* resolve_command = std::get_if<ResolveSubresource>(&command)) {
2945 if (!vk.resolve_image) return ReplayResult::unsupported; 3385 if (!vk.resolve_image) return unsupported_at(__LINE__);
2946 if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies 3386 if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies
2947 const ResourceBinding* source = resolve(resolve_command->src); 3387 const ResourceBinding* source = resolve(resolve_command->src);
2948 if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; 3388 if (!bind(resolve_command->dst) || !source) return unresolved_at(__LINE__);
2949 p.source = *source; 3389 p.source = *source;
2950 if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) 3390 if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success)
2951 return result; 3391 return result;
2952 if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { 3392 if (p.resolve_mode != VK_RESOLVE_MODE_NONE) {
2953 if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return ReplayResult::unsupported; 3393 if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return unsupported_at(__LINE__);
2954 p.view = vk.image_view(p.source, p.source_range); 3394 p.view = vk.image_view(p.source, p.source_range);
2955 p.resolve_view = vk.image_view(p.binding, p.range); 3395 p.resolve_view = vk.image_view(p.binding, p.range);
2956 if (!p.view || !p.resolve_view) return ReplayResult::unsupported; 3396 if (!p.view || !p.resolve_view) return unsupported_at(__LINE__);
2957 if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success) 3397 if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success)
2958 return result; 3398 return result;
2959 // D3D-417, a driver workaround: AMD's Windows driver (32.0.21042.62, Radeon RDNA2 iGPU) resolves a 3399 // D3D-417, a driver workaround: AMD's Windows driver (32.0.21042.62, Radeon RDNA2 iGPU) resolves a
@@ -2971,12 +3411,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2971 p.binding, p.resolve_view, 3411 p.binding, p.resolve_view,
2972 image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), p.resolve_mode, 3412 image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), p.resolve_mode,
2973 {std::min(from.width, to.width), std::min(from.height, to.height)}, p.resolve_pass); 3413 {std::min(from.width, to.width), std::min(from.height, to.height)}, p.resolve_pass);
2974 if (!p.resolve_framebuffer) return ReplayResult::unsupported; 3414 if (!p.resolve_framebuffer) return unsupported_at(__LINE__);
2975 } 3415 }
2976 } 3416 }
2977 } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { 3417 } else if (const auto* discard = std::get_if<DiscardResource>(&command)) {
2978 // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. 3418 // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows.
2979 if (!bind(discard->resource)) return ReplayResult::unresolved_resource; 3419 if (!bind(discard->resource)) return unresolved_at(__LINE__);
2980 const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; 3420 const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count;
2981 if (!p.binding.image) { 3421 if (!p.binding.image) {
2982 if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; 3422 if (!discard->whole && end > 1) return ReplayResult::invalid_subresource;
@@ -2992,27 +3432,29 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2992 if (!discard->partial) p.discards.push_back(range); 3432 if (!discard->partial) p.discards.push_back(range);
2993 } 3433 }
2994 } 3434 }
3435 } else if (std::holds_alternative<label::Write>(command)) {
3436 if (!vk.gpu_label) return ReplayResult::unsupported;
2995 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) { 3437 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) {
2996 if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; 3438 if (!vk.update_buffer || !vk.buffer_at) return unsupported_at(__LINE__);
2997 std::uint64_t bytes = 4; 3439 std::uint64_t bytes = 4;
2998 if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) 3440 if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4)
2999 return ReplayResult::unresolved_resource; 3441 return unresolved_at(__LINE__);
3000 if (p.write_offset % 4) return ReplayResult::invalid_copy; 3442 if (p.write_offset % 4) return ReplayResult::invalid_copy;
3001 // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. 3443 // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST.
3002 out.wrote_readback = true; 3444 out.wrote_readback = true;
3003 out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; 3445 out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT;
3004 } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { 3446 } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) {
3005 if (!vk.copy_buffer) return ReplayResult::unsupported; 3447 if (!vk.copy_buffer) return unsupported_at(__LINE__);
3006 if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies 3448 if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies
3007 const ResourceBinding* source = resolve(atomic->src); 3449 const ResourceBinding* source = resolve(atomic->src);
3008 if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; 3450 if (!bind(atomic->dst) || !source) return unresolved_at(__LINE__);
3009 p.source = *source; 3451 p.source = *source;
3010 if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || 3452 if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) ||
3011 !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) 3453 !detail::within(atomic->src_offset, atomic->bytes, p.source.size))
3012 return ReplayResult::invalid_copy; 3454 return ReplayResult::invalid_copy;
3013 for (const auto& d : atomic->dependencies) { 3455 for (const auto& d : atomic->dependencies) {
3014 const ResourceBinding* dependent = resolve(d.resource); 3456 const ResourceBinding* dependent = resolve(d.resource);
3015 if (!dependent) return ReplayResult::unresolved_resource; 3457 if (!dependent) return unresolved_at(__LINE__);
3016 if (!dependent->image) { 3458 if (!dependent->image) {
3017 const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; 3459 const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end;
3018 if (d.subresource != 0 || d.begin >= end || end > dependent->size) 3460 if (d.subresource != 0 || d.begin >= end || end > dependent->size)
@@ -3028,26 +3470,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3028 } else if (const auto* predication = std::get_if<Predication>(&command)) { 3470 } else if (const auto* predication = std::get_if<Predication>(&command)) {
3029 predicated = predication->buffer != 0; 3471 predicated = predication->buffer != 0;
3030 if (!predicated) continue; 3472 if (!predicated) continue;
3031 if (!conditional) return ReplayResult::unsupported; 3473 if (!conditional) return unsupported_at(__LINE__);
3032 // Without physical segments the capture dispatch would pollute CSInvocations. 3474 // Without physical segments the capture dispatch would pollute CSInvocations.
3033 if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; 3475 if (statistics_active && !statistics_helpers) return unsupported_at(__LINE__);
3034 if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; 3476 if (!bind(predication->buffer)) return unresolved_at(__LINE__);
3035 if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || 3477 if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) ||
3036 predication->offset > UINT64_MAX - p.binding.buffer_offset) 3478 predication->offset > UINT64_MAX - p.binding.buffer_offset)
3037 return ReplayResult::invalid_predication; 3479 return ReplayResult::invalid_predication;
3038 if (!vk.prepare_predicate || !vk.capture_predicate || 3480 if (!vk.prepare_predicate || !vk.capture_predicate ||
3039 !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) 3481 !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate))
3040 return ReplayResult::unsupported; 3482 return unsupported_at(__LINE__);
3041 } else if (const QueryRange range = query_range(command); range.count) { 3483 } else if (const QueryRange range = query_range(command); range.count) {
3042 // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, so a predicate does 3484 // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, so a predicate does
3043 // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). 3485 // not suppress them (emit_query suspends conditional rendering around ResolveQueryData).
3044 if (!queries) return ReplayResult::unsupported; 3486 if (!queries) return unsupported_at(__LINE__);
3045 QueryPool* heap = vk.query_pool(range.heap); 3487 QueryPool* heap = vk.query_pool(range.heap);
3046 if (!heap) return ReplayResult::unresolved_resource; 3488 if (!heap) return unresolved_at(__LINE__);
3047 if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; 3489 if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query;
3048 if (range.first >= heap->count || range.count > heap->count - range.first) 3490 if (range.first >= heap->count || range.count > heap->count - range.first)
3049 return ReplayResult::invalid_query; 3491 return ReplayResult::invalid_query;
3050 if (!query_result_size(range.type)) return ReplayResult::unsupported; 3492 if (!query_result_size(range.type)) return unsupported_at(__LINE__);
3051 if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { 3493 if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) {
3052 const bool begin = std::holds_alternative<BeginQuery>(command); 3494 const bool begin = std::holds_alternative<BeginQuery>(command);
3053 if (range.type == d3d12_query::occlusion) { 3495 if (range.type == d3d12_query::occlusion) {
@@ -3066,7 +3508,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3066 } 3508 }
3067 if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { 3509 if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) {
3068 // The destination is a buffer, as D3D12 requires, large enough for every result. 3510 // The destination is a buffer, as D3D12 requires, large enough for every result.
3069 if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; 3511 if (!bind(resolve_queries->dst)) return unresolved_at(__LINE__);
3070 const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); 3512 const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type);
3071 if (!p.binding.buffer || p.binding.buffer_offset % 8 || 3513 if (!p.binding.buffer || p.binding.buffer_offset % 8 ||
3072 !detail::within(resolve_queries->offset, bytes, p.binding.size) || 3514 !detail::within(resolve_queries->offset, bytes, p.binding.size) ||
@@ -3076,7 +3518,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3076 // Inside a pipeline-statistics query, QueryReplay::plan checks that the helper dispatch is kept out 3518 // Inside a pipeline-statistics query, QueryReplay::plan checks that the helper dispatch is kept out
3077 // of the application's counters. 3519 // of the application's counters.
3078 if (range.type == d3d12_query::binary_occlusion && !vk.resolve_binary_occlusion) 3520 if (range.type == d3d12_query::binary_occlusion && !vk.resolve_binary_occlusion)
3079 return ReplayResult::unsupported; 3521 return unsupported_at(__LINE__);
3080 if (p.binding.host_readable) { 3522 if (p.binding.host_readable) {
3081 out.wrote_readback = true; 3523 out.wrote_readback = true;
3082 out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; 3524 out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT;
@@ -3084,7 +3526,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3084 } 3526 }
3085 out.queries.push_back({i, heap, statistics_active}); 3527 out.queries.push_back({i, heap, statistics_active});
3086 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { 3528 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) {
3087 if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; 3529 if (!bind(ind->argument_buffer) || !p.binding.buffer) return unresolved_at(__LINE__);
3088 const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); 3530 const VkDeviceSize record_size = detail::indirect_record_size(ind->kind);
3089 if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) 3531 if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t))
3090 return ReplayResult::invalid_indirect_arguments; 3532 return ReplayResult::invalid_indirect_arguments;
@@ -3098,7 +3540,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3098 return ReplayResult::invalid_indirect_arguments; 3540 return ReplayResult::invalid_indirect_arguments;
3099 if (ind->count_buffer) { 3541 if (ind->count_buffer) {
3100 const ResourceBinding* cnt = resolve(ind->count_buffer); 3542 const ResourceBinding* cnt = resolve(ind->count_buffer);
3101 if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; 3543 if (!cnt || !cnt->buffer) return unresolved_at(__LINE__);
3102 if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) 3544 if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t)))
3103 return ReplayResult::invalid_indirect_arguments; 3545 return ReplayResult::invalid_indirect_arguments;
3104 p.source = *cnt; 3546 p.source = *cnt;
@@ -3110,57 +3552,61 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3110 !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, 3552 !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
3111 p.source.buffer, p.source.buffer_offset + ind->count_offset, 3553 p.source.buffer, p.source.buffer_offset + ind->count_offset,
3112 ind->stride, ind->max_count, p.counted_dispatch)) 3554 ind->stride, ind->max_count, p.counted_dispatch))
3113 return ReplayResult::unsupported; 3555 return unsupported_at(__LINE__);
3114 } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || 3556 } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) ||
3115 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { 3557 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) {
3116 return ReplayResult::unsupported; 3558 return unsupported_at(__LINE__);
3117 } 3559 }
3118 } else { 3560 } else {
3119 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || 3561 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) ||
3120 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || 3562 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) ||
3121 (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) 3563 (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect))
3122 return ReplayResult::unsupported; 3564 return unsupported_at(__LINE__);
3123 } 3565 }
3124 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded 3566 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded
3125 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; 3567 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return unsupported_at(__LINE__);
3126 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); 3568 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline);
3127 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 3569 if (!pipeline) return unresolved_at(__LINE__);
3128 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
3129 p.pipeline = *pipeline; 3570 p.pipeline = *pipeline;
3571 if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context);
3572 if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not
3573 if (!p.pipeline.pipeline && p.pipeline.async_build && !strict_replay()) continue;
3574 if (!p.pipeline.pipeline) return unresolved_at(__LINE__);
3575 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__);
3130 } 3576 }
3131 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 3577 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
3132 p.khr_instances = 0; 3578 p.khr_instances = 0;
3133 if (vk.xdxr_check) { 3579 if (vk.xdxr_check) {
3134 if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; 3580 if (!vk.xdxr_check(*build)) return unsupported_at(__LINE__);
3135 } else { 3581 } else {
3136 if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) 3582 if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure)
3137 return ReplayResult::unsupported; 3583 return unsupported_at(__LINE__);
3138 p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); 3584 p.accel_dst = vk.resolve_acceleration_structure(build->dst_va);
3139 if (!p.accel_dst) return ReplayResult::unresolved_resource; 3585 if (!p.accel_dst) return unresolved_at(__LINE__);
3140 if (build->update && build->src_va) { 3586 if (build->update && build->src_va) {
3141 p.accel_src = vk.resolve_acceleration_structure(build->src_va); 3587 p.accel_src = vk.resolve_acceleration_structure(build->src_va);
3142 if (!p.accel_src) return ReplayResult::unresolved_resource; 3588 if (!p.accel_src) return unresolved_at(__LINE__);
3143 } 3589 }
3144 if (build->is_tlas && build->instance_pointers && build->instance_count) { 3590 if (build->is_tlas && build->instance_pointers && build->instance_count) {
3145 if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; 3591 if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return unsupported_at(__LINE__);
3146 return vk.prepare_khr_instances(*build, p.khr_instances); 3592 return vk.prepare_khr_instances(*build, p.khr_instances);
3147 } 3593 }
3148 } 3594 }
3149 } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) { 3595 } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) {
3150 if (vk.xdxr_copy) { 3596 if (vk.xdxr_copy) {
3151 // XDXR structures: the destination's room bounds the copy, as the size is only known to the GPU. 3597 // XDXR structures: the destination's room bounds the copy, as the size is only known to the GPU.
3152 if (!vk.buffer_at || copy->mode > 1) return ReplayResult::unsupported; 3598 if (!vk.buffer_at || copy->mode > 1) return unsupported_at(__LINE__);
3153 std::uint64_t room = ~std::uint64_t(0); 3599 std::uint64_t room = ~std::uint64_t(0);
3154 VkBuffer buffer = VK_NULL_HANDLE; 3600 VkBuffer buffer = VK_NULL_HANDLE;
3155 VkDeviceSize offset = 0; 3601 VkDeviceSize offset = 0;
3156 if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource; 3602 if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return unresolved_at(__LINE__);
3157 std::uint64_t source = ~std::uint64_t(0); 3603 std::uint64_t source = ~std::uint64_t(0);
3158 if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource; 3604 if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return unresolved_at(__LINE__);
3159 p.xdxr_bytes = std::min(room, source); 3605 p.xdxr_bytes = std::min(room, source);
3160 } else { 3606 } else {
3161 if (vk.queue_stages == detail::queue_stages_copy || !vk.copy_acceleration_structure || 3607 if (vk.queue_stages == detail::queue_stages_copy || !vk.copy_acceleration_structure ||
3162 !vk.resolve_acceleration_structure || copy->mode > 1) 3608 !vk.resolve_acceleration_structure || copy->mode > 1)
3163 return ReplayResult::unsupported; 3609 return unsupported_at(__LINE__);
3164 p.accel_dst = vk.resolve_acceleration_structure(copy->dst_va); 3610 p.accel_dst = vk.resolve_acceleration_structure(copy->dst_va);
3165 p.accel_src = vk.resolve_acceleration_structure(copy->src_va); 3611 p.accel_src = vk.resolve_acceleration_structure(copy->src_va);
3166 if (!p.accel_dst || !p.accel_src) return ReplayResult::unresolved_resource; 3612 if (!p.accel_dst || !p.accel_src) return ReplayResult::unresolved_resource;
@@ -3169,18 +3615,23 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3169 } 3615 }
3170 } else if (const auto* info = std::get_if<AccelerationStructurePostbuild>(&command)) { 3616 } else if (const auto* info = std::get_if<AccelerationStructurePostbuild>(&command)) {
3171 if (vk.xdxr_postbuild) { 3617 if (vk.xdxr_postbuild) {
3172 if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return ReplayResult::unsupported; 3618 if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return unsupported_at(__LINE__);
3173 std::uint64_t room = 8 * info->sources.size(); 3619 std::uint64_t room = 8 * info->sources.size();
3174 VkBuffer buffer = VK_NULL_HANDLE; 3620 VkBuffer buffer = VK_NULL_HANDLE;
3175 VkDeviceSize offset = 0; 3621 VkDeviceSize offset = 0;
3176 if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; 3622 if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return unresolved_at(__LINE__);
3177 if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; 3623 if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy;
3624 if (!info->sources.empty()) {
3625 // dest_va is resolved by VA and may target a host-readable buffer; XDXR postbuild writes from compute.
3626 out.wrote_readback = true;
3627 out.readback_src_stages |= VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT;
3628 }
3178 } else if (info->type == 0 && vk.write_acceleration_structures_properties && 3629 } else if (info->type == 0 && vk.write_acceleration_structures_properties &&
3179 vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && 3630 vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results &&
3180 vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { 3631 vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) {
3181 if (vk.queue_stages == detail::queue_stages_copy || info->sources.empty() || 3632 if (vk.queue_stages == detail::queue_stages_copy || info->sources.empty() ||
3182 info->sources.size() > std::numeric_limits<std::uint32_t>::max() / 8u) 3633 info->sources.size() > std::numeric_limits<std::uint32_t>::max() / 8u)
3183 return ReplayResult::unsupported; 3634 return unsupported_at(__LINE__);
3184 const std::uint64_t need = 8ull * info->sources.size(); 3635 const std::uint64_t need = 8ull * info->sources.size();
3185 std::uint64_t room = need; 3636 std::uint64_t room = need;
3186 detail::PreparedKhrPostbuild pb; 3637 detail::PreparedKhrPostbuild pb;
@@ -3198,7 +3649,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3198 if (!vk.prepare_khr_postbuild(static_cast<std::uint32_t>(pb.sources.size()), pb.query_pool, 3649 if (!vk.prepare_khr_postbuild(static_cast<std::uint32_t>(pb.sources.size()), pb.query_pool,
3199 pb.first_query) || 3650 pb.first_query) ||
3200 !pb.query_pool) 3651 !pb.query_pool)
3201 return ReplayResult::unsupported; 3652 return unsupported_at(__LINE__);
3202 p.khr_postbuild = static_cast<std::uint32_t>(out.khr_postbuilds.size()); 3653 p.khr_postbuild = static_cast<std::uint32_t>(out.khr_postbuilds.size());
3203 out.khr_postbuilds.push_back(std::move(pb)); 3654 out.khr_postbuilds.push_back(std::move(pb));
3204 // dest_va is resolved by VA and may target a host-readable buffer in COPY_DEST. 3655 // dest_va is resolved by VA and may target a host-readable buffer in COPY_DEST.
@@ -3210,18 +3661,44 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3210 } 3661 }
3211 } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { 3662 } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) {
3212 if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) 3663 if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline)
3213 return ReplayResult::unsupported; 3664 return unsupported_at(__LINE__);
3214 const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); 3665 const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline);
3215 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 3666 // A dispatch or draw this runtime cannot resolve (a pipeline it could not make: an untranslated
3216 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 3667 // program, an amplification shader; a vertex or index buffer address that names memory it has no
3668 // buffer for) is dropped, logged by unresolved_at, and the rest of the list is submitted. Failing the
3669 // list instead loses every other draw of the frame: the retail title's lists mix such draws in.
3670 // LEONIDA_STRICT_REPLAY=1 restores the failure.
3671 const bool strict = strict_replay();
3672 if (!pipeline) {
3673 if (strict) return unresolved_at(__LINE__);
3674 unresolved_at(__LINE__);
3675 p.pipeline = {};
3676 continue;
3677 }
3217 p.pipeline = *pipeline; 3678 p.pipeline = *pipeline;
3679 if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context);
3680 if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not
3681 if (!p.pipeline.pipeline) {
3682 if (strict) return unresolved_at(__LINE__);
3683 if (!p.pipeline.async_build) unresolved_at(__LINE__);
3684 continue;
3685 }
3686 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__);
3218 } else if (const auto* draw = std::get_if<Draw>(&command)) { 3687 } else if (const auto* draw = std::get_if<Draw>(&command)) {
3219 if (out.draw_count == out.draws.size()) out.draws.emplace_back(); 3688 if (out.draw_count == out.draws.size()) out.draws.emplace_back();
3220 auto& prepared_draw = out.draws[out.draw_count]; 3689 auto& prepared_draw = out.draws[out.draw_count];
3221 prepared_draw.reset(); 3690 prepared_draw.reset();
3222 p.draw = std::uint32_t(out.draw_count++); 3691 p.draw = std::uint32_t(out.draw_count++);
3223 if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) 3692 if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) {
3224 return r; 3693 const bool strict = strict_replay();
3694 if (r != ReplayResult::unresolved_resource || strict) return r;
3695 prepared_draw.skipped = true; // dropped at emit (see the dispatch branch above)
3696 } else if (draw->indexed && !draw->mesh && draw->topology == topology_quad_list) {
3697 // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool.
3698 if (statistics_active && !statistics_helpers && draw->count >= 4) return ReplayResult::unsupported;
3699 if (const auto r = detail::prepare_quad_indices(*draw, vk, prepared_draw); r != ReplayResult::success)
3700 return r;
3701 }
3225 } 3702 }
3226 } 3703 }
3227 if (ordinary_active || binary_active) return ReplayResult::invalid_query; 3704 if (ordinary_active || binary_active) return ReplayResult::invalid_query;
@@ -3234,7 +3711,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3234 } 3711 }
3235 if (overlaps) { 3712 if (overlaps) {
3236 if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) 3713 if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment)
3237 return ReplayResult::unsupported; 3714 return unsupported_at(__LINE__);
3238 return plan_occlusion_segments(out); 3715 return plan_occlusion_segments(out);
3239 } 3716 }
3240 return ReplayResult::success; 3717 return ReplayResult::success;
@@ -3251,7 +3728,7 @@ public:
3251 const std::shared_ptr<const OcclusionSegmentPool>& statistics_pool = {}, 3728 const std::shared_ptr<const OcclusionSegmentPool>& statistics_pool = {},
3252 std::uint32_t statistics_base = 0) { 3729 std::uint32_t statistics_base = 0) {
3253 if (list.segment_count) { 3730 if (list.segment_count) {
3254 if (!pool) return ReplayResult::unsupported; 3731 if (!pool) return unsupported_at(__LINE__);
3255 retain(pool); 3732 retain(pool);
3256 list.segment_pool = pool->pool; 3733 list.segment_pool = pool->pool;
3257 list.segment_base = base; 3734 list.segment_base = base;
@@ -3267,14 +3744,14 @@ public:
3267 list.statistics_base = statistics_base; 3744 list.statistics_base = statistics_base;
3268 } else if (mesh) { 3745 } else if (mesh) {
3269 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. 3746 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there.
3270 return ReplayResult::unsupported; 3747 return unsupported_at(__LINE__);
3271 } else if (list.statistics_overlaps) { 3748 } else if (list.statistics_overlaps) {
3272 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. 3749 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once.
3273 return ReplayResult::unsupported; 3750 return unsupported_at(__LINE__);
3274 } else { 3751 } else {
3275 for (const auto& command : list.commands) 3752 for (const auto& command : list.commands)
3276 if (command.statistics_end != detail::PreparedQuery::no_segment) 3753 if (command.statistics_end != detail::PreparedQuery::no_segment)
3277 return ReplayResult::unsupported; 3754 return unsupported_at(__LINE__);
3278 for (auto& query : list.queries) { 3755 for (auto& query : list.queries) {
3279 query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment; 3756 query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment;
3280 query.statistics_count = 0; 3757 query.statistics_count = 0;
@@ -3306,7 +3783,7 @@ public:
3306 for (std::uint32_t i = 0; i < resolve.count; ++i) { 3783 for (std::uint32_t i = 0; i < resolve.count; ++i) {
3307 const auto index = resolve.first + i; 3784 const auto index = resolve.first + i;
3308 const auto value = lookup(*query.heap, index); 3785 const auto value = lookup(*query.heap, index);
3309 if (binary && value.ended && !uncounted) return ReplayResult::unsupported; 3786 if (binary && value.ended && !uncounted) return unsupported_at(__LINE__);
3310 needs_binary |= binary && value.ended; 3787 needs_binary |= binary && value.ended;
3311 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, 3788 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE,
3312 index, 1, offset + VkDeviceSize(i) * size}; 3789 index, 1, offset + VkDeviceSize(i) * size};
@@ -3323,7 +3800,7 @@ public:
3323 saved.count > 1 || any_mesh, saved.segments->mesh_pool, 3800 saved.count > 1 || any_mesh, saved.segments->mesh_pool,
3324 saved.segments->primitives_pool, kinds}; 3801 saved.segments->primitives_pool, kinds};
3325 if (any_mesh && !statistics) return ReplayResult::invalid_query; 3802 if (any_mesh && !statistics) return ReplayResult::invalid_query;
3326 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 3803 if (!can_sum || (run.sum && !uncounted)) return unsupported_at(__LINE__);
3327 if (statistics) needs_statistics_sum |= run.sum; 3804 if (statistics) needs_statistics_sum |= run.sum;
3328 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; 3805 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true;
3329 else needs_sum |= run.sum; 3806 else needs_sum |= run.sum;
@@ -3492,8 +3969,9 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions&
3492// `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open 3969// `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open
3493// is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer 3970// is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer
3494// (close_labels). Without it, the list's own events are balanced at its end. 3971// (close_labels). Without it, the list's own events are balanced at its end.
3495inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, 3972template<bool Checkpoints>
3496 LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { 3973inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk,
3974 LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) {
3497 std::uint32_t own_labels = 0; 3975 std::uint32_t own_labels = 0;
3498 std::uint32_t& labels = open_labels ? *open_labels : own_labels; 3976 std::uint32_t& labels = open_labels ? *open_labels : own_labels;
3499 const auto commands = prepared.list->commands(); 3977 const auto commands = prepared.list->commands();
@@ -3510,11 +3988,23 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3510 vk.depth24_run(command_buffer, job); 3988 vk.depth24_run(command_buffer, job);
3511 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); 3989 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
3512 }; 3990 };
3991 const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout) {
3992 if (p.depth_uav_copy != UINT32_MAX) {
3993 detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker);
3994 } else if (p.order_depth_uav) {
3995 // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children.
3996 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
3997 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
3998 }
3999 };
3513 4000
3514 for (std::size_t i = 0; i < commands.size(); ++i) { 4001 for (std::size_t i = 0; i < commands.size(); ++i) {
3515 const auto& command = commands[i]; 4002 const auto& command = commands[i];
3516 const auto& p = prepared.commands[i]; 4003 const auto& p = prepared.commands[i];
3517 if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { 4004 if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) {
4005 if constexpr (Checkpoints)
4006 if (std::holds_alternative<ResolveQueries>(command))
4007 checkpoints->record(command_buffer, i, CheckpointKind::resolve);
3518 emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); 4008 emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate);
3519 continue; 4009 continue;
3520 } 4010 }
@@ -3526,9 +4016,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3526 detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk); 4016 detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk);
3527 }; 4017 };
3528 // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the 4018 // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the
3529 // draw's own rendering scope begins. 4019 // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the
4020 // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside
4021 // the predicate, which skips it together with its draw.
3530 if (std::holds_alternative<Draw>(command) || std::holds_alternative<ExecuteIndirect>(command)) { 4022 if (std::holds_alternative<Draw>(command) || std::holds_alternative<ExecuteIndirect>(command)) {
3531 end_statistics(); 4023 end_statistics();
4024 if (std::holds_alternative<Draw>(command) && prepared.draws[p.draw].quad_indices.buffer)
4025 vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices);
3532 begin_statistics(); 4026 begin_statistics();
3533 } 4027 }
3534 if (const auto* predication = std::get_if<Predication>(&command)) { 4028 if (const auto* predication = std::get_if<Predication>(&command)) {
@@ -3577,6 +4071,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3577 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, 4071 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout,
3578 from.access, from.stages, to.access, to.stages); 4072 from.access, from.stages, to.access, to.stages);
3579 if (tracker) tracker->set(id, range, new_layout); 4073 if (tracker) tracker->set(id, range, new_layout);
4074 finish_depth_uav_barrier(p, new_layout);
3580 } else if (std::holds_alternative<UavBarrier>(command)) { 4075 } else if (std::holds_alternative<UavBarrier>(command)) {
3581 const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); 4076 const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false);
3582 VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; 4077 VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT;
@@ -3593,7 +4088,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3593 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 4088 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
3594 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, 4089 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
3595 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 4090 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
3596 } else if (std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command)) { 4091 } else if (const auto* texture_memory = std::get_if<TextureBarrier>(&command);
4092 std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command) ||
4093 (texture_memory && p.binding.depth_uav && texture_memory->layout_before == d3d12_layout::undefined &&
4094 texture_memory->layout_after == d3d12_layout::undefined)) {
3597 const auto [sync_before, sync_after, access_before, access_after] = std::visit( 4095 const auto [sync_before, sync_after, access_before, access_after] = std::visit(
3598 [](const auto& c) -> std::array<std::uint32_t, 4> { 4096 [](const auto& c) -> std::array<std::uint32_t, 4> {
3599 if constexpr (requires { c.sync_before; }) 4097 if constexpr (requires { c.sync_before; })
@@ -3619,16 +4117,26 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3619 const auto range = detail::planes_for_layout(p.binding, p.range, separate); 4117 const auto range = detail::planes_for_layout(p.binding, p.range, separate);
3620 const bool discard = (texture->flags & texture_barrier_discard) || 4118 const bool discard = (texture->flags & texture_barrier_discard) ||
3621 texture->layout_before == d3d12_layout::undefined; 4119 texture->layout_before == d3d12_layout::undefined;
4120 // LayoutAfter UNDEFINED from a defined layout: the contents are no longer needed (the memory is about to
4121 // be aliased, say). Vulkan has no transition into UNDEFINED (VUID-VkImageMemoryBarrier2-newLayout-01198),
4122 // so each piece keeps the layout it is in and the barrier only orders the accesses; the tracker keeps
4123 // that layout too. D3D12 has the next barrier on these subresources start from UNDEFINED, which discards
4124 // from whatever layout they are in.
4125 const bool release = texture->layout_after == d3d12_layout::undefined &&
4126 texture->layout_before != d3d12_layout::undefined;
3622 const VkImageLayout new_layout = 4127 const VkImageLayout new_layout =
3623 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); 4128 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable));
3624 LayoutPieces pieces; 4129 LayoutPieces pieces;
3625 if (discard) 4130 // With coupled layouts, discarding a single plane must preserve the other plane's data.
4131 const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask;
4132 if (discard && !release && !keep_sibling)
3626 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); 4133 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED});
3627 else { 4134 else {
3628 const VkImageLayout before = 4135 const VkImageLayout before =
4136 texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL :
3629 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); 4137 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable));
3630 pieces = detail::current(tracker, id, range, before); 4138 pieces = detail::current(tracker, id, range, before);
3631 detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); 4139 if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker);
3632 } 4140 }
3633 const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); 4141 const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates);
3634 const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); 4142 const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates);
@@ -3639,6 +4147,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3639 VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); 4147 VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data();
3640 std::uint32_t barrier_count = 0; 4148 std::uint32_t barrier_count = 0;
3641 for (const auto& piece : pieces) { 4149 for (const auto& piece : pieces) {
4150 // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order.
4151 if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue;
3642 VkImageMemoryBarrier2& b = barriers[barrier_count++]; 4152 VkImageMemoryBarrier2& b = barriers[barrier_count++];
3643 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; 4153 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2};
3644 b.srcStageMask = src.stages; 4154 b.srcStageMask = src.stages;
@@ -3646,7 +4156,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3646 b.srcAccessMask = src.access; 4156 b.srcAccessMask = src.access;
3647 b.dstAccessMask = dst.access; 4157 b.dstAccessMask = dst.access;
3648 b.oldLayout = piece.layout; 4158 b.oldLayout = piece.layout;
3649 b.newLayout = new_layout; 4159 b.newLayout = release ? piece.layout : new_layout;
3650 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 4160 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
3651 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 4161 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
3652 b.image = p.binding.image; 4162 b.image = p.binding.image;
@@ -3654,17 +4164,24 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3654 if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); 4164 if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask);
3655 if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); 4165 if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask);
3656 } 4166 }
3657 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 4167 if (barrier_count) {
3658 dependency.imageMemoryBarrierCount = barrier_count; 4168 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
3659 dependency.pImageMemoryBarriers = barriers; 4169 dependency.imageMemoryBarrierCount = barrier_count;
3660 vk.pipeline_barrier2(command_buffer, &dependency); 4170 dependency.pImageMemoryBarriers = barriers;
3661 if (tracker) tracker->set(id, range, new_layout); 4171 vk.pipeline_barrier2(command_buffer, &dependency);
4172 }
4173 if (tracker && !release) tracker->set(id, range, new_layout);
4174 if (!release) finish_depth_uav_barrier(p, new_layout);
3662 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { 4175 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
3663 if (p.skip) continue; 4176 if (p.skip) continue;
4177 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear);
3664 const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); 4178 const VulkanAccess state = vulkan_access(d3d12_state::render_target, false);
3665 auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); 4179 auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout));
3666 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 4180 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
3667 const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); 4181 auto clear_value=color_clear->color;
4182 if(p.binding.rgba4_render_fallback)for(auto& channel:clear_value)
4183 channel=std::nearbyint(std::clamp(channel,0.0f,1.0f)*15.0f)/15.0f;
4184 const VkClearColorValue color=detail::render_target_clear_color(p.clear_format,clear_value);
3668 if (p.rects.empty()) { 4185 if (p.rects.empty()) {
3669 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), 4186 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout),
3670 state, transfer_dst.access, transfer_dst.stages, [&] { 4187 state, transfer_dst.access, transfer_dst.stages, [&] {
@@ -3694,12 +4211,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3694 }); 4211 });
3695 } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { 4212 } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) {
3696 if (p.skip) continue; 4213 if (p.skip) continue;
4214 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear);
3697 // With separate layouts only the cleared planes move; otherwise both do. 4215 // With separate layouts only the cleared planes move; otherwise both do.
3698 const auto range = detail::planes_for_layout(p.binding, p.range, separate); 4216 const auto range = detail::planes_for_layout(p.binding, p.range, separate);
3699 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); 4217 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false);
3700 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); 4218 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout));
3701 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 4219 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
3702 float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h 4220 float depth = p.binding.xbox_depth16_stencil8 ? std::round(std::clamp(depth_clear->depth,0.0f,1.0f)*65535.0f)/65535.0f : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h
3703 : p.binding.format == VK_FORMAT_D16_UNORM 4221 : p.binding.format == VK_FORMAT_D16_UNORM
3704 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm 4222 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm
3705 : depth_clear->depth; 4223 : depth_clear->depth;
@@ -3736,6 +4254,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3736 }); 4254 });
3737 } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { 4255 } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) {
3738 if (p.skip) continue; 4256 if (p.skip) continue;
4257 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear);
3739 // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the 4258 // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the
3740 // clear stage, which is a transfer stage in the legacy masks. 4259 // clear stage, which is a transfer stage in the legacy masks.
3741 VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false); 4260 VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false);
@@ -3760,6 +4279,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3760 const VkImageLayout layout = image_layout(p.binding, state.layout); 4279 const VkImageLayout layout = image_layout(p.binding, state.layout);
3761 auto pieces = detail::current(tracker, id, p.range, layout); 4280 auto pieces = detail::current(tracker, id, p.range, layout);
3762 detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); 4281 detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker);
4282 if (p.clear_pattern_bytes) {
4283 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT,
4284 VK_PIPELINE_STAGE_TRANSFER_BIT, [&] {
4285 detail::emit_buffer_fill(vk, command_buffer, p.staged, p.element, p.staged_writes.front().bufferOffset,
4286 p.clear_pattern_bytes);
4287 for (const auto& region : p.staged_writes) {
4288 // The fill must be visible, and two clear rectangles may overlap.
4289 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
4290 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT,
4291 VK_PIPELINE_STAGE_TRANSFER_BIT);
4292 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, &region);
4293 }
4294 });
4295 continue;
4296 }
3763 if (p.rects.empty()) { 4297 if (p.rects.empty()) {
3764 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, 4298 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state,
3765 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { 4299 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] {
@@ -3788,12 +4322,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3788 }); 4322 });
3789 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || 4323 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) ||
3790 std::holds_alternative<CopyResource>(command)) { 4324 std::holds_alternative<CopyResource>(command)) {
4325 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy);
3791 const auto [dst_id, src_id] = copy_ids(command); 4326 const auto [dst_id, src_id] = copy_ids(command);
3792 if (!p.predicated_copy.empty()) { 4327 if (!p.predicated_copy.empty()) {
3793 end_statistics(); 4328 end_statistics();
3794 vk.emit_predicated_copy(command_buffer, p.predicated_copy); 4329 vk.emit_predicated_copy(command_buffer, p.predicated_copy);
3795 begin_statistics(); 4330 begin_statistics();
3796 } else if (!p.buffer_copies.empty()) { 4331 } else if (!p.buffer_copies.empty()) {
4332 // Transfer dependency from natterman12, ubiquitarianism/leonida PR #354 (GPL-3.0).
4333 // D3D12 orders buffer copies even across lists on one queue. A previous transfer write can
4334 // overlap this copy's source or destination without an application barrier.
4335 if (vk.pipeline_barrier && order_buffer_copies()) {
4336 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
4337 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT,
4338 VK_PIPELINE_STAGE_TRANSFER_BIT);
4339 }
3797 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), 4340 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()),
3798 p.buffer_copies.data()); 4341 p.buffer_copies.data());
3799 } else if (p.staged) { 4342 } else if (p.staged) {
@@ -3911,6 +4454,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3911 } 4454 }
3912 } 4455 }
3913 } else if (std::holds_alternative<ResolveSubresource>(command)) { 4456 } else if (std::holds_alternative<ResolveSubresource>(command)) {
4457 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::resolve);
3914 // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. 4458 // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are.
3915 const auto [dst_id, src_id] = copy_ids(command); 4459 const auto [dst_id, src_id] = copy_ids(command);
3916 if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { 4460 if (p.resolve_mode != VK_RESOLVE_MODE_NONE) {
@@ -4031,6 +4575,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4031 piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 4575 piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
4032 any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 4576 any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
4033 } 4577 }
4578 } else if (const auto* label_write=std::get_if<label::Write>(&command)) {
4579 vk.gpu_label(command_buffer, *label_write);
4034 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) { 4580 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) {
4035 // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish 4581 // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish
4036 // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a 4582 // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a
@@ -4049,6 +4595,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4049 vk.update_buffer(command_buffer, p.write_buffer, p.write_offset, 4, &write->value); 4595 vk.update_buffer(command_buffer, p.write_buffer, p.write_offset, 4, &write->value);
4050 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); 4596 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
4051 } else if (std::holds_alternative<AtomicCopyBuffer>(command)) { 4597 } else if (std::holds_alternative<AtomicCopyBuffer>(command)) {
4598 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy);
4052 // Every earlier write, to the dependent resources among others, finishes and is visible before the copy. 4599 // Every earlier write, to the dependent resources among others, finishes and is visible before the copy.
4053 // Vulkan promises no atomicity for a transfer; that a naturally aligned 4- or 8-byte copy is one write 4600 // Vulkan promises no atomicity for a transfer; that a naturally aligned 4- or 8-byte copy is one write
4054 // is an assumption about the hardware (docs/d3d12_vulkan.md, section 4.2). 4601 // is an assumption about the hardware (docs/d3d12_vulkan.md, section 4.2).
@@ -4057,6 +4604,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4057 VK_PIPELINE_STAGE_TRANSFER_BIT); 4604 VK_PIPELINE_STAGE_TRANSFER_BIT);
4058 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); 4605 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data());
4059 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { 4606 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) {
4607 if (ind->kind == IndirectKind::dispatch && ind->pipeline && !p.pipeline.pipeline &&
4608 (p.pipeline.async_build || p.pipeline.skipped))
4609 continue;
4610 if constexpr (Checkpoints) {
4611 if (ind->kind == IndirectKind::dispatch)
4612 checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, ind->pipeline, ind->user_data, {}, true,
4613 ind->argument_buffer, ind->argument_offset, ind->count_buffer,
4614 ind->count_offset, ind->max_count, ind->stride);
4615 else
4616 checkpoints->record(command_buffer, i, CheckpointKind::draw);
4617 }
4060 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; 4618 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset;
4061 if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { 4619 if (ind->count_buffer && ind->kind != IndirectKind::dispatch) {
4062 const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; 4620 const VkDeviceSize count = p.source.buffer_offset + ind->count_offset;
@@ -4105,6 +4663,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4105 xdxr_build && vk.xdxr_record) { 4663 xdxr_build && vk.xdxr_record) {
4106 vk.xdxr_record(command_buffer, *xdxr_build); 4664 vk.xdxr_record(command_buffer, *xdxr_build);
4107 } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) { 4665 } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) {
4666 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy);
4108 if (vk.xdxr_copy) { 4667 if (vk.xdxr_copy) {
4109 vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes); 4668 vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes);
4110 } else { 4669 } else {
@@ -4200,6 +4759,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4200 const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data(); 4759 const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data();
4201 vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr); 4760 vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr);
4202 } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { 4761 } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) {
4762 if (!p.pipeline.pipeline) continue; // could not be resolved in prepare: dropped
4763 if constexpr (Checkpoints)
4764 checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, dispatch->pipeline, dispatch->user_data,
4765 {dispatch->x, dispatch->y, dispatch->z});
4203 ShaderUserData data{}; 4766 ShaderUserData data{};
4204 std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); 4767 std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s);
4205 data.heap_base = vk.heap_base; 4768 data.heap_base = vk.heap_base;
@@ -4214,6 +4777,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4214 vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); 4777 vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z);
4215 } else if (const auto* draw = std::get_if<Draw>(&command)) { 4778 } else if (const auto* draw = std::get_if<Draw>(&command)) {
4216 const detail::PreparedDraw& d = prepared.draws[p.draw]; 4779 const detail::PreparedDraw& d = prepared.draws[p.draw];
4780 if (d.skipped) continue; // could not be resolved in prepare: dropped
4781 if constexpr (Checkpoints)
4782 checkpoints->record(command_buffer, i, CheckpointKind::draw,
4783 d.pipeline, draw->pipeline);
4217 constexpr VkAccessFlags color_access = 4784 constexpr VkAccessFlags color_access =
4218 VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; 4785 VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
4219 constexpr VkAccessFlags depth_access = 4786 constexpr VkAccessFlags depth_access =
@@ -4309,7 +4876,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4309 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology 4876 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology
4310 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). 4877 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065).
4311 if (!draw->mesh) { 4878 if (!draw->mesh) {
4312 const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); 4879 const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed
4880 ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology);
4313 vk.set_primitive_topology(command_buffer, topology); 4881 vk.set_primitive_topology(command_buffer, topology);
4314 const bool restart = draw->indexed && detail::strip_topology(topology) && 4882 const bool restart = draw->indexed && detail::strip_topology(topology) &&
4315 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || 4883 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) ||
@@ -4326,6 +4894,34 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4326 } 4894 }
4327 if (draw->mesh) { 4895 if (draw->mesh) {
4328 vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); 4896 vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first);
4897 if (vk.mesh_draw_count) ++*vk.mesh_draw_count;
4898 } else if (draw->topology == topology_quad_list) {
4899 if (draw->indexed) {
4900 // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3)
4901 // for each quad of the application's indices from draw->first on: one draw, so instances run
4902 // in D3D12's order, flat inputs come from each quad's first vertex, and VertexIndex - BaseVertex
4903 // is still the application's index. A draw of fewer than four indices has no quad.
4904 const QuadIndexExpansion& quads = d.quad_indices;
4905 if (quads.buffer) {
4906 vk.bind_index_buffer(command_buffer, quads.buffer, quads.offset, VK_INDEX_TYPE_UINT32);
4907 vk.draw_indexed(command_buffer, quads.quads * QuadIndexExpander::indices_per_quad,
4908 draw->instances, 0, draw->base_vertex, draw->first_instance);
4909 }
4910 } else {
4911 // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves
4912 // the original instance order, and VertexIndex - BaseVertex still gives 4q + k.
4913 constexpr auto indices_per_quad = std::uint32_t(quad_triangle_indices.size());
4914 const std::uint32_t wanted = draw->count / 4;
4915 const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad);
4916 if (quads < wanted)
4917 std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n",
4918 wanted, quads);
4919 if (quads) {
4920 vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32);
4921 vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0,
4922 std::int32_t(draw->first), draw->first_instance);
4923 }
4924 }
4329 } else if (draw->indexed) { 4925 } else if (draw->indexed) {
4330 vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); 4926 vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type);
4331 vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, 4927 vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex,
@@ -4341,6 +4937,11 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4341 if (!open_labels) close_labels(command_buffer, vk, own_labels); 4937 if (!open_labels) close_labels(command_buffer, vk, own_labels);
4342} 4938}
4343 4939
4940inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk,
4941 LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) {
4942 emit_commands<false>(prepared, command_buffer, vk, tracker, open_labels, nullptr);
4943}
4944
4344// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. 4945// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched.
4345// With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get 4946// With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get
4346// segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. 4947// segment pools as in the batched path; the caller holds `keep` until the command buffer has completed.
@@ -4349,20 +4950,20 @@ ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Res
4349 const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, 4950 const ReplayFunctions& vk, LayoutTracker* tracker = nullptr,
4350 std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) { 4951 std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) {
4351 if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) 4952 if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts)
4352 return ReplayResult::unsupported; 4953 return unsupported_at(__LINE__);
4353 const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && 4954 const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion &&
4354 vk.sum_statistics && vk.sum_binary_occlusion; 4955 vk.sum_statistics && vk.sum_binary_occlusion;
4355 PreparedList prepared; 4956 PreparedList prepared;
4356 if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) 4957 if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success)
4357 return result; 4958 return result;
4358 if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; 4959 if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return unsupported_at(__LINE__);
4359 std::shared_ptr<const OcclusionSegmentPool> physical, statistics; 4960 std::shared_ptr<const OcclusionSegmentPool> physical, statistics;
4360 if (pools && prepared.segment_count && 4961 if (pools && prepared.segment_count &&
4361 !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) 4962 !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count)))
4362 return ReplayResult::unsupported; 4963 return unsupported_at(__LINE__);
4363 if (pools && prepared.statistics_segment_count && 4964 if (pools && prepared.statistics_segment_count &&
4364 !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) 4965 !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count)))
4365 return ReplayResult::unsupported; 4966 return unsupported_at(__LINE__);
4366 QueryReplay queries; 4967 QueryReplay queries;
4367 if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) 4968 if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success)
4368 return result; 4969 return result;
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index 33d84bf72..753701e1c 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -3,12 +3,17 @@
3// it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour 3// it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour
4// copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own 4// copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own
5// scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24. 5// scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24.
6// The chunks are transfer sources and destinations; `extra_usage` adds what another user needs (the expanded indices
7// of quad lists, quad_index_expand.h: an index buffer written through its device address).
6#pragma once 8#pragma once
7 9
8#ifndef VK_NO_PROTOTYPES 10#ifndef VK_NO_PROTOTYPES
9#define VK_NO_PROTOTYPES 11#define VK_NO_PROTOTYPES
10#endif 12#endif
11#include <vulkan/vulkan.h> 13#include <vulkan/vulkan.h>
14#include "queue_families.h"
15
16#include "vulkan_device_fault.h"
12 17
13#include <algorithm> 18#include <algorithm>
14#include <cstdint> 19#include <cstdint>
@@ -23,14 +28,16 @@ public:
23 // A device-local allocation for a chunk; null on failure. 28 // A device-local allocation for a chunk; null on failure.
24 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>; 29 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>;
25 30
26 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) 31 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0,
27 : device_(device), allocate_(std::move(allocate)) { 32 std::vector<std::uint32_t> families = {}, DeviceFaultDiagnostics* diagnostics = nullptr)
33 : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), extra_usage_(extra_usage),
34 families_(std::move(families)) {
28 loaded_ = vk_.load(get, device); 35 loaded_ = vk_.load(get, device);
29 } 36 }
30 37
31 ~ScratchBuffers() { 38 ~ScratchBuffers() {
32 if (!loaded_) return; 39 if (!loaded_) return;
33 vk_.vkDeviceWaitIdle(device_); 40 DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle");
34 release(current_); 41 release(current_);
35 for (auto& batch : retired_) release(batch); 42 for (auto& batch : retired_) release(batch);
36 for (auto& chunk : spare_) destroy(chunk); 43 for (auto& chunk : spare_) destroy(chunk);
@@ -101,7 +108,9 @@ public:
101 if (retired_[i].ticket != 0) { 108 if (retired_[i].ticket != 0) {
102 std::uint64_t done = 0; 109 std::uint64_t done = 0;
103 if (!retired_[i].timeline || 110 if (!retired_[i].timeline ||
104 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS || 111 DeviceFaultDiagnostics::observe(diagnostics_,
112 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done),
113 "vkGetSemaphoreCounterValue (scratch)") != VK_SUCCESS ||
105 done < retired_[i].ticket) { 114 done < retired_[i].ticket) {
106 ++i; 115 ++i;
107 continue; 116 continue;
@@ -152,7 +161,9 @@ private:
152 bool make_chunk(std::uint64_t size, Chunk& out) { 161 bool make_chunk(std::uint64_t size, Chunk& out) {
153 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 162 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
154 info.size = size; 163 info.size = size;
155 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; 164 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | extra_usage_;
165 // A retired chunk can be reused by a submission on a different queue family.
166 share_across_queue_families(info, families_);
156 if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; 167 if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false;
157 VkMemoryRequirements requirements{}; 168 VkMemoryRequirements requirements{};
158 vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); 169 vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements);
@@ -175,7 +186,10 @@ private:
175 } 186 }
176 187
177 VkDevice device_; 188 VkDevice device_;
189 DeviceFaultDiagnostics* diagnostics_;
178 Allocate allocate_; 190 Allocate allocate_;
191 VkBufferUsageFlags extra_usage_ = 0;
192 std::vector<std::uint32_t> families_;
179 Functions vk_; 193 Functions vk_;
180 bool loaded_ = false; 194 bool loaded_ = false;
181 Batch current_; // handed out, not yet submitted 195 Batch current_; // handed out, not yet submitted
diff --git a/runtime/src/vulkan_title_image_pool.h b/runtime/src/vulkan_title_image_pool.h
new file mode 100644
index 000000000..94308f687
--- /dev/null
+++ b/runtime/src/vulkan_title_image_pool.h
@@ -0,0 +1,113 @@
1#pragma once
2
3#include <vulkan/vulkan.h>
4
5#include <algorithm>
6#include <bit>
7#include <cstdint>
8#include <map>
9#include <memory>
10#include <mutex>
11#include <vector>
12
13namespace leonida {
14
15// Only optimal-tiled, non-sparse images go in a page. A slot is returned after the owning
16// image is destroyed by the device's normal GPU retirement queue.
17struct TitleImagePage {
18 VkDevice device{};
19 VkDeviceMemory memory{};
20 PFN_vkFreeMemory free_memory{};
21 std::uint32_t type = 0, capacity = 0, allocated = 0;
22 std::mutex mutex;
23 std::vector<std::uint32_t> returned;
24
25 ~TitleImagePage() {
26 if (memory) free_memory(device, memory, nullptr);
27 }
28
29 bool take(std::uint32_t& slot) {
30 std::lock_guard lock(mutex);
31 if (!returned.empty()) {
32 slot = returned.back();
33 returned.pop_back();
34 } else if (allocated < capacity) {
35 slot = allocated++;
36 } else {
37 return false;
38 }
39 return true;
40 }
41
42 void release(std::uint32_t slot) {
43 std::lock_guard lock(mutex);
44 returned.push_back(slot); // the page reserves capacity at creation
45 }
46};
47
48struct PooledTitleImage {
49 PooledTitleImage() = default;
50 PooledTitleImage(const PooledTitleImage&) = delete;
51 PooledTitleImage& operator=(const PooledTitleImage&) = delete;
52
53 std::shared_ptr<TitleImagePage> page;
54 std::uint32_t slot = 0;
55 VkImage image{};
56 PFN_vkDestroyImage destroy_image{};
57
58 ~PooledTitleImage() {
59 if (image) destroy_image(page->device, image, nullptr);
60 if (page) page->release(slot);
61 }
62};
63
64class TitleImagePool {
65public:
66 // The caller has already excluded dedicated-only images. All allocations in one page have
67 // identical stride, compatible memory types and non-overlapping, individually aligned ranges.
68 template<class Allocate>
69 std::unique_ptr<PooledTitleImage> bind(VkDevice device, VkImage image, const VkMemoryRequirements& req,
70 PFN_vkBindImageMemory bind_image, PFN_vkDestroyImage destroy_image,
71 PFN_vkFreeMemory free_memory, Allocate allocate) {
72 constexpr VkDeviceSize largest_slot = VkDeviceSize{2} << 20;
73 const VkDeviceSize needed = std::max(req.size, req.alignment);
74 if (!needed || needed > largest_slot || !req.memoryTypeBits) return {};
75 // Eight size classes per power of two keep padding below one eighth (besides required alignment).
76 const VkDeviceSize quantum = std::max(req.alignment, std::max(VkDeviceSize{1}, std::bit_floor(needed) / 8));
77 const VkDeviceSize stride = (needed + quantum - 1) & ~(quantum - 1);
78 const VkDeviceSize page_size = std::min(VkDeviceSize{8} << 20, 256 * stride);
79 auto allocation = std::make_unique<PooledTitleImage>();
80 std::lock_guard lock(mutex_);
81 auto& pages = classes_[stride];
82 std::erase_if(pages, [](const auto& page) { return page.expired(); });
83 for (const auto& weak : pages) {
84 auto page = weak.lock();
85 if (page && (req.memoryTypeBits & (1u << page->type)) && page->take(allocation->slot)) {
86 allocation->page = std::move(page);
87 break;
88 }
89 }
90 if (!allocation->page) {
91 auto page = std::make_shared<TitleImagePage>();
92 page->device = device;
93 page->free_memory = free_memory;
94 page->capacity = static_cast<std::uint32_t>(page_size / stride);
95 page->returned.reserve(page->capacity);
96 page->memory = allocate(page_size, page->type);
97 if (!page->memory) return {};
98 pages.push_back(page);
99 page->take(allocation->slot);
100 allocation->page = std::move(page);
101 }
102 if (bind_image(device, image, allocation->page->memory, stride * allocation->slot) != VK_SUCCESS) return {};
103 allocation->destroy_image = destroy_image;
104 allocation->image = image;
105 return allocation;
106 }
107
108private:
109 std::mutex mutex_;
110 std::map<VkDeviceSize, std::vector<std::weak_ptr<TitleImagePage>>> classes_;
111};
112
113} // namespace leonida