diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:26:00 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:26:00 -0500 |
| commit | 154e4ec034902deffa4b89b2cbca9a949f38baec (patch) | |
| tree | 1b2ef5656de42c172291bc6009efa4c510650815 /runtime/src | |
| parent | eb6a08cd359d98b5777e70d54d0ae8a75879495a (diff) | |
| parent | 8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (diff) | |
Merge the #984 result (main + RT-PROTON-STORY-LOAD) into #939
The base is 8a242efeb, the merge of main and #984. 68 files conflicted; they were resolved in seven groups by
one rule: the same change in two forms keeps the base's form, everything only #939 has is kept, and where the
two solve one problem in two ways the base's is the frame and #939's plugs into it.
A, the Xbox proxy (d3d12_xs_device.cpp/.h, d3d12_xs.cpp, d3d12_xs_pso_stream.cpp/.h, d3d12_xs_alloc_size.h,
d3d12_xs_desc_clean.h, device_proxy_test.cpp, queue_proxy_test.cpp): the base's files with #939's additions
ported in. Device slot 57 asks #939's NativeGraphicsFactory first and falls back to the base's
proxy_create_graphics_pipeline_from_native_code on E_NOTIMPL. Kept from #939: the providers (texture lease,
raw texture view, resource by address, constant view, descriptor mapping, depth-stencil UAV, texture pages),
the title-backed descriptor mirror, slot 13's feature answers, GPU labels on list slots 71/72. Dropped: #939's
duplicates of the boot ladder routes, its fallback window, its slot 133 stand-in.
A2 (xs_proxy_mock_test.cpp): the base's test with #939's slot 70 raw-buffer case; presentation cases follow
#939's rule that a device which ever had a handler has no queue fallback.
B1, the Vulkan device (d3d12_vulkan_device.cpp, d3d12_com.cpp/.h, shader_library.h, queue_families.h,
pipeline_cache_file.h, startup_trace.h): one lazy-pipeline mechanism, the base's; #939's pending_base_compile
and first_use_backend_pipelines dropped, prepare_on_bind and cold_graphics_compile kept. create_texture keeps
the base's signature; #939's deferred backing is folded into the base's placed-memory binder. #939's quad
lists as triangle indices.
B2, the D3D12 tests (d3d12_existing_heap, a8_dimensions, pipeline_cache_seed, title_va, rect_list,
shader_library, loader_tls_index0, draw, compute, xmem_placed, shader_library_corpus): the base's tests where
both carry the same case, #939's cases added (rebound tables, linear texture map, large vertex batch,
executable shaders, default A8 views).
C, the backend (vulkan_replay.h, vulkan_backend.h, vulkan_bindless.h, vulkan_scratch.h, vulkan_present.h,
rect_list_geometry.h, vk_test_device.h, vk_pipeline_check.cpp, vk_store_test.cpp, bindless_sizing_test.cpp,
replay_texture_barrier_test.cpp): the base's prepare_draw and lazy compute, its #1055 release rule and its
rectangle generator; #939's rectangle variants, GPU quad index expansion, 1D/3D and depth-stencil UAVs, the
label fence on the base's submit.
D, memory, services, presentation (xmem.cpp/.h, xg_xs.cpp, xg_xs_test.cpp, title_va_alias.h and its test,
main.cpp, frame_pacer.h, xbox_present.cpp/.h; xgameruntime_offline.cpp for one comment): the base's xmem with
#939's label hooks, file-backed sections and pin_mapped_data; both texture computers in xg_xs.cpp, the base's
answering first; --first-run-ui kept without host speech in its profile.
E, build, tools, docs (runtime/CMakeLists.txt, make_game.py, tools/rdna2spirv.py, tools/shader_disasm.py,
scripts, tests, docs; docs/README.md and tests/test_exe_shaders_stage.py beyond the conflicts): the base's
v_dot4 decode, #281's disassembler form and tests/semantic/test_fspx_dot4_op_sel_disasm.py dropped; the
base's executable-shader step with #939's cache fix; 366 registered tests.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
54 files changed, 6377 insertions, 507 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). |
| 61 | inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { | 61 | inline 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 | |||
| 10 | namespace leonida::bcpack { | ||
| 11 | namespace { | ||
| 12 | using namespace detail; | ||
| 13 | |||
| 14 | void 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 | |||
| 26 | struct Endpoints { | ||
| 27 | int v[8]{}; | ||
| 28 | }; | ||
| 29 | |||
| 30 | bool 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 | |||
| 87 | struct 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. | ||
| 103 | struct BptcState { | ||
| 104 | array<int, 24> ep{}; | ||
| 105 | array<int, 32> ix{}; | ||
| 106 | int ep_root = -1, ix_root = -1; | ||
| 107 | }; | ||
| 108 | int mod_bits(int v, int n) { return v & ((1 << n) - 1); } | ||
| 109 | |||
| 110 | void 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 | |||
| 122 | bool 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 | |||
| 133 | bool 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 | |||
| 185 | bool 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. | ||
| 264 | struct 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 | |||
| 277 | bool 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 | |||
| 395 | Quality 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 | |||
| 7 | namespace leonida::bcpack { | ||
| 8 | enum 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. | ||
| 13 | struct 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 | }; | ||
| 28 | static_assert(sizeof(Calibration) == 256 * (70 + 168)); | ||
| 29 | Quality 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 | |||
| 9 | namespace leonida::bcpack::detail { | ||
| 10 | using namespace std; | ||
| 11 | struct Seed { | ||
| 12 | int16_t values[8]; | ||
| 13 | bool fitted; | ||
| 14 | }; | ||
| 15 | struct BC6Mode { | ||
| 16 | int code, transformed, base, delta[3], regions, first, count; | ||
| 17 | }; | ||
| 18 | #include "bcpack_tables.inc" | ||
| 19 | |||
| 20 | using Symbols = array<uint16_t, 16>; | ||
| 21 | constexpr uint32_t home = 1u << 24; | ||
| 22 | |||
| 23 | struct 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. | ||
| 69 | inline 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 | |||
| 80 | enum class Phase { header, length, long_length, symbols }; | ||
| 81 | struct 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 | |||
| 165 | inline int unzig(int value) { return value & 1 ? -((value + 1) >> 1) : value >> 1; } | ||
| 166 | inline 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 | |||
| 173 | struct BC7Format { | ||
| 174 | int subsets, color, alpha, pbits, index, partition; | ||
| 175 | }; | ||
| 176 | constexpr 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 | |||
| 182 | template<class Block> | ||
| 183 | bool 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 | |||
| 31 | namespace rt::clzero_patch { | ||
| 32 | |||
| 33 | struct 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. | ||
| 41 | inline 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 | |||
| 45 | inline 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. | ||
| 48 | inline unsigned rm_reg(uint8_t rex, uint8_t modrm) { return (modrm & 7) | ((rex & 1) << 3); } | ||
| 49 | inline 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. | ||
| 52 | inline 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). | ||
| 96 | inline 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). | ||
| 127 | inline 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 | |||
| 143 | inline 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 | |||
| 149 | struct 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. | ||
| 157 | inline 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 3e89e1cff..010abbbc0 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -415,6 +415,15 @@ struct DrawViews { | |||
| 415 | std::uint32_t render_target_count = 8; | 415 | std::uint32_t render_target_count = 8; |
| 416 | }; | 416 | }; |
| 417 | 417 | ||
| 418 | // Shared across draws that keep the same multi-viewport / multi-scissor state (null for the common 1-viewport case). | ||
| 419 | struct DrawViewports { | ||
| 420 | static constexpr std::uint32_t max_count = 16; | ||
| 421 | std::array<Viewport, max_count> viewports{}; | ||
| 422 | std::uint32_t viewport_count = 0; | ||
| 423 | std::array<Rect, max_count> scissors{}; | ||
| 424 | std::uint32_t scissor_count = 0; | ||
| 425 | }; | ||
| 426 | |||
| 418 | // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: | 427 | // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: |
| 419 | // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the | 428 | // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the |
| 420 | // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw | 429 | // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw |
| @@ -441,6 +450,7 @@ struct Draw { | |||
| 441 | std::int32_t base_vertex = 0; | 450 | std::int32_t base_vertex = 0; |
| 442 | std::uint32_t first_instance = 0; | 451 | std::uint32_t first_instance = 0; |
| 443 | bool mesh = false; | 452 | bool mesh = false; |
| 453 | std::shared_ptr<const DrawViewports> viewports; // non-null when >1 viewport or >1 scissor was bound | ||
| 444 | }; | 454 | }; |
| 445 | 455 | ||
| 446 | // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. | 456 | // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. |
| @@ -693,10 +703,11 @@ public: | |||
| 693 | return append(barrier); | 703 | return append(barrier); |
| 694 | } | 704 | } |
| 695 | 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. | ||
| 696 | bool barrier(const TextureBarrier& barrier) { | 709 | bool barrier(const TextureBarrier& barrier) { |
| 697 | 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; |
| 698 | if (barrier.layout_after == d3d12_layout::undefined && barrier.layout_before != d3d12_layout::undefined) | ||
| 699 | return false; | ||
| 700 | if (barrier.flags & ~texture_barrier_discard) return false; | 711 | if (barrier.flags & ~texture_barrier_discard) return false; |
| 701 | 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; |
| 702 | if (barrier.sync_after == d3d12_sync::split) return !closed_; | 713 | if (barrier.sync_after == d3d12_sync::split) return !closed_; |
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index fac13eeee..8df3b55d0 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h | |||
| @@ -272,6 +272,84 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt | |||
| 272 | return true; | 272 | return true; |
| 273 | } | 273 | } |
| 274 | 274 | ||
| 275 | inline uint64_t gpr_read(const CONTEXT* c, int r) { | ||
| 276 | switch (r) { | ||
| 277 | case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx; | ||
| 278 | case 4: return c->Rsp; case 5: return c->Rbp; case 6: return c->Rsi; case 7: return c->Rdi; | ||
| 279 | case 8: return c->R8; case 9: return c->R9; case 10: return c->R10; case 11: return c->R11; | ||
| 280 | case 12: return c->R12; case 13: return c->R13; case 14: return c->R14; case 15: return c->R15; | ||
| 281 | default: return 0; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | |||
| 285 | enum class ClzeroLoopResult { no_match, ok, faulted }; | ||
| 286 | |||
| 287 | inline void apply_cmp_flags(CONTEXT* c, uint64_t lhs, uint64_t rhs) { | ||
| 288 | const uint64_t diff = lhs - rhs; | ||
| 289 | uint32_t flags = c->EFlags & ~DWORD(0x8D5u); // clear CF(0), PF(2), AF(4), ZF(6), SF(7), OF(11) | ||
| 290 | if (lhs < rhs) flags |= 0x1u; // CF | ||
| 291 | uint8_t lo8 = static_cast<uint8_t>(diff); | ||
| 292 | lo8 ^= lo8 >> 4; | ||
| 293 | lo8 ^= lo8 >> 2; | ||
| 294 | lo8 ^= lo8 >> 1; | ||
| 295 | if ((lo8 & 1u) == 0) flags |= 0x4u; // PF | ||
| 296 | if ((lhs ^ rhs ^ diff) & 0x10u) flags |= 0x10u; // AF | ||
| 297 | if (diff == 0) flags |= 0x40u; // ZF | ||
| 298 | if (diff >> 63) flags |= 0x80u; // SF | ||
| 299 | if (((lhs ^ rhs) & (lhs ^ diff)) >> 63) flags |= 0x800u; // OF | ||
| 300 | c->EFlags = flags; | ||
| 301 | } | ||
| 302 | |||
| 303 | // Fast-path for the Zen 2 zeroing loop: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes). | ||
| 304 | // Zeroes the entire writable span in one memset instead of raising #UD + VirtualQuery per 64-byte line. | ||
| 305 | inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, CONTEXT* c, EXCEPTION_RECORD* fault) { | ||
| 306 | if (avail < 12) return ClzeroLoopResult::no_match; | ||
| 307 | if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return ClzeroLoopResult::no_match; | ||
| 308 | if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return ClzeroLoopResult::no_match; | ||
| 309 | if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) | ||
| 310 | return ClzeroLoopResult::no_match; | ||
| 311 | if (code[10] != 0x72 || code[11] != 0xF4) return ClzeroLoopResult::no_match; | ||
| 312 | |||
| 313 | const int limit_reg = ((code[9] >> 3) & 7) | ((code[7] & 4) << 1); | ||
| 314 | if (limit_reg == 0 || limit_reg == 4) return ClzeroLoopResult::no_match; | ||
| 315 | |||
| 316 | const uint64_t start = c->Rax; | ||
| 317 | const uint64_t limit = gpr_read(c, limit_reg); | ||
| 318 | if ((start & 63) != 0 || limit <= start + 64) return ClzeroLoopResult::no_match; | ||
| 319 | |||
| 320 | uint64_t total = (limit - start + 63) & ~uint64_t(63); | ||
| 321 | constexpr uint64_t kMaxBatch = uint64_t(64) << 20; | ||
| 322 | if (total > kMaxBatch) total = kMaxBatch; | ||
| 323 | const uint64_t end = start + total; | ||
| 324 | |||
| 325 | for (uint64_t cur = start; cur < end;) { | ||
| 326 | const DWORD err = writable(cur); | ||
| 327 | if (err) { | ||
| 328 | if (cur > start) { | ||
| 329 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(cur - start)); | ||
| 330 | c->Rax = cur; | ||
| 331 | apply_cmp_flags(c, cur, limit); | ||
| 332 | } | ||
| 333 | if (fault) { | ||
| 334 | std::memset(fault, 0, sizeof *fault); | ||
| 335 | fault->ExceptionCode = err; | ||
| 336 | fault->NumberParameters = 2; | ||
| 337 | fault->ExceptionInformation[0] = 1; | ||
| 338 | fault->ExceptionInformation[1] = ULONG_PTR(cur); | ||
| 339 | } | ||
| 340 | return ClzeroLoopResult::faulted; | ||
| 341 | } | ||
| 342 | const uint64_t next_page = (cur & ~uint64_t(0xFFF)) + 0x1000; | ||
| 343 | cur = next_page < end ? next_page : end; | ||
| 344 | } | ||
| 345 | |||
| 346 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(total)); | ||
| 347 | c->Rax = end; | ||
| 348 | apply_cmp_flags(c, end, limit); | ||
| 349 | if (end >= limit) c->Rip += 12; | ||
| 350 | return ClzeroLoopResult::ok; | ||
| 351 | } | ||
| 352 | |||
| 275 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | 353 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { |
| 276 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; | 354 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; |
| 277 | CONTEXT* c = info->ContextRecord; | 355 | CONTEXT* c = info->ContextRecord; |
| @@ -281,6 +359,25 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | |||
| 281 | const Decoded d = decode(code, avail); | 359 | const Decoded d = decode(code, avail); |
| 282 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; | 360 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; |
| 283 | EXCEPTION_RECORD fault; | 361 | EXCEPTION_RECORD fault; |
| 362 | if (d.op == Op::clzero && !d.addr32 && d.length == 3) { | ||
| 363 | const uint64_t fault_rip = c->Rip; | ||
| 364 | const ClzeroLoopResult lr = try_clzero_loop(code, avail, c, &fault); | ||
| 365 | if (lr == ClzeroLoopResult::ok) { | ||
| 366 | if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0) | ||
| 367 | std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), | ||
| 368 | reinterpret_cast<void*>(fault_rip)); | ||
| 369 | return EXCEPTION_CONTINUE_EXECUTION; | ||
| 370 | } | ||
| 371 | if (lr == ClzeroLoopResult::faulted) { | ||
| 372 | EXCEPTION_RECORD* r = info->ExceptionRecord; | ||
| 373 | r->ExceptionCode = fault.ExceptionCode; | ||
| 374 | r->ExceptionFlags = 0; | ||
| 375 | r->NumberParameters = fault.NumberParameters; | ||
| 376 | r->ExceptionInformation[0] = fault.ExceptionInformation[0]; | ||
| 377 | r->ExceptionInformation[1] = fault.ExceptionInformation[1]; | ||
| 378 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 379 | } | ||
| 380 | } | ||
| 284 | if (!apply(d, c, &fault)) { | 381 | if (!apply(d, c, &fault)) { |
| 285 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers | 382 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers |
| 286 | // see it instead of the #UD (RIP still points at the instruction). | 383 | // see it instead of the #UD (RIP still points at the instruction). |
diff --git a/runtime/src/crt_timed_wait.cpp b/runtime/src/crt_timed_wait.cpp index 6441f2868..cd26e7d3a 100644 --- a/runtime/src/crt_timed_wait.cpp +++ b/runtime/src/crt_timed_wait.cpp | |||
| @@ -25,7 +25,9 @@ extern "C" { | |||
| 25 | // absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). | 25 | // absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). |
| 26 | __declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; | 26 | __declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; |
| 27 | 27 | ||
| 28 | _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | 28 | namespace { |
| 29 | |||
| 30 | _Thrd_result timedwait_for_impl(_Cnd_t cond, _Mtx_t mtx, unsigned int ms, bool unchecked) noexcept { | ||
| 29 | _timespec64 deadline{}; | 31 | _timespec64 deadline{}; |
| 30 | if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; | 32 | if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; |
| 31 | deadline.tv_sec += ms / 1000; | 33 | deadline.tv_sec += ms / 1000; |
| @@ -34,13 +36,32 @@ _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, uns | |||
| 34 | deadline.tv_sec += 1; | 36 | deadline.tv_sec += 1; |
| 35 | deadline.tv_nsec -= 1000000000L; | 37 | deadline.tv_nsec -= 1000000000L; |
| 36 | } | 38 | } |
| 37 | // A spurious or early return is allowed ("unchecked"): the STL's callers check the clock themselves. | 39 | // Preserve the caller's LastError across the wait while detecting OS timer timeouts cleanly. |
| 38 | return static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); | 40 | const DWORD saved_error = GetLastError(); |
| 41 | SetLastError(ERROR_SUCCESS); | ||
| 42 | const auto res = static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); | ||
| 43 | const DWORD wait_error = GetLastError(); | ||
| 44 | SetLastError(saved_error); | ||
| 45 | // msvcp140's _Cnd_timedwait checks _Xtime_diff_to_millis2(target, &now) == 0 after SleepConditionVariableSRW | ||
| 46 | // returns FALSE/ERROR_TIMEOUT, so an OS timer wake even <1 ms before `deadline` turns into _Thrd_result::_Success. | ||
| 47 | // STL wait_for/wait_until callers treat _Success from _Cnd_timedwait_for_unchecked as a notification/spurious | ||
| 48 | // wake (cv_status::no_timeout) instead of looping until steady_clock reaches the target; report _Timedout here | ||
| 49 | // so the caller checks steady_clock and waits for the remaining time. | ||
| 50 | if (unchecked && res == _Thrd_result::_Success && wait_error == ERROR_TIMEOUT) { | ||
| 51 | return _Thrd_result::_Timedout; | ||
| 52 | } | ||
| 53 | return res; | ||
| 54 | } | ||
| 55 | |||
| 56 | } // namespace | ||
| 57 | |||
| 58 | _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | ||
| 59 | return timedwait_for_impl(cond, mtx, ms, true); | ||
| 39 | } | 60 | } |
| 40 | 61 | ||
| 41 | // Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. | 62 | // Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. |
| 42 | _Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | 63 | _Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { |
| 43 | return _Cnd_timedwait_for_unchecked(cond, mtx, ms); | 64 | return timedwait_for_impl(cond, mtx, ms, false); |
| 44 | } | 65 | } |
| 45 | 66 | ||
| 46 | void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { | 67 | void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { |
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 | |||
| 16 | namespace leonida::d3d12_xs { | ||
| 17 | |||
| 18 | // Device slot 81 (GetFrameEventsX) output event record (exact stride 0x38 bytes). | ||
| 19 | struct 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 | }; | ||
| 27 | static_assert(sizeof(XboxFrameEvent) == 0x38); | ||
| 28 | static_assert(offsetof(XboxFrameEvent, event_type) == 0x00); | ||
| 29 | static_assert(offsetof(XboxFrameEvent, status) == 0x08); | ||
| 30 | static_assert(offsetof(XboxFrameEvent, timestamp) == 0x18); | ||
| 31 | |||
| 32 | enum 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. | ||
| 40 | inline 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 | |||
| 6 | namespace 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. | ||
| 10 | class DeferredImageBinding { | ||
| 11 | public: | ||
| 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 | |||
| 24 | private: | ||
| 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/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. |
| 27 | using DescriptorKey = std::array<std::uint32_t, 8>; | 27 | using DescriptorKey = std::array<std::uint32_t, 8>; |
| 28 | 28 | ||
| 29 | inline 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. | ||
| 34 | enum class DescriptorHashKind : std::uint8_t { fnv1a = 0, fnv1a_fmix32 = 1 }; | ||
| 35 | |||
| 36 | inline 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. | ||
| 41 | inline 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. | ||
| 50 | inline 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 | |||
| 59 | inline 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 | |||
| 64 | inline 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. | ||
| 69 | inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) { | ||
| 70 | return hash_descriptor_key(key, DescriptorHashKind::fnv1a); | ||
| 71 | } | ||
| 72 | |||
| 37 | inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) { | 73 | inline 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 { | |||
| 69 | public: | 105 | public: |
| 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 | |||
| 6 | namespace 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. | ||
| 10 | inline constexpr unsigned stripes[][5] = {{}, {1, 1, 2}, {1, 1, 6}, {1, 3, 1, 1, 2}, {1, 3, 1, 3}}; | ||
| 11 | |||
| 12 | inline size_t group_size(unsigned mode) { return mode == 1 ? 16384 : 32768; } | ||
| 13 | |||
| 14 | inline 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 | |||
| 4 | namespace leonida::dstorage { | ||
| 5 | inline 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 e157e39a3..2c9f1fd7e 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h | |||
| @@ -32,14 +32,19 @@ | |||
| 32 | // suspended) is unchanged. | 32 | // suspended) is unchanged. |
| 33 | 33 | ||
| 34 | #include <algorithm> | 34 | #include <algorithm> |
| 35 | #include <array> | ||
| 35 | #include <atomic> | 36 | #include <atomic> |
| 36 | #include <chrono> | 37 | #include <chrono> |
| 37 | #include <condition_variable> | 38 | #include <condition_variable> |
| 39 | #include <cstddef> | ||
| 38 | #include <cstdint> | 40 | #include <cstdint> |
| 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> | ||
| 47 | #include <vector> | ||
| 43 | 48 | ||
| 44 | namespace leonida { | 49 | namespace leonida { |
| 45 | 50 | ||
| @@ -152,6 +157,25 @@ struct FrameStatistic { | |||
| 152 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) | 157 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) |
| 153 | }; | 158 | }; |
| 154 | 159 | ||
| 160 | // Fixed-capacity ring buffer size for recent frame-time and origin-to-present latency samples (BL-6). | ||
| 161 | inline constexpr std::size_t frame_pacing_window = 1024; | ||
| 162 | |||
| 163 | // Summary over the most recent `frame_pacing_window` presented frames (p50/p95/p99 and mean drift against target). | ||
| 164 | struct FramePacingSummary { | ||
| 165 | std::uint64_t frames = 0; // total presented frames recorded | ||
| 166 | std::uint64_t samples = 0; // present-to-present intervals in the ring buffer (<= frame_pacing_window) | ||
| 167 | std::uint32_t target_interval_us = 0; // active target interval in us (0 when unpaced or uncapped) | ||
| 168 | double mean_us = 0.0; // mean present-to-present interval over `samples` | ||
| 169 | double drift_us = 0.0; // mean_us - target_interval_us (0 when unpaced/uncapped or samples == 0) | ||
| 170 | std::uint64_t p50_us = 0; // nearest-rank 50th percentile frame interval in us | ||
| 171 | std::uint64_t p95_us = 0; // nearest-rank 95th percentile frame interval in us | ||
| 172 | std::uint64_t p99_us = 0; // nearest-rank 99th percentile frame interval in us | ||
| 173 | std::uint64_t latency_samples = 0; // origin-to-present latency samples in the ring buffer | ||
| 174 | std::uint64_t latency_p50_us = 0; // nearest-rank 50th percentile origin-to-present latency in us | ||
| 175 | std::uint64_t latency_p95_us = 0; // nearest-rank 95th 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 | ||
| 177 | }; | ||
| 178 | |||
| 155 | class FrameTokenSource { | 179 | class FrameTokenSource { |
| 156 | public: | 180 | public: |
| 157 | std::uint64_t issue() { return last_.fetch_add(1, std::memory_order_acq_rel) + 1; } | 181 | std::uint64_t issue() { return last_.fetch_add(1, std::memory_order_acq_rel) + 1; } |
| @@ -328,6 +352,7 @@ public: | |||
| 328 | std::lock_guard guard(mutex_); | 352 | std::lock_guard guard(mutex_); |
| 329 | const std::uint64_t now = clock_.now_us(); | 353 | const std::uint64_t now = clock_.now_us(); |
| 330 | retire_locked(now); | 354 | retire_locked(now); |
| 355 | record_present_timing_locked(now, token); | ||
| 331 | last_presented_ = std::max(last_presented_, token); | 356 | last_presented_ = std::max(last_presented_, token); |
| 332 | if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once | 357 | if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once |
| 333 | for (Record& r : records_) | 358 | for (Record& r : records_) |
| @@ -357,8 +382,9 @@ public: | |||
| 357 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. | 382 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. |
| 358 | void note_untokened_present() { | 383 | void note_untokened_present() { |
| 359 | std::lock_guard guard(mutex_); | 384 | std::lock_guard guard(mutex_); |
| 360 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | ||
| 361 | const std::uint64_t now = clock_.now_us(); | 385 | const std::uint64_t now = clock_.now_us(); |
| 386 | record_present_timing_locked(now, 0); | ||
| 387 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | ||
| 362 | retire_locked(now); | 388 | retire_locked(now); |
| 363 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | 389 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; |
| 364 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | 390 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; |
| @@ -372,6 +398,7 @@ public: | |||
| 372 | std::lock_guard guard(mutex_); | 398 | std::lock_guard guard(mutex_); |
| 373 | suspended_ = true; | 399 | suspended_ = true; |
| 374 | interval_set_ = false; | 400 | interval_set_ = false; |
| 401 | has_last_present_ = false; // do not count the suspended pause as a frame interval after resume | ||
| 375 | for (bool& a : event_armed_) a = false; | 402 | for (bool& a : event_armed_) a = false; |
| 376 | pending_.clear(); | 403 | pending_.clear(); |
| 377 | cv_.notify_all(); | 404 | cv_.notify_all(); |
| @@ -403,6 +430,47 @@ public: | |||
| 403 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } | 430 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } |
| 404 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } | 431 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } |
| 405 | 432 | ||
| 433 | // Frame-time percentiles, mean drift against the active target interval, and origin-to-present latency over | ||
| 434 | // the last `frame_pacing_window` presented frames (BL-6). | ||
| 435 | FramePacingSummary pacing_summary() const { | ||
| 436 | FramePacingSummary out; | ||
| 437 | std::vector<std::uint64_t> intervals; | ||
| 438 | std::vector<std::uint64_t> latencies; | ||
| 439 | { | ||
| 440 | std::lock_guard guard(mutex_); | ||
| 441 | out.frames = presents_recorded_; | ||
| 442 | out.target_interval_us = (interval_set_ && !uncapped_) ? period_us_ : 0u; | ||
| 443 | intervals.reserve(interval_count_); | ||
| 444 | for (std::size_t i = 0; i < interval_count_; ++i) intervals.push_back(interval_ring_[i]); | ||
| 445 | latencies.reserve(latency_count_); | ||
| 446 | for (std::size_t i = 0; i < latency_count_; ++i) latencies.push_back(latency_ring_[i]); | ||
| 447 | } | ||
| 448 | auto percentile = [](const std::vector<std::uint64_t>& sorted, std::size_t pct) -> std::uint64_t { | ||
| 449 | if (sorted.empty()) return 0; | ||
| 450 | const std::size_t idx = (pct * sorted.size() + 99) / 100 - 1; | ||
| 451 | return sorted[std::min(idx, sorted.size() - 1)]; | ||
| 452 | }; | ||
| 453 | if (!intervals.empty()) { | ||
| 454 | out.samples = intervals.size(); | ||
| 455 | double sum = 0.0; | ||
| 456 | for (std::uint64_t v : intervals) sum += double(v); | ||
| 457 | out.mean_us = sum / double(intervals.size()); | ||
| 458 | if (out.target_interval_us != 0) out.drift_us = out.mean_us - double(out.target_interval_us); | ||
| 459 | std::sort(intervals.begin(), intervals.end()); | ||
| 460 | out.p50_us = percentile(intervals, 50); | ||
| 461 | out.p95_us = percentile(intervals, 95); | ||
| 462 | out.p99_us = percentile(intervals, 99); | ||
| 463 | } | ||
| 464 | if (!latencies.empty()) { | ||
| 465 | out.latency_samples = latencies.size(); | ||
| 466 | std::sort(latencies.begin(), latencies.end()); | ||
| 467 | out.latency_p50_us = percentile(latencies, 50); | ||
| 468 | out.latency_p95_us = percentile(latencies, 95); | ||
| 469 | out.latency_p99_us = percentile(latencies, 99); | ||
| 470 | } | ||
| 471 | return out; | ||
| 472 | } | ||
| 473 | |||
| 406 | private: | 474 | private: |
| 407 | struct Pending { | 475 | struct Pending { |
| 408 | std::uint64_t token; | 476 | std::uint64_t token; |
| @@ -416,6 +484,29 @@ private: | |||
| 416 | bool presented = false, displayed = false; | 484 | bool presented = false, displayed = false; |
| 417 | }; | 485 | }; |
| 418 | 486 | ||
| 487 | void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { | ||
| 488 | ++presents_recorded_; | ||
| 489 | if (has_last_present_ && now >= last_present_us_) { | ||
| 490 | interval_ring_[interval_head_] = now - last_present_us_; | ||
| 491 | interval_head_ = (interval_head_ + 1) % frame_pacing_window; | ||
| 492 | if (interval_count_ < frame_pacing_window) ++interval_count_; | ||
| 493 | } | ||
| 494 | has_last_present_ = true; | ||
| 495 | last_present_us_ = now; | ||
| 496 | if (token != 0) { | ||
| 497 | for (const Record& r : records_) { | ||
| 498 | if (r.token == token) { | ||
| 499 | if (now >= r.origin_us) { | ||
| 500 | latency_ring_[latency_head_] = now - r.origin_us; | ||
| 501 | latency_head_ = (latency_head_ + 1) % frame_pacing_window; | ||
| 502 | if (latency_count_ < frame_pacing_window) ++latency_count_; | ||
| 503 | } | ||
| 504 | break; | ||
| 505 | } | ||
| 506 | } | ||
| 507 | } | ||
| 508 | } | ||
| 509 | |||
| 419 | // Frames whose vblank has come are shown. | 510 | // Frames whose vblank has come are shown. |
| 420 | void retire_locked(std::uint64_t now) { | 511 | void retire_locked(std::uint64_t now) { |
| 421 | while (!pending_.empty() && pending_.front().flip_us <= now) { | 512 | while (!pending_.empty() && pending_.front().flip_us <= now) { |
| @@ -452,7 +543,7 @@ private: | |||
| 452 | } | 543 | } |
| 453 | 544 | ||
| 454 | 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) { |
| 455 | const std::uint64_t tok = tokens_->issue(); | 546 | const std::uint64_t tok = tokens_->issue(); // the shared token source (the device proxy and PresentX pace with it) |
| 456 | Record record; | 547 | Record record; |
| 457 | record.token = tok; | 548 | record.token = tok; |
| 458 | record.origin_us = origin_us; | 549 | record.origin_us = origin_us; |
| @@ -531,6 +622,15 @@ private: | |||
| 531 | bool current_origin_poll_ = false; | 622 | bool current_origin_poll_ = false; |
| 532 | std::uint64_t last_presented_ = 0; | 623 | std::uint64_t last_presented_ = 0; |
| 533 | std::uint64_t immediate_presents_ = 0; | 624 | std::uint64_t immediate_presents_ = 0; |
| 625 | std::uint64_t presents_recorded_ = 0; | ||
| 626 | bool has_last_present_ = false; | ||
| 627 | std::uint64_t last_present_us_ = 0; | ||
| 628 | std::array<std::uint64_t, frame_pacing_window> interval_ring_{}; | ||
| 629 | std::size_t interval_head_ = 0; | ||
| 630 | std::size_t interval_count_ = 0; | ||
| 631 | std::array<std::uint64_t, frame_pacing_window> latency_ring_{}; | ||
| 632 | std::size_t latency_head_ = 0; | ||
| 633 | std::size_t latency_count_ = 0; | ||
| 534 | std::deque<Pending> pending_; | 634 | std::deque<Pending> pending_; |
| 535 | std::deque<Record> records_; | 635 | std::deque<Record> records_; |
| 536 | }; | 636 | }; |
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 | |||
| 20 | namespace leonida::fsdraw { | ||
| 21 | |||
| 22 | struct 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 | |||
| 34 | inline State& state() { | ||
| 35 | static State s; | ||
| 36 | return s; | ||
| 37 | } | ||
| 38 | |||
| 39 | inline 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 | |||
| 44 | inline std::size_t pipeline_count() { // LOCAL DIAGNOSTIC (mem probe) | ||
| 45 | std::lock_guard lock(state().mutex); | ||
| 46 | return state().pipelines.size(); | ||
| 47 | } | ||
| 48 | |||
| 49 | inline 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 | |||
| 55 | inline 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 | |||
| 62 | inline 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 | |||
| 69 | inline 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. | ||
| 77 | inline 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). | ||
| 86 | inline 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 | |||
| 95 | inline std::vector<std::uint64_t> targets() { | ||
| 96 | std::lock_guard lock(state().mutex); | ||
| 97 | return state().readback; | ||
| 98 | } | ||
| 99 | |||
| 100 | inline 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 | |||
| 107 | inline 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 | |||
| 113 | inline 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 | |||
| 120 | inline 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 | |||
| 128 | inline 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. | ||
| 139 | inline 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 | |||
| 147 | inline 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. | ||
| 156 | inline 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. | ||
| 211 | inline 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 | |||
| 219 | inline 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 85ea2edfc..fb80b3f30 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -403,6 +403,13 @@ inline constexpr VkFormat vulkan_view_format(VkFormat image_format, std::uint32_ | |||
| 403 | if (!image) return VK_FORMAT_UNDEFINED; | 403 | if (!image) return VK_FORMAT_UNDEFINED; |
| 404 | if (image->gfx10 == gfx10_format) return image_format; | 404 | if (image->gfx10 == gfx10_format) return image_format; |
| 405 | if (is_depth_stencil_format(image_format)) return VK_FORMAT_UNDEFINED; | 405 | if (is_depth_stencil_format(image_format)) return VK_FORMAT_UNDEFINED; |
| 406 | // An R9G9B9E5 render target on a GPU that cannot render to E5B9G9R9 is an R11G11B10F image (the D3D12 device's | ||
| 407 | // r9g9b9e5_target_stand_in): a T# that names 5_9_9_9 views it in the image's own format. The image is not | ||
| 408 | // mutable, and the two formats have the same channels, so the swizzle is unchanged. | ||
| 409 | if (image_format == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && gfx10_format == 132) return image_format; | ||
| 410 | // The same for a B4G4R4A4 render target stored as BGRA8 (b4g4r4a4_target_stand_in): 4_4_4_4 names its channels | ||
| 411 | // in the order BGRA8 has them. | ||
| 412 | if (image_format == VK_FORMAT_B8G8R8A8_UNORM && gfx10_format == 136) return image_format; | ||
| 406 | const FormatRow* fallback = nullptr; | 413 | const FormatRow* fallback = nullptr; |
| 407 | for (const FormatRow& row : format_table) { | 414 | for (const FormatRow& row : format_table) { |
| 408 | if (row.gfx10 != gfx10_format || is_depth_stencil_format(row.vulkan)) continue; | 415 | if (row.gfx10 != gfx10_format || is_depth_stencil_format(row.vulkan)) continue; |
| @@ -655,8 +662,9 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 655 | if (sampler.unnormalized) { | 662 | if (sampler.unnormalized) { |
| 656 | info.unnormalizedCoordinates = VK_TRUE; | 663 | info.unnormalizedCoordinates = VK_TRUE; |
| 657 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a | 664 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a |
| 658 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. | 665 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag; |
| 659 | // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). | 666 | // -01074: mipLodBias must be zero. The S# allows any address mode or LOD bias with FORCE_UNNORMALIZED, and |
| 667 | // WRAP is its default (word 0 = 0). | ||
| 660 | const auto clamp_or_border = [](VkSamplerAddressMode m) { | 668 | const auto clamp_or_border = [](VkSamplerAddressMode m) { |
| 661 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; | 669 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; |
| 662 | }; | 670 | }; |
| @@ -664,6 +672,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 664 | info.addressModeV = clamp_or_border(info.addressModeV); | 672 | info.addressModeV = clamp_or_border(info.addressModeV); |
| 665 | info.minFilter = info.magFilter; | 673 | info.minFilter = info.magFilter; |
| 666 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; | 674 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; |
| 675 | info.mipLodBias = 0.0f; | ||
| 667 | info.minLod = info.maxLod = 0.0f; | 676 | info.minLod = info.maxLod = 0.0f; |
| 668 | info.anisotropyEnable = VK_FALSE; | 677 | info.anisotropyEnable = VK_FALSE; |
| 669 | info.maxAnisotropy = 1.0f; | 678 | info.maxAnisotropy = 1.0f; |
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 | |||
| 24 | namespace 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. | ||
| 28 | class BlockRanges { | ||
| 29 | public: | ||
| 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 | |||
| 79 | private: | ||
| 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. | ||
| 98 | template<typename Memory> | ||
| 99 | class ImageMemoryPool { | ||
| 100 | public: | ||
| 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 | |||
| 188 | private: | ||
| 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() == █ }); | ||
| 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 | |||
| 12 | namespace leonida { | ||
| 13 | |||
| 14 | inline 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 8ea202fa0..b57bbca29 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,112 @@ | |||
| 27 | #include <system_error> | 28 | #include <system_error> |
| 28 | #include <vector> | 29 | #include <vector> |
| 29 | 30 | ||
| 31 | #include <cstring> | ||
| 32 | |||
| 33 | namespace { | ||
| 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. Unless LEONIDA_TITLE_WATCHDOG=1, and only when that exact trap instruction sits where it | ||
| 40 | // does in this build, a runtime thread sets the kick byte twice a second so the title's watchdog never fires. | ||
| 41 | constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35; | ||
| 42 | constexpr std::uint32_t kWatchdogKickRva = 0x71b6331; | ||
| 43 | constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 | ||
| 44 | |||
| 45 | void keep_title_watchdog_kicked(std::uint8_t* base) { | ||
| 46 | char keep[4]{}; | ||
| 47 | if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)) == 1 && keep[0] == '1') return; | ||
| 48 | MEMORY_BASIC_INFORMATION trap{}, kick{}; | ||
| 49 | if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT || | ||
| 50 | std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0) | ||
| 51 | return; // not the build this was measured on: leave the title's watchdog alone | ||
| 52 | const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; | ||
| 53 | if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT || | ||
| 54 | !(kick.Protect & writable)) | ||
| 55 | return; | ||
| 56 | volatile std::uint8_t* const byte = base + kWatchdogKickRva; | ||
| 57 | const HANDLE thread = CreateThread( | ||
| 58 | nullptr, 0, | ||
| 59 | [](LPVOID p) -> DWORD { | ||
| 60 | auto* b = static_cast<volatile std::uint8_t*>(p); | ||
| 61 | for (;;) { | ||
| 62 | *b = 1; | ||
| 63 | Sleep(500); | ||
| 64 | } | ||
| 65 | }, | ||
| 66 | const_cast<std::uint8_t*>(byte), 0, nullptr); | ||
| 67 | if (thread) { | ||
| 68 | CloseHandle(thread); | ||
| 69 | std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG=1 keeps it armed)\n"); | ||
| 70 | } | ||
| 71 | } | ||
| 72 | |||
| 73 | // LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the | ||
| 74 | // title's image (":n" = n consecutive values) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this | ||
| 75 | // global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly | ||
| 76 | // that. Reads are checked; nothing is written. | ||
| 77 | void start_title_peek(std::uint8_t* base) { | ||
| 78 | static char spec[1024]; | ||
| 79 | const DWORD n = GetEnvironmentVariableA("LEONIDA_PEEK", spec, sizeof(spec)); | ||
| 80 | if (!n || n >= sizeof(spec)) return; | ||
| 81 | static std::uint8_t* image = base; | ||
| 82 | const HANDLE thread = CreateThread( | ||
| 83 | nullptr, 0, | ||
| 84 | [](LPVOID) -> DWORD { | ||
| 85 | char seconds[16]{}; | ||
| 86 | DWORD period = 10; | ||
| 87 | if (GetEnvironmentVariableA("LEONIDA_PEEK_SECONDS", seconds, sizeof(seconds)) > 0) | ||
| 88 | period = std::max<DWORD>(1, static_cast<DWORD>(std::strtoul(seconds, nullptr, 10))); | ||
| 89 | for (unsigned tick = 0;; ++tick) { | ||
| 90 | std::string line = "[rt] peek t=" + std::to_string(tick * period) + "s:"; | ||
| 91 | for (const char* at = spec; *at;) { | ||
| 92 | char* end = nullptr; | ||
| 93 | const std::uint64_t rva = std::strtoull(at, &end, 16); | ||
| 94 | if (end == at) break; | ||
| 95 | unsigned count = 1; | ||
| 96 | if (*end == ':') count = static_cast<unsigned>(std::strtoul(end + 1, &end, 10)); | ||
| 97 | char text[40]; | ||
| 98 | std::snprintf(text, sizeof(text), " 0x%llx=", static_cast<unsigned long long>(rva)); | ||
| 99 | line += text; | ||
| 100 | for (unsigned i = 0; i < count && i < 16; ++i) { | ||
| 101 | std::uint64_t value = 0; | ||
| 102 | SIZE_T got = 0; | ||
| 103 | const bool ok = ReadProcessMemory(GetCurrentProcess(), image + rva + 8ull * i, &value, | ||
| 104 | sizeof(value), &got) && got == sizeof(value); | ||
| 105 | std::snprintf(text, sizeof(text), ok ? "%s%llx" : "%s?", i ? "," : "", | ||
| 106 | static_cast<unsigned long long>(value)); | ||
| 107 | line += text; | ||
| 108 | } | ||
| 109 | at = *end == ',' ? end + 1 : end; | ||
| 110 | if (at == end && *end) break; | ||
| 111 | } | ||
| 112 | std::fprintf(stderr, "%s\n", line.c_str()); | ||
| 113 | Sleep(period * 1000); | ||
| 114 | } | ||
| 115 | }, | ||
| 116 | nullptr, 0, nullptr); | ||
| 117 | if (thread) CloseHandle(thread); | ||
| 118 | } | ||
| 119 | |||
| 120 | } // namespace | ||
| 121 | |||
| 30 | #include "base_reservation.h" | 122 | #include "base_reservation.h" |
| 31 | #include "code_hooks.h" | 123 | #include "code_hooks.h" |
| 32 | #include "cpu_emulation.h" | 124 | #include "cpu_emulation.h" |
| 33 | #include "host_cpu.h" | 125 | #include "host_cpu.h" |
| 34 | #include "mods.h" | 126 | #include "mods.h" |
| 35 | #include "pe_loader.h" | 127 | #include "pe_loader.h" |
| 128 | #include "thread_stacks.h" | ||
| 129 | #include "title_page_watch.h" | ||
| 130 | #include "title_geometry_watch.h" | ||
| 36 | #include "../shims/d3d12_trace.h" | 131 | #include "../shims/d3d12_trace.h" |
| 37 | #include "../shims/d3d12_xs_device.h" | 132 | #include "../shims/d3d12_xs_device.h" |
| 38 | #include "../shims/file_system.h" | 133 | #include "../shims/file_system.h" |
| 134 | #ifdef LEONIDA_VULKAN_DEVICE | ||
| 135 | #include "../shims/package_splash.h" | ||
| 136 | #endif | ||
| 39 | #include "../shims/process_shim.h" | 137 | #include "../shims/process_shim.h" |
| 40 | #include "../shims/shims.h" | 138 | #include "../shims/shims.h" |
| 41 | #include "../shims/startup_trace.h" | 139 | #include "../shims/startup_trace.h" |
| @@ -71,7 +169,7 @@ bool configure_first_run_ui(const std::filesystem::path& package, std::filesyste | |||
| 71 | {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, | 169 | {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, |
| 72 | {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, | 170 | {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, |
| 73 | {L"LEONIDA_GPU_LABELS", L"1"}, {L"LEONIDA_FRAME_PACING", L"1"}, | 171 | {L"LEONIDA_GPU_LABELS", L"1"}, {L"LEONIDA_FRAME_PACING", L"1"}, |
| 74 | {L"LEONIDA_LOCAL_SPEECH", L"1"}, {L"LEONIDA_KEYBOARD_PAD", L"always"}, | 172 | {L"LEONIDA_KEYBOARD_PAD", L"always"}, |
| 75 | }; | 173 | }; |
| 76 | for (const auto& setting : settings) { | 174 | for (const auto& setting : settings) { |
| 77 | if (!set_default(setting.name, setting.value)) return false; | 175 | if (!set_default(setting.name, setting.value)) return false; |
| @@ -102,6 +200,17 @@ int usage() { | |||
| 102 | 200 | ||
| 103 | } // namespace | 201 | } // namespace |
| 104 | 202 | ||
| 203 | #ifdef LEONIDA_VULKAN_DEVICE | ||
| 204 | static BOOL WINAPI show_package_window(HWND window, int command) { | ||
| 205 | const BOOL previous = ShowWindow(window, command); | ||
| 206 | const DWORD error = GetLastError(); | ||
| 207 | if (command != SW_HIDE && rt::package_splash::paint_window(window)) | ||
| 208 | rt::startup_trace::event("package_splash_window"); | ||
| 209 | SetLastError(error); | ||
| 210 | return previous; | ||
| 211 | } | ||
| 212 | #endif | ||
| 213 | |||
| 105 | int wmain(int argc, wchar_t** argv) { | 214 | int wmain(int argc, wchar_t** argv) { |
| 106 | std::filesystem::path image, game_dir, overlay_dir, mods_dir; | 215 | std::filesystem::path image, game_dir, overlay_dir, mods_dir; |
| 107 | uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash | 216 | uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash |
| @@ -167,6 +276,15 @@ int wmain(int argc, wchar_t** argv) { | |||
| 167 | if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring(); | 276 | if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring(); |
| 168 | } | 277 | } |
| 169 | game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); | 278 | game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); |
| 279 | // An unattended run can select a fresh write root even when its launcher supplies --overlay. | ||
| 280 | if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", nullptr, 0)) { | ||
| 281 | std::wstring dir(size, 0); | ||
| 282 | const DWORD n = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", dir.data(), size); | ||
| 283 | if (n && n < size) { | ||
| 284 | dir.resize(n); | ||
| 285 | overlay_dir = dir; | ||
| 286 | } | ||
| 287 | } | ||
| 170 | if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); | 288 | if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); |
| 171 | // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. | 289 | // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. |
| 172 | if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) { | 290 | if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) { |
| @@ -188,6 +306,18 @@ int wmain(int argc, wchar_t** argv) { | |||
| 188 | } | 306 | } |
| 189 | if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; | 307 | if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; |
| 190 | rt::fs::configure(game_dir, overlay_dir); | 308 | rt::fs::configure(game_dir, overlay_dir); |
| 309 | #ifdef LEONIDA_VULKAN_DEVICE | ||
| 310 | if (run) { | ||
| 311 | rt::package_splash::configure(game_dir); | ||
| 312 | if (rt::package_splash::configured()) { | ||
| 313 | const rt::shims::Entry window_imports[] = { | ||
| 314 | {"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow", reinterpret_cast<void*>(&show_package_window)}, | ||
| 315 | {"user32.dll", "ShowWindow", reinterpret_cast<void*>(&show_package_window)}, | ||
| 316 | }; | ||
| 317 | rt::shims::Table{window_imports, std::size(window_imports)}; | ||
| 318 | } | ||
| 319 | } | ||
| 320 | #endif | ||
| 191 | // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here; | 321 | // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here; |
| 192 | // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version. | 322 | // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version. |
| 193 | if (mods_dir.empty()) { | 323 | if (mods_dir.empty()) { |
| @@ -219,6 +349,9 @@ int wmain(int argc, wchar_t** argv) { | |||
| 219 | rt::d3d12_trace::set_enabled(trace_d3d12); | 349 | rt::d3d12_trace::set_enabled(trace_d3d12); |
| 220 | // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. | 350 | // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. |
| 221 | rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); | 351 | rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); |
| 352 | // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h). | ||
| 353 | leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases); | ||
| 354 | leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range); | ||
| 222 | rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); | 355 | rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); |
| 223 | if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { | 356 | if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { |
| 224 | std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" | 357 | std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" |
| @@ -338,7 +471,13 @@ int wmain(int argc, wchar_t** argv) { | |||
| 338 | } | 471 | } |
| 339 | std::printf("running %s\n", main_module.name.c_str()); | 472 | std::printf("running %s\n", main_module.name.c_str()); |
| 340 | std::fflush(stdout); | 473 | std::fflush(stdout); |
| 341 | const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); | 474 | keep_title_watchdog_kicked(main_module.base); |
| 475 | start_title_peek(main_module.base); | ||
| 476 | int code; | ||
| 477 | { | ||
| 478 | auto stacks = rt::start_thread_stacks(); | ||
| 479 | code = rt::process::run_entry(main_module.base + main_module.entry_rva); | ||
| 480 | } | ||
| 342 | std::fflush(stdout); | 481 | std::fflush(stdout); |
| 343 | std::printf("game exited with code %d\n", code); | 482 | std::printf("game exited with code %d\n", code); |
| 344 | rt::shims::report_called_unimplemented(); | 483 | 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 | |||
| 35 | namespace leonida::mem_probe { | ||
| 36 | |||
| 37 | struct 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 | |||
| 45 | struct 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 | |||
| 67 | inline State& state() { | ||
| 68 | static State s; | ||
| 69 | return s; | ||
| 70 | } | ||
| 71 | |||
| 72 | inline 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 | |||
| 82 | inline 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 | |||
| 91 | inline 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 | |||
| 102 | inline 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 | |||
| 112 | inline 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 | |||
| 126 | inline 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 | |||
| 135 | inline 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 | |||
| 150 | inline 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 | |||
| 163 | inline 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 | |||
| 169 | inline 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 | |||
| 181 | inline 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. | ||
| 184 | inline 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 | |||
| 190 | inline 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 | |||
| 197 | inline 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 | |||
| 214 | inline 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 | |||
| 227 | inline 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. | ||
| 241 | template<typename Functions> | ||
| 242 | void 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 ---- | ||
| 265 | enum 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 | }; | ||
| 277 | inline 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 | |||
| 283 | struct Usage { | ||
| 284 | std::uint64_t rss = 0, anon = 0, swap = 0, vmas = 0; | ||
| 285 | }; | ||
| 286 | |||
| 287 | using Ranges = std::vector<std::pair<std::uint64_t, std::uint64_t>>; // [begin, end), sorted | ||
| 288 | |||
| 289 | inline 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 | |||
| 296 | inline 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). | ||
| 310 | inline 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. | ||
| 338 | inline 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), ®ion, 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. | ||
| 434 | inline 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. | ||
| 451 | struct 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 | |||
| 457 | inline 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 | |||
| 466 | inline 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 | |||
| 474 | inline 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. | ||
| 556 | inline 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/mods.h b/runtime/src/mods.h index 10155bf19..bd635e9a0 100644 --- a/runtime/src/mods.h +++ b/runtime/src/mods.h | |||
| @@ -78,8 +78,8 @@ struct LoadResult { | |||
| 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. | 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. |
| 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { | 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { |
| 80 | if (text.empty()) return false; | 80 | if (text.empty()) return false; |
| 81 | if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { | 81 | if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { |
| 82 | if (text.size() > 10) return false; | 82 | if (text.size() == 2 || text.size() > 10) return false; |
| 83 | uint32_t v = 0; | 83 | uint32_t v = 0; |
| 84 | for (std::size_t i = 2; i < text.size(); ++i) { | 84 | for (std::size_t i = 2; i < text.size(); ++i) { |
| 85 | const char c = text[i]; | 85 | const char c = text[i]; |
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 57822d1ec..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 | ||
| 23 | namespace rt { | 25 | namespace rt { |
| 24 | 26 | ||
| @@ -2182,6 +2184,24 @@ void Loader::bind_imports(Module& m) { | |||
| 2182 | void Loader::protect_sections(Module& m) { | 2184 | void Loader::protect_sections(Module& m) { |
| 2183 | 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); |
| 2184 | 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 | } | ||
| 2185 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); | 2205 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); |
| 2186 | auto* sec = IMAGE_FIRST_SECTION(nt); | 2206 | auto* sec = IMAGE_FIRST_SECTION(nt); |
| 2187 | 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/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h index 95afbd10a..98e5788a8 100644 --- a/runtime/src/pipeline_cache_file.h +++ b/runtime/src/pipeline_cache_file.h | |||
| @@ -1,7 +1,8 @@ | |||
| 1 | // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. | 1 | // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. |
| 2 | // | 2 | // |
| 3 | // Used by vk_pipeline_check (its corpus checkpoints) and by the runtime itself, which writes the session cache on | 3 | // Used by vk_pipeline_check (its corpus checkpoints) and by the runtime, which writes the session cache on device |
| 4 | // device teardown (pipeline_cache_store.h). A reader of the old file keeps it open until its rename completes. | 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). | ||
| 5 | #pragma once | 6 | #pragma once |
| 6 | 7 | ||
| 7 | #include <algorithm> | 8 | #include <algorithm> |
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 | |||
| 13 | namespace leonida::pipeline_profile { | ||
| 14 | |||
| 15 | inline 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 | |||
| 23 | inline 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. | ||
| 29 | inline 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 | |||
| 42 | class DriverCall { | ||
| 43 | public: | ||
| 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 | } | ||
| 64 | private: | ||
| 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/queue_families.h b/runtime/src/queue_families.h index 51a8c40c1..5682d9e54 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h | |||
| @@ -8,10 +8,23 @@ | |||
| 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 | ||
| 13 | namespace leonida { | 14 | namespace leonida { |
| 14 | 15 | ||
| 16 | constexpr 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. | ||
| 21 | constexpr 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 | |||
| 15 | // The device's distinct family indices. An object used on more than one family keeps its contents | 28 | // The device's distinct family indices. An object used on more than one family keeps its contents |
| 16 | // across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers. | 29 | // across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers. |
| 17 | template<typename CreateInfo> | 30 | template<typename CreateInfo> |
diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index e90173095..c807fb2bc 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h | |||
| @@ -2,26 +2,26 @@ | |||
| 2 | 2 | ||
| 3 | // Console rectangle lists on Vulkan, which has no such primitive. | 3 | // Console rectangle lists on Vulkan, which has no such primitive. |
| 4 | // | 4 | // |
| 5 | // A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its | 5 | // A rectangle is three corners (v1, v2, v3) of a screen-aligned rectangle and the hardware makes the fourth, for the |
| 6 | // neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: | 6 | // position and for every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY |
| 7 | // the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest | 7 | // 17) and a pipeline whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit |
| 8 | // screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline | 8 | // 53af7df77c10, notes in its backlog); no code is taken from it. The corner between the other two (the right angle) |
| 9 | // whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in | 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 | // its backlog); no code is taken from it. | 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. | ||
| 11 | // | 13 | // |
| 12 | // The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after | 14 | // The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after |
| 13 | // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and | 15 | // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and |
| 14 | // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a | 16 | // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a |
| 15 | // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) | 17 | // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) |
| 16 | // the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of | 18 | // the list draws, finds the corner between the other two as the one opposite the longest side (from the positions' |
| 17 | // (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole | 19 | // x and y; a degenerate triangle takes v1), makes the fourth corner v4 = the other two's sum minus that corner, and |
| 18 | // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), | 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), | ||
| 19 | // and so is the stage's Position; the generated stage reads and writes exactly those. | 23 | // and so is the stage's Position; the generated stage reads and writes exactly those. |
| 20 | // | 24 | // |
| 21 | // The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the | ||
| 22 | // usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a | ||
| 23 | // different corner than the pixel-space right angle. | ||
| 24 | // | ||
| 25 | // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or | 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. | 26 | // ViewportIndex, or a Location output that is not a vec4 float. |
| 27 | // | 27 | // |
| @@ -49,10 +49,10 @@ inline std::vector<std::uint32_t> rect_list_geometry(const std::vector<std::uint | |||
| 49 | enum : std::uint32_t { | 49 | enum : std::uint32_t { |
| 50 | op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, | 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, | 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, | ||
| 52 | op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, | 54 | op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, |
| 53 | op_decorate = 71, op_fadd = 129, op_fsub = 131, op_fmul = 133, op_fdiv = 136, | 55 | op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, |
| 54 | op_type_bool = 20, op_composite_construct = 80, op_composite_extract = 81, op_logical_and = 167, | ||
| 55 | op_logical_not = 168, op_select = 169, op_ford_greater_equal = 190, 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, | 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, | 57 | deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, |
| 58 | storage_input = 1, storage_output = 3 | 58 | storage_input = 1, storage_output = 3 |
| @@ -127,14 +127,12 @@ inline std::vector<std::uint32_t> rect_list_geometry(const std::vector<std::uint | |||
| 127 | }; | 127 | }; |
| 128 | const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), | 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(), | 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(), t_bool = id(), t_bool4 = id(); | 130 | t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); |
| 131 | emit(globals, op_type_void, {t_void}); | 131 | emit(globals, op_type_void, {t_void}); |
| 132 | emit(globals, op_type_function, {t_fn, t_void}); | 132 | emit(globals, op_type_function, {t_fn, t_void}); |
| 133 | emit(globals, op_type_int, {t_uint, 32, 0}); | 133 | emit(globals, op_type_int, {t_uint, 32, 0}); |
| 134 | emit(globals, op_type_float, {t_float, 32}); | 134 | emit(globals, op_type_float, {t_float, 32}); |
| 135 | emit(globals, op_type_vector, {t_v4, t_float, 4}); | 135 | emit(globals, op_type_vector, {t_v4, t_float, 4}); |
| 136 | emit(globals, op_type_bool, {t_bool}); | ||
| 137 | emit(globals, op_type_vector, {t_bool4, t_bool, 4}); | ||
| 138 | emit(globals, op_constant, {t_uint, c3, 3}); | 136 | emit(globals, op_constant, {t_uint, c3, 3}); |
| 139 | emit(globals, op_constant, {t_uint, c0, 0}); | 137 | emit(globals, op_constant, {t_uint, c0, 0}); |
| 140 | emit(globals, op_constant, {t_uint, c1, 1}); | 138 | emit(globals, op_constant, {t_uint, c1, 1}); |
| @@ -165,82 +163,79 @@ inline std::vector<std::uint32_t> rect_list_geometry(const std::vector<std::uint | |||
| 165 | const std::uint32_t main_fn = id(), entry_label = id(); | 163 | const std::uint32_t main_fn = id(), entry_label = id(); |
| 166 | emit(body, op_function, {t_void, main_fn, 0, t_fn}); | 164 | emit(body, op_function, {t_void, main_fn, 0, t_fn}); |
| 167 | emit(body, op_label, {entry_label}); | 165 | emit(body, op_label, {entry_label}); |
| 168 | // Per variable: the three vertices as drawn, loaded first. | 166 | // Per variable: the three corners. |
| 169 | struct Corners { std::uint32_t v[4]; }; // v[0] the right-angle corner, v[1], v[2] its neighbours, v[3] the fourth | 167 | struct Corners { std::uint32_t v[3]; }; |
| 170 | std::vector<Corners> corners; | 168 | std::vector<Corners> corners; |
| 171 | std::vector<std::array<std::uint32_t, 3>> loaded; | ||
| 172 | const std::uint32_t cs[3] = {c0, c1, c2}; | 169 | const std::uint32_t cs[3] = {c0, c1, c2}; |
| 173 | for (const Var& v : vars) { | 170 | for (const Var& v : vars) { |
| 174 | std::array<std::uint32_t, 3> three{}; | 171 | Corners c{}; |
| 175 | for (int k = 0; k < 3; ++k) { | 172 | for (int k = 0; k < 3; ++k) { |
| 176 | const std::uint32_t ptr = id(); | 173 | const std::uint32_t ptr = id(); |
| 177 | three[k] = id(); | 174 | c.v[k] = id(); |
| 178 | emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); | 175 | emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); |
| 179 | emit(body, op_load, {t_v4, three[k], ptr}); | 176 | emit(body, op_load, {t_v4, c.v[k], ptr}); |
| 180 | } | 177 | } |
| 181 | loaded.push_back(three); | 178 | corners.push_back(c); |
| 182 | } | ||
| 183 | // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; | ||
| 184 | // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain | ||
| 185 | // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right | ||
| 186 | // triangle gets the same rule, so the choice is at least consistent. | ||
| 187 | std::uint32_t screen[3][2]; | ||
| 188 | for (int k = 0; k < 3; ++k) { | ||
| 189 | const std::uint32_t x = id(), y = id(), w = id(); | ||
| 190 | emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); | ||
| 191 | emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); | ||
| 192 | emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); | ||
| 193 | screen[k][0] = id(); | ||
| 194 | screen[k][1] = id(); | ||
| 195 | emit(body, op_fdiv, {t_float, screen[k][0], x, w}); | ||
| 196 | emit(body, op_fdiv, {t_float, screen[k][1], y, w}); | ||
| 197 | } | 179 | } |
| 198 | const auto squared_edge = [&](int a, int b) { | 180 | // The corner between the other two, opposite the longest side: squared lengths from the positions' x and y. |
| 199 | const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); | 181 | const std::uint32_t t_bool = id(), t_bv4 = id(); |
| 200 | emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); | 182 | emit(globals, op_type_bool, {t_bool}); |
| 201 | emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); | 183 | emit(globals, op_type_vector, {t_bv4, t_bool, 4}); |
| 202 | emit(body, op_fmul, {t_float, xx, dx, dx}); | 184 | const auto extract = [&](std::uint32_t vector, std::uint32_t component) { |
| 203 | emit(body, op_fmul, {t_float, yy, dy, dy}); | 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}); | ||
| 204 | emit(body, op_fadd, {t_float, sum, xx, yy}); | 195 | emit(body, op_fadd, {t_float, sum, xx, yy}); |
| 205 | return sum; | 196 | return sum; |
| 206 | }; | 197 | }; |
| 207 | const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); | 198 | const auto at_least = [&](std::uint32_t a, std::uint32_t b) { |
| 208 | const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); | 199 | const std::uint32_t r = id(); |
| 209 | emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); | 200 | emit(body, op_ford_greater_than_equal, {t_bool, r, a, b}); |
| 210 | emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); | 201 | return r; |
| 211 | emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner | 202 | }; |
| 212 | emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); | 203 | const auto both = [&](std::uint32_t a, std::uint32_t b) { |
| 213 | emit(body, op_logical_not, {t_bool, not_first, at_first}); | 204 | const std::uint32_t r = id(); |
| 214 | emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 | 205 | emit(body, op_logical_and, {t_bool, r, a, b}); |
| 215 | const std::uint32_t first4 = id(), second4 = id(); | 206 | return r; |
| 216 | emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); | 207 | }; |
| 217 | emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); | 208 | const auto splat = [&](std::uint32_t b) { // OpSelect on vectors takes a vector condition before SPIR-V 1.4 |
| 218 | // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding | 209 | const std::uint32_t r = id(); |
| 219 | // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. | 210 | emit(body, op_composite_construct, {t_bv4, r, b, b, b, b}); |
| 220 | for (const auto& three : loaded) { | 211 | return r; |
| 221 | Corners c{}; | 212 | }; |
| 222 | const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { | 213 | const std::uint32_t* p = corners[0].v; // vars[0] is the Position |
| 223 | const std::uint32_t inner = id(), outer = id(); | 214 | const std::uint32_t l12 = length2(p[0], p[1]), l23 = length2(p[1], p[2]), l31 = length2(p[2], p[0]); |
| 224 | emit(body, op_select, {t_v4, inner, second4, second, third}); | 215 | const std::uint32_t at_v1 = both(at_least(l23, l12), at_least(l23, l31)), not_v1 = id(); |
| 225 | emit(body, op_select, {t_v4, outer, first4, first, inner}); | 216 | emit(body, op_logical_not, {t_bool, not_v1, at_v1}); |
| 226 | return outer; | 217 | const std::uint32_t at_v2 = both(not_v1, at_least(l31, l12)); |
| 227 | }; | 218 | const std::uint32_t c_v1 = splat(at_v1), c_v2 = splat(at_v2); |
| 228 | c.v[0] = pick(three[0], three[1], three[2]); | 219 | const auto pick = [&](std::uint32_t condition, std::uint32_t yes, std::uint32_t no) { |
| 229 | c.v[1] = pick(three[1], three[2], three[0]); | 220 | const std::uint32_t r = id(); |
| 230 | c.v[2] = pick(three[2], three[0], three[1]); | 221 | emit(body, op_select, {t_v4, r, condition, yes, no}); |
| 231 | const std::uint32_t sum = id(), diff = id(); | 222 | return r; |
| 232 | emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); | 223 | }; |
| 233 | emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); | 224 | // Per variable: the fourth corner, v1 + v2 + v3 - 2 * corner, and the six vertices of the two triangles. |
| 234 | c.v[3] = diff; | 225 | std::vector<std::array<std::uint32_t, 6>> emitted; |
| 235 | corners.push_back(c); | 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]))}); | ||
| 236 | } | 235 | } |
| 237 | // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input | 236 | for (int triangle = 0; triangle < 2; ++triangle) { |
| 238 | // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are | 237 | for (int k = 0; k < 3; ++k) { |
| 239 | // affine over the parallelogram, so the split does not change any interpolated value. | 238 | for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, emitted[i][triangle * 3 + k]}); |
| 240 | const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; | ||
| 241 | for (const auto& triangle : triangles) { | ||
| 242 | for (int k : triangle) { | ||
| 243 | for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); | ||
| 244 | emit(body, op_emit_vertex, {}); | 239 | emit(body, op_emit_vertex, {}); |
| 245 | } | 240 | } |
| 246 | emit(body, op_end_primitive, {}); | 241 | emit(body, op_end_primitive, {}); |
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h index a48302859..675460cac 100644 --- a/runtime/src/retire_tickets.h +++ b/runtime/src/retire_tickets.h | |||
| @@ -24,7 +24,7 @@ public: | |||
| 24 | while (!pending_.empty()) { | 24 | while (!pending_.empty()) { |
| 25 | const Entry& front = pending_.front(); | 25 | const Entry& front = pending_.front(); |
| 26 | if (!front.idle && !query(front.semaphore, front.value)) break; | 26 | if (!front.idle && !query(front.semaphore, front.value)) break; |
| 27 | completed_ = front.ticket; | 27 | if (front.ticket > completed_) completed_ = front.ticket; |
| 28 | pending_.pop_front(); | 28 | pending_.pop_front(); |
| 29 | } | 29 | } |
| 30 | return completed_; | 30 | return completed_; |
| @@ -34,8 +34,18 @@ public: | |||
| 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. | 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. |
| 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { | 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { |
| 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; | 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; |
| 37 | for (const Entry& entry : pending_) | 37 | for (const Entry& entry : pending_) { |
| 38 | if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); | 38 | if (entry.ticket > ticket || entry.idle) continue; |
| 39 | bool merged = false; | ||
| 40 | for (auto& [sem, val] : out) { | ||
| 41 | if (sem == entry.semaphore) { | ||
| 42 | if (entry.value > val) val = entry.value; | ||
| 43 | merged = true; | ||
| 44 | break; | ||
| 45 | } | ||
| 46 | } | ||
| 47 | if (!merged) out.emplace_back(entry.semaphore, entry.value); | ||
| 48 | } | ||
| 39 | return out; | 49 | return out; |
| 40 | } | 50 | } |
| 41 | 51 | ||
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..60b0d5632 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h | |||
| @@ -132,7 +132,9 @@ constexpr uint32_t kMaxD3d12Cost = 64; | |||
| 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: a hypothesis from the corpus census only (lowest pointer SGPR per stage); |
| 133 | // no signature confirms them, and visibility is not modelled (every parameter takes its place in every stage). | 133 | // no signature confirms them, and visibility is not modelled (every parameter takes its place in every stage). |
| 134 | // A parameter that does not fit goes to the console's spill array behind s[0:1] (compute, section 7) together with | 134 | // 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. | 135 | // every parameter after it. For compute that packed spill array (1 dword per 32-bit constant, 2 per root descriptor, |
| 136 | // 1 per descriptor table, no alignment padding) is modelled in StagePackResult; non-compute stages still refuse spills | ||
| 137 | // because their spill pointer SGPR is unmeasured. | ||
| 136 | enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 }; | 138 | enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 }; |
| 137 | 139 | ||
| 138 | [[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept { | 140 | [[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept { |
| @@ -163,19 +165,23 @@ enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, | |||
| 163 | } | 165 | } |
| 164 | 166 | ||
| 165 | constexpr uint32_t kNoSgpr = 0xFFFFFFFFu; | 167 | constexpr uint32_t kNoSgpr = 0xFFFFFFFFu; |
| 168 | constexpr uint32_t kNoSpill = 0xFFFFFFFFu; | ||
| 166 | 169 | ||
| 167 | struct StagePackResult { | 170 | struct StagePackResult { |
| 168 | bool ok = false; | 171 | bool ok = false; |
| 169 | std::string error; // set when !ok; names the refusing parameter | 172 | std::string error; // set when !ok; names the refusing parameter |
| 170 | Stage stage = Stage::Compute; | 173 | Stage stage = Stage::Compute; |
| 171 | uint32_t base = 0; // stage_base(stage) | 174 | 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) | 175 | 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 | 176 | 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 | 177 | uint32_t end_sgpr = 0; // one past the last inline SGPR used: the RSRC2 USER_SGPR count |
| 178 | uint32_t spill_dwords = 0; // total dwords in the packed spill array (0 when nothing spills) | ||
| 179 | uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit | ||
| 175 | }; | 180 | }; |
| 176 | 181 | ||
| 177 | // Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, a | 182 | // 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. | 183 | // unknown parameter type, a constant parameter of 0 values, or the 64-dword cost limit. Compute spills any trailing |
| 184 | // 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); | 185 | [[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); |
| 180 | 186 | ||
| 181 | // D3D12 cost of one parameter against the 64-dword limit. | 187 | // 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 | |||
| 11 | namespace 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. | ||
| 14 | inline 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 | |||
| 34 | inline 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 e1ac82cb1..ae045e80b 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 | ||
| 222 | inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const Huffman& lengths, | 223 | inline 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, |
| @@ -246,9 +247,26 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co | |||
| 246 | if (d < 0 || d >= 30) return ZlibError::data; | 247 | if (d < 0 || d >= 30) return ZlibError::data; |
| 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() + length > limit) 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. |
| 262 | inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint8_t>& out, | 280 | inline 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; |
| @@ -284,7 +302,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 284 | if (!reader.byte(x)) return fail(ZlibError::data); | 302 | if (!reader.byte(x)) return fail(ZlibError::data); |
| 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); | 303 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); |
| 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); | 304 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); |
| 287 | if (out.size() + length > limit) return fail(ZlibError::limit); | 305 | if (out.size() > limit || length > limit - out.size()) return fail(ZlibError::limit); |
| 288 | for (unsigned i = 0; i < length; ++i) { | 306 | for (unsigned i = 0; i < length; ++i) { |
| 289 | std::uint8_t x; | 307 | std::uint8_t x; |
| 290 | if (!reader.byte(x)) return fail(ZlibError::data); | 308 | if (!reader.byte(x)) return fail(ZlibError::data); |
| @@ -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); |
| @@ -349,11 +367,25 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 349 | } | 367 | } |
| 350 | // Adler-32, big-endian, after the deflate data's last whole byte. | 368 | // Adler-32, big-endian, after the deflate data's last whole byte. |
| 351 | const std::size_t at = 2 + reader.position(); | 369 | const std::size_t at = 2 + reader.position(); |
| 352 | if (at + 4 > in.size()) 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 | ||
| 809 | struct ShaderEntry { | 841 | struct 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,6 +860,10 @@ 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"; } |
| 830 | std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed | 868 | 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 | 869 | std::vector<std::uint32_t> inputs; // pixel shaders: input locations declared |
| @@ -841,20 +879,55 @@ struct ShaderEntry { | |||
| 841 | std::uint32_t max_primitives = 0; | 879 | std::uint32_t max_primitives = 0; |
| 842 | }; | 880 | }; |
| 843 | 881 | ||
| 882 | // Which descriptor-table hash finalizer the loaded modules probe with (descriptor_table.h). Each module's index.json | ||
| 883 | // meta may carry `"descriptor_hash": "fnv1a_fmix32"`; an absent key means the old bare `"fnv1a"`. The runtime has one | ||
| 884 | // table for all shaders, so it counts the kinds over every loaded module (the root index and each sub-index) and picks | ||
| 885 | // the majority; a mixed library still works, because the minority's lookups simply miss to index 0. | ||
| 886 | struct DescriptorHashCensus { | ||
| 887 | std::size_t fnv1a = 0; | ||
| 888 | std::size_t fnv1a_fmix32 = 0; | ||
| 889 | std::size_t total() const { return fnv1a + fnv1a_fmix32; } | ||
| 890 | }; | ||
| 891 | |||
| 892 | // The kind most modules declare. A tie (or no modules) is fnv1a, the behaviour before the marker existed. | ||
| 893 | inline DescriptorHashKind majority_descriptor_hash_kind(const DescriptorHashCensus& census) { | ||
| 894 | return census.fnv1a_fmix32 > census.fnv1a ? DescriptorHashKind::fnv1a_fmix32 : DescriptorHashKind::fnv1a; | ||
| 895 | } | ||
| 896 | |||
| 897 | // LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32 overrides the modules' majority. False when `value` is null, empty or not | ||
| 898 | // one of the two kinds (an unrecognised value is ignored rather than failing startup). | ||
| 899 | inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* kind) { | ||
| 900 | if (!value || !*value) return false; | ||
| 901 | if (std::strcmp(value, "fnv1a_fmix32") == 0) { | ||
| 902 | if (kind) *kind = DescriptorHashKind::fnv1a_fmix32; | ||
| 903 | return true; | ||
| 904 | } | ||
| 905 | if (std::strcmp(value, "fnv1a") == 0) { | ||
| 906 | if (kind) *kind = DescriptorHashKind::fnv1a; | ||
| 907 | return true; | ||
| 908 | } | ||
| 909 | return false; | ||
| 910 | } | ||
| 911 | |||
| 844 | class ShaderLibrary { | 912 | class ShaderLibrary { |
| 845 | public: | 913 | public: |
| 846 | // Reads <dir>/index.json, then the indexes of the programs make_game.py translates outside the game's shader | 914 | // Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's DLLs and the |
| 847 | // entries, each when it is there: | 915 | // 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); | 916 | // - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md); |
| 917 | // - <dir>/fspx_compute/index.json, the compute programs from shaders.rpf's pipeline library; | ||
| 918 | // - <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 | 919 | // - <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); | 920 | // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md); |
| 921 | // - <dir>/exe/index.json, game_scarlett_master.exe's own DXBC containers, entries named "exe/<name>" and found | ||
| 922 | // 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 | 923 | // - <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 | 924 | // 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); | 925 | // like the FSPX ones (docs/shader_library.md). |
| 854 | // - <dir>/exe/index.json, game_scarlett_master.exe's embedded FSSM programs, entries named "exe/<name>" and | 926 | // fspx_compute/ and library/ are two builds of the same slot-67 programs (make_game.py's library_shaders() writes |
| 855 | // found by fssm_sha256 like the game's own shaders (docs/embedded_shaders.md). | 927 | // library/; fspx_compute/ is the set translated from every console-path miss): both go into the same FSPX lookup |
| 856 | // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The folders | 928 | // 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 |
| 857 | // are optional: a missing or unreadable index there leaves the main one, and the other folders', loaded. | 929 | // program. Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The |
| 930 | // sub-indexes are optional: a missing or unreadable index there leaves the main one and the other folders loaded. | ||
| 858 | bool load(const std::filesystem::path& dir, std::string* error = nullptr) { | 931 | bool load(const std::filesystem::path& dir, std::string* error = nullptr) { |
| 859 | const auto fail = [&](const std::string& why) { | 932 | const auto fail = [&](const std::string& why) { |
| 860 | if (error) *error = why; | 933 | if (error) *error = why; |
| @@ -872,7 +945,7 @@ public: | |||
| 872 | } catch (...) { | 945 | } catch (...) { |
| 873 | return fail("index.json could not be read"); | 946 | return fail("index.json could not be read"); |
| 874 | } | 947 | } |
| 875 | for (const char* sub_folder : {"fspx", "bvh", "library", "exe"}) { | 948 | for (const char* sub_folder : {"fspx", "fspx_compute", "fspx_gfx", "bvh", "exe", "library"}) { |
| 876 | try { | 949 | try { |
| 877 | const auto ignore = [](const std::string&) { return false; }; | 950 | const auto ignore = [](const std::string&) { return false; }; |
| 878 | const std::filesystem::path sub = folder / sub_folder; | 951 | const std::filesystem::path sub = folder / sub_folder; |
| @@ -884,19 +957,52 @@ public: | |||
| 884 | return true; | 957 | return true; |
| 885 | } | 958 | } |
| 886 | 959 | ||
| 960 | // Loads only the optional FSPX sub-indexes (<dir>/fspx/index.json and <dir>/fspx_gfx/index.json) without parsing | ||
| 961 | // the 26,565-entry main index.json, for fast stage/hash lookups in the Xbox device proxy. | ||
| 962 | bool load_fspx_only(const std::filesystem::path& dir) { | ||
| 963 | dir_ = dir; | ||
| 964 | entries_.clear(); | ||
| 965 | fspx_entries_.clear(); | ||
| 966 | count_ = 0; | ||
| 967 | fspx_count_ = 0; | ||
| 968 | fspx_compute_count_ = 0; | ||
| 969 | fspx_gfx_count_ = 0; | ||
| 970 | bvh_count_ = 0; | ||
| 971 | exe_count_ = 0; | ||
| 972 | descriptor_hash_census_ = {}; | ||
| 973 | for (const char* folder : {"fspx", "fspx_gfx"}) { | ||
| 974 | try { | ||
| 975 | const auto ignore = [](const std::string&) { return false; }; | ||
| 976 | const std::filesystem::path sub = dir / folder; | ||
| 977 | if (std::ifstream(sub / "index.json", std::ios::binary)) | ||
| 978 | load_index(sub, std::string(folder) + "/", ignore); | ||
| 979 | } catch (...) { | ||
| 980 | } | ||
| 981 | } | ||
| 982 | return (fspx_count_ + fspx_gfx_count_) > 0; | ||
| 983 | } | ||
| 984 | |||
| 887 | bool loaded() const { return !dir_.empty(); } | 985 | bool loaded() const { return !dir_.empty(); } |
| 888 | // The folder load() read, made absolute; empty before. | 986 | // The folder load() read, made absolute; empty before. |
| 889 | const std::filesystem::path& directory() const { return dir_; } | 987 | const std::filesystem::path& directory() const { return dir_; } |
| 890 | std::size_t size() const { return count_; } | 988 | std::size_t size() const { return count_; } |
| 989 | // The descriptor-hash kinds the loaded modules declare, and the kind the majority of them probe with (fnv1a when | ||
| 990 | // they tie or none declares one). The device takes this once, before its descriptor table's first insert, unless | ||
| 991 | // LEONIDA_DESCRIPTOR_HASH names a kind. | ||
| 992 | const DescriptorHashCensus& descriptor_hash_census() const { return descriptor_hash_census_; } | ||
| 993 | DescriptorHashKind descriptor_hash_kind() const { return majority_descriptor_hash_kind(descriptor_hash_census_); } | ||
| 891 | // Entries loaded from <dir>/fspx/index.json and <dir>/library/index.json. A corpus of RPF containers never | 994 | // Entries loaded from <dir>/fspx/index.json and <dir>/library/index.json. A corpus of RPF containers never |
| 892 | // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached | 995 | // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached |
| 893 | // entries with size() must leave them out. | 996 | // entries with size() must leave them out. |
| 894 | std::size_t fspx_size() const { return fspx_count_; } | 997 | std::size_t fspx_size() const { return fspx_count_; } |
| 998 | std::size_t fspx_compute_size() const { return fspx_compute_count_; } | ||
| 999 | // Entries loaded from <dir>/fspx_gfx/index.json (graphics FSPX programs from shaders.rpf's pipeline library). | ||
| 1000 | std::size_t fspx_gfx_size() const { return fspx_gfx_count_; } | ||
| 895 | // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes | 1001 | // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes |
| 896 | // their containers itself. | 1002 | // their containers itself. |
| 897 | std::size_t bvh_size() const { return bvh_count_; } | 1003 | std::size_t bvh_size() const { return bvh_count_; } |
| 898 | // Entries loaded from <dir>/exe/index.json. No RPF container reaches these either: game_scarlett_master.exe | 1004 | // Entries loaded from <dir>/exe/index.json: game_scarlett_master.exe's inline containers, which no shader |
| 899 | // embeds their containers itself. | 1005 | // archive holds. |
| 900 | std::size_t exe_size() const { return exe_count_; } | 1006 | std::size_t exe_size() const { return exe_count_; } |
| 901 | 1007 | ||
| 902 | // The first entry for this program. Two containers can hold the same FSSM program with different input | 1008 | // The first entry for this program. Two containers can hold the same FSSM program with different input |
| @@ -915,6 +1021,15 @@ public: | |||
| 915 | return lookup(fspx_entries_, stage, fspx_code_sha256); | 1021 | return lookup(fspx_entries_, stage, fspx_code_sha256); |
| 916 | } | 1022 | } |
| 917 | 1023 | ||
| 1024 | // Finds an FSPX program by its kind-6 SHA-256 across all stages so the stage comes from the index entry itself. | ||
| 1025 | const ShaderEntry* find_fspx_by_code(std::string_view fspx_code_sha256) const { | ||
| 1026 | for (std::string_view st : {"vs", "ps", "ms", "gs", "cs"}) { | ||
| 1027 | const auto all = fspx_candidates(st, fspx_code_sha256); | ||
| 1028 | if (!all.empty()) return all.front(); | ||
| 1029 | } | ||
| 1030 | return nullptr; | ||
| 1031 | } | ||
| 1032 | |||
| 918 | // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time | 1033 | // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time |
| 919 | // lookup"): | 1034 | // lookup"): |
| 920 | // - FSSM: by fssm_sha256, as before; | 1035 | // - FSSM: by fssm_sha256, as before; |
| @@ -951,11 +1066,30 @@ public: | |||
| 951 | return all; | 1066 | return all; |
| 952 | } | 1067 | } |
| 953 | 1068 | ||
| 1069 | // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it. | ||
| 1070 | std::size_t spirv_bytes(const ShaderEntry& entry) const { | ||
| 1071 | std::error_code ec; | ||
| 1072 | auto path = dir_; | ||
| 1073 | path += "/" + entry.name + ".spv"; | ||
| 1074 | auto size = std::filesystem::file_size(path, ec); | ||
| 1075 | if (ec && !entry.spv_file.empty()) { | ||
| 1076 | auto alt = dir_; | ||
| 1077 | alt += "/" + entry.spv_file; | ||
| 1078 | size = std::filesystem::file_size(alt, ec); | ||
| 1079 | } | ||
| 1080 | return ec ? 0 : static_cast<std::size_t>(size); | ||
| 1081 | } | ||
| 1082 | |||
| 954 | // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. | 1083 | // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. |
| 955 | std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { | 1084 | std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { |
| 956 | auto path = dir_; | 1085 | auto path = dir_; |
| 957 | path += "/" + entry.name + ".spv"; | 1086 | path += "/" + entry.name + ".spv"; |
| 958 | std::ifstream file(path, std::ios::binary | std::ios::ate); | 1087 | std::ifstream file(path, std::ios::binary | std::ios::ate); |
| 1088 | if (!file && !entry.spv_file.empty()) { | ||
| 1089 | auto alt = dir_; | ||
| 1090 | alt += "/" + entry.spv_file; | ||
| 1091 | file.open(alt, std::ios::binary | std::ios::ate); | ||
| 1092 | } | ||
| 959 | return read_spirv_words(file, file.tellg()); | 1093 | return read_spirv_words(file, file.tellg()); |
| 960 | } | 1094 | } |
| 961 | 1095 | ||
| @@ -1004,8 +1138,11 @@ private: | |||
| 1004 | fspx_entries_.clear(); | 1138 | fspx_entries_.clear(); |
| 1005 | count_ = 0; | 1139 | count_ = 0; |
| 1006 | fspx_count_ = 0; | 1140 | fspx_count_ = 0; |
| 1141 | fspx_compute_count_ = 0; | ||
| 1142 | fspx_gfx_count_ = 0; | ||
| 1007 | bvh_count_ = 0; | 1143 | bvh_count_ = 0; |
| 1008 | exe_count_ = 0; | 1144 | exe_count_ = 0; |
| 1145 | descriptor_hash_census_ = {}; | ||
| 1009 | } | 1146 | } |
| 1010 | for (const auto& [name, meta] : root.object) { | 1147 | for (const auto& [name, meta] : root.object) { |
| 1011 | const Json* hash = meta.find("fssm_sha256"); | 1148 | const Json* hash = meta.find("fssm_sha256"); |
| @@ -1016,6 +1153,8 @@ private: | |||
| 1016 | if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue; | 1153 | if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue; |
| 1017 | ShaderEntry e; | 1154 | ShaderEntry e; |
| 1018 | e.name = prefix + name; | 1155 | e.name = prefix + name; |
| 1156 | if (const Json* spv = meta.find("spv"); spv && spv->kind == Json::Kind::string && !spv->string.empty()) | ||
| 1157 | e.spv_file = prefix + spv->string; | ||
| 1019 | e.stage = stage->string; | 1158 | e.stage = stage->string; |
| 1020 | if (by_fssm) e.fssm_sha256 = hash->string; | 1159 | if (by_fssm) e.fssm_sha256 = hash->string; |
| 1021 | if (by_fspx) e.fspx_code_sha256 = code_hash->string; | 1160 | if (by_fspx) e.fspx_code_sha256 = code_hash->string; |
| @@ -1026,12 +1165,20 @@ private: | |||
| 1026 | e.lds_bytes = u32(meta.find("lds_bytes")); | 1165 | e.lds_bytes = u32(meta.find("lds_bytes")); |
| 1027 | if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array) | 1166 | if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array) |
| 1028 | for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); | 1167 | for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); |
| 1029 | if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; | 1168 | // The paired FSPX translator emits uses_code_base only when true. Older |
| 1169 | // key-only indexes have no such contract; retain their program bytes. | ||
| 1170 | e.code_base_known = !e.fspx_state_sha256.empty(); | ||
| 1171 | if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) { | ||
| 1172 | e.uses_code_base = c->boolean; | ||
| 1173 | e.code_base_known = true; | ||
| 1174 | } | ||
| 1030 | if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; | 1175 | if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; |
| 1031 | if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) | 1176 | if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) |
| 1032 | e.subgroup_size = u32(g); | 1177 | e.subgroup_size = u32(g); |
| 1033 | if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string) | 1178 | if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string) |
| 1034 | e.wave64_exchange = x->string; | 1179 | e.wave64_exchange = x->string; |
| 1180 | if (const Json* wg = meta.find("wave64_graphics"); wg && wg->kind == Json::Kind::string) | ||
| 1181 | e.wave64_graphics = wg->string; | ||
| 1035 | if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { | 1182 | if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { |
| 1036 | for (const Json& item : s->array) { | 1183 | for (const Json& item : s->array) { |
| 1037 | SignatureElement element; | 1184 | SignatureElement element; |
| @@ -1051,9 +1198,20 @@ private: | |||
| 1051 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { | 1198 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { |
| 1052 | for (const auto& [key, val] : fh->object) { | 1199 | for (const auto& [key, val] : fh->object) { |
| 1053 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; | 1200 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; |
| 1054 | char* end = nullptr; | 1201 | std::uint64_t param = 0; |
| 1055 | const unsigned long param = std::strtoul(key.c_str(), &end, 10); | 1202 | bool ok = true; |
| 1056 | if (!end || *end != '\0') continue; | 1203 | for (const char c : key) { |
| 1204 | if (c < '0' || c > '9') { | ||
| 1205 | ok = false; | ||
| 1206 | break; | ||
| 1207 | } | ||
| 1208 | param = param * 10u + std::uint64_t(c - '0'); | ||
| 1209 | if (param > UINT32_MAX) { | ||
| 1210 | ok = false; | ||
| 1211 | break; | ||
| 1212 | } | ||
| 1213 | } | ||
| 1214 | if (!ok) continue; | ||
| 1057 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; | 1215 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; |
| 1058 | } | 1216 | } |
| 1059 | } | 1217 | } |
| @@ -1067,9 +1225,18 @@ private: | |||
| 1067 | } | 1225 | } |
| 1068 | e.max_vertices = u32(meta.find("max_vertices")); | 1226 | e.max_vertices = u32(meta.find("max_vertices")); |
| 1069 | e.max_primitives = u32(meta.find("max_primitives")); | 1227 | e.max_primitives = u32(meta.find("max_primitives")); |
| 1228 | // Which finalizer this module's shader probes the descriptor table with (descriptor_table.h). Absent, or not | ||
| 1229 | // a kind this runtime knows, is the old bare FNV-1a. | ||
| 1230 | if (const Json* dh = meta.find("descriptor_hash"); | ||
| 1231 | dh && dh->kind == Json::Kind::string && dh->string == "fnv1a_fmix32") | ||
| 1232 | ++descriptor_hash_census_.fnv1a_fmix32; | ||
| 1233 | else | ||
| 1234 | ++descriptor_hash_census_.fnv1a; | ||
| 1070 | if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); | 1235 | if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); |
| 1071 | if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); | 1236 | if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); |
| 1072 | if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; | 1237 | if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; |
| 1238 | if (by_fspx && prefix == "fspx_compute/") ++fspx_compute_count_; | ||
| 1239 | if (by_fspx && prefix == "fspx_gfx/") ++fspx_gfx_count_; | ||
| 1073 | if (prefix == "bvh/") ++bvh_count_; | 1240 | if (prefix == "bvh/") ++bvh_count_; |
| 1074 | if (prefix == "exe/") ++exe_count_; | 1241 | if (prefix == "exe/") ++exe_count_; |
| 1075 | ++count_; | 1242 | ++count_; |
| @@ -1080,11 +1247,14 @@ private: | |||
| 1080 | std::filesystem::path dir_; | 1247 | std::filesystem::path dir_; |
| 1081 | std::size_t count_ = 0; | 1248 | std::size_t count_ = 0; |
| 1082 | std::size_t fspx_count_ = 0; | 1249 | std::size_t fspx_count_ = 0; |
| 1250 | std::size_t fspx_compute_count_ = 0; | ||
| 1251 | std::size_t fspx_gfx_count_ = 0; | ||
| 1083 | std::size_t bvh_count_ = 0; | 1252 | std::size_t bvh_count_ = 0; |
| 1084 | std::size_t exe_count_ = 0; | 1253 | std::size_t exe_count_ = 0; |
| 1085 | // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. | 1254 | // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. |
| 1086 | Entries entries_; | 1255 | Entries entries_; |
| 1087 | Entries fspx_entries_; | 1256 | Entries fspx_entries_; |
| 1257 | DescriptorHashCensus descriptor_hash_census_; | ||
| 1088 | }; | 1258 | }; |
| 1089 | 1259 | ||
| 1090 | } // namespace leonida | 1260 | } // 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. | ||
| 67 | inline 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 | |||
| 64 | enum class SubgroupOutcome { | 72 | enum 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 | |||
| 18 | namespace rt { | ||
| 19 | namespace { | ||
| 20 | |||
| 21 | using Clock = std::chrono::steady_clock; | ||
| 22 | using GetDescription = HRESULT(WINAPI*)(HANDLE, PWSTR*); | ||
| 23 | using QueryThread = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); | ||
| 24 | |||
| 25 | struct 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. | ||
| 32 | bool 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), ®ion, 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. | ||
| 56 | bool 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 | |||
| 76 | size_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 | |||
| 101 | std::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 | |||
| 117 | struct 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 | |||
| 124 | void 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 | |||
| 145 | void 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 | |||
| 177 | StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite<std::byte[]>(kMaxStackBytes)) {} | ||
| 178 | |||
| 179 | std::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 | |||
| 190 | bool 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 | |||
| 210 | std::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 | |||
| 10 | namespace rt { | ||
| 11 | |||
| 12 | // One thread's call chain, taken without stopping the thread for longer than a context and stack copy. | ||
| 13 | class StackSampler { | ||
| 14 | public: | ||
| 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 | |||
| 27 | private: | ||
| 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. | ||
| 32 | bool 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. | ||
| 36 | std::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 | |||
| 7 | namespace leonida::geometry_writes { | ||
| 8 | |||
| 9 | constexpr std::uintptr_t tile_size = 65536, page_size = 4096; | ||
| 10 | using Aliases = void (*)(std::uintptr_t, std::vector<std::uintptr_t>&); | ||
| 11 | inline std::atomic<Aliases> aliases{}; | ||
| 12 | |||
| 13 | struct 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 | }; | ||
| 18 | struct 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 | }; | ||
| 24 | inline State& state() { static State s; return s; } | ||
| 25 | |||
| 26 | inline 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. | ||
| 36 | inline 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 | } | ||
| 43 | inline 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 | } | ||
| 55 | inline 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 | } | ||
| 65 | enum class Event { write, open, fault, mapping, replaced }; | ||
| 66 | inline 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. | ||
| 98 | inline 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. | ||
| 59 | namespace leonida::host_heap { | ||
| 60 | |||
| 61 | inline 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 | |||
| 71 | template <class T> | ||
| 72 | struct 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 | |||
| 89 | template <class T> | ||
| 90 | using vector = std::vector<T, Allocator<T>>; | ||
| 91 | template <class K, class V> | ||
| 92 | using map = std::map<K, V, std::less<K>, Allocator<std::pair<const K, V>>>; | ||
| 93 | |||
| 94 | } // namespace leonida::host_heap | ||
| 95 | |||
| 96 | namespace leonida::title_memory_map { | ||
| 97 | |||
| 98 | inline std::atomic<std::uint64_t> map_generation{0}; | ||
| 99 | |||
| 100 | inline std::uint64_t generation() { return map_generation.load(std::memory_order_acquire); } | ||
| 101 | inline void changed() { map_generation.fetch_add(1, std::memory_order_release); } | ||
| 102 | |||
| 103 | } // namespace leonida::title_memory_map | ||
| 104 | |||
| 105 | namespace leonida::title_page_aliases { | ||
| 106 | |||
| 107 | constexpr std::uintptr_t kPageSize = 0x10000; | ||
| 108 | |||
| 109 | struct 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 | |||
| 118 | inline 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. | ||
| 124 | inline 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(). | ||
| 133 | inline 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). | ||
| 136 | template<class F> | ||
| 137 | void 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). | ||
| 154 | namespace leonida::title_gpu_views { | ||
| 155 | |||
| 156 | struct View { | ||
| 157 | std::uintptr_t gpu, cpu, size; | ||
| 158 | }; | ||
| 159 | |||
| 160 | struct 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 | |||
| 167 | inline 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. | ||
| 173 | inline 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. | ||
| 189 | inline 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. | ||
| 200 | inline 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. | ||
| 217 | namespace leonida::title_texel_writes { | ||
| 218 | |||
| 219 | struct 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 | |||
| 226 | inline State& state() { | ||
| 227 | static State s; | ||
| 228 | return s; | ||
| 229 | } | ||
| 230 | |||
| 231 | inline 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. | ||
| 242 | inline 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. | ||
| 260 | namespace leonida::title_xg_layouts { | ||
| 261 | |||
| 262 | struct 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 | |||
| 271 | struct State { | ||
| 272 | std::mutex mutex; | ||
| 273 | std::map<Shape, std::uint32_t> layouts; | ||
| 274 | }; | ||
| 275 | |||
| 276 | inline State& state() { | ||
| 277 | static State s; | ||
| 278 | return s; | ||
| 279 | } | ||
| 280 | |||
| 281 | inline 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. | ||
| 288 | inline 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). | ||
| 317 | namespace leonida::title_write_watch { | ||
| 318 | |||
| 319 | constexpr 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. | ||
| 322 | constexpr std::size_t kMaxPages = std::size_t(1) << 18; | ||
| 323 | constexpr 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. | ||
| 327 | inline 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). | ||
| 340 | struct 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. | ||
| 347 | struct 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 | |||
| 366 | inline 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). | ||
| 374 | inline 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. | ||
| 390 | inline 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 | |||
| 401 | inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } | ||
| 402 | |||
| 403 | // Whether `address` is in a write-watched reservation. | ||
| 404 | inline 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. | ||
| 413 | inline 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. | ||
| 422 | template <class F> | ||
| 423 | void 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. | ||
| 438 | inline 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). | ||
| 453 | inline 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 | |||
| 461 | inline 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). | ||
| 468 | inline 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. | ||
| 476 | inline 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. | ||
| 490 | template <class Runs, class Dirty, class Refused> | ||
| 491 | std::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 | |||
| 556 | namespace leonida::kernel_writes { | ||
| 557 | |||
| 558 | // The layer's side: makes every watched page in [begin, end) writable. Set once the first shadow exists. | ||
| 559 | using 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. | ||
| 563 | using Committer = bool (*)(const void* address, std::size_t bytes); | ||
| 564 | |||
| 565 | struct Pin { | ||
| 566 | std::uintptr_t begin, end; | ||
| 567 | const OVERLAPPED* overlapped; // null: ends when the call returns | ||
| 568 | std::uint64_t id; | ||
| 569 | }; | ||
| 570 | |||
| 571 | struct 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 | |||
| 580 | inline State& state() { | ||
| 581 | static State s; | ||
| 582 | return s; | ||
| 583 | } | ||
| 584 | |||
| 585 | inline void set_opener(Opener opener) { state().opener.store(opener, std::memory_order_release); } | ||
| 586 | inline 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). | ||
| 590 | inline 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. | ||
| 600 | template<class F> | ||
| 601 | void 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. | ||
| 613 | inline 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. | ||
| 631 | inline 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. | ||
| 641 | inline 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). | ||
| 657 | inline 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 | |||
| 668 | inline 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. | ||
| 681 | inline 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 | |||
| 7 | namespace leonida { | ||
| 8 | |||
| 9 | // Keep negative probes until the title changes the map or a writer reports this footprint. | ||
| 10 | class TextureReadability { | ||
| 11 | public: | ||
| 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_; } | ||
| 23 | private: | ||
| 24 | std::uint64_t generation_ = 0; | ||
| 25 | bool pending_ = false, retry_ = false; | ||
| 26 | }; | ||
| 27 | |||
| 28 | using 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. | ||
| 31 | inline 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, ®ion, 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, ®ion, 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 | |||
| 7 | namespace leonida { | ||
| 8 | |||
| 9 | using 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. | ||
| 12 | inline 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 | |||
| 25 | inline 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. | ||
| 33 | template<class Registry, class Visit, class Exhausted> | ||
| 34 | void 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 index ac1871e17..6e97d7f1d 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h | |||
| @@ -12,8 +12,10 @@ | |||
| 12 | // submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 | 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. | 13 | // buffer). Addresses that are not in the title's memory are passed through unchanged. |
| 14 | // | 14 | // |
| 15 | // The table is process-wide, like the title's address space. A resolver makes a GPU copy for an address in the | 15 | // The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver |
| 16 | // title's memory that has none yet. Without it the table only translates previously added ranges. | 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). | ||
| 17 | #include <algorithm> | 19 | #include <algorithm> |
| 18 | #include <array> | 20 | #include <array> |
| 19 | #include <atomic> | 21 | #include <atomic> |
| @@ -23,6 +25,8 @@ | |||
| 23 | #include <map> | 25 | #include <map> |
| 24 | #include <mutex> | 26 | #include <mutex> |
| 25 | #include <shared_mutex> | 27 | #include <shared_mutex> |
| 28 | #include <utility> | ||
| 29 | #include <vector> | ||
| 26 | 30 | ||
| 27 | namespace leonida { | 31 | namespace leonida { |
| 28 | 32 | ||
| @@ -36,6 +40,7 @@ public: | |||
| 36 | // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when | 40 | // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when |
| 37 | // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). | 41 | // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). |
| 38 | using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); | 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); | ||
| 39 | 44 | ||
| 40 | // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one | 45 | // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one |
| 41 | // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. | 46 | // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. |
| @@ -59,16 +64,30 @@ public: | |||
| 59 | 64 | ||
| 60 | // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged | 65 | // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged |
| 61 | // elsewhere. No copy is made here. | 66 | // elsewhere. No copy is made here. |
| 62 | std::uint64_t shader_va(std::uint64_t va) const { | 67 | std::uint64_t shader_va(std::uint64_t va, std::uint64_t bytes = 1) const { |
| 63 | if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all | 68 | if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all |
| 64 | std::shared_lock lock(mutex_); | 69 | std::shared_lock lock(mutex_); |
| 65 | auto it = ranges_.upper_bound(va); | 70 | auto it = ranges_.upper_bound(va); |
| 66 | if (it == ranges_.begin()) return va; | 71 | if (it == ranges_.begin()) return va; |
| 67 | --it; | 72 | --it; |
| 68 | if (va >= it->second.end) return va; | 73 | if (va >= it->second.end || bytes > it->second.end - va) return va; |
| 69 | return it->second.shader_va + (va - it->first); | 74 | return it->second.shader_va + (va - it->first); |
| 70 | } | 75 | } |
| 71 | 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 | |||
| 72 | // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never | 91 | // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never |
| 73 | // replaces a range another buffer still uses. | 92 | // replaces a range another buffer still uses. |
| 74 | void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { | 93 | void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { |
| @@ -107,6 +126,19 @@ public: | |||
| 107 | if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); | 126 | if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); |
| 108 | } | 127 | } |
| 109 | 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 | |||
| 110 | // The scan's cost, per ExecuteCommandLists that had tables to scan. | 142 | // The scan's cost, per ExecuteCommandLists that had tables to scan. |
| 111 | void note_scan(std::uint64_t nanoseconds) { | 143 | void note_scan(std::uint64_t nanoseconds) { |
| 112 | scans_.fetch_add(1, std::memory_order_relaxed); | 144 | scans_.fetch_add(1, std::memory_order_relaxed); |
| @@ -140,6 +172,11 @@ public: | |||
| 140 | std::unique_lock lock(memory_mutex_); | 172 | std::unique_lock lock(memory_mutex_); |
| 141 | memory_.erase(base); | 173 | memory_.erase(base); |
| 142 | } | 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 | } | ||
| 143 | // The title range that holds `va`: [lo, hi). False when none does. | 180 | // The title range that holds `va`: [lo, hi). False when none does. |
| 144 | bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { | 181 | bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { |
| 145 | std::shared_lock lock(memory_mutex_); | 182 | std::shared_lock lock(memory_mutex_); |
| @@ -174,19 +211,65 @@ public: | |||
| 174 | } | 211 | } |
| 175 | std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } | 212 | std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } |
| 176 | 213 | ||
| 177 | // The first device to register keeps the resolver until it clears it. | 214 | // The end of the first title range that overlaps [lo, hi), or 0 when none does. The GPU address arena keeps its |
| 178 | void set_resolver(void* context, Resolver resolver) { | 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) { | ||
| 179 | std::lock_guard lock(hook_mutex_); | 257 | std::lock_guard lock(hook_mutex_); |
| 180 | if (hook_context_) return; | 258 | if (hook_context_) return; |
| 181 | hook_context_ = context; | 259 | hook_context_ = context; |
| 182 | resolver_ = resolver; | 260 | resolver_ = resolver; |
| 261 | scanner_ = scanner; | ||
| 183 | } | 262 | } |
| 184 | void clear_resolver(void* context) { | 263 | void clear_hooks(void* context) { |
| 185 | std::lock_guard lock(hook_mutex_); | 264 | std::lock_guard lock(hook_mutex_); |
| 186 | if (hook_context_ != context) return; | 265 | if (hook_context_ != context) return; |
| 187 | hook_context_ = nullptr; | 266 | hook_context_ = nullptr; |
| 188 | resolver_ = nullptr; | 267 | resolver_ = nullptr; |
| 268 | scanner_ = nullptr; | ||
| 189 | } | 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); } | ||
| 190 | 273 | ||
| 191 | std::size_t size() const { return count_.load(std::memory_order_acquire); } | 274 | std::size_t size() const { return count_.load(std::memory_order_acquire); } |
| 192 | std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } | 275 | std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } |
| @@ -212,7 +295,10 @@ private: | |||
| 212 | std::atomic<std::size_t> count_{0}; | 295 | std::atomic<std::size_t> count_{0}; |
| 213 | std::mutex hook_mutex_; | 296 | std::mutex hook_mutex_; |
| 214 | void* hook_context_ = nullptr; | 297 | void* hook_context_ = nullptr; |
| 298 | void* maker_context_ = nullptr; | ||
| 299 | BufferMaker maker_ = nullptr; | ||
| 215 | Resolver resolver_ = nullptr; | 300 | Resolver resolver_ = nullptr; |
| 301 | TableScanner scanner_ = nullptr; | ||
| 216 | void* source_context_ = nullptr; | 302 | void* source_context_ = nullptr; |
| 217 | DescriptorSource source_ = nullptr; | 303 | DescriptorSource source_ = nullptr; |
| 218 | std::atomic<std::uint64_t> pulled_{0}; | 304 | std::atomic<std::uint64_t> pulled_{0}; |
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h index b73ec50e1..385d55950 100644 --- a/runtime/src/uav_clear.h +++ b/runtime/src/uav_clear.h | |||
| @@ -91,6 +91,10 @@ inline constexpr Layout layouts[] = { | |||
| 91 | {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, | 91 | {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, |
| 92 | // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). | 92 | // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). |
| 93 | {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, | 93 | {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, |
| 94 | // B5G6R5, B5G5R5A1 and B4G4R4A4_UNORM, likewise (WARP has all three). | ||
| 95 | {VK_FORMAT_R5G6B5_UNORM_PACK16, Kind::unorm, 2, {{{11, 5}, {5, 6}, {0, 5}, {}}}}, | ||
| 96 | {VK_FORMAT_A1R5G5B5_UNORM_PACK16, Kind::unorm, 2, {{{10, 5}, {5, 5}, {0, 5}, {15, 1}}}}, | ||
| 97 | {VK_FORMAT_A4R4G4B4_UNORM_PACK16, Kind::unorm, 2, {{{8, 4}, {4, 4}, {0, 4}, {12, 4}}}}, | ||
| 94 | {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, | 98 | {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, |
| 95 | {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, | 99 | {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, |
| 96 | {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, | 100 | {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 87ae6f436..b89c005c0 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -12,17 +12,20 @@ | |||
| 12 | #endif | 12 | #endif |
| 13 | #include "binary_occlusion_spirv.h" | 13 | #include "binary_occlusion_spirv.h" |
| 14 | #include "buffer_va_index.h" | 14 | #include "buffer_va_index.h" |
| 15 | #include "image_memory.h" | ||
| 15 | #include "occlusion_sum_spirv.h" | 16 | #include "occlusion_sum_spirv.h" |
| 16 | #include "queue_holds.h" | 17 | #include "queue_holds.h" |
| 17 | #include "retire_tickets.h" | 18 | #include "retire_tickets.h" |
| 18 | #include "statistics_sum_spirv.h" | 19 | #include "statistics_sum_spirv.h" |
| 19 | #include "vulkan13_features.h" | 20 | #include "vulkan13_features.h" |
| 20 | #include "vulkan_depth24.h" | 21 | #include "vulkan_depth24.h" |
| 22 | #include "vulkan_title_image_pool.h" | ||
| 21 | #include "vulkan_indirect_dispatch_count.h" | 23 | #include "vulkan_indirect_dispatch_count.h" |
| 22 | #include "vulkan_scratch.h" | 24 | #include "vulkan_scratch.h" |
| 23 | #include "vulkan_replay.h" | 25 | #include "vulkan_replay.h" |
| 24 | #include "queue_families.h" | 26 | #include "queue_families.h" |
| 25 | #include "resource_tiling.h" | 27 | #include "resource_tiling.h" |
| 28 | #include "pipeline_profile.h" | ||
| 26 | #include "xdxr_build.h" | 29 | #include "xdxr_build.h" |
| 27 | 30 | ||
| 28 | #include <algorithm> | 31 | #include <algorithm> |
| @@ -47,6 +50,15 @@ | |||
| 47 | 50 | ||
| 48 | namespace leonida { | 51 | namespace leonida { |
| 49 | 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. | ||
| 55 | inline 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 | |||
| 50 | // 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. |
| 51 | // 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. |
| 52 | struct KhrInstanceStage { | 64 | struct KhrInstanceStage { |
| @@ -102,6 +114,7 @@ struct VulkanDeviceFunctions { | |||
| 102 | X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ | 114 | X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ |
| 103 | X(vkCmdPushConstants) X(vkCmdDispatch) \ | 115 | X(vkCmdPushConstants) X(vkCmdDispatch) \ |
| 104 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ | 116 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ |
| 117 | X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ | ||
| 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) \ |
| @@ -426,6 +439,7 @@ private: | |||
| 426 | }; | 439 | }; |
| 427 | 440 | ||
| 428 | struct SparseResource; | 441 | struct SparseResource; |
| 442 | using 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. |
| 431 | class DeferredDeletionQueue { | 445 | class 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). | ||
| 580 | inline std::atomic<unsigned> device_lost_reports{0}; | ||
| 581 | inline 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; |
| @@ -992,6 +1038,8 @@ public: | |||
| 992 | replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; | 1038 | replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; |
| 993 | replay_.set_viewport = vk.vkCmdSetViewport; | 1039 | replay_.set_viewport = vk.vkCmdSetViewport; |
| 994 | replay_.set_scissor = vk.vkCmdSetScissor; | 1040 | replay_.set_scissor = vk.vkCmdSetScissor; |
| 1041 | replay_.set_viewport_with_count = vk.vkCmdSetViewportWithCount; | ||
| 1042 | replay_.set_scissor_with_count = vk.vkCmdSetScissorWithCount; | ||
| 995 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; | 1043 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; |
| 996 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; | 1044 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; |
| 997 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; | 1045 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; |
| @@ -1022,7 +1070,7 @@ public: | |||
| 1022 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. | 1070 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. |
| 1023 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { | 1071 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { |
| 1024 | BufferVaIndex<ResourceId>::Hit hit{}; | 1072 | BufferVaIndex<ResourceId>::Hit hit{}; |
| 1025 | if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; | 1073 | if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent; |
| 1026 | const ResourceBinding* b = resolve(hit.id); | 1074 | const ResourceBinding* b = resolve(hit.id); |
| 1027 | if (!b) return HostReadStatus::absent; | 1075 | if (!b) return HostReadStatus::absent; |
| 1028 | if (!b->host) return HostReadStatus::not_cpu_written; | 1076 | if (!b->host) return HostReadStatus::not_cpu_written; |
| @@ -1108,6 +1156,7 @@ public: | |||
| 1108 | } | 1156 | } |
| 1109 | 1157 | ||
| 1110 | ~VulkanContext() { | 1158 | ~VulkanContext() { |
| 1159 | progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away | ||
| 1111 | gpu_labels_.stop(device_); | 1160 | gpu_labels_.stop(device_); |
| 1112 | fence_dispatcher_.reset(); | 1161 | fence_dispatcher_.reset(); |
| 1113 | deletion_queue_.drain(UINT64_MAX, device_, vk); | 1162 | deletion_queue_.drain(UINT64_MAX, device_, vk); |
| @@ -1121,6 +1170,22 @@ public: | |||
| 1121 | VulkanContext& operator=(const VulkanContext&) = delete; | 1170 | VulkanContext& operator=(const VulkanContext&) = delete; |
| 1122 | 1171 | ||
| 1123 | 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 | } | ||
| 1124 | void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, | 1189 | void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, |
| 1125 | VkDeviceSize max_range, std::uint32_t family) { | 1190 | VkDeviceSize max_range, std::uint32_t family) { |
| 1126 | std::unique_lock lock(resource_mutex_); | 1191 | std::unique_lock lock(resource_mutex_); |
| @@ -1166,10 +1231,9 @@ public: | |||
| 1166 | set_resource_locked(id, binding); | 1231 | set_resource_locked(id, binding); |
| 1167 | } | 1232 | } |
| 1168 | // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). | 1233 | // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). |
| 1169 | bool knows_buffer_va(std::uint64_t va) { | 1234 | bool knows_buffer_va(std::uint64_t va, std::uint64_t bytes = 1) { |
| 1170 | std::shared_lock lock(resource_mutex_); | 1235 | std::shared_lock lock(resource_mutex_); |
| 1171 | BufferVaIndex<ResourceId>::Hit hit{}; | 1236 | return buffer_vas_.covers(va, bytes); |
| 1172 | return buffer_vas_.find(va, hit); | ||
| 1173 | } | 1237 | } |
| 1174 | void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { | 1238 | void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { |
| 1175 | std::unique_lock rlock(resource_mutex_); | 1239 | std::unique_lock rlock(resource_mutex_); |
| @@ -1305,6 +1369,11 @@ public: | |||
| 1305 | replay_.zero_size = size; | 1369 | replay_.zero_size = size; |
| 1306 | } | 1370 | } |
| 1307 | 1371 | ||
| 1372 | void set_depth_range_unrestricted(bool enabled) { | ||
| 1373 | std::unique_lock lock(resource_mutex_); | ||
| 1374 | replay_.depth_range_unrestricted = enabled; | ||
| 1375 | } | ||
| 1376 | |||
| 1308 | struct GeometryUpload { | 1377 | struct GeometryUpload { |
| 1309 | std::uint64_t source{}, size{}; | 1378 | std::uint64_t source{}, size{}; |
| 1310 | VkBuffer buffer{}; | 1379 | VkBuffer buffer{}; |
| @@ -1342,24 +1411,77 @@ public: | |||
| 1342 | } | 1411 | } |
| 1343 | 1412 | ||
| 1344 | // 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. |
| 1345 | 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) { |
| 1346 | std::unique_lock lock(resource_mutex_); | 1415 | std::unique_lock lock(resource_mutex_); |
| 1347 | pipelines_[id] = pipeline; | 1416 | pipelines_[id] = pipeline; |
| 1417 | if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; | ||
| 1348 | } | 1418 | } |
| 1349 | void remove_pipeline(std::uintptr_t id) { | 1419 | void remove_pipeline(std::uintptr_t id) { |
| 1350 | std::unique_lock lock(resource_mutex_); | 1420 | std::unique_lock lock(resource_mutex_); |
| 1351 | pipelines_.erase(id); | 1421 | pipelines_.erase(id); |
| 1352 | graphics_pipelines_.erase(id); | 1422 | graphics_pipelines_.erase(id); |
| 1423 | if (device_fault_) device_fault_->pipeline_names.erase(id); | ||
| 1353 | } | 1424 | } |
| 1354 | 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) { | ||
| 1355 | std::unique_lock lock(resource_mutex_); | 1427 | std::unique_lock lock(resource_mutex_); |
| 1356 | graphics_pipelines_[id] = pipeline; | 1428 | graphics_pipelines_[id] = pipeline; |
| 1429 | if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; | ||
| 1357 | } | 1430 | } |
| 1358 | // Configure before queue creation, when the selected queue family supports compute. | 1431 | // Configure before queue creation, when the selected queue family supports compute. |
| 1359 | void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { | 1432 | void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { |
| 1360 | occlusion_resolve_memory_ = memory; | 1433 | occlusion_resolve_memory_ = memory; |
| 1361 | } | 1434 | } |
| 1362 | 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 | |||
| 1363 | // For tests and traces. | 1485 | // For tests and traces. |
| 1364 | VkImageLayout layout(ResourceId id, std::uint32_t subresource) { | 1486 | VkImageLayout layout(ResourceId id, std::uint32_t subresource) { |
| 1365 | std::lock_guard lock(tracker_mutex_); | 1487 | std::lock_guard lock(tracker_mutex_); |
| @@ -1485,6 +1607,29 @@ public: | |||
| 1485 | if (table_scanner_) table_scanner_(va, descriptors); | 1607 | if (table_scanner_) table_scanner_(va, descriptors); |
| 1486 | } | 1608 | } |
| 1487 | 1609 | ||
| 1610 | // `before` is called at the start of every submission of command lists (a held batch: when it is released), | ||
| 1611 | // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. | ||
| 1612 | // Set once, before the first queue exists. | ||
| 1613 | using InputProbe = std::function<void(std::span<const CommandList* const>, std::uint64_t, const char*)>; | ||
| 1614 | void set_input_probe(InputProbe probe) { input_probe_ = std::move(probe); } | ||
| 1615 | bool diagnostic_buffer(std::uint64_t va, std::uint64_t& host, std::uint64_t& room) { | ||
| 1616 | std::shared_lock lock(resource_mutex_); | ||
| 1617 | BufferVaIndex<ResourceId>::Hit hit{}; | ||
| 1618 | if (!buffer_vas_.find(va, hit)) return false; | ||
| 1619 | const auto* b = resolve(hit.id); | ||
| 1620 | if (!b || va - b->va >= b->size) return false; | ||
| 1621 | const auto offset = va - b->va; | ||
| 1622 | host = b->host ? reinterpret_cast<std::uint64_t>(b->host + offset) : 0; | ||
| 1623 | room = b->size - offset; | ||
| 1624 | return true; | ||
| 1625 | } | ||
| 1626 | const char* diagnostic_compute_name(std::uintptr_t id) { | ||
| 1627 | std::shared_lock lock(resource_mutex_); | ||
| 1628 | if (!device_fault_) return nullptr; | ||
| 1629 | const auto it = device_fault_->pipeline_names.find(id); | ||
| 1630 | return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; | ||
| 1631 | } | ||
| 1632 | |||
| 1488 | void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { | 1633 | void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { |
| 1489 | std::unique_lock lock(resource_mutex_); | 1634 | std::unique_lock lock(resource_mutex_); |
| 1490 | bindless_prepare_ = std::move(prepare); | 1635 | bindless_prepare_ = std::move(prepare); |
| @@ -1495,7 +1640,8 @@ public: | |||
| 1495 | void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, | 1640 | void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, |
| 1496 | std::uint64_t max_storage_range = 1u << 27) { | 1641 | std::uint64_t max_storage_range = 1u << 27) { |
| 1497 | std::unique_lock lock(resource_mutex_); | 1642 | std::unique_lock lock(resource_mutex_); |
| 1498 | depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); | 1643 | depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range, |
| 1644 | device_fault_.get()); | ||
| 1499 | if (!depth24_->loaded()) { | 1645 | if (!depth24_->loaded()) { |
| 1500 | depth24_.reset(); | 1646 | depth24_.reset(); |
| 1501 | return; | 1647 | return; |
| @@ -1512,7 +1658,8 @@ public: | |||
| 1512 | void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, | 1658 | void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, |
| 1513 | VkBufferUsageFlags extra_usage = 0, std::vector<std::uint32_t> families = {}) { | 1659 | VkBufferUsageFlags extra_usage = 0, std::vector<std::uint32_t> families = {}) { |
| 1514 | std::unique_lock lock(resource_mutex_); | 1660 | std::unique_lock lock(resource_mutex_); |
| 1515 | scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage, std::move(families)); | 1661 | scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage, std::move(families), |
| 1662 | device_fault_.get()); | ||
| 1516 | if (!scratch_->loaded()) scratch_.reset(); | 1663 | if (!scratch_->loaded()) scratch_.reset(); |
| 1517 | } | 1664 | } |
| 1518 | 1665 | ||
| @@ -1576,7 +1723,8 @@ public: | |||
| 1576 | wait.semaphoreCount = std::uint32_t(semaphores.size()); | 1723 | wait.semaphoreCount = std::uint32_t(semaphores.size()); |
| 1577 | wait.pSemaphores = semaphores.data(); | 1724 | wait.pSemaphores = semaphores.data(); |
| 1578 | wait.pValues = values.data(); | 1725 | wait.pValues = values.data(); |
| 1579 | vk.vkWaitSemaphores(device_, &wait, UINT64_MAX); // outside submit_mutex_: a signal may need it | 1726 | // Outside submit_mutex_: a signal may need it. |
| 1727 | observe_result(vk.vkWaitSemaphores(device_, &wait, UINT64_MAX), "vkWaitSemaphores (retirement)"); | ||
| 1580 | } | 1728 | } |
| 1581 | return completed_retire_ticket(); | 1729 | return completed_retire_ticket(); |
| 1582 | } | 1730 | } |
| @@ -1594,7 +1742,8 @@ public: | |||
| 1594 | if (is_device_lost()) return 0; | 1742 | if (is_device_lost()) return 0; |
| 1595 | ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { | 1743 | ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { |
| 1596 | std::uint64_t done = 0; | 1744 | std::uint64_t done = 0; |
| 1597 | const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); | 1745 | const VkResult result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done), |
| 1746 | "vkGetSemaphoreCounterValue (retirement)"); | ||
| 1598 | if (result == VK_ERROR_DEVICE_LOST) lost = true; | 1747 | if (result == VK_ERROR_DEVICE_LOST) lost = true; |
| 1599 | return result == VK_SUCCESS && done >= value; | 1748 | return result == VK_SUCCESS && done >= value; |
| 1600 | }); | 1749 | }); |
| @@ -1615,6 +1764,7 @@ public: | |||
| 1615 | void record_submit_locked(VkSemaphore progress, std::uint64_t value) { | 1764 | void record_submit_locked(VkSemaphore progress, std::uint64_t value) { |
| 1616 | const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; | 1765 | const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; |
| 1617 | retire_tickets_.record(ticket, progress, value); | 1766 | retire_tickets_.record(ticket, progress, value); |
| 1767 | note_image_work_locked(); | ||
| 1618 | } | 1768 | } |
| 1619 | void retire_queue_idle_locked(VkSemaphore progress) { | 1769 | void retire_queue_idle_locked(VkSemaphore progress) { |
| 1620 | retire_tickets_.queue_idle(progress); | 1770 | retire_tickets_.queue_idle(progress); |
| @@ -1625,8 +1775,8 @@ public: | |||
| 1625 | // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. | 1775 | // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. |
| 1626 | std::mutex& submit_mutex() { return submit_mutex_; } | 1776 | std::mutex& submit_mutex() { return submit_mutex_; } |
| 1627 | 1777 | ||
| 1628 | void mark_device_lost() noexcept { | 1778 | void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept { |
| 1629 | device_lost_.store(true, std::memory_order_release); | 1779 | set_device_lost(device_lost_, where); |
| 1630 | if (fence_dispatcher_) { | 1780 | if (fence_dispatcher_) { |
| 1631 | try { | 1781 | try { |
| 1632 | fence_dispatcher_->notify_device_lost(); | 1782 | fence_dispatcher_->notify_device_lost(); |
| @@ -1686,8 +1836,11 @@ private: | |||
| 1686 | const auto it = resources_.find(id); | 1836 | const auto it = resources_.find(id); |
| 1687 | if (it == resources_.end()) return nullptr; | 1837 | if (it == resources_.end()) return nullptr; |
| 1688 | const auto& binding = it->second; | 1838 | const auto& binding = it->second; |
| 1839 | if (auto* memory = binding.deferred_memory; memory && !memory->ensure()) return nullptr; | ||
| 1689 | // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind. | 1840 | // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind. |
| 1690 | if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr; | 1841 | if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr; |
| 1842 | if (auto* seen = binding.replay_seen; seen && !seen->load(std::memory_order_relaxed)) | ||
| 1843 | seen->store(true, std::memory_order_relaxed); | ||
| 1691 | return &binding; | 1844 | return &binding; |
| 1692 | } | 1845 | } |
| 1693 | 1846 | ||
| @@ -1776,6 +1929,52 @@ private: | |||
| 1776 | return framebuffer; | 1929 | return framebuffer; |
| 1777 | } | 1930 | } |
| 1778 | 1931 | ||
| 1932 | std::uint64_t poll_retirement_locked(VkResult& result) { | ||
| 1933 | return retire_tickets_.completed([&](VkSemaphore semaphore, std::uint64_t value) { | ||
| 1934 | std::uint64_t done = 0; | ||
| 1935 | result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done), | ||
| 1936 | "vkGetSemaphoreCounterValue (retirement)"); | ||
| 1937 | return result == VK_SUCCESS && done >= value; | ||
| 1938 | }); | ||
| 1939 | } | ||
| 1940 | |||
| 1941 | void watch_queue_progress(std::stop_token stop) { | ||
| 1942 | using Watch = SubmissionProgressWatch; | ||
| 1943 | Watch watch; | ||
| 1944 | std::uint64_t retired = 0; | ||
| 1945 | std::mutex timer_mutex; | ||
| 1946 | std::condition_variable_any timer; | ||
| 1947 | std::unique_lock timer_lock(timer_mutex); | ||
| 1948 | while (!stop.stop_requested()) { | ||
| 1949 | timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; }); | ||
| 1950 | if (stop.stop_requested() || is_device_lost()) break; | ||
| 1951 | auto state = Watch::State::submit_lock_busy; | ||
| 1952 | VkResult result = VK_SUCCESS; | ||
| 1953 | std::uint64_t submitted; | ||
| 1954 | { | ||
| 1955 | // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait | ||
| 1956 | // blocked inside the driver can hold this mutex indefinitely. | ||
| 1957 | std::unique_lock lock(submit_mutex_, std::try_to_lock); | ||
| 1958 | submitted = submitted_retire_ticket(); | ||
| 1959 | if (lock.owns_lock()) { | ||
| 1960 | if (is_device_lost()) break; | ||
| 1961 | retired = poll_retirement_locked(result); | ||
| 1962 | state = retired < submitted ? Watch::State::pending : Watch::State::idle; | ||
| 1963 | } | ||
| 1964 | } | ||
| 1965 | if (result == VK_ERROR_DEVICE_LOST) { | ||
| 1966 | mark_device_lost(); | ||
| 1967 | break; | ||
| 1968 | } | ||
| 1969 | // A failed counter query does not measure GPU progress. | ||
| 1970 | if (result != VK_SUCCESS) state = Watch::State::idle; | ||
| 1971 | if (watch.sample(state, retired, Watch::Clock::now())) | ||
| 1972 | device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced" | ||
| 1973 | : "could not sample the submit lock", | ||
| 1974 | submitted, retired); | ||
| 1975 | } | ||
| 1976 | } | ||
| 1977 | |||
| 1779 | VkDevice device_; | 1978 | VkDevice device_; |
| 1780 | bool loaded_ = false; | 1979 | bool loaded_ = false; |
| 1781 | bool ray_tracing_ = false; | 1980 | bool ray_tracing_ = false; |
| @@ -1785,9 +1984,13 @@ private: | |||
| 1785 | alignas(64) std::mutex tracker_mutex_; | 1984 | alignas(64) std::mutex tracker_mutex_; |
| 1786 | alignas(64) std::mutex views_mutex_; | 1985 | alignas(64) std::mutex views_mutex_; |
| 1787 | alignas(64) std::mutex submit_mutex_; | 1986 | alignas(64) std::mutex submit_mutex_; |
| 1987 | bool image_work_pending_ = false; // under submit_mutex_ | ||
| 1988 | HostTextureStats host_texture_stats_; // under submit_mutex_ | ||
| 1788 | RetireTickets<VkSemaphore> retire_tickets_; | 1989 | RetireTickets<VkSemaphore> retire_tickets_; |
| 1789 | std::atomic<std::uint64_t> submitted_ticket_{0}; | 1990 | std::atomic<std::uint64_t> submitted_ticket_{0}; |
| 1790 | DeferredDeletionQueue deletion_queue_; | 1991 | DeferredDeletionQueue deletion_queue_; |
| 1992 | std::unique_ptr<DeviceFaultDiagnostics> device_fault_; | ||
| 1993 | std::jthread progress_watch_; | ||
| 1791 | std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; | 1994 | std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; |
| 1792 | QueueHolds<VkSemaphore> holds_; | 1995 | QueueHolds<VkSemaphore> holds_; |
| 1793 | std::unordered_map<ResourceId, ResourceBinding> resources_; | 1996 | std::unordered_map<ResourceId, ResourceBinding> resources_; |
| @@ -1816,6 +2019,7 @@ private: | |||
| 1816 | resolve_passes_; | 2019 | resolve_passes_; |
| 1817 | std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; | 2020 | std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; |
| 1818 | std::function<void()> before_execute_; | 2021 | std::function<void()> before_execute_; |
| 2022 | InputProbe input_probe_; | ||
| 1819 | TableScanner table_scanner_; | 2023 | TableScanner table_scanner_; |
| 1820 | GeometryProvider geometry_provider_; | 2024 | GeometryProvider geometry_provider_; |
| 1821 | std::function<bool(std::uint64_t,std::uint32_t)> sample_table_resolver_; | 2025 | std::function<bool(std::uint64_t,std::uint32_t)> sample_table_resolver_; |
| @@ -1875,7 +2079,8 @@ public: | |||
| 1875 | std::uint64_t completed() const { | 2079 | std::uint64_t completed() const { |
| 1876 | if (context_.is_device_lost()) return UINT64_MAX; | 2080 | if (context_.is_device_lost()) return UINT64_MAX; |
| 1877 | std::uint64_t value = 0; | 2081 | std::uint64_t value = 0; |
| 1878 | const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); | 2082 | const VkResult result = context_.observe_result( |
| 2083 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value), "vkGetSemaphoreCounterValue"); | ||
| 1879 | if (result == VK_ERROR_DEVICE_LOST) { | 2084 | if (result == VK_ERROR_DEVICE_LOST) { |
| 1880 | context_.mark_device_lost(); | 2085 | context_.mark_device_lost(); |
| 1881 | return UINT64_MAX; | 2086 | return UINT64_MAX; |
| @@ -1891,13 +2096,15 @@ public: | |||
| 1891 | // it marks the context lost on a query error and prevents the dispatcher from waking. | 2096 | // it marks the context lost on a query error and prevents the dispatcher from waking. |
| 1892 | if (context_.is_device_lost()) return false; | 2097 | if (context_.is_device_lost()) return false; |
| 1893 | std::uint64_t current = 0; | 2098 | std::uint64_t current = 0; |
| 1894 | if (context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, ¤t) == VK_SUCCESS && | 2099 | if (context_.observe_result(context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, ¤t), |
| 2100 | "vkGetSemaphoreCounterValue") == VK_SUCCESS && | ||
| 1895 | value <= current) | 2101 | value <= current) |
| 1896 | return false; | 2102 | return false; |
| 1897 | VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; | 2103 | VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; |
| 1898 | info.semaphore = semaphore_; | 2104 | info.semaphore = semaphore_; |
| 1899 | info.value = value; | 2105 | info.value = value; |
| 1900 | const VkResult result = context_.vk.vkSignalSemaphore(context_.device(), &info); | 2106 | const VkResult result = context_.observe_result(context_.vk.vkSignalSemaphore(context_.device(), &info), |
| 2107 | "vkSignalSemaphore"); | ||
| 1901 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); | 2108 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); |
| 1902 | if (result != VK_SUCCESS) return false; | 2109 | if (result != VK_SUCCESS) return false; |
| 1903 | context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now | 2110 | context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now |
| @@ -1911,7 +2118,8 @@ public: | |||
| 1911 | info.semaphoreCount = 1; | 2118 | info.semaphoreCount = 1; |
| 1912 | info.pSemaphores = &semaphore_; | 2119 | info.pSemaphores = &semaphore_; |
| 1913 | info.pValues = &value; | 2120 | info.pValues = &value; |
| 1914 | const VkResult result = context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns); | 2121 | const VkResult result = context_.observe_result( |
| 2122 | context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns), "vkWaitSemaphores"); | ||
| 1915 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); | 2123 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); |
| 1916 | return result == VK_SUCCESS; | 2124 | return result == VK_SUCCESS; |
| 1917 | } | 2125 | } |
| @@ -1984,7 +2192,7 @@ public: | |||
| 1984 | if (queue_) { | 2192 | if (queue_) { |
| 1985 | std::lock_guard lock(context_.submit_mutex()); | 2193 | std::lock_guard lock(context_.submit_mutex()); |
| 1986 | for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); | 2194 | for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); |
| 1987 | const VkResult idle_result = vk.vkQueueWaitIdle(queue_); | 2195 | const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); |
| 1988 | if (idle_result == VK_SUCCESS) { | 2196 | if (idle_result == VK_SUCCESS) { |
| 1989 | if (progress_) context_.retire_queue_idle_locked(progress_); | 2197 | if (progress_) context_.retire_queue_idle_locked(progress_); |
| 1990 | } else { | 2198 | } else { |
| @@ -2105,18 +2313,21 @@ public: | |||
| 2105 | using PinFn = std::function<std::shared_ptr<void>()>; | 2313 | using PinFn = std::function<std::shared_ptr<void>()>; |
| 2106 | 2314 | ||
| 2107 | ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { | 2315 | ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { |
| 2316 | auto* diagnostics = context_.device_fault(); | ||
| 2317 | const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; | ||
| 2108 | ReplayResult result = ReplayResult::success; | 2318 | ReplayResult result = ReplayResult::success; |
| 2109 | bool held = false; | 2319 | bool held = false; |
| 2110 | std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released | 2320 | std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released |
| 2111 | { | 2321 | { |
| 2112 | std::lock_guard state(state_mutex_); | 2322 | std::lock_guard state(state_mutex_); |
| 2113 | if (!must_hold()) { | 2323 | if (!must_hold()) { |
| 2114 | result = execute_now(lists); | 2324 | result = execute_now(lists, execute_call); |
| 2115 | } else if (context_.is_device_lost()) { | 2325 | } else if (context_.is_device_lost()) { |
| 2116 | result = ReplayResult::unsupported; | 2326 | result = queue_unsupported(__LINE__); |
| 2117 | } else { | 2327 | } else { |
| 2118 | Deferred op; | 2328 | Deferred op; |
| 2119 | op.kind = Deferred::Kind::batch; | 2329 | op.kind = Deferred::Kind::batch; |
| 2330 | op.execute_call = execute_call; | ||
| 2120 | op.lists.reserve(lists.size()); | 2331 | op.lists.reserve(lists.size()); |
| 2121 | for (const CommandList* list : lists) op.lists.push_back(*list); | 2332 | for (const CommandList* list : lists) op.lists.push_back(*list); |
| 2122 | if (pin) op.pins.push_back(pin()); | 2333 | if (pin) op.pins.push_back(pin()); |
| @@ -2195,7 +2406,7 @@ public: | |||
| 2195 | 2406 | ||
| 2196 | bool idle() { | 2407 | bool idle() { |
| 2197 | std::lock_guard lock(context_.submit_mutex()); | 2408 | std::lock_guard lock(context_.submit_mutex()); |
| 2198 | return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; | 2409 | return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; |
| 2199 | } | 2410 | } |
| 2200 | 2411 | ||
| 2201 | private: | 2412 | private: |
| @@ -2281,11 +2492,11 @@ private: | |||
| 2281 | !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || | 2492 | !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || |
| 2282 | !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || | 2493 | !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || |
| 2283 | !build.instance_count) | 2494 | !build.instance_count) |
| 2284 | return ReplayResult::unsupported; | 2495 | return queue_unsupported(__LINE__); |
| 2285 | const std::uint64_t bytes = 8ull * build.instance_count; | 2496 | const std::uint64_t bytes = 8ull * build.instance_count; |
| 2286 | const std::uint8_t* guest = nullptr; | 2497 | const std::uint8_t* guest = nullptr; |
| 2287 | const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); | 2498 | const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); |
| 2288 | if (status == HostReadStatus::not_cpu_written) return ReplayResult::unsupported; | 2499 | if (status == HostReadStatus::not_cpu_written) return queue_unsupported(__LINE__); |
| 2289 | if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; | 2500 | if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; |
| 2290 | 2501 | ||
| 2291 | KhrInstanceStage stage{}; | 2502 | KhrInstanceStage stage{}; |
| @@ -2308,7 +2519,7 @@ private: | |||
| 2308 | info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | | 2519 | info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | |
| 2309 | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; | 2520 | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; |
| 2310 | if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) | 2521 | if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) |
| 2311 | return ReplayResult::unsupported; | 2522 | return queue_unsupported(__LINE__); |
| 2312 | VkMemoryRequirements requirements{}; | 2523 | VkMemoryRequirements requirements{}; |
| 2313 | funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); | 2524 | funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); |
| 2314 | const auto& memory = context_.occlusion_resolve_memory_; | 2525 | const auto& memory = context_.occlusion_resolve_memory_; |
| @@ -2324,7 +2535,7 @@ private: | |||
| 2324 | } | 2535 | } |
| 2325 | if (type == memory.memoryTypeCount) { | 2536 | if (type == memory.memoryTypeCount) { |
| 2326 | discard(); | 2537 | discard(); |
| 2327 | return ReplayResult::unsupported; | 2538 | return queue_unsupported(__LINE__); |
| 2328 | } | 2539 | } |
| 2329 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; | 2540 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; |
| 2330 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; | 2541 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; |
| @@ -2334,7 +2545,7 @@ private: | |||
| 2334 | if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || | 2545 | if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || |
| 2335 | funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { | 2546 | funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { |
| 2336 | discard(); | 2547 | discard(); |
| 2337 | return ReplayResult::unsupported; | 2548 | return queue_unsupported(__LINE__); |
| 2338 | } | 2549 | } |
| 2339 | stage.size = bytes; | 2550 | stage.size = bytes; |
| 2340 | } | 2551 | } |
| @@ -2342,7 +2553,7 @@ private: | |||
| 2342 | void* mapped = nullptr; | 2553 | void* mapped = nullptr; |
| 2343 | if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { | 2554 | if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { |
| 2344 | discard(); | 2555 | discard(); |
| 2345 | return ReplayResult::unsupported; | 2556 | return queue_unsupported(__LINE__); |
| 2346 | } | 2557 | } |
| 2347 | // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. | 2558 | // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. |
| 2348 | for (std::uint32_t i = 0; i < build.instance_count; ++i) { | 2559 | for (std::uint32_t i = 0; i < build.instance_count; ++i) { |
| @@ -2368,22 +2579,25 @@ private: | |||
| 2368 | stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); | 2579 | stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); |
| 2369 | if (!stage.address) { | 2580 | if (!stage.address) { |
| 2370 | discard(); | 2581 | discard(); |
| 2371 | return ReplayResult::unsupported; | 2582 | return queue_unsupported(__LINE__); |
| 2372 | } | 2583 | } |
| 2373 | stages.push_back(std::move(stage)); | 2584 | stages.push_back(std::move(stage)); |
| 2374 | address = stages.back().address; | 2585 | address = stages.back().address; |
| 2375 | return ReplayResult::success; | 2586 | return ReplayResult::success; |
| 2376 | } | 2587 | } |
| 2377 | 2588 | ||
| 2378 | ReplayResult execute_now(std::span<const CommandList* const> lists) { | 2589 | ReplayResult execute_now(std::span<const CommandList* const> lists, std::uint64_t execute_call) { |
| 2379 | if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; | 2590 | if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__); |
| 2380 | if (context_.before_execute_) context_.before_execute_(); | 2591 | if (context_.before_execute_) context_.before_execute_(); |
| 2592 | if (context_.input_probe_) | ||
| 2593 | context_.input_probe_(lists, execute_call, kind_ == QueueKind::direct ? "direct" : | ||
| 2594 | kind_ == QueueKind::compute ? "compute" : "copy"); | ||
| 2381 | if (kind_ != QueueKind::direct) | 2595 | if (kind_ != QueueKind::direct) |
| 2382 | for (const auto* list : lists) | 2596 | for (const auto* list : lists) |
| 2383 | for (const auto& command : list->commands()) | 2597 | for (const auto& command : list->commands()) |
| 2384 | if (std::holds_alternative<ClearRenderTarget>(command) || | 2598 | if (std::holds_alternative<ClearRenderTarget>(command) || |
| 2385 | std::holds_alternative<ClearDepthStencil>(command)) | 2599 | std::holds_alternative<ClearDepthStencil>(command)) |
| 2386 | return ReplayResult::unsupported; | 2600 | return queue_unsupported(__LINE__); |
| 2387 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; | 2601 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; |
| 2388 | struct KhrGuard { | 2602 | struct KhrGuard { |
| 2389 | VulkanQueue* queue; | 2603 | VulkanQueue* queue; |
| @@ -2429,6 +2643,8 @@ private: | |||
| 2429 | // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. | 2643 | // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. |
| 2430 | if (prepared.size() < lists.size()) prepared.resize(lists.size()); | 2644 | if (prepared.size() < lists.size()) prepared.resize(lists.size()); |
| 2431 | ReplayFunctions replay = context_.replay_; | 2645 | ReplayFunctions replay = context_.replay_; |
| 2646 | unsigned mesh_draws = 0; | ||
| 2647 | if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; | ||
| 2432 | std::vector<VulkanContext::GeometryUpload> geometry; | 2648 | std::vector<VulkanContext::GeometryUpload> geometry; |
| 2433 | if (context_.geometry_provider_) { | 2649 | if (context_.geometry_provider_) { |
| 2434 | replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { | 2650 | replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { |
| @@ -2468,12 +2684,12 @@ private: | |||
| 2468 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; | 2684 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; |
| 2469 | if (captures) { | 2685 | if (captures) { |
| 2470 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) | 2686 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) |
| 2471 | return ReplayResult::unsupported; | 2687 | return queue_unsupported(__LINE__); |
| 2472 | // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, | 2688 | // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, |
| 2473 | // retaining main's resource -> tracker -> submit lock order through emit and submission. | 2689 | // retaining main's resource -> tracker -> submit lock order through emit and submission. |
| 2474 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 2690 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 2475 | batch = context_.predicate_reducer_->batch(captures); | 2691 | batch = context_.predicate_reducer_->batch(captures); |
| 2476 | if (!batch) return ReplayResult::unsupported; | 2692 | if (!batch) return queue_unsupported(__LINE__); |
| 2477 | replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { | 2693 | replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { |
| 2478 | return batch->prepare(buffer, offset, out); | 2694 | return batch->prepare(buffer, offset, out); |
| 2479 | }; | 2695 | }; |
| @@ -2571,7 +2787,7 @@ private: | |||
| 2571 | if (result != ReplayResult::success) return result; | 2787 | if (result != ReplayResult::success) return result; |
| 2572 | if (prepared[i].segment_count > UINT32_MAX - segments || | 2788 | if (prepared[i].segment_count > UINT32_MAX - segments || |
| 2573 | prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) | 2789 | prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) |
| 2574 | return ReplayResult::unsupported; | 2790 | return queue_unsupported(__LINE__); |
| 2575 | segments += prepared[i].segment_count; | 2791 | segments += prepared[i].segment_count; |
| 2576 | statistics_segments += prepared[i].statistics_segment_count; | 2792 | statistics_segments += prepared[i].statistics_segment_count; |
| 2577 | has_queries = has_queries || !prepared[i].queries.empty(); | 2793 | has_queries = has_queries || !prepared[i].queries.empty(); |
| @@ -2591,12 +2807,12 @@ private: | |||
| 2591 | return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS; | 2807 | return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS; |
| 2592 | }; | 2808 | }; |
| 2593 | std::shared_ptr<OcclusionSegmentPool> physical, statistics; | 2809 | std::shared_ptr<OcclusionSegmentPool> physical, statistics; |
| 2594 | if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; | 2810 | if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return queue_unsupported(__LINE__); |
| 2595 | // Without the compute helper a split query could not be summed: leave statistics queries whole, as before | 2811 | // Without the compute helper a split query could not be summed: leave statistics queries whole, as before |
| 2596 | // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). | 2812 | // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). |
| 2597 | if (statistics_segments && can_resolve_occlusion) { | 2813 | if (statistics_segments && can_resolve_occlusion) { |
| 2598 | if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) | 2814 | if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) |
| 2599 | return ReplayResult::unsupported; | 2815 | return queue_unsupported(__LINE__); |
| 2600 | for (const auto& list : prepared) | 2816 | for (const auto& list : prepared) |
| 2601 | statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), | 2817 | statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), |
| 2602 | list.statistics_mesh.end()); | 2818 | list.statistics_mesh.end()); |
| @@ -2611,7 +2827,7 @@ private: | |||
| 2611 | info.pipelineStatistics = kMeshStatisticsFlags; | 2827 | info.pipelineStatistics = kMeshStatisticsFlags; |
| 2612 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != | 2828 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != |
| 2613 | VK_SUCCESS) | 2829 | VK_SUCCESS) |
| 2614 | return ReplayResult::unsupported; | 2830 | return queue_unsupported(__LINE__); |
| 2615 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, | 2831 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, |
| 2616 | // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, | 2832 | // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, |
| 2617 | // or the clipping field of a mesh segment stays 0. | 2833 | // or the clipping field of a mesh segment stays 0. |
| @@ -2621,7 +2837,7 @@ private: | |||
| 2621 | primitives.queryCount = statistics_segments; | 2837 | primitives.queryCount = statistics_segments; |
| 2622 | if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, | 2838 | if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, |
| 2623 | &statistics->primitives_pool) != VK_SUCCESS) | 2839 | &statistics->primitives_pool) != VK_SUCCESS) |
| 2624 | return ReplayResult::unsupported; | 2840 | return queue_unsupported(__LINE__); |
| 2625 | } | 2841 | } |
| 2626 | } | 2842 | } |
| 2627 | } | 2843 | } |
| @@ -2641,16 +2857,16 @@ private: | |||
| 2641 | if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) { | 2857 | if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) { |
| 2642 | if (!occlusion_resolve_) { | 2858 | if (!occlusion_resolve_) { |
| 2643 | auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); | 2859 | auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); |
| 2644 | if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; | 2860 | if (!helper->initialize(occlusion_memory)) return queue_unsupported(__LINE__); |
| 2645 | occlusion_resolve_ = std::move(helper); | 2861 | occlusion_resolve_ = std::move(helper); |
| 2646 | } | 2862 | } |
| 2647 | if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum, | 2863 | if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum, |
| 2648 | queries.needs_sum_binary)) | 2864 | queries.needs_sum_binary)) |
| 2649 | return ReplayResult::unsupported; | 2865 | return queue_unsupported(__LINE__); |
| 2650 | } | 2866 | } |
| 2651 | 2867 | ||
| 2652 | CommandSlot* slot = acquire(); | 2868 | CommandSlot* slot = acquire(); |
| 2653 | if (!slot) return ReplayResult::unsupported; | 2869 | if (!slot) return queue_unsupported(__LINE__); |
| 2654 | slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused | 2870 | slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused |
| 2655 | khr_guard.stages.clear(); | 2871 | khr_guard.stages.clear(); |
| 2656 | slot->khr_as_queries = std::move(khr_guard.as_queries); | 2872 | slot->khr_as_queries = std::move(khr_guard.as_queries); |
| @@ -2680,13 +2896,27 @@ private: | |||
| 2680 | VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | 2896 | VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; |
| 2681 | begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; | 2897 | begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; |
| 2682 | context_.gpu_labels_.begin_record(command_buffer); | 2898 | context_.gpu_labels_.begin_record(command_buffer); |
| 2683 | if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { | 2899 | if (context_.observe_result(context_.vk.vkBeginCommandBuffer(command_buffer, &begin), |
| 2900 | "vkBeginCommandBuffer") != VK_SUCCESS) { | ||
| 2684 | discard(); | 2901 | discard(); |
| 2685 | return ReplayResult::unsupported; | 2902 | return queue_unsupported(__LINE__); |
| 2903 | } | ||
| 2904 | // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the | ||
| 2905 | // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier: | ||
| 2906 | // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their | ||
| 2907 | // barriers say, so this one starts with a full memory barrier against everything submitted before it | ||
| 2908 | // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies). | ||
| 2909 | if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out | ||
| 2910 | VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 2911 | full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2912 | full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2913 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | ||
| 2914 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); | ||
| 2686 | } | 2915 | } |
| 2687 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 2916 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 2688 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { | 2917 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { |
| 2689 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | 2918 | const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), |
| 2919 | "vkEndCommandBuffer") == VK_SUCCESS; | ||
| 2690 | resource_lock.unlock(); | 2920 | resource_lock.unlock(); |
| 2691 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | 2921 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); |
| 2692 | if (!submitted) discard(); | 2922 | if (!submitted) discard(); |
| @@ -2700,7 +2930,7 @@ private: | |||
| 2700 | } | 2930 | } |
| 2701 | if (bindless_commit) bindless_commit(submitted); | 2931 | if (bindless_commit) bindless_commit(submitted); |
| 2702 | tracker_lock.unlock(); | 2932 | tracker_lock.unlock(); |
| 2703 | return ReplayResult::unsupported; | 2933 | return queue_unsupported(__LINE__); |
| 2704 | } | 2934 | } |
| 2705 | replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; | 2935 | replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; |
| 2706 | const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); | 2936 | const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); |
| @@ -2754,9 +2984,23 @@ private: | |||
| 2754 | bool wrote_readback = false; | 2984 | bool wrote_readback = false; |
| 2755 | VkPipelineStageFlags2 readback_stages = 0; | 2985 | VkPipelineStageFlags2 readback_stages = 0; |
| 2756 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists | 2986 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists |
| 2987 | CheckpointSubmission diagnostics; | ||
| 2988 | PFN_vkCmdSetCheckpointNV checkpoint = nullptr; | ||
| 2989 | if (execute_call) { | ||
| 2990 | auto& fault = *context_.device_fault(); | ||
| 2991 | checkpoint = fault.checkpoint_command(); | ||
| 2992 | const char* queue_kind = kind_ == QueueKind::direct ? "direct" : | ||
| 2993 | kind_ == QueueKind::compute ? "compute" : "copy"; | ||
| 2994 | diagnostics = fault.begin_submission(execute_call, queue_, queue_kind, lists.size()); | ||
| 2995 | } | ||
| 2757 | for (std::size_t i = 0; i < lists.size(); ++i) { | 2996 | for (std::size_t i = 0; i < lists.size(); ++i) { |
| 2758 | const auto& list = prepared[i]; | 2997 | const auto& list = prepared[i]; |
| 2759 | emit(list, command_buffer, replay, &next_tracker, &open_labels); | 2998 | if (execute_call && i < diagnostics.lists.size()) { |
| 2999 | const CheckpointRecorder recorder{checkpoint, diagnostics, context_.device_fault()->pipeline_names, i}; | ||
| 3000 | emit_commands<true>(list, command_buffer, replay, &next_tracker, &open_labels, &recorder); | ||
| 3001 | } else { | ||
| 3002 | emit(list, command_buffer, replay, &next_tracker, &open_labels); | ||
| 3003 | } | ||
| 2760 | wrote_readback |= list.wrote_readback; | 3004 | wrote_readback |= list.wrote_readback; |
| 2761 | readback_stages |= list.readback_src_stages; | 3005 | readback_stages |= list.readback_src_stages; |
| 2762 | } | 3006 | } |
| @@ -2791,14 +3035,19 @@ private: | |||
| 2791 | 0, 1, &host, 0, nullptr, 0, nullptr); | 3035 | 0, 1, &host, 0, nullptr, 0, nullptr); |
| 2792 | } | 3036 | } |
| 2793 | } | 3037 | } |
| 2794 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | 3038 | const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), |
| 3039 | "vkEndCommandBuffer") == VK_SUCCESS; | ||
| 2795 | resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held | 3040 | resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held |
| 2796 | const bool wait_previous = ordered_timestamps && submitted_; | 3041 | const bool wait_previous = ordered_timestamps && submitted_; |
| 2797 | if (wait_previous) { | 3042 | if (wait_previous) { |
| 2798 | waits_.push_back(progress_); | 3043 | waits_.push_back(progress_); |
| 2799 | wait_values_.push_back(submitted_); | 3044 | wait_values_.push_back(submitted_); |
| 2800 | } | 3045 | } |
| 2801 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | 3046 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0, |
| 3047 | execute_call ? &diagnostics : nullptr); | ||
| 3048 | if (mesh_draws) | ||
| 3049 | std::fprintf(stderr, "[rt] pso-mesh unix_ms=%lld draws=%u submitted=%d\n", | ||
| 3050 | pipeline_profile::unix_ms(), mesh_draws, int(submitted)); | ||
| 2802 | if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { | 3051 | if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { |
| 2803 | // not initialized after all: try again with the next submission | 3052 | // not initialized after all: try again with the next submission |
| 2804 | std::lock_guard lock(context_.storage_mutex_); | 3053 | std::lock_guard lock(context_.storage_mutex_); |
| @@ -2846,7 +3095,7 @@ private: | |||
| 2846 | // the queue (it keeps a single upload obligation). | 3095 | // the queue (it keeps a single upload obligation). |
| 2847 | if (bindless_commit) bindless_commit(submitted); | 3096 | if (bindless_commit) bindless_commit(submitted); |
| 2848 | tracker_lock.unlock(); | 3097 | tracker_lock.unlock(); |
| 2849 | return submitted ? ReplayResult::success : ReplayResult::unsupported; | 3098 | return submitted ? ReplayResult::success : queue_unsupported(__LINE__); |
| 2850 | } | 3099 | } |
| 2851 | 3100 | ||
| 2852 | void marker_now(DebugMarker::Kind kind, const char* label) { | 3101 | void marker_now(DebugMarker::Kind kind, const char* label) { |
| @@ -2874,6 +3123,7 @@ private: | |||
| 2874 | enum class Kind : std::uint8_t { batch, signal, marker }; | 3123 | enum class Kind : std::uint8_t { batch, signal, marker }; |
| 2875 | Kind kind = Kind::batch; | 3124 | Kind kind = Kind::batch; |
| 2876 | std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues | 3125 | std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues |
| 3126 | std::uint64_t execute_call = 0; // original ExecuteCommandLists call for a held batch | ||
| 2877 | std::vector<VkSemaphore> waits; | 3127 | std::vector<VkSemaphore> waits; |
| 2878 | std::vector<std::uint64_t> wait_values; | 3128 | std::vector<std::uint64_t> wait_values; |
| 2879 | std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call | 3129 | std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call |
| @@ -2958,7 +3208,7 @@ private: | |||
| 2958 | for (const CommandList& list : op.lists) lists.push_back(&list); | 3208 | for (const CommandList& list : op.lists) lists.push_back(&list); |
| 2959 | // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until | 3209 | // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until |
| 2960 | // the batch has been recorded and then, with the fences, until its submission has completed (below). | 3210 | // the batch has been recorded and then, with the fences, until its submission has completed (below). |
| 2961 | const ReplayResult result = execute_now(lists); | 3211 | const ReplayResult result = execute_now(lists, op.execute_call); |
| 2962 | if (result != ReplayResult::success) { | 3212 | if (result != ReplayResult::success) { |
| 2963 | int none = static_cast<int>(ReplayResult::success); | 3213 | int none = static_cast<int>(ReplayResult::success); |
| 2964 | held_failure_.compare_exchange_strong(none, static_cast<int>(result)); | 3214 | held_failure_.compare_exchange_strong(none, static_cast<int>(result)); |
| @@ -3184,7 +3434,8 @@ private: | |||
| 3184 | pending_bindings_.push_back(std::move(pending)); | 3434 | pending_bindings_.push_back(std::move(pending)); |
| 3185 | { | 3435 | { |
| 3186 | std::lock_guard lock(context_.submit_mutex()); | 3436 | std::lock_guard lock(context_.submit_mutex()); |
| 3187 | const auto result = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE); | 3437 | const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE), |
| 3438 | "vkQueueBindSparse"); | ||
| 3188 | if (result != VK_SUCCESS) { | 3439 | if (result != VK_SUCCESS) { |
| 3189 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); | 3440 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); |
| 3190 | pending_bindings_.pop_back(); | 3441 | pending_bindings_.pop_back(); |
| @@ -3206,7 +3457,8 @@ private: | |||
| 3206 | std::uint64_t completed() const { | 3457 | std::uint64_t completed() const { |
| 3207 | if (context_.is_device_lost()) return 0; | 3458 | if (context_.is_device_lost()) return 0; |
| 3208 | std::uint64_t done = 0; | 3459 | std::uint64_t done = 0; |
| 3209 | const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); | 3460 | const VkResult result = context_.observe_result( |
| 3461 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done), "vkGetSemaphoreCounterValue"); | ||
| 3210 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); | 3462 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); |
| 3211 | // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. | 3463 | // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. |
| 3212 | return result == VK_SUCCESS ? done : 0; | 3464 | return result == VK_SUCCESS ? done : 0; |
| @@ -3275,7 +3527,8 @@ private: | |||
| 3275 | info.semaphoreCount = 1; | 3527 | info.semaphoreCount = 1; |
| 3276 | info.pSemaphores = &progress_; | 3528 | info.pSemaphores = &progress_; |
| 3277 | info.pValues = &oldest; | 3529 | info.pValues = &oldest; |
| 3278 | return context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs); | 3530 | return context_.observe_result(context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs), |
| 3531 | "vkWaitSemaphores (queue progress)"); | ||
| 3279 | } | 3532 | } |
| 3280 | 3533 | ||
| 3281 | CommandSlot* acquire() { | 3534 | CommandSlot* acquire() { |
| @@ -3315,7 +3568,8 @@ private: | |||
| 3315 | return event; | 3568 | return event; |
| 3316 | } | 3569 | } |
| 3317 | 3570 | ||
| 3318 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { | 3571 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value, |
| 3572 | CheckpointSubmission* diagnostics = nullptr) { | ||
| 3319 | if (context_.is_device_lost()) return false; | 3573 | if (context_.is_device_lost()) return false; |
| 3320 | const std::uint64_t ticket = submitted_ + 1; | 3574 | const std::uint64_t ticket = submitted_ + 1; |
| 3321 | if (last_sparse_) { | 3575 | if (last_sparse_) { |
| @@ -3364,8 +3618,11 @@ private: | |||
| 3364 | submit.pCommandBuffers = &command_buffer; | 3618 | submit.pCommandBuffers = &command_buffer; |
| 3365 | submit.signalSemaphoreCount = signal_count; | 3619 | submit.signalSemaphoreCount = signal_count; |
| 3366 | submit.pSignalSemaphores = signals; | 3620 | submit.pSignalSemaphores = signals; |
| 3621 | // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. | ||
| 3622 | if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); | ||
| 3367 | const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); | 3623 | const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); |
| 3368 | res = context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence); | 3624 | res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence), |
| 3625 | "vkQueueSubmit"); | ||
| 3369 | context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); | 3626 | context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); |
| 3370 | if (res == VK_SUCCESS) { | 3627 | if (res == VK_SUCCESS) { |
| 3371 | context_.record_submit_locked(progress_, ticket); | 3628 | context_.record_submit_locked(progress_, ticket); |
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index 1477a9924..589cadffd 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h | |||
| @@ -12,8 +12,9 @@ | |||
| 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 | // bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4). | 14 | // bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4). |
| 15 | // These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays | 15 | // These are the default counts (BindlessFeatures::counts). size_bindings() sizes the sampled arrays of every |
| 16 | // from the device's limits instead; the shaders declare runtime arrays, so any count works for them. | 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. | ||
| 17 | // | 18 | // |
| 18 | // 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 |
| 19 | // 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 |
| @@ -38,6 +39,15 @@ | |||
| 38 | // 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 |
| 39 | // 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. |
| 40 | // | 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 | // | ||
| 41 | // Not thread-safe: the owner serialises calls. | 51 | // Not thread-safe: the owner serialises calls. |
| 42 | 52 | ||
| 43 | #ifndef VK_NO_PROTOTYPES | 53 | #ifndef VK_NO_PROTOTYPES |
| @@ -209,9 +219,13 @@ struct SetLayout { | |||
| 209 | }; | 219 | }; |
| 210 | 220 | ||
| 211 | // 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 |
| 212 | // roughly 4-8 MiB with 119137 descriptors when all MS classes and array bindings reach their limits. | 222 | // 5-10 MiB with 153697 descriptors when all MS classes and array bindings reach their limits (an RTX 5070). |
| 213 | inline constexpr std::uint32_t max_2d_images = 65536; | 223 | inline 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. | ||
| 214 | inline constexpr std::uint32_t max_2d_array_images = 16384; | 226 | inline constexpr std::uint32_t max_2d_array_images = 16384; |
| 227 | inline constexpr std::uint32_t max_3d_images = 4096; | ||
| 228 | inline constexpr std::uint32_t max_1d_images = 4096; | ||
| 215 | inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images | 229 | inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images |
| 216 | // 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 |
| 217 | // 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. |
| @@ -226,8 +240,9 @@ inline constexpr std::uint32_t growth_headroom = 64; | |||
| 226 | // 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. |
| 227 | // 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. |
| 228 | // 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). |
| 229 | // 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 |
| 230 | // 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 |
| 245 | // more), so it never shrinks step 1. | ||
| 231 | // A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never | 246 | // A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never |
| 232 | // gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256. | 247 | // gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256. |
| 233 | // The other bindings keep their default counts. | 248 | // The other bindings keep their default counts. |
| @@ -258,12 +273,16 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi | |||
| 258 | auto& counts = features.counts; | 273 | auto& counts = features.counts; |
| 259 | counts = default_counts(); | 274 | counts = default_counts(); |
| 260 | std::uint32_t images = 1, samplers = 1, storage = 1; | 275 | std::uint32_t images = 1, samplers = 1, storage = 1; |
| 261 | std::uint32_t array_images = bindings[sampled_binding(ImageDimension::dim_2d_array)].count; | 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)]; | ||
| 262 | // 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 |
| 263 | // take descriptors away. | 280 | // take descriptors away. |
| 264 | const auto apply = [&](bool final) { | 281 | const auto apply = [&](bool final) { |
| 265 | counts[sampled_binding(ImageDimension::dim_2d)] = images; | 282 | counts[sampled_binding(ImageDimension::dim_2d)] = images; |
| 266 | counts[sampled_binding(ImageDimension::dim_2d_array)] = array_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; | ||
| 267 | counts[sampler_binding] = samplers; | 286 | counts[sampler_binding] = samplers; |
| 268 | for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) { | 287 | for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) { |
| 269 | const auto dimension = ImageDimension(d); | 288 | const auto dimension = ImageDimension(d); |
| @@ -325,9 +344,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi | |||
| 325 | 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); |
| 326 | 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); |
| 327 | 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); |
| 328 | // A material can keep many array-layer and cube views alive at once. Grow them only out of | 347 | grow(arrays, std::max(arrays, max_2d_array_images), growth_headroom, set_limit); |
| 329 | // the remaining set budget, including any storage bindings that share their index range. | 348 | grow(volumes, std::max(volumes, max_3d_images), growth_headroom, set_limit); |
| 330 | grow(array_images, max_2d_array_images, growth_headroom, set_limit); | 349 | grow(lines, std::max(lines, max_1d_images), growth_headroom, set_limit); |
| 331 | apply(true); | 350 | apply(true); |
| 332 | return full; | 351 | return full; |
| 333 | } | 352 | } |
| @@ -336,14 +355,20 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi | |||
| 336 | 355 | ||
| 337 | class BindlessSet { | 356 | class BindlessSet { |
| 338 | public: | 357 | public: |
| 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. | ||
| 339 | BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, | 360 | BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, |
| 340 | BindlessFeatures features = {}, std::vector<std::uint32_t> families = {}) | 361 | BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a, |
| 341 | : device_(device), memory_(memory), features_(features), families_(std::move(families)) { | 362 | std::vector<std::uint32_t> families = {}) |
| 363 | : device_(device), memory_(memory), features_(features), families_(std::move(families)), | ||
| 364 | table_(64, descriptor_hash) { | ||
| 342 | 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(); |
| 343 | } | 366 | } |
| 344 | 367 | ||
| 345 | ~BindlessSet() { | 368 | ~BindlessSet() { |
| 346 | release_retired(); | 369 | release_retired(); |
| 370 | for (Generation& spare : spares_) destroy(spare); | ||
| 371 | spares_.clear(); | ||
| 347 | destroy(table_buffers_); | 372 | destroy(table_buffers_); |
| 348 | if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); | 373 | if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); |
| 349 | for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); | 374 | for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); |
| @@ -439,16 +464,20 @@ public: | |||
| 439 | 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, |
| 440 | const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { | 465 | const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { |
| 441 | const auto& used = image_used_[std::uint32_t(dimension)]; | 466 | const auto& used = image_used_[std::uint32_t(dimension)]; |
| 442 | if (index && index < used.size() && used[index]) | 467 | if (index && index < used.size() && used[index] == in_use) |
| 443 | write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); | 468 | write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); |
| 444 | } | 469 | } |
| 445 | 470 | ||
| 446 | // 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. | ||
| 447 | void remove_image(ImageDimension dimension, std::uint32_t index) { | 475 | void remove_image(ImageDimension dimension, std::uint32_t index) { |
| 448 | auto& used = image_used_[std::uint32_t(dimension)]; | 476 | auto& used = image_used_[std::uint32_t(dimension)]; |
| 449 | if (!index || index >= used.size() || !used[index]) return; | 477 | if (!index || index >= used.size() || used[index] != in_use) return; |
| 450 | 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); |
| 451 | used[index] = 0; | 479 | used[index] = table_dirty_ ? held : 0; |
| 480 | if (table_dirty_) held_images_.push_back({dimension, index}); | ||
| 452 | } | 481 | } |
| 453 | 482 | ||
| 454 | // 0 when the sampler array is full. | 483 | // 0 when the sampler array is full. |
| @@ -459,9 +488,10 @@ public: | |||
| 459 | } | 488 | } |
| 460 | 489 | ||
| 461 | void remove_sampler(std::uint32_t index) { | 490 | void remove_sampler(std::uint32_t index) { |
| 462 | if (!index || index >= sampler_used_.size() || !sampler_used_[index]) return; | 491 | if (!index || index >= sampler_used_.size() || sampler_used_[index] != in_use) return; |
| 463 | write_sampler(index, fallback_sampler_); | 492 | write_sampler(index, fallback_sampler_); |
| 464 | sampler_used_[index] = 0; | 493 | sampler_used_[index] = table_dirty_ ? held : 0; |
| 494 | if (table_dirty_) held_samplers_.push_back(index); | ||
| 465 | } | 495 | } |
| 466 | 496 | ||
| 467 | // 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 |
| @@ -504,7 +534,10 @@ public: | |||
| 504 | void table_upload_result(bool submitted) { | 534 | void table_upload_result(bool submitted) { |
| 505 | if (!upload_in_flight_) return; | 535 | if (!upload_in_flight_) return; |
| 506 | upload_in_flight_ = false; | 536 | upload_in_flight_ = false; |
| 507 | if (submitted) return; | 537 | if (submitted) { |
| 538 | table_on_gpu_ = true; // the current buffers hold a table the GPU was given | ||
| 539 | return; | ||
| 540 | } | ||
| 508 | table_dirty_ = true; | 541 | table_dirty_ = true; |
| 509 | force_full_upload_ = true; | 542 | force_full_upload_ = true; |
| 510 | } | 543 | } |
| @@ -513,17 +546,42 @@ public: | |||
| 513 | // 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 |
| 514 | // 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 |
| 515 | // 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() |
| 516 | // 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. |
| 517 | // 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 |
| 518 | 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; | ||
| 519 | bool replaced = false; | 561 | bool replaced = false; |
| 520 | bool written = true; | 562 | bool written = true; |
| 521 | const bool must_replace = flush_replaces_table(); | 563 | const bool must_replace = flush_replaces_table(); |
| 564 | last_flush_degraded_ = false; | ||
| 522 | 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 | } | ||
| 523 | last_flush_replaced_ = replaced; | 574 | last_flush_replaced_ = replaced; |
| 524 | // 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 |
| 525 | // 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 |
| 526 | 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 | } | ||
| 527 | for (const Pending& pending : pending_) { | 585 | for (const Pending& pending : pending_) { |
| 528 | 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; |
| 529 | shadow_[pending.binding][pending.index] = pending.info; | 587 | shadow_[pending.binding][pending.index] = pending.info; |
| @@ -546,17 +604,29 @@ public: | |||
| 546 | } | 604 | } |
| 547 | pending_.clear(); | 605 | pending_.clear(); |
| 548 | pending_slots_.clear(); | 606 | pending_slots_.clear(); |
| 549 | 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; | ||
| 550 | } | 615 | } |
| 551 | 616 | ||
| 552 | // 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 |
| 553 | // 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. | ||
| 554 | void release_retired(std::uint64_t completed = UINT64_MAX) { | 621 | void release_retired(std::uint64_t completed = UINT64_MAX) { |
| 555 | std::size_t kept = 0; | 622 | std::size_t kept = 0; |
| 556 | for (auto& generation : retired_) { | 623 | for (auto& generation : retired_) { |
| 557 | if (generation.ticket <= completed) { | 624 | if (generation.ticket <= completed) { |
| 558 | destroy(generation.buffers); | 625 | if (spares_.size() < max_spares && generation.pool && generation.buffers.staging.mapped && |
| 559 | 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); | ||
| 560 | } else { | 630 | } else { |
| 561 | retired_[kept++] = generation; | 631 | retired_[kept++] = generation; |
| 562 | } | 632 | } |
| @@ -573,11 +643,32 @@ public: | |||
| 573 | std::uint64_t generations_made() const { return generations_made_; } | 643 | std::uint64_t generations_made() const { return generations_made_; } |
| 574 | std::size_t retired_count() const { return retired_.size(); } | 644 | std::size_t retired_count() const { return retired_.size(); } |
| 575 | 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 | |||
| 576 | private: | 666 | private: |
| 577 | struct Functions { | 667 | struct Functions { |
| 578 | #define LEONIDA_BINDLESS_FUNCTIONS(X) \ | 668 | #define LEONIDA_BINDLESS_FUNCTIONS(X) \ |
| 579 | X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ | 669 | X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ |
| 580 | X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) \ | 670 | X(vkDestroyDescriptorPool) X(vkResetDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ |
| 671 | X(vkCreateBuffer) \ | ||
| 581 | X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ | 672 | X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ |
| 582 | X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ | 673 | X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ |
| 583 | X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ | 674 | X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ |
| @@ -608,6 +699,7 @@ private: | |||
| 608 | VkDeviceMemory memory = VK_NULL_HANDLE; | 699 | VkDeviceMemory memory = VK_NULL_HANDLE; |
| 609 | void* mapped = nullptr; | 700 | void* mapped = nullptr; |
| 610 | std::size_t size = 0; | 701 | std::size_t size = 0; |
| 702 | bool device_local = false; // the memory is DEVICE_LOCAL | ||
| 611 | }; | 703 | }; |
| 612 | 704 | ||
| 613 | // 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. |
| @@ -616,6 +708,13 @@ private: | |||
| 616 | TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT | 708 | TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT |
| 617 | }; | 709 | }; |
| 618 | 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 | |||
| 619 | struct Pending { | 718 | struct Pending { |
| 620 | std::uint32_t binding; | 719 | std::uint32_t binding; |
| 621 | std::uint32_t index; | 720 | std::uint32_t index; |
| @@ -623,6 +722,9 @@ private: | |||
| 623 | }; | 722 | }; |
| 624 | 723 | ||
| 625 | static constexpr std::uint32_t dimensions = 7, 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; | ||
| 626 | 728 | ||
| 627 | // 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. |
| 628 | 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) { |
| @@ -670,21 +772,35 @@ private: | |||
| 670 | pool_info.maxSets = 1; | 772 | pool_info.maxSets = 1; |
| 671 | pool_info.poolSizeCount = pool_size_count_; | 773 | pool_info.poolSizeCount = pool_size_count_; |
| 672 | pool_info.pPoolSizes = pool_sizes_.data(); | 774 | pool_info.pPoolSizes = pool_sizes_.data(); |
| 673 | 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) { | ||
| 674 | pool = VK_NULL_HANDLE; | 777 | pool = VK_NULL_HANDLE; |
| 778 | note_failure("descriptor set", result); | ||
| 675 | return false; | 779 | return false; |
| 676 | } | 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 { | ||
| 677 | VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; | 788 | VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; |
| 678 | set_info.descriptorPool = pool; | 789 | set_info.descriptorPool = pool; |
| 679 | set_info.descriptorSetCount = 1; | 790 | set_info.descriptorSetCount = 1; |
| 680 | set_info.pSetLayouts = &layout_; | 791 | set_info.pSetLayouts = &layout_; |
| 681 | if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set) == VK_SUCCESS) return true; | 792 | const VkResult result = vk_.vkAllocateDescriptorSets(device_, &set_info, &set); |
| 682 | vk_.vkDestroyDescriptorPool(device_, pool, nullptr); | 793 | if (result == VK_SUCCESS) return true; |
| 683 | pool = VK_NULL_HANDLE; | ||
| 684 | set = VK_NULL_HANDLE; | 794 | set = VK_NULL_HANDLE; |
| 795 | note_failure("descriptor set", result); | ||
| 685 | return false; | 796 | return false; |
| 686 | } | 797 | } |
| 687 | 798 | ||
| 799 | void note_failure(const char* what, VkResult result) const { | ||
| 800 | last_failure_ = what; | ||
| 801 | last_failure_result_ = result; | ||
| 802 | } | ||
| 803 | |||
| 688 | // 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 |
| 689 | // 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. |
| 690 | void write_shadow() const { | 806 | void write_shadow() const { |
| @@ -781,7 +897,11 @@ private: | |||
| 781 | return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; | 897 | return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; |
| 782 | } | 898 | } |
| 783 | 899 | ||
| 784 | 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"; | ||
| 785 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; | 905 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; |
| 786 | info.size = bytes; | 906 | info.size = bytes; |
| 787 | info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | | 907 | info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | |
| @@ -789,29 +909,42 @@ private: | |||
| 789 | TableBuffer made; | 909 | TableBuffer made; |
| 790 | made.size = bytes; | 910 | made.size = bytes; |
| 791 | share_across_queue_families(info, families_); | 911 | share_across_queue_families(info, families_); |
| 792 | if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; | 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 | } | ||
| 793 | VkMemoryRequirements requirements{}; | 917 | VkMemoryRequirements requirements{}; |
| 794 | vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); | 918 | vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); |
| 795 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | 919 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; |
| 796 | allocation.allocationSize = requirements.size; | 920 | allocation.allocationSize = requirements.size; |
| 797 | allocation.memoryTypeIndex = | 921 | const auto allocate = [&](std::uint32_t type) { |
| 798 | device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) | 922 | if (type == 0xffffffffu) return VK_ERROR_OUT_OF_DEVICE_MEMORY; |
| 799 | : memory_type(requirements.memoryTypeBits, | 923 | allocation.memoryTypeIndex = type; |
| 800 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); | 924 | const VkResult result = vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory); |
| 801 | if (device_local && allocation.memoryTypeIndex == 0xffffffffu) | 925 | if (result != VK_SUCCESS) made.memory = VK_NULL_HANDLE; |
| 802 | allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, | 926 | return result; |
| 803 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | | 927 | }; |
| 804 | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); | 928 | const std::uint32_t local = device_local |
| 805 | if (got_device_local) | 929 | ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) |
| 806 | *got_device_local = allocation.memoryTypeIndex != 0xffffffffu && | 930 | : 0xffffffffu; |
| 807 | (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 & | ||
| 808 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; | 941 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; |
| 809 | bool ready = allocation.memoryTypeIndex != 0xffffffffu && | 942 | result = vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0); |
| 810 | vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && | 943 | } |
| 811 | vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS; | 944 | if (result == VK_SUCCESS && !device_local) |
| 812 | if (ready && !device_local) | 945 | result = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped); |
| 813 | ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; | 946 | if (result != VK_SUCCESS) { |
| 814 | if (!ready) { | 947 | note_failure(what, result); |
| 815 | destroy(made); | 948 | destroy(made); |
| 816 | return false; | 949 | return false; |
| 817 | } | 950 | } |
| @@ -830,17 +963,55 @@ private: | |||
| 830 | destroy(buffers.table); | 963 | destroy(buffers.table); |
| 831 | } | 964 | } |
| 832 | 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 | |||
| 833 | bool create_table_buffers() { | 1004 | bool create_table_buffers() { |
| 834 | const std::size_t bytes = table_.size_bytes(); | 1005 | const std::size_t bytes = table_.size_bytes(); |
| 835 | TableBuffers made; | 1006 | TableBuffers made; |
| 836 | bool device_local = false; | 1007 | if (!create(made.table, bytes, true) || !create(made.staging, bytes, false)) { |
| 837 | if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) { | ||
| 838 | destroy(made); | 1008 | destroy(made); |
| 839 | return false; | 1009 | return false; |
| 840 | } | 1010 | } |
| 841 | table_buffers_ = made; | 1011 | table_buffers_ = made; |
| 842 | table_device_local_ = device_local; | 1012 | table_device_local_ = made.table.device_local; |
| 843 | 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; | ||
| 844 | table_dirty_ = existing_entries_changed_ = false; | 1015 | table_dirty_ = existing_entries_changed_ = false; |
| 845 | return true; | 1016 | return true; |
| 846 | } | 1017 | } |
| @@ -858,15 +1029,11 @@ private: | |||
| 858 | TableBuffers larger; | 1029 | TableBuffers larger; |
| 859 | VkDescriptorPool pool = VK_NULL_HANDLE; | 1030 | VkDescriptorPool pool = VK_NULL_HANDLE; |
| 860 | VkDescriptorSet set = VK_NULL_HANDLE; | 1031 | VkDescriptorSet set = VK_NULL_HANDLE; |
| 861 | bool device_local = false; | 1032 | if (!make_generation(bytes, larger, pool, set)) return false; |
| 862 | if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false) || | 1033 | table_device_local_ = larger.table.device_local; |
| 863 | !make_set(pool, set)) { | ||
| 864 | destroy(larger); | ||
| 865 | return false; | ||
| 866 | } | ||
| 867 | table_device_local_ = device_local; | ||
| 868 | retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); | 1034 | retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); |
| 869 | table_buffers_ = larger; | 1035 | table_buffers_ = larger; |
| 1036 | table_on_gpu_ = false; // until this generation's upload is submitted (table_upload_result) | ||
| 870 | pool_ = pool; | 1037 | pool_ = pool; |
| 871 | set_ = set; | 1038 | set_ = set; |
| 872 | write_table_binding(table_buffers_.table.buffer); | 1039 | write_table_binding(table_buffers_.table.buffer); |
| @@ -922,6 +1089,25 @@ private: | |||
| 922 | return true; | 1089 | return true; |
| 923 | } | 1090 | } |
| 924 | 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 | |||
| 925 | // 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 |
| 926 | // 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. |
| 927 | 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, |
| @@ -1057,25 +1243,30 @@ private: | |||
| 1057 | bool fallbacks_ready_ = false; | 1243 | bool fallbacks_ready_ = false; |
| 1058 | std::array<std::vector<std::uint8_t>, dimensions> image_used_; | 1244 | std::array<std::vector<std::uint8_t>, dimensions> image_used_; |
| 1059 | 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_; | ||
| 1060 | std::vector<Pending> pending_; | 1248 | std::vector<Pending> pending_; |
| 1061 | 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_ |
| 1062 | DescriptorTable table_{64}; | 1250 | DescriptorTable table_; // 64 slots, and the device's hash kind, from the constructor |
| 1063 | TableBuffers table_buffers_; | 1251 | TableBuffers table_buffers_; |
| 1064 | 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) | ||
| 1065 | bool table_device_local_ = false; | 1254 | bool table_device_local_ = false; |
| 1066 | bool table_dirty_ = false; // the table differs from the buffer | 1255 | bool table_dirty_ = false; // the table differs from the buffer |
| 1067 | bool existing_entries_changed_ = false; // ... and not only by entries added | 1256 | bool existing_entries_changed_ = false; // ... and not only by entries added |
| 1068 | 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 |
| 1069 | 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 |
| 1070 | struct Generation { // what a replaced table leaves for release_retired() | ||
| 1071 | TableBuffers buffers; | ||
| 1072 | VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set | ||
| 1073 | VkDescriptorSet set = VK_NULL_HANDLE; | ||
| 1074 | std::uint64_t ticket = 0; | ||
| 1075 | }; | ||
| 1076 | std::vector<Generation> retired_; | 1259 | std::vector<Generation> retired_; |
| 1260 | std::vector<Generation> spares_; // released generations kept for reuse (release_retired) | ||
| 1077 | std::uint64_t generations_made_ = 0; | 1261 | std::uint64_t generations_made_ = 0; |
| 1078 | 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; | ||
| 1079 | std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{}; | 1270 | std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{}; |
| 1080 | std::uint32_t pool_size_count_ = 0; | 1271 | std::uint32_t pool_size_count_ = 0; |
| 1081 | // 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 | |||
| 21 | namespace leonida { | ||
| 22 | |||
| 23 | struct DeviceFaultExtensions { | ||
| 24 | bool fault = false; | ||
| 25 | bool checkpoints = false; | ||
| 26 | bool diagnostics_config = false; | ||
| 27 | }; | ||
| 28 | |||
| 29 | // Owns the feature structures until vkCreateDevice returns. | ||
| 30 | struct 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 | |||
| 75 | enum class CheckpointKind : std::uint8_t { draw = 1, dispatch, copy, resolve, clear }; | ||
| 76 | |||
| 77 | struct 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 | |||
| 116 | using CheckpointShaders = std::array<const char*, 3>; // Immutable ShaderLibrary names, valid until context teardown. | ||
| 117 | |||
| 118 | struct CheckpointPipeline { | ||
| 119 | VkPipeline handle = VK_NULL_HANDLE; | ||
| 120 | std::uintptr_t id = 0; | ||
| 121 | CheckpointShaders shaders{}; | ||
| 122 | }; | ||
| 123 | |||
| 124 | struct 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. | ||
| 134 | struct 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 | |||
| 148 | struct 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 | |||
| 166 | struct 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. | ||
| 203 | class SubmissionProgressWatch { | ||
| 204 | public: | ||
| 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 | |||
| 221 | private: | ||
| 222 | State state_ = State::idle; | ||
| 223 | std::uint64_t retired_ = 0; | ||
| 224 | Clock::time_point since_{}; | ||
| 225 | bool reported_ = false; | ||
| 226 | }; | ||
| 227 | |||
| 228 | class DeviceFaultDiagnostics { | ||
| 229 | public: | ||
| 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 | |||
| 286 | private: | ||
| 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_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. | ||
| 61 | inline 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 efdbd583d..f01167cf4 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h | |||
| @@ -27,6 +27,8 @@ | |||
| 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" | ||
| 30 | #include "present_dump.h" | 32 | #include "present_dump.h" |
| 31 | 33 | ||
| 32 | // 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. |
| @@ -186,6 +188,11 @@ public: | |||
| 186 | 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)); |
| 187 | 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", |
| 188 | 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 | } | ||
| 189 | } | 196 | } |
| 190 | ok_ = recreate(true, false); | 197 | ok_ = recreate(true, false); |
| 191 | if (!ok_ && capture_to_disk_) { | 198 | if (!ok_ && capture_to_disk_) { |
| @@ -205,7 +212,7 @@ public: | |||
| 205 | const VkDevice device = context_.device(); | 212 | const VkDevice device = context_.device(); |
| 206 | { | 213 | { |
| 207 | std::lock_guard lock(context_.submit_mutex()); | 214 | std::lock_guard lock(context_.submit_mutex()); |
| 208 | vk.vkQueueWaitIdle(queue_); | 215 | context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); |
| 209 | // 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. |
| 210 | // Keep that implicit idle serialized with submits from every context queue. | 217 | // Keep that implicit idle serialized with submits from every context queue. |
| 211 | release(swapchain_); | 218 | release(swapchain_); |
| @@ -220,6 +227,7 @@ public: | |||
| 220 | if (frame.done) vkDestroyFence_(device, frame.done, nullptr); | 227 | if (frame.done) vkDestroyFence_(device, frame.done, nullptr); |
| 221 | if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); | 228 | if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); |
| 222 | } | 229 | } |
| 230 | if (probe_fence_) vkDestroyFence_(device, probe_fence_, nullptr); // LOCAL DIAGNOSTIC | ||
| 223 | if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); | 231 | if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); |
| 224 | if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); | 232 | if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); |
| 225 | } | 233 | } |
| @@ -341,6 +349,7 @@ public: | |||
| 341 | bool enable_capture() { | 349 | bool enable_capture() { |
| 342 | std::lock_guard lock(present_mutex_); | 350 | std::lock_guard lock(present_mutex_); |
| 343 | if (!ok_) return false; | 351 | if (!ok_) return false; |
| 352 | splash_capture_only_ = false; | ||
| 344 | capture_ = true; | 353 | capture_ = true; |
| 345 | stale_ = true; | 354 | stale_ = true; |
| 346 | if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { | 355 | if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { |
| @@ -350,6 +359,9 @@ public: | |||
| 350 | return true; | 359 | return true; |
| 351 | } | 360 | } |
| 352 | 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 | |||
| 353 | // 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). |
| 354 | // 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 |
| 355 | // 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 |
| @@ -358,7 +370,8 @@ public: | |||
| 358 | std::lock_guard lock(present_mutex_); | 370 | std::lock_guard lock(present_mutex_); |
| 359 | if (!capture_ || !capture_ptr_ || !captured_) return false; | 371 | if (!capture_ || !capture_ptr_ || !captured_) return false; |
| 360 | const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; | 372 | const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; |
| 361 | 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) | ||
| 362 | return false; | 375 | return false; |
| 363 | 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); |
| 364 | if (extent) *extent = captured_extent_; | 377 | if (extent) *extent = captured_extent_; |
| @@ -394,6 +407,9 @@ public: | |||
| 394 | if (source_rect) pending.rect = *source_rect; | 407 | if (source_rect) pending.rect = *source_rect; |
| 395 | if (planes) pending.planes = *planes; | 408 | if (planes) pending.planes = *planes; |
| 396 | 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()); | ||
| 397 | last_tore_ = false; | 413 | last_tore_ = false; |
| 398 | context_.holds().after_held(this, [this] { run_deferred(); }); | 414 | context_.holds().after_held(this, [this] { run_deferred(); }); |
| 399 | return VK_SUCCESS; | 415 | return VK_SUCCESS; |
| @@ -456,6 +472,7 @@ private: | |||
| 456 | 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, |
| 457 | bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { | 473 | bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { |
| 458 | last_tore_ = false; | 474 | last_tore_ = false; |
| 475 | probe_path(binding, source, planes); // LOCAL DIAGNOSTIC | ||
| 459 | if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; | 476 | if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; |
| 460 | 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 |
| 461 | // 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). |
| @@ -479,7 +496,7 @@ private: | |||
| 479 | 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_) { |
| 480 | // 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 |
| 481 | // recreate is tried again at the next present. | 498 | // recreate is tried again at the next present. |
| 482 | 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; |
| 483 | } | 500 | } |
| 484 | if (!swapchain_) { // minimised: try again next frame | 501 | if (!swapchain_) { // minimised: try again next frame |
| 485 | stale_ = true; | 502 | stale_ = true; |
| @@ -493,7 +510,9 @@ private: | |||
| 493 | auto& vk = context_.vk; | 510 | auto& vk = context_.vk; |
| 494 | const VkDevice device = context_.device(); | 511 | const VkDevice device = context_.device(); |
| 495 | Frame& frame = frames_[frame_index_ % frames_.size()]; | 512 | Frame& frame = frames_[frame_index_ % frames_.size()]; |
| 496 | 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) | ||
| 497 | return stop(waited); | 516 | return stop(waited); |
| 498 | // 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. |
| 499 | 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); |
| @@ -501,7 +520,7 @@ private: | |||
| 501 | std::uint32_t image = 0; | 520 | std::uint32_t image = 0; |
| 502 | VkResult acquired = acquire(frame.acquired, &image); | 521 | VkResult acquired = acquire(frame.acquired, &image); |
| 503 | if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { | 522 | if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { |
| 504 | if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; | 523 | if (!recreate_for_present(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; |
| 505 | if (!swapchain_) { // minimised since the last present: skipped, as above | 524 | if (!swapchain_) { // minimised since the last present: skipped, as above |
| 506 | captured_ = false; | 525 | captured_ = false; |
| 507 | return VK_SUCCESS; | 526 | return VK_SUCCESS; |
| @@ -572,7 +591,8 @@ private: | |||
| 572 | plane_rollbacks[i].layout); | 591 | plane_rollbacks[i].layout); |
| 573 | }; | 592 | }; |
| 574 | 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() |
| 575 | 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) { | ||
| 576 | rollback(); | 596 | rollback(); |
| 577 | return stop(reset); | 597 | return stop(reset); |
| 578 | } | 598 | } |
| @@ -604,15 +624,34 @@ private: | |||
| 604 | const bool tearing = false; | 624 | const bool tearing = false; |
| 605 | (void)tear; | 625 | (void)tear; |
| 606 | #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 | } | ||
| 607 | VkResult submitted, result = VK_SUCCESS; | 633 | VkResult submitted, result = VK_SUCCESS; |
| 608 | { | 634 | { |
| 609 | std::lock_guard lock(context_.submit_mutex()); | 635 | std::lock_guard lock(context_.submit_mutex()); |
| 610 | 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(); | ||
| 611 | if (submitted != VK_SUCCESS) rollback(); | 639 | if (submitted != VK_SUCCESS) rollback(); |
| 612 | // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission | 640 | if (submitted == VK_SUCCESS && inspect) { |
| 613 | // 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 | } | ||
| 614 | if (tracker_lock.owns_lock()) tracker_lock.unlock(); | 644 | if (tracker_lock.owns_lock()) tracker_lock.unlock(); |
| 615 | 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 | } | ||
| 616 | } | 655 | } |
| 617 | if (submitted != VK_SUCCESS) return give_back(frame, submitted); | 656 | if (submitted != VK_SUCCESS) return give_back(frame, submitted); |
| 618 | ++frame_index_; | 657 | ++frame_index_; |
| @@ -657,6 +696,310 @@ private: | |||
| 657 | } | 696 | } |
| 658 | 697 | ||
| 659 | private: | 698 | private: |
| 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, ©); | ||
| 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 | |||
| 660 | struct Frame { | 1003 | struct Frame { |
| 661 | VkCommandBuffer commands = VK_NULL_HANDLE; | 1004 | VkCommandBuffer commands = VK_NULL_HANDLE; |
| 662 | VkFence done = VK_NULL_HANDLE; | 1005 | VkFence done = VK_NULL_HANDLE; |
| @@ -664,6 +1007,9 @@ private: | |||
| 664 | 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 |
| 665 | }; | 1008 | }; |
| 666 | 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 | |||
| 667 | // 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. |
| 668 | bool presentable(ResourceId source) { | 1014 | bool presentable(ResourceId source) { |
| 669 | 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) |
| @@ -676,7 +1022,8 @@ private: | |||
| 676 | // 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. |
| 677 | VkResult give_back(Frame& frame, VkResult failure) { | 1023 | VkResult give_back(Frame& frame, VkResult failure) { |
| 678 | const VkDevice device = context_.device(); | 1024 | const VkDevice device = context_.device(); |
| 679 | 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); | ||
| 680 | const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; | 1027 | const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; |
| 681 | VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; | 1028 | VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; |
| 682 | submit_info.waitSemaphoreCount = 1; | 1029 | submit_info.waitSemaphoreCount = 1; |
| @@ -685,7 +1032,8 @@ private: | |||
| 685 | VkResult submitted; | 1032 | VkResult submitted; |
| 686 | { | 1033 | { |
| 687 | std::lock_guard lock(context_.submit_mutex()); | 1034 | std::lock_guard lock(context_.submit_mutex()); |
| 688 | 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)"); | ||
| 689 | } | 1037 | } |
| 690 | if (submitted != VK_SUCCESS) return stop(failure); | 1038 | if (submitted != VK_SUCCESS) return stop(failure); |
| 691 | stale_ = true; | 1039 | stale_ = true; |
| @@ -716,7 +1064,8 @@ private: | |||
| 716 | const VkDevice device = context_.device(); | 1064 | const VkDevice device = context_.device(); |
| 717 | { | 1065 | { |
| 718 | std::lock_guard lock(context_.submit_mutex()); | 1066 | std::lock_guard lock(context_.submit_mutex()); |
| 719 | 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)"); | ||
| 720 | release(swapchain_); | 1069 | release(swapchain_); |
| 721 | } | 1070 | } |
| 722 | swapchain_ = VK_NULL_HANDLE; | 1071 | swapchain_ = VK_NULL_HANDLE; |
| @@ -805,7 +1154,8 @@ private: | |||
| 805 | return true; | 1154 | return true; |
| 806 | { | 1155 | { |
| 807 | std::lock_guard lock(context_.submit_mutex()); | 1156 | std::lock_guard lock(context_.submit_mutex()); |
| 808 | 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)"); | ||
| 809 | } | 1159 | } |
| 810 | bool changed = false; | 1160 | bool changed = false; |
| 811 | return composer_->ensure_target(extent_, changed); | 1161 | return composer_->ensure_target(extent_, changed); |
| @@ -930,8 +1280,9 @@ private: | |||
| 930 | 1280 | ||
| 931 | VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) { | 1281 | VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) { |
| 932 | for (;;) { | 1282 | for (;;) { |
| 933 | const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, | 1283 | const VkResult result = context_.observe_result( |
| 934 | VK_NULL_HANDLE, image); | 1284 | vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, VK_NULL_HANDLE, image), |
| 1285 | "vkAcquireNextImageKHR"); | ||
| 935 | if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; | 1286 | if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; |
| 936 | if (should_abort()) return VK_NOT_READY; | 1287 | if (should_abort()) return VK_NOT_READY; |
| 937 | } | 1288 | } |
| @@ -1063,7 +1414,8 @@ private: | |||
| 1063 | 1414 | ||
| 1064 | VkResult finish_pending_capture() { | 1415 | VkResult finish_pending_capture() { |
| 1065 | if (!pending_capture_) return VK_SUCCESS; | 1416 | if (!pending_capture_) return VK_SUCCESS; |
| 1066 | 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)"); | ||
| 1067 | pending_capture_ = VK_NULL_HANDLE; | 1419 | pending_capture_ = VK_NULL_HANDLE; |
| 1068 | if (waited == VK_SUCCESS) write_capture(); | 1420 | if (waited == VK_SUCCESS) write_capture(); |
| 1069 | return waited; | 1421 | return waited; |
| @@ -1158,7 +1510,8 @@ private: | |||
| 1158 | const VkDevice device = context_.device(); | 1510 | const VkDevice device = context_.device(); |
| 1159 | { | 1511 | { |
| 1160 | std::lock_guard lock(context_.submit_mutex()); | 1512 | std::lock_guard lock(context_.submit_mutex()); |
| 1161 | 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)"); | ||
| 1162 | } | 1515 | } |
| 1163 | if (finish_pending_capture() != VK_SUCCESS) return false; | 1516 | if (finish_pending_capture() != VK_SUCCESS) return false; |
| 1164 | stale_ = true; // until this succeeds | 1517 | stale_ = true; // until this succeeds |
| @@ -1303,7 +1656,8 @@ private: | |||
| 1303 | swapchain_ = VK_NULL_HANDLE; | 1656 | swapchain_ = VK_NULL_HANDLE; |
| 1304 | info.oldSwapchain = old; | 1657 | info.oldSwapchain = old; |
| 1305 | VkSwapchainKHR fresh = VK_NULL_HANDLE; | 1658 | VkSwapchainKHR fresh = VK_NULL_HANDLE; |
| 1306 | const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); | 1659 | const VkResult created = context_.observe_result(vkCreateSwapchainKHR_(device, &info, nullptr, &fresh), |
| 1660 | "vkCreateSwapchainKHR"); | ||
| 1307 | { | 1661 | { |
| 1308 | std::lock_guard lock(context_.submit_mutex()); | 1662 | std::lock_guard lock(context_.submit_mutex()); |
| 1309 | 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 |
| @@ -1456,6 +1810,10 @@ private: | |||
| 1456 | 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 |
| 1457 | std::map<VkFormat, VkFormatFeatureFlags> features_; | 1811 | std::map<VkFormat, VkFormatFeatureFlags> features_; |
| 1458 | 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; | ||
| 1459 | bool capture_ = false; | 1817 | bool capture_ = false; |
| 1460 | present_dump::PresentDump dump_; | 1818 | present_dump::PresentDump dump_; |
| 1461 | bool dump_pq_ = false; | 1819 | bool dump_pq_ = false; |
| @@ -1497,3 +1855,5 @@ private: | |||
| 1497 | }; | 1855 | }; |
| 1498 | 1856 | ||
| 1499 | } // 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 | |||
| 5 | namespace leonida { | ||
| 6 | |||
| 7 | inline 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. | ||
| 30 | inline 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. | ||
| 41 | inline 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 cdaf89321..1bea0ea33 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | #include <atomic> | ||
| 2 | #pragma once | 1 | #pragma once |
| 2 | #include <atomic> | ||
| 3 | #include <cfloat> | 3 | #include <cfloat> |
| 4 | #include <cstdlib> | ||
| 4 | 5 | ||
| 5 | #include "resource_tiling.h" | 6 | #include "resource_tiling.h" |
| 6 | 7 | ||
| @@ -33,6 +34,8 @@ | |||
| 33 | // 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. |
| 34 | 35 | ||
| 35 | #include "command_list.h" | 36 | #include "command_list.h" |
| 37 | #include "deferred_image_binding.h" | ||
| 38 | #include "vulkan_device_fault.h" | ||
| 36 | #include "depth24.h" | 39 | #include "depth24.h" |
| 37 | #include "quad_index_expand.h" | 40 | #include "quad_index_expand.h" |
| 38 | #include "rect_list_geometry.h" | 41 | #include "rect_list_geometry.h" |
| @@ -45,9 +48,11 @@ | |||
| 45 | 48 | ||
| 46 | #include <algorithm> | 49 | #include <algorithm> |
| 47 | #include <array> | 50 | #include <array> |
| 51 | #include <atomic> | ||
| 48 | #include <cmath> | 52 | #include <cmath> |
| 49 | #include <cstdint> | 53 | #include <cstdint> |
| 50 | #include <cstdio> | 54 | #include <cstdio> |
| 55 | #include <cstdlib> | ||
| 51 | #include <functional> | 56 | #include <functional> |
| 52 | #include <limits> | 57 | #include <limits> |
| 53 | #include <map> | 58 | #include <map> |
| @@ -102,6 +107,8 @@ struct ResourceBinding { | |||
| 102 | 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 |
| 103 | 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 |
| 104 | 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. | ||
| 105 | bool xbox_depth16_stencil8=false; | 112 | bool xbox_depth16_stencil8=false; |
| 106 | bool rgba4_render_fallback=false; | 113 | bool rgba4_render_fallback=false; |
| 107 | // The two independently addressable storage images of an Xbox depth/stencil UAV. | 114 | // The two independently addressable storage images of an Xbox depth/stencil UAV. |
| @@ -228,7 +235,10 @@ inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) { | |||
| 228 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, | 235 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, |
| 229 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, | 236 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, |
| 230 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 237 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| 231 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, | 238 | // CLEAR as well: two D3D12 copy-scope commands are recorded as Vulkan clear commands, WriteBufferImmediate |
| 239 | // as vkCmdUpdateBuffer and ResolveQueryData's never-written queries as vkCmdFillBuffer, and synchronization2 | ||
| 240 | // puts both in the CLEAR stage, not COPY. | ||
| 241 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT}, | ||
| 232 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, | 242 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, |
| 233 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, | 243 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, |
| 234 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 244 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| @@ -518,6 +528,21 @@ inline bool two_planes(const ResourceBinding& resource) { | |||
| 518 | // 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 |
| 519 | // 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 |
| 520 | // 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. | ||
| 536 | inline 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 | |||
| 521 | inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { | 546 | inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { |
| 522 | const auto family = [](VkFormat format) -> int { | 547 | const auto family = [](VkFormat format) -> int { |
| 523 | switch (format) { | 548 | switch (format) { |
| @@ -773,7 +798,12 @@ struct ComputePipeline { | |||
| 773 | VkPipelineLayout layout = VK_NULL_HANDLE; | 798 | VkPipelineLayout layout = VK_NULL_HANDLE; |
| 774 | std::uint64_t code_base = 0; | 799 | std::uint64_t code_base = 0; |
| 775 | 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 |
| 776 | std::function<VkPipeline()> materialize; | 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 | ||
| 777 | }; | 807 | }; |
| 778 | 808 | ||
| 779 | // 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 |
| @@ -791,6 +821,7 @@ struct GraphicsPipeline { | |||
| 791 | std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time | 821 | std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time |
| 792 | std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) | 822 | std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) |
| 793 | bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only | 823 | bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only |
| 824 | bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT | ||
| 794 | // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots | 825 | // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots |
| 795 | // 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 |
| 796 | // and stencil. Null when it cannot be built. | 827 | // and stencil. Null when it cannot be built. |
| @@ -800,7 +831,7 @@ struct GraphicsPipeline { | |||
| 800 | std::uint32_t rectangle_variant_topology = 0; | 831 | std::uint32_t rectangle_variant_topology = 0; |
| 801 | std::function<VkPipeline(std::uint32_t flags)> variant; | 832 | std::function<VkPipeline(std::uint32_t flags)> variant; |
| 802 | 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 |
| 803 | bool pending_base_compile = false; | 834 | bool async_build = false; |
| 804 | }; | 835 | }; |
| 805 | 836 | ||
| 806 | // 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. |
| @@ -828,6 +859,62 @@ enum class ReplayResult { | |||
| 828 | invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has | 859 | invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has |
| 829 | unsupported | 860 | unsupported |
| 830 | }; | 861 | }; |
| 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. | ||
| 867 | inline 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 | |||
| 881 | inline 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 | |||
| 895 | inline 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. | ||
| 907 | inline 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 | |||
| 831 | struct ReplayFunctions { | 918 | struct ReplayFunctions { |
| 832 | std::function<void(VkCommandBuffer, const label::Write&)> gpu_label; | 919 | std::function<void(VkCommandBuffer, const label::Write&)> gpu_label; |
| 833 | // 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 |
| @@ -836,6 +923,7 @@ struct ReplayFunctions { | |||
| 836 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; | 923 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; |
| 837 | PFN_vkCmdClearColorImage clear_color_image = nullptr; | 924 | PFN_vkCmdClearColorImage clear_color_image = nullptr; |
| 838 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; | 925 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; |
| 926 | bool depth_range_unrestricted = false; // Allows out-of-range float depth clear values. | ||
| 839 | // 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. |
| 840 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers | 928 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers |
| 841 | VkPipelineStageFlags2 queue_stages = 0; | 929 | VkPipelineStageFlags2 queue_stages = 0; |
| @@ -880,11 +968,14 @@ struct ReplayFunctions { | |||
| 880 | PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; | 968 | PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; |
| 881 | PFN_vkCmdSetViewport set_viewport = nullptr; | 969 | PFN_vkCmdSetViewport set_viewport = nullptr; |
| 882 | PFN_vkCmdSetScissor set_scissor = nullptr; | 970 | PFN_vkCmdSetScissor set_scissor = nullptr; |
| 971 | PFN_vkCmdSetViewportWithCount set_viewport_with_count = nullptr; | ||
| 972 | PFN_vkCmdSetScissorWithCount set_scissor_with_count = nullptr; | ||
| 883 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; | 973 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; |
| 884 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; | 974 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; |
| 885 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; | 975 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; |
| 886 | PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; | 976 | PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; |
| 887 | PFN_vkCmdDraw draw = nullptr; | 977 | PFN_vkCmdDraw draw = nullptr; |
| 978 | unsigned* mesh_draw_count = nullptr; // opt-in count for this submission | ||
| 888 | 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 |
| 889 | PFN_vkCmdDrawIndexed draw_indexed = nullptr; | 980 | PFN_vkCmdDrawIndexed draw_indexed = nullptr; |
| 890 | std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline; | 981 | std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline; |
| @@ -1144,9 +1235,13 @@ struct PreparedDraw { | |||
| 1144 | QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead | 1235 | QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead |
| 1145 | VkExtent2D area{}; | 1236 | VkExtent2D area{}; |
| 1146 | 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; | ||
| 1147 | 1241 | ||
| 1148 | // Back to a new draw's state, keeping the vectors' storage. | 1242 | // Back to a new draw's state, keeping the vectors' storage. |
| 1149 | void reset() { | 1243 | void reset() { |
| 1244 | skipped = false; | ||
| 1150 | graphics = nullptr; | 1245 | graphics = nullptr; |
| 1151 | pipeline = VK_NULL_HANDLE; | 1246 | pipeline = VK_NULL_HANDLE; |
| 1152 | colors.clear(); | 1247 | colors.clear(); |
| @@ -1484,19 +1579,23 @@ inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command | |||
| 1484 | } | 1579 | } |
| 1485 | } | 1580 | } |
| 1486 | if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { | 1581 | if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { |
| 1582 | // vkCmdFillBuffer requires 4-byte aligned dstOffset and size (VUID-vkCmdFillBuffer-dstOffset-00024 / | ||
| 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). | ||
| 1487 | const VkDeviceSize align = std::max<VkDeviceSize>(4, fmt.bytes); | 1585 | const VkDeviceSize align = std::max<VkDeviceSize>(4, fmt.bytes); |
| 1488 | const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align; | 1586 | const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align; |
| 1489 | VkBuffer scratch = VK_NULL_HANDLE; | 1587 | VkBuffer scratch = VK_NULL_HANDLE; |
| 1490 | VkDeviceSize offset = 0; | 1588 | VkDeviceSize offset = 0; |
| 1491 | if (vk.copy_scratch(fill_bytes, scratch, offset)) { | 1589 | if (vk.copy_scratch(fill_bytes, scratch, offset)) { |
| 1492 | const VkDeviceSize pad = (align - (offset % align)) % align; | 1590 | const VkDeviceSize pad = (align - (offset % align)) % align; |
| 1493 | if (fill_bytes >= pad + fmt.bytes) { | 1591 | const VkDeviceSize usable = fill_bytes > pad ? ((fill_bytes - pad) / align) * align : 0; |
| 1494 | 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); | ||
| 1495 | 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, |
| 1496 | VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); | 1595 | VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); |
| 1497 | zero_buf = scratch; | 1596 | zero_buf = scratch; |
| 1498 | zero_off = offset + pad; | 1597 | zero_off = offset + pad; |
| 1499 | zero_cap = fill_bytes - pad; | 1598 | zero_cap = usable; |
| 1500 | } | 1599 | } |
| 1501 | } | 1600 | } |
| 1502 | } | 1601 | } |
| @@ -1575,6 +1674,14 @@ inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command | |||
| 1575 | return true; | 1674 | return true; |
| 1576 | } | 1675 | } |
| 1577 | 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). | ||
| 1679 | inline 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 | |||
| 1578 | // 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, |
| 1579 | // 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 |
| 1580 | // 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 |
| @@ -1671,7 +1778,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, | |||
| 1671 | 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); |
| 1672 | if (view.format) { | 1779 | if (view.format) { |
| 1673 | 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)) |
| 1674 | return ReplayResult::unsupported; | 1781 | return unsupported_at(__LINE__); |
| 1675 | if (view.element_size != p.element.size) return ReplayResult::invalid_clear; | 1782 | if (view.element_size != p.element.size) return ReplayResult::invalid_clear; |
| 1676 | } else { | 1783 | } else { |
| 1677 | p.element = uav_clear::raw_element(clear.values); | 1784 | p.element = uav_clear::raw_element(clear.values); |
| @@ -1683,8 +1790,9 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, | |||
| 1683 | if (offset > UINT64_MAX - p.binding.buffer_offset || | 1790 | if (offset > UINT64_MAX - p.binding.buffer_offset || |
| 1684 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; | 1791 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; |
| 1685 | 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 |
| 1793 | if (offset % std::min(e, 4u)) return ReplayResult::unsupported; | ||
| 1686 | if (e > 4 && bytes % 4) { | 1794 | if (e > 4 && bytes % 4) { |
| 1687 | return ReplayResult::unsupported; | 1795 | return unsupported_at(__LINE__); |
| 1688 | } | 1796 | } |
| 1689 | p.fills.push_back({offset, bytes}); | 1797 | p.fills.push_back({offset, bytes}); |
| 1690 | return ReplayResult::success; | 1798 | return ReplayResult::success; |
| @@ -1892,7 +2000,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1892 | const BlockFormat format = copy_block_format(image, range.aspectMask); | 2000 | const BlockFormat format = copy_block_format(image, range.aspectMask); |
| 1893 | // 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 |
| 1894 | // 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. |
| 1895 | 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__); |
| 1896 | const VkExtent2D mip = mip_extent(image, range.baseMipLevel); | 2004 | const VkExtent2D mip = mip_extent(image, range.baseMipLevel); |
| 1897 | const auto mip_depth = std::max(1u, image.depth >> range.baseMipLevel); | 2005 | const auto mip_depth = std::max(1u, image.depth >> range.baseMipLevel); |
| 1898 | // 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. |
| @@ -1925,7 +2033,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1925 | // 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), |
| 1926 | // 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. |
| 1927 | 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; |
| 1928 | if (offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; | 2036 | if (offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__); |
| 1929 | 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; |
| 1930 | 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; |
| 1931 | 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) || |
| @@ -1934,7 +2042,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1934 | return ReplayResult::invalid_copy; | 2042 | return ReplayResult::invalid_copy; |
| 1935 | 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; |
| 1936 | const VkDeviceSize backing_offset = buffer.buffer_offset + offset; | 2044 | const VkDeviceSize backing_offset = buffer.buffer_offset + offset; |
| 1937 | if (backing_offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; | 2045 | if (backing_offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__); |
| 1938 | VkBufferImageCopy region{}; | 2046 | VkBufferImageCopy region{}; |
| 1939 | region.bufferOffset = backing_offset; | 2047 | region.bufferOffset = backing_offset; |
| 1940 | region.bufferRowLength = placed.row_pitch / format.bytes * format.block; | 2048 | region.bufferRowLength = placed.row_pitch / format.bytes * format.block; |
| @@ -1943,7 +2051,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1943 | 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)}; |
| 1944 | region.imageExtent = {w, h, depth}; | 2052 | region.imageExtent = {w, h, depth}; |
| 1945 | 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 |
| 1946 | 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__); |
| 1947 | p.rgb96_row_words = std::uint32_t(placed.row_pitch / 4); | 2055 | p.rgb96_row_words = std::uint32_t(placed.row_pitch / 4); |
| 1948 | p.rgb96_slice_words = std::uint32_t(slice_pitch / 4); | 2056 | p.rgb96_slice_words = std::uint32_t(slice_pitch / 4); |
| 1949 | region.bufferRowLength = 0; | 2057 | region.bufferRowLength = 0; |
| @@ -1954,27 +2062,48 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1954 | return ReplayResult::success; | 2062 | return ReplayResult::success; |
| 1955 | } | 2063 | } |
| 1956 | 2064 | ||
| 1957 | // RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel | 2065 | // CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block |
| 1958 | // alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. | 2066 | // alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned |
| 1959 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { | 2067 | // transfer scratch; leave partial-tile padding alone. |
| 2068 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image, | ||
| 2069 | const BlockFormat& fmt, bool upload) { | ||
| 1960 | auto& region = p.buffer_image_copies.front(); | 2070 | auto& region = p.buffer_image_copies.front(); |
| 1961 | const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; | 2071 | if (!fmt.bytes || !fmt.block || image.rgb96 || |
| 1962 | const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; | 2072 | (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)) |
| 1963 | const auto rows = region.imageExtent.height; | 2073 | return false; |
| 2074 | const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block; | ||
| 2075 | const VkDeviceSize rows = (VkDeviceSize(region.imageExtent.height) + fmt.block - 1) / fmt.block; | ||
| 2076 | const VkDeviceSize depth = region.imageExtent.depth; | ||
| 2077 | const VkDeviceSize row_bytes = blocks_w * fmt.bytes; | ||
| 2078 | const VkDeviceSize pitch = | ||
| 2079 | region.bufferRowLength ? VkDeviceSize(region.bufferRowLength / fmt.block) * fmt.bytes : row_bytes; | ||
| 2080 | const VkDeviceSize slice_rows = | ||
| 2081 | region.bufferImageHeight ? VkDeviceSize(region.bufferImageHeight / fmt.block) : rows; | ||
| 2082 | const VkDeviceSize slice_pitch = slice_rows * pitch; | ||
| 2083 | const VkDeviceSize slice_bytes = row_bytes * rows; | ||
| 2084 | const VkDeviceSize total_bytes = slice_bytes * depth; | ||
| 1964 | VkDeviceSize scratch_offset = 0; | 2085 | VkDeviceSize scratch_offset = 0; |
| 1965 | if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; | 2086 | if (!total_bytes || !vk.copy_scratch || !vk.copy_scratch(total_bytes, p.tile_scratch, scratch_offset)) return false; |
| 1966 | const auto app_offset = region.bufferOffset; | 2087 | const auto app_offset = region.bufferOffset; |
| 1967 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { | 2088 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { |
| 1968 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); | 2089 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); |
| 1969 | }; | 2090 | }; |
| 1970 | if (row_bytes == pitch) { | 2091 | if (row_bytes == pitch && (depth == 1 || slice_rows == rows)) { |
| 1971 | add_copy(app_offset, scratch_offset, row_bytes * rows); | 2092 | add_copy(app_offset, scratch_offset, total_bytes); |
| 2093 | } else if (row_bytes == pitch) { | ||
| 2094 | for (VkDeviceSize z = 0; z < depth; ++z) | ||
| 2095 | add_copy(app_offset + z * slice_pitch, scratch_offset + z * slice_bytes, slice_bytes); | ||
| 1972 | } else { | 2096 | } else { |
| 1973 | for (std::uint32_t row = 0; row < rows; ++row) | 2097 | for (VkDeviceSize z = 0; z < depth; ++z) { |
| 1974 | add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); | 2098 | const VkDeviceSize linear_slice = app_offset + z * slice_pitch; |
| 2099 | const VkDeviceSize scratch_slice = scratch_offset + z * slice_bytes; | ||
| 2100 | for (VkDeviceSize row = 0; row < rows; ++row) | ||
| 2101 | add_copy(linear_slice + row * pitch, scratch_slice + row * row_bytes, row_bytes); | ||
| 2102 | } | ||
| 1975 | } | 2103 | } |
| 1976 | region.bufferOffset = scratch_offset; | 2104 | region.bufferOffset = scratch_offset; |
| 1977 | region.bufferRowLength = 0; | 2105 | region.bufferRowLength = 0; |
| 2106 | region.bufferImageHeight = 0; | ||
| 1978 | return true; | 2107 | return true; |
| 1979 | } | 2108 | } |
| 1980 | 2109 | ||
| @@ -2053,15 +2182,15 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& | |||
| 2053 | } else if (from.width != to.width || from.height != to.height) { | 2182 | } else if (from.width != to.width || from.height != to.height) { |
| 2054 | return ReplayResult::invalid_copy; | 2183 | return ReplayResult::invalid_copy; |
| 2055 | } | 2184 | } |
| 2056 | 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__); |
| 2057 | const auto& region = resolve.region; | 2186 | const auto& region = resolve.region; |
| 2058 | if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { | 2187 | if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { |
| 2059 | if (region && region->mode != d3d12_resolve_mode::average) return ReplayResult::unsupported; | 2188 | if (region && region->mode != d3d12_resolve_mode::average) return unsupported_at(__LINE__); |
| 2060 | } else { | 2189 | } else { |
| 2061 | // 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. |
| 2062 | 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 || |
| 2063 | (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)) |
| 2064 | return ReplayResult::unsupported; | 2193 | return unsupported_at(__LINE__); |
| 2065 | 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 |
| 2066 | : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT | 2195 | : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT |
| 2067 | : VK_RESOLVE_MODE_AVERAGE_BIT; | 2196 | : VK_RESOLVE_MODE_AVERAGE_BIT; |
| @@ -2105,7 +2234,7 @@ inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) | |||
| 2105 | VkDeviceSize base = 0; | 2234 | VkDeviceSize base = 0; |
| 2106 | 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 || |
| 2107 | !vk.copy_scratch(total, p.staged, base)) | 2236 | !vk.copy_scratch(total, p.staged, base)) |
| 2108 | return ReplayResult::unsupported; | 2237 | return unsupported_at(__LINE__); |
| 2109 | for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base; | 2238 | for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base; |
| 2110 | return ReplayResult::success; | 2239 | return ReplayResult::success; |
| 2111 | } | 2240 | } |
| @@ -2254,13 +2383,16 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2254 | !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 || |
| 2255 | !vk.set_blend_constants || !vk.draw || | 2384 | !vk.set_blend_constants || !vk.draw || |
| 2256 | !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) | 2385 | !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) |
| 2257 | return ReplayResult::unsupported; | 2386 | return unsupported_at(__LINE__); |
| 2258 | const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); | 2387 | const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); |
| 2259 | if (!pipeline || (!pipeline->pipeline && !pipeline->pending_base_compile)) 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__); | ||
| 2260 | if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; | 2390 | if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; |
| 2261 | if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; | 2391 | if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__); |
| 2262 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; | 2392 | if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) |
| 2263 | if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; | 2393 | return unsupported_at(__LINE__); |
| 2394 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); | ||
| 2395 | if (pipeline->color_formats.size() > max_render_targets) return unsupported_at(__LINE__); | ||
| 2264 | p.graphics = pipeline; | 2396 | p.graphics = pipeline; |
| 2265 | p.pipeline = pipeline->pipeline; | 2397 | p.pipeline = pipeline->pipeline; |
| 2266 | p.area = {UINT32_MAX, UINT32_MAX}; | 2398 | p.area = {UINT32_MAX, UINT32_MAX}; |
| @@ -2277,7 +2409,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2277 | const TargetView& target = draw.views->render_targets[slot]; | 2409 | const TargetView& target = draw.views->render_targets[slot]; |
| 2278 | if (!target.resource) continue; | 2410 | if (!target.resource) continue; |
| 2279 | const ResourceBinding* binding = resolve(target.resource); | 2411 | const ResourceBinding* binding = resolve(target.resource); |
| 2280 | if (!binding) return ReplayResult::unresolved_resource; | 2412 | if (!binding) return unresolved_at(__LINE__); |
| 2281 | auto& a = p.colors[slot]; | 2413 | auto& a = p.colors[slot]; |
| 2282 | a.binding = *binding; | 2414 | a.binding = *binding; |
| 2283 | a.id = target.resource; | 2415 | a.id = target.resource; |
| @@ -2289,12 +2421,12 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2289 | ResourceBinding viewed = a.binding; | 2421 | ResourceBinding viewed = a.binding; |
| 2290 | 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]; |
| 2291 | a.view = vk.image_view(viewed, a.range); | 2423 | a.view = vk.image_view(viewed, a.range); |
| 2292 | if (!a.view) return ReplayResult::unsupported; | 2424 | if (!a.view) return unsupported_at(__LINE__); |
| 2293 | shrink(a.binding, target, a.range); | 2425 | shrink(a.binding, target, a.range); |
| 2294 | } | 2426 | } |
| 2295 | if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { | 2427 | if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { |
| 2296 | const ResourceBinding* binding = resolve(draw.depth.resource); | 2428 | const ResourceBinding* binding = resolve(draw.depth.resource); |
| 2297 | if (!binding) return ReplayResult::unresolved_resource; | 2429 | if (!binding) return unresolved_at(__LINE__); |
| 2298 | auto& a = p.depth; | 2430 | auto& a = p.depth; |
| 2299 | a.binding = *binding; | 2431 | a.binding = *binding; |
| 2300 | a.id = draw.depth.resource; | 2432 | a.id = draw.depth.resource; |
| @@ -2304,12 +2436,20 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2304 | ResourceBinding viewed = a.binding; | 2436 | ResourceBinding viewed = a.binding; |
| 2305 | viewed.format = pipeline->depth_format; | 2437 | viewed.format = pipeline->depth_format; |
| 2306 | a.view = vk.image_view(viewed, a.range); | 2438 | a.view = vk.image_view(viewed, a.range); |
| 2307 | if (!a.view) return ReplayResult::unsupported; | 2439 | if (!a.view) return unsupported_at(__LINE__); |
| 2308 | shrink(a.binding, draw.depth, a.range); | 2440 | shrink(a.binding, draw.depth, a.range); |
| 2309 | } | 2441 | } |
| 2310 | if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering | 2442 | if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering |
| 2311 | p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), | 2443 | std::uint32_t max_w = std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)); |
| 2312 | std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; | 2444 | std::uint32_t max_h = std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height)); |
| 2445 | if (draw.viewports) { | ||
| 2446 | for (std::uint32_t i = 0; i < draw.viewports->viewport_count; ++i) { | ||
| 2447 | const Viewport& v = draw.viewports->viewports[i]; | ||
| 2448 | max_w = std::max(max_w, std::uint32_t(std::max(0.0f, v.x + v.width))); | ||
| 2449 | max_h = std::max(max_h, std::uint32_t(std::max(0.0f, v.y + v.height))); | ||
| 2450 | } | ||
| 2451 | } | ||
| 2452 | p.area = {max_w, max_h}; | ||
| 2313 | } | 2453 | } |
| 2314 | p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); | 2454 | p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); |
| 2315 | 2455 | ||
| @@ -2321,9 +2461,13 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2321 | for (std::size_t slot = 0; slot < p.colors.size(); ++slot) | 2461 | for (std::size_t slot = 0; slot < p.colors.size(); ++slot) |
| 2322 | 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; |
| 2323 | 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; |
| 2324 | if (unbound || (!p.pipeline && pipeline->pending_base_compile)) { | 2464 | if (unbound || !p.pipeline) { |
| 2325 | p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; | 2465 | p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; |
| 2326 | 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__); | ||
| 2327 | } | 2471 | } |
| 2328 | 2472 | ||
| 2329 | // 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 |
| @@ -2337,7 +2481,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2337 | const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && | 2481 | const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && |
| 2338 | draw.views->vertex_buffers[slot].va; | 2482 | draw.views->vertex_buffers[slot].va; |
| 2339 | if (!bound) { | 2483 | if (!bound) { |
| 2340 | if (!vk.zero_buffer) return ReplayResult::unresolved_resource; | 2484 | if (!vk.zero_buffer) return unresolved_at(__LINE__); |
| 2341 | p.vertex_buffers[slot] = vk.zero_buffer; | 2485 | p.vertex_buffers[slot] = vk.zero_buffer; |
| 2342 | p.vertex_offsets[slot] = vk.zero_offset; | 2486 | p.vertex_offsets[slot] = vk.zero_offset; |
| 2343 | p.vertex_sizes[slot] = vk.zero_size; | 2487 | p.vertex_sizes[slot] = vk.zero_size; |
| @@ -2348,29 +2492,41 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2348 | std::uint64_t size = view.size; | 2492 | std::uint64_t size = view.size; |
| 2349 | 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])) { |
| 2350 | size = view.size; | 2494 | size = view.size; |
| 2351 | if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) | 2495 | if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { |
| 2352 | return ReplayResult::unresolved_resource; | 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 | } | ||
| 2353 | } | 2503 | } |
| 2354 | p.vertex_sizes[slot] = size; | 2504 | p.vertex_sizes[slot] = size; |
| 2355 | 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; |
| 2356 | } | 2506 | } |
| 2357 | // A non-indexed quad list is drawn from the shared triangle index buffer (emit). | 2507 | // A non-indexed quad list is drawn from the shared triangle index buffer (emit). |
| 2358 | if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) | 2508 | if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) |
| 2359 | return ReplayResult::unresolved_resource; | 2509 | return unresolved_at(__LINE__); |
| 2360 | if (draw.indexed) { | 2510 | if (draw.indexed) { |
| 2361 | 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; |
| 2362 | 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; |
| 2363 | else if (draw.index.va) return ReplayResult::unsupported; | 2513 | else if (draw.index.va) return unsupported_at(__LINE__); |
| 2364 | if (!draw.index.va) { // no index buffer: every index reads 0 | 2514 | if (!draw.index.va) { // no index buffer: every index reads 0 |
| 2365 | if (!vk.zero_buffer) return ReplayResult::unresolved_resource; | 2515 | if (!vk.zero_buffer) return unresolved_at(__LINE__); |
| 2366 | p.index_buffer = vk.zero_buffer; | 2516 | p.index_buffer = vk.zero_buffer; |
| 2367 | p.index_offset = vk.zero_offset; | 2517 | p.index_offset = vk.zero_offset; |
| 2368 | } else { | 2518 | } else { |
| 2369 | std::uint64_t size = draw.index.size; | 2519 | std::uint64_t size = draw.index.size; |
| 2370 | 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)) { |
| 2371 | size = draw.index.size; | 2521 | size = draw.index.size; |
| 2372 | if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) | 2522 | if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) { |
| 2373 | return ReplayResult::unresolved_resource; | 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 | } | ||
| 2374 | } | 2530 | } |
| 2375 | p.index_size = size; | 2531 | p.index_size = size; |
| 2376 | } | 2532 | } |
| @@ -2887,7 +3043,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2887 | }; | 3043 | }; |
| 2888 | 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) { |
| 2889 | if (rects.empty()) return ReplayResult::success; | 3045 | if (rects.empty()) return ReplayResult::success; |
| 2890 | if (!rendering) return ReplayResult::unsupported; | 3046 | if (!rendering) return unsupported_at(__LINE__); |
| 2891 | 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); |
| 2892 | if (p.rects.empty()) { | 3048 | if (p.rects.empty()) { |
| 2893 | p.skip = true; | 3049 | p.skip = true; |
| @@ -2907,7 +3063,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2907 | }; | 3063 | }; |
| 2908 | 3064 | ||
| 2909 | if (const auto* transition = std::get_if<TransitionBarrier>(&command)) { | 3065 | if (const auto* transition = std::get_if<TransitionBarrier>(&command)) { |
| 2910 | if (!bind(transition->resource)) return ReplayResult::unresolved_resource; | 3066 | if (!bind(transition->resource)) return unresolved_at(__LINE__); |
| 2911 | if (p.binding.image == VK_NULL_HANDLE) { | 3067 | if (p.binding.image == VK_NULL_HANDLE) { |
| 2912 | if (transition->subresource != 0 && transition->subresource != all_subresources) | 3068 | if (transition->subresource != 0 && transition->subresource != all_subresources) |
| 2913 | return ReplayResult::invalid_subresource; | 3069 | return ReplayResult::invalid_subresource; |
| @@ -2918,12 +3074,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2918 | transition->after & d3d12_state::unordered_access); | 3074 | transition->after & d3d12_state::unordered_access); |
| 2919 | if (result != ReplayResult::success) return result; | 3075 | if (result != ReplayResult::success) return result; |
| 2920 | } 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)) { |
| 2921 | if (!vk.pipeline_barrier2) return ReplayResult::unsupported; | 3077 | if (!vk.pipeline_barrier2) return unsupported_at(__LINE__); |
| 2922 | if (const auto* buffer_barrier = std::get_if<BufferBarrier>(&command)) | 3078 | if (const auto* buffer_barrier = std::get_if<BufferBarrier>(&command)) |
| 2923 | if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; | 3079 | if (!bind(buffer_barrier->resource)) return unresolved_at(__LINE__); |
| 2924 | } else if (const auto* texture = std::get_if<TextureBarrier>(&command)) { | 3080 | } else if (const auto* texture = std::get_if<TextureBarrier>(&command)) { |
| 2925 | if (!vk.pipeline_barrier2) return ReplayResult::unsupported; | 3081 | if (!vk.pipeline_barrier2) return unsupported_at(__LINE__); |
| 2926 | if (!bind(texture->resource)) return ReplayResult::unresolved_resource; | 3082 | if (!bind(texture->resource)) return unresolved_at(__LINE__); |
| 2927 | 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)) |
| 2928 | return ReplayResult::invalid_subresource; | 3084 | return ReplayResult::invalid_subresource; |
| 2929 | // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the | 3085 | // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the |
| @@ -2939,7 +3095,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2939 | if (result != ReplayResult::success) return result; | 3095 | if (result != ReplayResult::success) return result; |
| 2940 | } | 3096 | } |
| 2941 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { | 3097 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { |
| 2942 | if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; | 3098 | if (!bind(color_clear->target.resource)) return unresolved_at(__LINE__); |
| 2943 | 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; |
| 2944 | 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)) |
| 2945 | return ReplayResult::invalid_subresource; | 3101 | return ReplayResult::invalid_subresource; |
| @@ -2959,9 +3115,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2959 | VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; | 3115 | VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; |
| 2960 | } 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); |
| 2961 | r != ReplayResult::success) return r; | 3117 | r != ReplayResult::success) return r; |
| 2962 | 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__); |
| 2963 | } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { | 3119 | } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { |
| 2964 | if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; | 3120 | if (!bind(depth_clear->target.resource)) return unresolved_at(__LINE__); |
| 2965 | VkImageAspectFlags aspects = 0; | 3121 | VkImageAspectFlags aspects = 0; |
| 2966 | 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; |
| 2967 | 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; |
| @@ -2978,12 +3134,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2978 | 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); |
| 2979 | r != ReplayResult::success) | 3135 | r != ReplayResult::success) |
| 2980 | return r; | 3136 | return r; |
| 2981 | 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__); |
| 2982 | } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { | 3138 | } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { |
| 2983 | const UavView& view = uav->view; | 3139 | const UavView& view = uav->view; |
| 2984 | if (!bind(view.resource)) return ReplayResult::unresolved_resource; | 3140 | if (!bind(view.resource)) return unresolved_at(__LINE__); |
| 2985 | if (view.buffer) { | 3141 | if (view.buffer) { |
| 2986 | 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__); |
| 2987 | if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands | 3143 | if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands |
| 2988 | 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; |
| 2989 | 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) { |
| @@ -2992,7 +3148,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2992 | if (short_fill && (!vk.copy_scratch || | 3148 | if (short_fill && (!vk.copy_scratch || |
| 2993 | !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 || |
| 2994 | 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)) |
| 2995 | return ReplayResult::unsupported; | 3151 | return unsupported_at(__LINE__); |
| 2996 | if (!p.skip && !p.fills.empty() && p.binding.host_readable) { | 3152 | if (!p.skip && !p.fills.empty() && p.binding.host_readable) { |
| 2997 | out.wrote_readback = true; | 3153 | out.wrote_readback = true; |
| 2998 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; | 3154 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; |
| @@ -3013,10 +3169,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3013 | const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 && | 3169 | const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 && |
| 3014 | p.binding.format == VK_FORMAT_R32_UINT; | 3170 | p.binding.format == VK_FORMAT_R32_UINT; |
| 3015 | 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)) |
| 3016 | return ReplayResult::unsupported; | 3172 | return unsupported_at(__LINE__); |
| 3017 | const auto* image_layout = uav_clear::layout(p.binding.format); | 3173 | const auto* image_layout = uav_clear::layout(p.binding.format); |
| 3018 | if (!image_layout || image_layout->bytes != p.element.size) | 3174 | if (!image_layout || image_layout->bytes != p.element.size) |
| 3019 | return ReplayResult::unsupported; | 3175 | return unsupported_at(__LINE__); |
| 3020 | // The UAV attachment path supports 1D-array and 2D-array views. Keep 3D clears on the transfer | 3176 | // The UAV attachment path supports 1D-array and 2D-array views. Keep 3D clears on the transfer |
| 3021 | // path and retain the exact-format restriction for 1D/3D UAVs below. | 3177 | // path and retain the exact-format restriction for 1D/3D UAVs below. |
| 3022 | const bool attachment = p.binding.color_attachment && !p.binding.volume && | 3178 | const bool attachment = p.binding.color_attachment && !p.binding.volume && |
| @@ -3029,7 +3185,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3029 | return ReplayResult::unsupported; | 3185 | return ReplayResult::unsupported; |
| 3030 | const VkFormat clear_format = reinterpret ? view_format : p.binding.format; | 3186 | const VkFormat clear_format = reinterpret ? view_format : p.binding.format; |
| 3031 | if (!uav_clear::decode(clear_format, p.element, p.clear_color)) | 3187 | if (!uav_clear::decode(clear_format, p.element, p.clear_color)) |
| 3032 | return ReplayResult::unsupported; | 3188 | return unsupported_at(__LINE__); |
| 3033 | if (reinterpret) p.clear_format = view_format; | 3189 | if (reinterpret) p.clear_format = view_format; |
| 3034 | // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. | 3190 | // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. |
| 3035 | // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. | 3191 | // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. |
| @@ -3060,7 +3216,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3060 | continue; | 3216 | continue; |
| 3061 | } | 3217 | } |
| 3062 | if (!uav->rects.empty() && !attachment) | 3218 | if (!uav->rects.empty() && !attachment) |
| 3063 | return ReplayResult::unsupported; | 3219 | return unsupported_at(__LINE__); |
| 3064 | // 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 |
| 3065 | // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted. | 3221 | // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted. |
| 3066 | if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies; | 3222 | if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies; |
| @@ -3069,14 +3225,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3069 | : attachment ? clear_rects(uav->rects) : std::span<const Rect>(uav->rects); | 3225 | : attachment ? clear_rects(uav->rects) : std::span<const Rect>(uav->rects); |
| 3070 | 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) |
| 3071 | return r; | 3227 | return r; |
| 3072 | 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__); |
| 3073 | } 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) || |
| 3074 | std::holds_alternative<CopyResource>(command)) { | 3230 | std::holds_alternative<CopyResource>(command)) { |
| 3075 | if (!copies) return ReplayResult::unsupported; | 3231 | if (!copies) return unsupported_at(__LINE__); |
| 3076 | if (predicated && !std::holds_alternative<CopyBuffer>(command)) ++out.unpredicated_copies; | 3232 | if (predicated && !std::holds_alternative<CopyBuffer>(command)) ++out.unpredicated_copies; |
| 3077 | const auto [dst_id, src_id] = copy_ids(command); | 3233 | const auto [dst_id, src_id] = copy_ids(command); |
| 3078 | const ResourceBinding* source = resolve(src_id); | 3234 | const ResourceBinding* source = resolve(src_id); |
| 3079 | if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; | 3235 | if (!bind(dst_id) || !source) return unresolved_at(__LINE__); |
| 3080 | p.source = *source; | 3236 | p.source = *source; |
| 3081 | ReplayResult result = ReplayResult::success; | 3237 | ReplayResult result = ReplayResult::success; |
| 3082 | if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { | 3238 | if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { |
| @@ -3100,7 +3256,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3100 | if (predicated) { | 3256 | if (predicated) { |
| 3101 | 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 || |
| 3102 | !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)) |
| 3103 | return ReplayResult::unsupported; | 3259 | return unsupported_at(__LINE__); |
| 3104 | } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); | 3260 | } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); |
| 3105 | } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { | 3261 | } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { |
| 3106 | result = detail::prepare_texture_copy(*texture_copy, p); | 3262 | result = detail::prepare_texture_copy(*texture_copy, p); |
| @@ -3121,9 +3277,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3121 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. | 3277 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. |
| 3122 | const bool upload = texture_copy->src.footprint; | 3278 | const bool upload = texture_copy->src.footprint; |
| 3123 | const ResourceBinding& image = upload ? p.binding : p.source; | 3279 | const ResourceBinding& image = upload ? p.binding : p.source; |
| 3124 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && | 3280 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) { |
| 3125 | p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) | 3281 | const auto& region = p.buffer_image_copies.front(); |
| 3126 | return ReplayResult::unsupported; | 3282 | const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask); |
| 3283 | const std::uint32_t alignment = | ||
| 3284 | (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes; | ||
| 3285 | if (alignment > 1 && region.bufferOffset % alignment && | ||
| 3286 | !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) | ||
| 3287 | return unsupported_at(__LINE__); | ||
| 3288 | } | ||
| 3127 | if(result==ReplayResult::success && image.rgba4_render_fallback) return ReplayResult::unsupported; | 3289 | if(result==ReplayResult::success && image.rgba4_render_fallback) return ReplayResult::unsupported; |
| 3128 | if(result==ReplayResult::success && image.xbox_depth16_stencil8 && image.format!=VK_FORMAT_D16_UNORM_S8_UINT && | 3290 | if(result==ReplayResult::success && image.xbox_depth16_stencil8 && image.format!=VK_FORMAT_D16_UNORM_S8_UINT && |
| 3129 | !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask==VK_IMAGE_ASPECT_DEPTH_BIT) return ReplayResult::unsupported; | 3291 | !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask==VK_IMAGE_ASPECT_DEPTH_BIT) return ReplayResult::unsupported; |
| @@ -3133,7 +3295,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3133 | const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 && | 3295 | const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 && |
| 3134 | !p.buffer_image_copies.empty(); | 3296 | !p.buffer_image_copies.empty(); |
| 3135 | // Without a segment pool, refuse before allocating conversion scratch/descriptors. | 3297 | // Without a segment pool, refuse before allocating conversion scratch/descriptors. |
| 3136 | if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported; | 3298 | if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return unsupported_at(__LINE__); |
| 3137 | if (depth24_footprint) { | 3299 | if (depth24_footprint) { |
| 3138 | const VkBufferImageCopy& region = p.buffer_image_copies[0]; | 3300 | const VkBufferImageCopy& region = p.buffer_image_copies[0]; |
| 3139 | const ResourceBinding& buffer = upload ? p.source : p.binding; | 3301 | const ResourceBinding& buffer = upload ? p.source : p.binding; |
| @@ -3147,7 +3309,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3147 | job.slices = region.imageExtent.depth; | 3309 | job.slices = region.imageExtent.depth; |
| 3148 | job.app_row_words = region.bufferRowLength ? region.bufferRowLength : job.width; | 3310 | job.app_row_words = region.bufferRowLength ? region.bufferRowLength : job.width; |
| 3149 | job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); | 3311 | job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); |
| 3150 | if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; | 3312 | if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return unsupported_at(__LINE__); |
| 3151 | p.has_depth24 = true; | 3313 | p.has_depth24 = true; |
| 3152 | } else if (rgb96_footprint) { | 3314 | } else if (rgb96_footprint) { |
| 3153 | // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. | 3315 | // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. |
| @@ -3164,16 +3326,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3164 | job.slices = region.imageExtent.depth; | 3326 | job.slices = region.imageExtent.depth; |
| 3165 | job.app_row_words = p.rgb96_row_words; | 3327 | job.app_row_words = p.rgb96_row_words; |
| 3166 | job.app_slice_words = p.rgb96_slice_words; | 3328 | job.app_slice_words = p.rgb96_slice_words; |
| 3167 | if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; | 3329 | if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return unsupported_at(__LINE__); |
| 3168 | p.has_depth24 = true; | 3330 | p.has_depth24 = true; |
| 3169 | } | 3331 | } |
| 3170 | } else { | 3332 | } else { |
| 3171 | result = detail::prepare_resource_copy(p); | 3333 | result = detail::prepare_resource_copy(p); |
| 3172 | } | 3334 | } |
| 3173 | if (result == ReplayResult::success && !p.image_copies.empty() && | 3335 | if (result == ReplayResult::success && !p.image_copies.empty() && |
| 3174 | p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask) { | 3336 | (p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask || |
| 3337 | a8_mixed_backing(p.source.format, p.binding.format))) { | ||
| 3175 | // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, | 3338 | // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, |
| 3176 | // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. | 3339 | // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. The two |
| 3340 | // backings of A8_UNORM take the same route: one byte per texel on both sides, but Vulkan does not | ||
| 3341 | // count VK_FORMAT_A8_UNORM_KHR as size-compatible with R8_UNORM (VUID-vkCmdCopyImage-srcImage-01548). | ||
| 3177 | const std::uint32_t texel = | 3342 | const std::uint32_t texel = |
| 3178 | block_format(p.source.format, p.image_copies[0].srcSubresource.aspectMask).bytes; | 3343 | block_format(p.source.format, p.image_copies[0].srcSubresource.aspectMask).bytes; |
| 3179 | VkDeviceSize total = 0; | 3344 | VkDeviceSize total = 0; |
| @@ -3185,7 +3350,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3185 | } | 3350 | } |
| 3186 | VkDeviceSize base = 0; | 3351 | VkDeviceSize base = 0; |
| 3187 | if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base)) | 3352 | if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base)) |
| 3188 | return ReplayResult::unsupported; | 3353 | return unsupported_at(__LINE__); |
| 3189 | for (std::size_t r = 0; r < p.image_copies.size(); ++r) { | 3354 | for (std::size_t r = 0; r < p.image_copies.size(); ++r) { |
| 3190 | const VkImageCopy& c = p.image_copies[r]; | 3355 | const VkImageCopy& c = p.image_copies[r]; |
| 3191 | VkBufferImageCopy region{}; | 3356 | VkBufferImageCopy region{}; |
| @@ -3209,18 +3374,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3209 | ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; | 3374 | ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; |
| 3210 | } | 3375 | } |
| 3211 | } else if (const auto* resolve_command = std::get_if<ResolveSubresource>(&command)) { | 3376 | } else if (const auto* resolve_command = std::get_if<ResolveSubresource>(&command)) { |
| 3212 | if (!vk.resolve_image) return ReplayResult::unsupported; | 3377 | if (!vk.resolve_image) return unsupported_at(__LINE__); |
| 3213 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies | 3378 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies |
| 3214 | const ResourceBinding* source = resolve(resolve_command->src); | 3379 | const ResourceBinding* source = resolve(resolve_command->src); |
| 3215 | if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; | 3380 | if (!bind(resolve_command->dst) || !source) return unresolved_at(__LINE__); |
| 3216 | p.source = *source; | 3381 | p.source = *source; |
| 3217 | if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) | 3382 | if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) |
| 3218 | return result; | 3383 | return result; |
| 3219 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { | 3384 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { |
| 3220 | if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return ReplayResult::unsupported; | 3385 | if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return unsupported_at(__LINE__); |
| 3221 | p.view = vk.image_view(p.source, p.source_range); | 3386 | p.view = vk.image_view(p.source, p.source_range); |
| 3222 | p.resolve_view = vk.image_view(p.binding, p.range); | 3387 | p.resolve_view = vk.image_view(p.binding, p.range); |
| 3223 | if (!p.view || !p.resolve_view) return ReplayResult::unsupported; | 3388 | if (!p.view || !p.resolve_view) return unsupported_at(__LINE__); |
| 3224 | if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success) | 3389 | if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success) |
| 3225 | return result; | 3390 | return result; |
| 3226 | // D3D-417, a driver workaround: AMD's Windows driver (32.0.21042.62, Radeon RDNA2 iGPU) resolves a | 3391 | // D3D-417, a driver workaround: AMD's Windows driver (32.0.21042.62, Radeon RDNA2 iGPU) resolves a |
| @@ -3238,12 +3403,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3238 | p.binding, p.resolve_view, | 3403 | p.binding, p.resolve_view, |
| 3239 | image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), p.resolve_mode, | 3404 | image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), p.resolve_mode, |
| 3240 | {std::min(from.width, to.width), std::min(from.height, to.height)}, p.resolve_pass); | 3405 | {std::min(from.width, to.width), std::min(from.height, to.height)}, p.resolve_pass); |
| 3241 | if (!p.resolve_framebuffer) return ReplayResult::unsupported; | 3406 | if (!p.resolve_framebuffer) return unsupported_at(__LINE__); |
| 3242 | } | 3407 | } |
| 3243 | } | 3408 | } |
| 3244 | } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { | 3409 | } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { |
| 3245 | // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. | 3410 | // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. |
| 3246 | if (!bind(discard->resource)) return ReplayResult::unresolved_resource; | 3411 | if (!bind(discard->resource)) return unresolved_at(__LINE__); |
| 3247 | const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; | 3412 | const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; |
| 3248 | if (!p.binding.image) { | 3413 | if (!p.binding.image) { |
| 3249 | if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; | 3414 | if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; |
| @@ -3262,26 +3427,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3262 | } else if (std::holds_alternative<label::Write>(command)) { | 3427 | } else if (std::holds_alternative<label::Write>(command)) { |
| 3263 | if (!vk.gpu_label) return ReplayResult::unsupported; | 3428 | if (!vk.gpu_label) return ReplayResult::unsupported; |
| 3264 | } else if (const auto* write = std::get_if<WriteImmediate>(&command)) { | 3429 | } else if (const auto* write = std::get_if<WriteImmediate>(&command)) { |
| 3265 | if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; | 3430 | if (!vk.update_buffer || !vk.buffer_at) return unsupported_at(__LINE__); |
| 3266 | std::uint64_t bytes = 4; | 3431 | std::uint64_t bytes = 4; |
| 3267 | if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) | 3432 | if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) |
| 3268 | return ReplayResult::unresolved_resource; | 3433 | return unresolved_at(__LINE__); |
| 3269 | if (p.write_offset % 4) return ReplayResult::invalid_copy; | 3434 | if (p.write_offset % 4) return ReplayResult::invalid_copy; |
| 3270 | // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. | 3435 | // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. |
| 3271 | out.wrote_readback = true; | 3436 | out.wrote_readback = true; |
| 3272 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; | 3437 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; |
| 3273 | } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { | 3438 | } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { |
| 3274 | if (!vk.copy_buffer) return ReplayResult::unsupported; | 3439 | if (!vk.copy_buffer) return unsupported_at(__LINE__); |
| 3275 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies | 3440 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies |
| 3276 | const ResourceBinding* source = resolve(atomic->src); | 3441 | const ResourceBinding* source = resolve(atomic->src); |
| 3277 | if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; | 3442 | if (!bind(atomic->dst) || !source) return unresolved_at(__LINE__); |
| 3278 | p.source = *source; | 3443 | p.source = *source; |
| 3279 | if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || | 3444 | if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || |
| 3280 | !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) | 3445 | !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) |
| 3281 | return ReplayResult::invalid_copy; | 3446 | return ReplayResult::invalid_copy; |
| 3282 | for (const auto& d : atomic->dependencies) { | 3447 | for (const auto& d : atomic->dependencies) { |
| 3283 | const ResourceBinding* dependent = resolve(d.resource); | 3448 | const ResourceBinding* dependent = resolve(d.resource); |
| 3284 | if (!dependent) return ReplayResult::unresolved_resource; | 3449 | if (!dependent) return unresolved_at(__LINE__); |
| 3285 | if (!dependent->image) { | 3450 | if (!dependent->image) { |
| 3286 | const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; | 3451 | const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; |
| 3287 | if (d.subresource != 0 || d.begin >= end || end > dependent->size) | 3452 | if (d.subresource != 0 || d.begin >= end || end > dependent->size) |
| @@ -3297,26 +3462,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3297 | } else if (const auto* predication = std::get_if<Predication>(&command)) { | 3462 | } else if (const auto* predication = std::get_if<Predication>(&command)) { |
| 3298 | predicated = predication->buffer != 0; | 3463 | predicated = predication->buffer != 0; |
| 3299 | if (!predicated) continue; | 3464 | if (!predicated) continue; |
| 3300 | if (!conditional) return ReplayResult::unsupported; | 3465 | if (!conditional) return unsupported_at(__LINE__); |
| 3301 | // Without physical segments the capture dispatch would pollute CSInvocations. | 3466 | // Without physical segments the capture dispatch would pollute CSInvocations. |
| 3302 | if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; | 3467 | if (statistics_active && !statistics_helpers) return unsupported_at(__LINE__); |
| 3303 | if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; | 3468 | if (!bind(predication->buffer)) return unresolved_at(__LINE__); |
| 3304 | if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || | 3469 | if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || |
| 3305 | predication->offset > UINT64_MAX - p.binding.buffer_offset) | 3470 | predication->offset > UINT64_MAX - p.binding.buffer_offset) |
| 3306 | return ReplayResult::invalid_predication; | 3471 | return ReplayResult::invalid_predication; |
| 3307 | if (!vk.prepare_predicate || !vk.capture_predicate || | 3472 | if (!vk.prepare_predicate || !vk.capture_predicate || |
| 3308 | !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) | 3473 | !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) |
| 3309 | return ReplayResult::unsupported; | 3474 | return unsupported_at(__LINE__); |
| 3310 | } else if (const QueryRange range = query_range(command); range.count) { | 3475 | } else if (const QueryRange range = query_range(command); range.count) { |
| 3311 | // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, so a predicate does | 3476 | // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, so a predicate does |
| 3312 | // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). | 3477 | // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). |
| 3313 | if (!queries) return ReplayResult::unsupported; | 3478 | if (!queries) return unsupported_at(__LINE__); |
| 3314 | QueryPool* heap = vk.query_pool(range.heap); | 3479 | QueryPool* heap = vk.query_pool(range.heap); |
| 3315 | if (!heap) return ReplayResult::unresolved_resource; | 3480 | if (!heap) return unresolved_at(__LINE__); |
| 3316 | if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; | 3481 | if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; |
| 3317 | if (range.first >= heap->count || range.count > heap->count - range.first) | 3482 | if (range.first >= heap->count || range.count > heap->count - range.first) |
| 3318 | return ReplayResult::invalid_query; | 3483 | return ReplayResult::invalid_query; |
| 3319 | if (!query_result_size(range.type)) return ReplayResult::unsupported; | 3484 | if (!query_result_size(range.type)) return unsupported_at(__LINE__); |
| 3320 | if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { | 3485 | if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { |
| 3321 | const bool begin = std::holds_alternative<BeginQuery>(command); | 3486 | const bool begin = std::holds_alternative<BeginQuery>(command); |
| 3322 | if (range.type == d3d12_query::occlusion) { | 3487 | if (range.type == d3d12_query::occlusion) { |
| @@ -3335,7 +3500,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3335 | } | 3500 | } |
| 3336 | if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { | 3501 | if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { |
| 3337 | // The destination is a buffer, as D3D12 requires, large enough for every result. | 3502 | // The destination is a buffer, as D3D12 requires, large enough for every result. |
| 3338 | if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; | 3503 | if (!bind(resolve_queries->dst)) return unresolved_at(__LINE__); |
| 3339 | const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); | 3504 | const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); |
| 3340 | if (!p.binding.buffer || p.binding.buffer_offset % 8 || | 3505 | if (!p.binding.buffer || p.binding.buffer_offset % 8 || |
| 3341 | !detail::within(resolve_queries->offset, bytes, p.binding.size) || | 3506 | !detail::within(resolve_queries->offset, bytes, p.binding.size) || |
| @@ -3345,7 +3510,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3345 | // Inside a pipeline-statistics query, QueryReplay::plan checks that the helper dispatch is kept out | 3510 | // Inside a pipeline-statistics query, QueryReplay::plan checks that the helper dispatch is kept out |
| 3346 | // of the application's counters. | 3511 | // of the application's counters. |
| 3347 | if (range.type == d3d12_query::binary_occlusion && !vk.resolve_binary_occlusion) | 3512 | if (range.type == d3d12_query::binary_occlusion && !vk.resolve_binary_occlusion) |
| 3348 | return ReplayResult::unsupported; | 3513 | return unsupported_at(__LINE__); |
| 3349 | if (p.binding.host_readable) { | 3514 | if (p.binding.host_readable) { |
| 3350 | out.wrote_readback = true; | 3515 | out.wrote_readback = true; |
| 3351 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | 3516 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; |
| @@ -3353,21 +3518,21 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3353 | } | 3518 | } |
| 3354 | out.queries.push_back({i, heap, statistics_active}); | 3519 | out.queries.push_back({i, heap, statistics_active}); |
| 3355 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { | 3520 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { |
| 3356 | if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; | 3521 | if (!bind(ind->argument_buffer) || !p.binding.buffer) return unresolved_at(__LINE__); |
| 3357 | const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); | 3522 | const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); |
| 3358 | if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) | 3523 | if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) |
| 3359 | return ReplayResult::invalid_indirect_arguments; | 3524 | return ReplayResult::invalid_indirect_arguments; |
| 3360 | // The span is max_count * stride, the bytes the signature can walk, as D3D12 measures it: a record that | 3525 | // The range is the bytes the commands read, (max_count - 1) * stride + record_size: the rule recording |
| 3361 | // fits at the end of the buffer while its stride runs past it is refused (`240` with stride `20` in a | 3526 | // applies (d3d12_com.cpp, ExecuteIndirect) and the one vkCmdDraw*Indirect states. A zero max_count is a |
| 3362 | // `256`-byte buffer). A zero max_count still has to name an offset inside the buffer. | 3527 | // no-op that recording never passes on; if one arrives it reads nothing and needs no range. |
| 3363 | if (ind->argument_offset > p.binding.size || | 3528 | if (ind->max_count |
| 3364 | ind->max_count > (p.binding.size - ind->argument_offset) / ind->stride || | 3529 | ? !detail::indirect_range(p.binding, ind->argument_offset, |
| 3365 | !detail::indirect_range(p.binding, ind->argument_offset, | 3530 | VkDeviceSize(ind->max_count - 1) * ind->stride + record_size) |
| 3366 | VkDeviceSize(ind->max_count) * ind->stride)) | 3531 | : (p.binding.buffer_offset | ind->argument_offset) % sizeof(std::uint32_t) != 0) |
| 3367 | return ReplayResult::invalid_indirect_arguments; | 3532 | return ReplayResult::invalid_indirect_arguments; |
| 3368 | if (ind->count_buffer) { | 3533 | if (ind->count_buffer) { |
| 3369 | const ResourceBinding* cnt = resolve(ind->count_buffer); | 3534 | const ResourceBinding* cnt = resolve(ind->count_buffer); |
| 3370 | if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; | 3535 | if (!cnt || !cnt->buffer) return unresolved_at(__LINE__); |
| 3371 | if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) | 3536 | if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) |
| 3372 | return ReplayResult::invalid_indirect_arguments; | 3537 | return ReplayResult::invalid_indirect_arguments; |
| 3373 | p.source = *cnt; | 3538 | p.source = *cnt; |
| @@ -3379,61 +3544,61 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3379 | !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, | 3544 | !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, |
| 3380 | p.source.buffer, p.source.buffer_offset + ind->count_offset, | 3545 | p.source.buffer, p.source.buffer_offset + ind->count_offset, |
| 3381 | ind->stride, ind->max_count, p.counted_dispatch)) | 3546 | ind->stride, ind->max_count, p.counted_dispatch)) |
| 3382 | return ReplayResult::unsupported; | 3547 | return unsupported_at(__LINE__); |
| 3383 | } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || | 3548 | } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || |
| 3384 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { | 3549 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { |
| 3385 | return ReplayResult::unsupported; | 3550 | return unsupported_at(__LINE__); |
| 3386 | } | 3551 | } |
| 3387 | } else { | 3552 | } else { |
| 3388 | if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || | 3553 | if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || |
| 3389 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || | 3554 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || |
| 3390 | (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) | 3555 | (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) |
| 3391 | return ReplayResult::unsupported; | 3556 | return unsupported_at(__LINE__); |
| 3392 | } | 3557 | } |
| 3393 | if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded | 3558 | if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded |
| 3394 | if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; | 3559 | if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return unsupported_at(__LINE__); |
| 3395 | const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); | 3560 | const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); |
| 3396 | if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource; | 3561 | if (!pipeline) return unresolved_at(__LINE__); |
| 3397 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; | ||
| 3398 | p.pipeline = *pipeline; | 3562 | p.pipeline = *pipeline; |
| 3399 | if (!p.pipeline.pipeline) { | 3563 | if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context); |
| 3400 | p.pipeline.pipeline=pipeline->materialize(); | 3564 | if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not |
| 3401 | if (!p.pipeline.pipeline) return ReplayResult::unsupported; | 3565 | if (!p.pipeline.pipeline && p.pipeline.async_build && !strict_replay()) continue; |
| 3402 | } | 3566 | if (!p.pipeline.pipeline) return unresolved_at(__LINE__); |
| 3567 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); | ||
| 3403 | } | 3568 | } |
| 3404 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { | 3569 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { |
| 3405 | p.khr_instances = 0; | 3570 | p.khr_instances = 0; |
| 3406 | if (vk.xdxr_check) { | 3571 | if (vk.xdxr_check) { |
| 3407 | if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; | 3572 | if (!vk.xdxr_check(*build)) return unsupported_at(__LINE__); |
| 3408 | } else { | 3573 | } else { |
| 3409 | if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) | 3574 | if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) |
| 3410 | return ReplayResult::unsupported; | 3575 | return unsupported_at(__LINE__); |
| 3411 | p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); | 3576 | p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); |
| 3412 | if (!p.accel_dst) return ReplayResult::unresolved_resource; | 3577 | if (!p.accel_dst) return unresolved_at(__LINE__); |
| 3413 | if (build->update && build->src_va) { | 3578 | if (build->update && build->src_va) { |
| 3414 | p.accel_src = vk.resolve_acceleration_structure(build->src_va); | 3579 | p.accel_src = vk.resolve_acceleration_structure(build->src_va); |
| 3415 | if (!p.accel_src) return ReplayResult::unresolved_resource; | 3580 | if (!p.accel_src) return unresolved_at(__LINE__); |
| 3416 | } | 3581 | } |
| 3417 | if (build->is_tlas && build->instance_pointers && build->instance_count) { | 3582 | if (build->is_tlas && build->instance_pointers && build->instance_count) { |
| 3418 | if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; | 3583 | if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return unsupported_at(__LINE__); |
| 3419 | return vk.prepare_khr_instances(*build, p.khr_instances); | 3584 | return vk.prepare_khr_instances(*build, p.khr_instances); |
| 3420 | } | 3585 | } |
| 3421 | } | 3586 | } |
| 3422 | } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) { | 3587 | } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) { |
| 3423 | if (vk.xdxr_copy) { | 3588 | if (vk.xdxr_copy) { |
| 3424 | // XDXR structures: the destination's room bounds the copy, as the size is only known to the GPU. | 3589 | // XDXR structures: the destination's room bounds the copy, as the size is only known to the GPU. |
| 3425 | if (!vk.buffer_at || copy->mode > 1) return ReplayResult::unsupported; | 3590 | if (!vk.buffer_at || copy->mode > 1) return unsupported_at(__LINE__); |
| 3426 | std::uint64_t room = ~std::uint64_t(0); | 3591 | std::uint64_t room = ~std::uint64_t(0); |
| 3427 | VkBuffer buffer = VK_NULL_HANDLE; | 3592 | VkBuffer buffer = VK_NULL_HANDLE; |
| 3428 | VkDeviceSize offset = 0; | 3593 | VkDeviceSize offset = 0; |
| 3429 | if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource; | 3594 | if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return unresolved_at(__LINE__); |
| 3430 | std::uint64_t source = ~std::uint64_t(0); | 3595 | std::uint64_t source = ~std::uint64_t(0); |
| 3431 | if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource; | 3596 | if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return unresolved_at(__LINE__); |
| 3432 | p.xdxr_bytes = std::min(room, source); | 3597 | p.xdxr_bytes = std::min(room, source); |
| 3433 | } else { | 3598 | } else { |
| 3434 | if (vk.queue_stages == detail::queue_stages_copy || !vk.copy_acceleration_structure || | 3599 | if (vk.queue_stages == detail::queue_stages_copy || !vk.copy_acceleration_structure || |
| 3435 | !vk.resolve_acceleration_structure || copy->mode > 1) | 3600 | !vk.resolve_acceleration_structure || copy->mode > 1) |
| 3436 | return ReplayResult::unsupported; | 3601 | return unsupported_at(__LINE__); |
| 3437 | p.accel_dst = vk.resolve_acceleration_structure(copy->dst_va); | 3602 | p.accel_dst = vk.resolve_acceleration_structure(copy->dst_va); |
| 3438 | p.accel_src = vk.resolve_acceleration_structure(copy->src_va); | 3603 | p.accel_src = vk.resolve_acceleration_structure(copy->src_va); |
| 3439 | if (!p.accel_dst || !p.accel_src) return ReplayResult::unresolved_resource; | 3604 | if (!p.accel_dst || !p.accel_src) return ReplayResult::unresolved_resource; |
| @@ -3442,18 +3607,23 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3442 | } | 3607 | } |
| 3443 | } else if (const auto* info = std::get_if<AccelerationStructurePostbuild>(&command)) { | 3608 | } else if (const auto* info = std::get_if<AccelerationStructurePostbuild>(&command)) { |
| 3444 | if (vk.xdxr_postbuild) { | 3609 | if (vk.xdxr_postbuild) { |
| 3445 | if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return ReplayResult::unsupported; | 3610 | if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return unsupported_at(__LINE__); |
| 3446 | std::uint64_t room = 8 * info->sources.size(); | 3611 | std::uint64_t room = 8 * info->sources.size(); |
| 3447 | VkBuffer buffer = VK_NULL_HANDLE; | 3612 | VkBuffer buffer = VK_NULL_HANDLE; |
| 3448 | VkDeviceSize offset = 0; | 3613 | VkDeviceSize offset = 0; |
| 3449 | if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; | 3614 | if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return unresolved_at(__LINE__); |
| 3450 | if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; | 3615 | if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; |
| 3616 | if (!info->sources.empty()) { | ||
| 3617 | // dest_va is resolved by VA and may target a host-readable buffer; XDXR postbuild writes from compute. | ||
| 3618 | out.wrote_readback = true; | ||
| 3619 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; | ||
| 3620 | } | ||
| 3451 | } else if (info->type == 0 && vk.write_acceleration_structures_properties && | 3621 | } else if (info->type == 0 && vk.write_acceleration_structures_properties && |
| 3452 | vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && | 3622 | vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && |
| 3453 | vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { | 3623 | vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { |
| 3454 | if (vk.queue_stages == detail::queue_stages_copy || info->sources.empty() || | 3624 | if (vk.queue_stages == detail::queue_stages_copy || info->sources.empty() || |
| 3455 | info->sources.size() > std::numeric_limits<std::uint32_t>::max() / 8u) | 3625 | info->sources.size() > std::numeric_limits<std::uint32_t>::max() / 8u) |
| 3456 | return ReplayResult::unsupported; | 3626 | return unsupported_at(__LINE__); |
| 3457 | const std::uint64_t need = 8ull * info->sources.size(); | 3627 | const std::uint64_t need = 8ull * info->sources.size(); |
| 3458 | std::uint64_t room = need; | 3628 | std::uint64_t room = need; |
| 3459 | detail::PreparedKhrPostbuild pb; | 3629 | detail::PreparedKhrPostbuild pb; |
| @@ -3471,7 +3641,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3471 | if (!vk.prepare_khr_postbuild(static_cast<std::uint32_t>(pb.sources.size()), pb.query_pool, | 3641 | if (!vk.prepare_khr_postbuild(static_cast<std::uint32_t>(pb.sources.size()), pb.query_pool, |
| 3472 | pb.first_query) || | 3642 | pb.first_query) || |
| 3473 | !pb.query_pool) | 3643 | !pb.query_pool) |
| 3474 | return ReplayResult::unsupported; | 3644 | return unsupported_at(__LINE__); |
| 3475 | p.khr_postbuild = static_cast<std::uint32_t>(out.khr_postbuilds.size()); | 3645 | p.khr_postbuild = static_cast<std::uint32_t>(out.khr_postbuilds.size()); |
| 3476 | out.khr_postbuilds.push_back(std::move(pb)); | 3646 | out.khr_postbuilds.push_back(std::move(pb)); |
| 3477 | // dest_va is resolved by VA and may target a host-readable buffer in COPY_DEST. | 3647 | // dest_va is resolved by VA and may target a host-readable buffer in COPY_DEST. |
| @@ -3483,23 +3653,39 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3483 | } | 3653 | } |
| 3484 | } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { | 3654 | } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { |
| 3485 | if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) | 3655 | if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) |
| 3486 | return ReplayResult::unsupported; | 3656 | return unsupported_at(__LINE__); |
| 3487 | const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); | 3657 | const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); |
| 3488 | if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource; | 3658 | // A dispatch or draw this runtime cannot resolve (a pipeline it could not make: an untranslated |
| 3489 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; | 3659 | // program, an amplification shader; a vertex or index buffer address that names memory it has no |
| 3660 | // buffer for) is dropped, logged by unresolved_at, and the rest of the list is submitted. Failing the | ||
| 3661 | // list instead loses every other draw of the frame: the retail title's lists mix such draws in. | ||
| 3662 | // LEONIDA_STRICT_REPLAY=1 restores the failure. | ||
| 3663 | const bool strict = strict_replay(); | ||
| 3664 | if (!pipeline) { | ||
| 3665 | if (strict) return unresolved_at(__LINE__); | ||
| 3666 | unresolved_at(__LINE__); | ||
| 3667 | p.pipeline = {}; | ||
| 3668 | continue; | ||
| 3669 | } | ||
| 3490 | p.pipeline = *pipeline; | 3670 | p.pipeline = *pipeline; |
| 3491 | if (!p.pipeline.pipeline) { | 3671 | if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context); |
| 3492 | p.pipeline.pipeline=pipeline->materialize(); | 3672 | if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not |
| 3493 | if (!p.pipeline.pipeline) return ReplayResult::unsupported; | 3673 | if (!p.pipeline.pipeline) { |
| 3494 | } | 3674 | if (strict) return unresolved_at(__LINE__); |
| 3675 | if (!p.pipeline.async_build) unresolved_at(__LINE__); | ||
| 3676 | continue; | ||
| 3677 | } | ||
| 3678 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); | ||
| 3495 | } else if (const auto* draw = std::get_if<Draw>(&command)) { | 3679 | } else if (const auto* draw = std::get_if<Draw>(&command)) { |
| 3496 | if (out.draw_count == out.draws.size()) out.draws.emplace_back(); | 3680 | if (out.draw_count == out.draws.size()) out.draws.emplace_back(); |
| 3497 | auto& prepared_draw = out.draws[out.draw_count]; | 3681 | auto& prepared_draw = out.draws[out.draw_count]; |
| 3498 | prepared_draw.reset(); | 3682 | prepared_draw.reset(); |
| 3499 | p.draw = std::uint32_t(out.draw_count++); | 3683 | p.draw = std::uint32_t(out.draw_count++); |
| 3500 | if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) | 3684 | if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) { |
| 3501 | return r; | 3685 | const bool strict = strict_replay(); |
| 3502 | if (draw->indexed && !draw->mesh && draw->topology == topology_quad_list) { | 3686 | if (r != ReplayResult::unresolved_resource || strict) return r; |
| 3687 | prepared_draw.skipped = true; // dropped at emit (see the dispatch branch above) | ||
| 3688 | } else if (draw->indexed && !draw->mesh && draw->topology == topology_quad_list) { | ||
| 3503 | // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. | 3689 | // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. |
| 3504 | if (statistics_active && !statistics_helpers && draw->count >= 4) return ReplayResult::unsupported; | 3690 | if (statistics_active && !statistics_helpers && draw->count >= 4) return ReplayResult::unsupported; |
| 3505 | if (const auto r = detail::prepare_quad_indices(*draw, vk, prepared_draw); r != ReplayResult::success) | 3691 | if (const auto r = detail::prepare_quad_indices(*draw, vk, prepared_draw); r != ReplayResult::success) |
| @@ -3517,7 +3703,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3517 | } | 3703 | } |
| 3518 | if (overlaps) { | 3704 | if (overlaps) { |
| 3519 | if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) | 3705 | if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) |
| 3520 | return ReplayResult::unsupported; | 3706 | return unsupported_at(__LINE__); |
| 3521 | return plan_occlusion_segments(out); | 3707 | return plan_occlusion_segments(out); |
| 3522 | } | 3708 | } |
| 3523 | return ReplayResult::success; | 3709 | return ReplayResult::success; |
| @@ -3534,7 +3720,7 @@ public: | |||
| 3534 | const std::shared_ptr<const OcclusionSegmentPool>& statistics_pool = {}, | 3720 | const std::shared_ptr<const OcclusionSegmentPool>& statistics_pool = {}, |
| 3535 | std::uint32_t statistics_base = 0) { | 3721 | std::uint32_t statistics_base = 0) { |
| 3536 | if (list.segment_count) { | 3722 | if (list.segment_count) { |
| 3537 | if (!pool) return ReplayResult::unsupported; | 3723 | if (!pool) return unsupported_at(__LINE__); |
| 3538 | retain(pool); | 3724 | retain(pool); |
| 3539 | list.segment_pool = pool->pool; | 3725 | list.segment_pool = pool->pool; |
| 3540 | list.segment_base = base; | 3726 | list.segment_base = base; |
| @@ -3550,14 +3736,14 @@ public: | |||
| 3550 | list.statistics_base = statistics_base; | 3736 | list.statistics_base = statistics_base; |
| 3551 | } else if (mesh) { | 3737 | } else if (mesh) { |
| 3552 | // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. | 3738 | // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. |
| 3553 | return ReplayResult::unsupported; | 3739 | return unsupported_at(__LINE__); |
| 3554 | } else if (list.statistics_overlaps) { | 3740 | } else if (list.statistics_overlaps) { |
| 3555 | // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. | 3741 | // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. |
| 3556 | return ReplayResult::unsupported; | 3742 | return unsupported_at(__LINE__); |
| 3557 | } else { | 3743 | } else { |
| 3558 | for (const auto& command : list.commands) | 3744 | for (const auto& command : list.commands) |
| 3559 | if (command.statistics_end != detail::PreparedQuery::no_segment) | 3745 | if (command.statistics_end != detail::PreparedQuery::no_segment) |
| 3560 | return ReplayResult::unsupported; | 3746 | return unsupported_at(__LINE__); |
| 3561 | for (auto& query : list.queries) { | 3747 | for (auto& query : list.queries) { |
| 3562 | query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment; | 3748 | query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment; |
| 3563 | query.statistics_count = 0; | 3749 | query.statistics_count = 0; |
| @@ -3589,7 +3775,7 @@ public: | |||
| 3589 | for (std::uint32_t i = 0; i < resolve.count; ++i) { | 3775 | for (std::uint32_t i = 0; i < resolve.count; ++i) { |
| 3590 | const auto index = resolve.first + i; | 3776 | const auto index = resolve.first + i; |
| 3591 | const auto value = lookup(*query.heap, index); | 3777 | const auto value = lookup(*query.heap, index); |
| 3592 | if (binary && value.ended && !uncounted) return ReplayResult::unsupported; | 3778 | if (binary && value.ended && !uncounted) return unsupported_at(__LINE__); |
| 3593 | needs_binary |= binary && value.ended; | 3779 | needs_binary |= binary && value.ended; |
| 3594 | detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, | 3780 | detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, |
| 3595 | index, 1, offset + VkDeviceSize(i) * size}; | 3781 | index, 1, offset + VkDeviceSize(i) * size}; |
| @@ -3606,7 +3792,7 @@ public: | |||
| 3606 | saved.count > 1 || any_mesh, saved.segments->mesh_pool, | 3792 | saved.count > 1 || any_mesh, saved.segments->mesh_pool, |
| 3607 | saved.segments->primitives_pool, kinds}; | 3793 | saved.segments->primitives_pool, kinds}; |
| 3608 | if (any_mesh && !statistics) return ReplayResult::invalid_query; | 3794 | if (any_mesh && !statistics) return ReplayResult::invalid_query; |
| 3609 | if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; | 3795 | if (!can_sum || (run.sum && !uncounted)) return unsupported_at(__LINE__); |
| 3610 | if (statistics) needs_statistics_sum |= run.sum; | 3796 | if (statistics) needs_statistics_sum |= run.sum; |
| 3611 | else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; | 3797 | else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; |
| 3612 | else needs_sum |= run.sum; | 3798 | else needs_sum |= run.sum; |
| @@ -3775,8 +3961,9 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& | |||
| 3775 | // `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open | 3961 | // `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open |
| 3776 | // is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer | 3962 | // is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer |
| 3777 | // (close_labels). Without it, the list's own events are balanced at its end. | 3963 | // (close_labels). Without it, the list's own events are balanced at its end. |
| 3778 | inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, | 3964 | template<bool Checkpoints> |
| 3779 | LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { | 3965 | inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, |
| 3966 | LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { | ||
| 3780 | std::uint32_t own_labels = 0; | 3967 | std::uint32_t own_labels = 0; |
| 3781 | std::uint32_t& labels = open_labels ? *open_labels : own_labels; | 3968 | std::uint32_t& labels = open_labels ? *open_labels : own_labels; |
| 3782 | const auto commands = prepared.list->commands(); | 3969 | const auto commands = prepared.list->commands(); |
| @@ -3807,6 +3994,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3807 | const auto& command = commands[i]; | 3994 | const auto& command = commands[i]; |
| 3808 | const auto& p = prepared.commands[i]; | 3995 | const auto& p = prepared.commands[i]; |
| 3809 | if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { | 3996 | if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { |
| 3997 | if constexpr (Checkpoints) | ||
| 3998 | if (std::holds_alternative<ResolveQueries>(command)) | ||
| 3999 | checkpoints->record(command_buffer, i, CheckpointKind::resolve); | ||
| 3810 | emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); | 4000 | emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); |
| 3811 | continue; | 4001 | continue; |
| 3812 | } | 4002 | } |
| @@ -3919,19 +4109,26 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3919 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); | 4109 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); |
| 3920 | const bool discard = (texture->flags & texture_barrier_discard) || | 4110 | const bool discard = (texture->flags & texture_barrier_discard) || |
| 3921 | texture->layout_before == d3d12_layout::undefined; | 4111 | texture->layout_before == d3d12_layout::undefined; |
| 4112 | // LayoutAfter UNDEFINED from a defined layout: the contents are no longer needed (the memory is about to | ||
| 4113 | // be aliased, say). Vulkan has no transition into UNDEFINED (VUID-VkImageMemoryBarrier2-newLayout-01198), | ||
| 4114 | // so each piece keeps the layout it is in and the barrier only orders the accesses; the tracker keeps | ||
| 4115 | // that layout too. D3D12 has the next barrier on these subresources start from UNDEFINED, which discards | ||
| 4116 | // from whatever layout they are in. | ||
| 4117 | const bool release = texture->layout_after == d3d12_layout::undefined && | ||
| 4118 | texture->layout_before != d3d12_layout::undefined; | ||
| 3922 | const VkImageLayout new_layout = | 4119 | const VkImageLayout new_layout = |
| 3923 | image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); | 4120 | image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); |
| 3924 | LayoutPieces pieces; | 4121 | LayoutPieces pieces; |
| 3925 | // With coupled layouts, discarding a single plane must preserve the other plane's data. | 4122 | // With coupled layouts, discarding a single plane must preserve the other plane's data. |
| 3926 | const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask; | 4123 | const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask; |
| 3927 | if (discard && !keep_sibling) | 4124 | if (discard && !release && !keep_sibling) |
| 3928 | pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); | 4125 | pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); |
| 3929 | else { | 4126 | else { |
| 3930 | const VkImageLayout before = | 4127 | const VkImageLayout before = |
| 3931 | texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL : | 4128 | texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL : |
| 3932 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); | 4129 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); |
| 3933 | pieces = detail::current(tracker, id, range, before); | 4130 | pieces = detail::current(tracker, id, range, before); |
| 3934 | detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); | 4131 | if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); |
| 3935 | } | 4132 | } |
| 3936 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); | 4133 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); |
| 3937 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); | 4134 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); |
| @@ -3942,6 +4139,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3942 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); | 4139 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); |
| 3943 | std::uint32_t barrier_count = 0; | 4140 | std::uint32_t barrier_count = 0; |
| 3944 | for (const auto& piece : pieces) { | 4141 | for (const auto& piece : pieces) { |
| 4142 | // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. | ||
| 4143 | if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue; | ||
| 3945 | VkImageMemoryBarrier2& b = barriers[barrier_count++]; | 4144 | VkImageMemoryBarrier2& b = barriers[barrier_count++]; |
| 3946 | b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; | 4145 | b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; |
| 3947 | b.srcStageMask = src.stages; | 4146 | b.srcStageMask = src.stages; |
| @@ -3949,7 +4148,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3949 | b.srcAccessMask = src.access; | 4148 | b.srcAccessMask = src.access; |
| 3950 | b.dstAccessMask = dst.access; | 4149 | b.dstAccessMask = dst.access; |
| 3951 | b.oldLayout = piece.layout; | 4150 | b.oldLayout = piece.layout; |
| 3952 | b.newLayout = new_layout; | 4151 | b.newLayout = release ? piece.layout : new_layout; |
| 3953 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 4152 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 3954 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 4153 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 3955 | b.image = p.binding.image; | 4154 | b.image = p.binding.image; |
| @@ -3957,14 +4156,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3957 | if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); | 4156 | if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); |
| 3958 | if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); | 4157 | if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); |
| 3959 | } | 4158 | } |
| 3960 | VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; | 4159 | if (barrier_count) { |
| 3961 | dependency.imageMemoryBarrierCount = barrier_count; | 4160 | VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; |
| 3962 | dependency.pImageMemoryBarriers = barriers; | 4161 | dependency.imageMemoryBarrierCount = barrier_count; |
| 3963 | vk.pipeline_barrier2(command_buffer, &dependency); | 4162 | dependency.pImageMemoryBarriers = barriers; |
| 3964 | if (tracker) tracker->set(id, range, new_layout); | 4163 | vk.pipeline_barrier2(command_buffer, &dependency); |
| 3965 | finish_depth_uav_barrier(p, new_layout); | 4164 | } |
| 4165 | if (tracker && !release) tracker->set(id, range, new_layout); | ||
| 4166 | if (!release) finish_depth_uav_barrier(p, new_layout); | ||
| 3966 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { | 4167 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { |
| 3967 | if (p.skip) continue; | 4168 | if (p.skip) continue; |
| 4169 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); | ||
| 3968 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); | 4170 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); |
| 3969 | auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); | 4171 | auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); |
| 3970 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 4172 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); |
| @@ -4001,15 +4203,19 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4001 | }); | 4203 | }); |
| 4002 | } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { | 4204 | } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { |
| 4003 | if (p.skip) continue; | 4205 | if (p.skip) continue; |
| 4206 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); | ||
| 4004 | // With separate layouts only the cleared planes move; otherwise both do. | 4207 | // With separate layouts only the cleared planes move; otherwise both do. |
| 4005 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); | 4208 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); |
| 4006 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); | 4209 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); |
| 4007 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); | 4210 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); |
| 4008 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 4211 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); |
| 4009 | const 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 | 4212 | 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 |
| 4010 | : p.binding.format == VK_FORMAT_D16_UNORM | 4213 | : p.binding.format == VK_FORMAT_D16_UNORM |
| 4011 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm | 4214 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm |
| 4012 | : depth_clear->depth; | 4215 | : depth_clear->depth; |
| 4216 | // Without the extension both clear commands require a depth in [0, 1], including for float images. | ||
| 4217 | if (!vk.depth_range_unrestricted) | ||
| 4218 | depth = std::isnan(depth) ? 0.0f : std::clamp(depth, 0.0f, 1.0f); | ||
| 4013 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; | 4219 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; |
| 4014 | if (p.rects.empty()) { | 4220 | if (p.rects.empty()) { |
| 4015 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), | 4221 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), |
| @@ -4040,6 +4246,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4040 | }); | 4246 | }); |
| 4041 | } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { | 4247 | } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { |
| 4042 | if (p.skip) continue; | 4248 | if (p.skip) continue; |
| 4249 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); | ||
| 4043 | // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the | 4250 | // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the |
| 4044 | // clear stage, which is a transfer stage in the legacy masks. | 4251 | // clear stage, which is a transfer stage in the legacy masks. |
| 4045 | VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false); | 4252 | VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false); |
| @@ -4107,12 +4314,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4107 | }); | 4314 | }); |
| 4108 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || | 4315 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || |
| 4109 | std::holds_alternative<CopyResource>(command)) { | 4316 | std::holds_alternative<CopyResource>(command)) { |
| 4317 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); | ||
| 4110 | const auto [dst_id, src_id] = copy_ids(command); | 4318 | const auto [dst_id, src_id] = copy_ids(command); |
| 4111 | if (!p.predicated_copy.empty()) { | 4319 | if (!p.predicated_copy.empty()) { |
| 4112 | end_statistics(); | 4320 | end_statistics(); |
| 4113 | vk.emit_predicated_copy(command_buffer, p.predicated_copy); | 4321 | vk.emit_predicated_copy(command_buffer, p.predicated_copy); |
| 4114 | begin_statistics(); | 4322 | begin_statistics(); |
| 4115 | } else if (!p.buffer_copies.empty()) { | 4323 | } else if (!p.buffer_copies.empty()) { |
| 4324 | // Transfer dependency from natterman12, ubiquitarianism/leonida PR #354 (GPL-3.0). | ||
| 4325 | // D3D12 orders buffer copies even across lists on one queue. A previous transfer write can | ||
| 4326 | // overlap this copy's source or destination without an application barrier. | ||
| 4327 | if (vk.pipeline_barrier && order_buffer_copies()) { | ||
| 4328 | detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, | ||
| 4329 | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, | ||
| 4330 | VK_PIPELINE_STAGE_TRANSFER_BIT); | ||
| 4331 | } | ||
| 4116 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), | 4332 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), |
| 4117 | p.buffer_copies.data()); | 4333 | p.buffer_copies.data()); |
| 4118 | } else if (p.staged) { | 4334 | } else if (p.staged) { |
| @@ -4230,6 +4446,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4230 | } | 4446 | } |
| 4231 | } | 4447 | } |
| 4232 | } else if (std::holds_alternative<ResolveSubresource>(command)) { | 4448 | } else if (std::holds_alternative<ResolveSubresource>(command)) { |
| 4449 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::resolve); | ||
| 4233 | // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. | 4450 | // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. |
| 4234 | const auto [dst_id, src_id] = copy_ids(command); | 4451 | const auto [dst_id, src_id] = copy_ids(command); |
| 4235 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { | 4452 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { |
| @@ -4370,6 +4587,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4370 | vk.update_buffer(command_buffer, p.write_buffer, p.write_offset, 4, &write->value); | 4587 | vk.update_buffer(command_buffer, p.write_buffer, p.write_offset, 4, &write->value); |
| 4371 | if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); | 4588 | if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); |
| 4372 | } else if (std::holds_alternative<AtomicCopyBuffer>(command)) { | 4589 | } else if (std::holds_alternative<AtomicCopyBuffer>(command)) { |
| 4590 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); | ||
| 4373 | // Every earlier write, to the dependent resources among others, finishes and is visible before the copy. | 4591 | // Every earlier write, to the dependent resources among others, finishes and is visible before the copy. |
| 4374 | // Vulkan promises no atomicity for a transfer; that a naturally aligned 4- or 8-byte copy is one write | 4592 | // Vulkan promises no atomicity for a transfer; that a naturally aligned 4- or 8-byte copy is one write |
| 4375 | // is an assumption about the hardware (docs/d3d12_vulkan.md, section 4.2). | 4593 | // is an assumption about the hardware (docs/d3d12_vulkan.md, section 4.2). |
| @@ -4378,6 +4596,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4378 | VK_PIPELINE_STAGE_TRANSFER_BIT); | 4596 | VK_PIPELINE_STAGE_TRANSFER_BIT); |
| 4379 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); | 4597 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); |
| 4380 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { | 4598 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { |
| 4599 | if (ind->kind == IndirectKind::dispatch && ind->pipeline && !p.pipeline.pipeline && | ||
| 4600 | (p.pipeline.async_build || p.pipeline.skipped)) | ||
| 4601 | continue; | ||
| 4602 | if constexpr (Checkpoints) { | ||
| 4603 | if (ind->kind == IndirectKind::dispatch) | ||
| 4604 | checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, ind->pipeline, ind->user_data, {}, true, | ||
| 4605 | ind->argument_buffer, ind->argument_offset, ind->count_buffer, | ||
| 4606 | ind->count_offset, ind->max_count, ind->stride); | ||
| 4607 | else | ||
| 4608 | checkpoints->record(command_buffer, i, CheckpointKind::draw); | ||
| 4609 | } | ||
| 4381 | const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; | 4610 | const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; |
| 4382 | if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { | 4611 | if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { |
| 4383 | const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; | 4612 | const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; |
| @@ -4426,6 +4655,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4426 | xdxr_build && vk.xdxr_record) { | 4655 | xdxr_build && vk.xdxr_record) { |
| 4427 | vk.xdxr_record(command_buffer, *xdxr_build); | 4656 | vk.xdxr_record(command_buffer, *xdxr_build); |
| 4428 | } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) { | 4657 | } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) { |
| 4658 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); | ||
| 4429 | if (vk.xdxr_copy) { | 4659 | if (vk.xdxr_copy) { |
| 4430 | vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes); | 4660 | vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes); |
| 4431 | } else { | 4661 | } else { |
| @@ -4521,6 +4751,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4521 | const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data(); | 4751 | const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data(); |
| 4522 | vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr); | 4752 | vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr); |
| 4523 | } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { | 4753 | } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { |
| 4754 | if (!p.pipeline.pipeline) continue; // could not be resolved in prepare: dropped | ||
| 4755 | if constexpr (Checkpoints) | ||
| 4756 | checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, dispatch->pipeline, dispatch->user_data, | ||
| 4757 | {dispatch->x, dispatch->y, dispatch->z}); | ||
| 4524 | ShaderUserData data{}; | 4758 | ShaderUserData data{}; |
| 4525 | std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); | 4759 | std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); |
| 4526 | data.heap_base = vk.heap_base; | 4760 | data.heap_base = vk.heap_base; |
| @@ -4535,6 +4769,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4535 | vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); | 4769 | vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); |
| 4536 | } else if (const auto* draw = std::get_if<Draw>(&command)) { | 4770 | } else if (const auto* draw = std::get_if<Draw>(&command)) { |
| 4537 | const detail::PreparedDraw& d = prepared.draws[p.draw]; | 4771 | const detail::PreparedDraw& d = prepared.draws[p.draw]; |
| 4772 | if (d.skipped) continue; // could not be resolved in prepare: dropped | ||
| 4773 | if constexpr (Checkpoints) | ||
| 4774 | checkpoints->record(command_buffer, i, CheckpointKind::draw, | ||
| 4775 | d.pipeline, draw->pipeline); | ||
| 4538 | constexpr VkAccessFlags color_access = | 4776 | constexpr VkAccessFlags color_access = |
| 4539 | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; | 4777 | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; |
| 4540 | constexpr VkAccessFlags depth_access = | 4778 | constexpr VkAccessFlags depth_access = |
| @@ -4587,14 +4825,46 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4587 | vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); | 4825 | vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); |
| 4588 | // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the | 4826 | // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the |
| 4589 | // image upright, and winding as D3D12 sees it. | 4827 | // image upright, and winding as D3D12 sees it. |
| 4590 | const Viewport& v = draw->viewport; | 4828 | if (graphics.viewport_with_count) { |
| 4591 | const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | 4829 | std::array<VkViewport, DrawViewports::max_count> vps{}; |
| 4592 | vk.set_viewport(command_buffer, 0, 1, &viewport); | 4830 | std::array<VkRect2D, DrawViewports::max_count> scs{}; |
| 4593 | const Rect& s = draw->scissor; | 4831 | const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u; |
| 4594 | const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, | 4832 | const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u; |
| 4595 | {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), | 4833 | const std::uint32_t count = std::clamp(std::max(vp_n, sc_n), 1u, DrawViewports::max_count); |
| 4596 | std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; | 4834 | for (std::uint32_t k = 0; k < count; ++k) { |
| 4597 | vk.set_scissor(command_buffer, 0, 1, &scissor); | 4835 | const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k] |
| 4836 | : (k == 0 ? draw->viewport : Viewport{}); | ||
| 4837 | const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f); | ||
| 4838 | if (valid_vp) { | ||
| 4839 | vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | ||
| 4840 | } else { | ||
| 4841 | // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing | ||
| 4842 | // rasterizes into an unbound/empty D3D12 viewport slot. | ||
| 4843 | vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; | ||
| 4844 | } | ||
| 4845 | if (valid_vp && k < sc_n) { | ||
| 4846 | const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor; | ||
| 4847 | const std::int32_t left = std::max(0, s.left); | ||
| 4848 | const std::int32_t top = std::max(0, s.top); | ||
| 4849 | scs[k] = {{left, top}, | ||
| 4850 | {std::uint32_t(std::max(0, s.right - left)), | ||
| 4851 | std::uint32_t(std::max(0, s.bottom - top))}}; | ||
| 4852 | } else { | ||
| 4853 | scs[k] = {{0, 0}, {0, 0}}; | ||
| 4854 | } | ||
| 4855 | } | ||
| 4856 | vk.set_viewport_with_count(command_buffer, count, vps.data()); | ||
| 4857 | vk.set_scissor_with_count(command_buffer, count, scs.data()); | ||
| 4858 | } else { | ||
| 4859 | const Viewport& v = draw->viewport; | ||
| 4860 | const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | ||
| 4861 | vk.set_viewport(command_buffer, 0, 1, &viewport); | ||
| 4862 | const Rect& s = draw->scissor; | ||
| 4863 | const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, | ||
| 4864 | {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), | ||
| 4865 | std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; | ||
| 4866 | vk.set_scissor(command_buffer, 0, 1, &scissor); | ||
| 4867 | } | ||
| 4598 | // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology | 4868 | // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology |
| 4599 | // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). | 4869 | // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). |
| 4600 | if (!draw->mesh) { | 4870 | if (!draw->mesh) { |
| @@ -4616,6 +4886,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4616 | } | 4886 | } |
| 4617 | if (draw->mesh) { | 4887 | if (draw->mesh) { |
| 4618 | vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); | 4888 | vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); |
| 4889 | if (vk.mesh_draw_count) ++*vk.mesh_draw_count; | ||
| 4619 | } else if (draw->topology == topology_quad_list) { | 4890 | } else if (draw->topology == topology_quad_list) { |
| 4620 | if (draw->indexed) { | 4891 | if (draw->indexed) { |
| 4621 | // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) | 4892 | // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) |
| @@ -4658,6 +4929,11 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4658 | if (!open_labels) close_labels(command_buffer, vk, own_labels); | 4929 | if (!open_labels) close_labels(command_buffer, vk, own_labels); |
| 4659 | } | 4930 | } |
| 4660 | 4931 | ||
| 4932 | inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, | ||
| 4933 | LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { | ||
| 4934 | emit_commands<false>(prepared, command_buffer, vk, tracker, open_labels, nullptr); | ||
| 4935 | } | ||
| 4936 | |||
| 4661 | // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. | 4937 | // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. |
| 4662 | // With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get | 4938 | // With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get |
| 4663 | // segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. | 4939 | // segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. |
| @@ -4666,20 +4942,20 @@ ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Res | |||
| 4666 | const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, | 4942 | const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, |
| 4667 | std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) { | 4943 | std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) { |
| 4668 | if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) | 4944 | if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) |
| 4669 | return ReplayResult::unsupported; | 4945 | return unsupported_at(__LINE__); |
| 4670 | const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && | 4946 | const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && |
| 4671 | vk.sum_statistics && vk.sum_binary_occlusion; | 4947 | vk.sum_statistics && vk.sum_binary_occlusion; |
| 4672 | PreparedList prepared; | 4948 | PreparedList prepared; |
| 4673 | if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) | 4949 | if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) |
| 4674 | return result; | 4950 | return result; |
| 4675 | if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; | 4951 | if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return unsupported_at(__LINE__); |
| 4676 | std::shared_ptr<const OcclusionSegmentPool> physical, statistics; | 4952 | std::shared_ptr<const OcclusionSegmentPool> physical, statistics; |
| 4677 | if (pools && prepared.segment_count && | 4953 | if (pools && prepared.segment_count && |
| 4678 | !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) | 4954 | !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) |
| 4679 | return ReplayResult::unsupported; | 4955 | return unsupported_at(__LINE__); |
| 4680 | if (pools && prepared.statistics_segment_count && | 4956 | if (pools && prepared.statistics_segment_count && |
| 4681 | !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) | 4957 | !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) |
| 4682 | return ReplayResult::unsupported; | 4958 | return unsupported_at(__LINE__); |
| 4683 | QueryReplay queries; | 4959 | QueryReplay queries; |
| 4684 | if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) | 4960 | if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) |
| 4685 | return result; | 4961 | return result; |
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 58b9e6967..753701e1c 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h | |||
| @@ -13,6 +13,8 @@ | |||
| 13 | #include <vulkan/vulkan.h> | 13 | #include <vulkan/vulkan.h> |
| 14 | #include "queue_families.h" | 14 | #include "queue_families.h" |
| 15 | 15 | ||
| 16 | #include "vulkan_device_fault.h" | ||
| 17 | |||
| 16 | #include <algorithm> | 18 | #include <algorithm> |
| 17 | #include <cstdint> | 19 | #include <cstdint> |
| 18 | #include <functional> | 20 | #include <functional> |
| @@ -27,14 +29,15 @@ public: | |||
| 27 | using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>; | 29 | using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>; |
| 28 | 30 | ||
| 29 | ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0, | 31 | ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0, |
| 30 | std::vector<std::uint32_t> families = {}) | 32 | std::vector<std::uint32_t> families = {}, DeviceFaultDiagnostics* diagnostics = nullptr) |
| 31 | : device_(device), allocate_(std::move(allocate)), extra_usage_(extra_usage), families_(std::move(families)) { | 33 | : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), extra_usage_(extra_usage), |
| 34 | families_(std::move(families)) { | ||
| 32 | loaded_ = vk_.load(get, device); | 35 | loaded_ = vk_.load(get, device); |
| 33 | } | 36 | } |
| 34 | 37 | ||
| 35 | ~ScratchBuffers() { | 38 | ~ScratchBuffers() { |
| 36 | if (!loaded_) return; | 39 | if (!loaded_) return; |
| 37 | vk_.vkDeviceWaitIdle(device_); | 40 | DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle"); |
| 38 | release(current_); | 41 | release(current_); |
| 39 | for (auto& batch : retired_) release(batch); | 42 | for (auto& batch : retired_) release(batch); |
| 40 | for (auto& chunk : spare_) destroy(chunk); | 43 | for (auto& chunk : spare_) destroy(chunk); |
| @@ -105,7 +108,9 @@ public: | |||
| 105 | if (retired_[i].ticket != 0) { | 108 | if (retired_[i].ticket != 0) { |
| 106 | std::uint64_t done = 0; | 109 | std::uint64_t done = 0; |
| 107 | if (!retired_[i].timeline || | 110 | if (!retired_[i].timeline || |
| 108 | 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 || | ||
| 109 | done < retired_[i].ticket) { | 114 | done < retired_[i].ticket) { |
| 110 | ++i; | 115 | ++i; |
| 111 | continue; | 116 | continue; |
| @@ -181,6 +186,7 @@ private: | |||
| 181 | } | 186 | } |
| 182 | 187 | ||
| 183 | VkDevice device_; | 188 | VkDevice device_; |
| 189 | DeviceFaultDiagnostics* diagnostics_; | ||
| 184 | Allocate allocate_; | 190 | Allocate allocate_; |
| 185 | VkBufferUsageFlags extra_usage_ = 0; | 191 | VkBufferUsageFlags extra_usage_ = 0; |
| 186 | std::vector<std::uint32_t> families_; | 192 | std::vector<std::uint32_t> families_; |
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 | |||
| 13 | namespace 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. | ||
| 17 | struct 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 | |||
| 48 | struct 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 | |||
| 64 | class TitleImagePool { | ||
| 65 | public: | ||
| 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 | |||
| 108 | private: | ||
| 109 | std::mutex mutex_; | ||
| 110 | std::map<VkDeviceSize, std::vector<std::weak_ptr<TitleImagePage>>> classes_; | ||
| 111 | }; | ||
| 112 | |||
| 113 | } // namespace leonida | ||
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h index e0851098f..e1c1a233e 100644 --- a/runtime/src/xdxr_build.h +++ b/runtime/src/xdxr_build.h | |||
| @@ -133,7 +133,13 @@ public: | |||
| 133 | // update ignores `pair`. | 133 | // update ignores `pair`. |
| 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, | 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, |
| 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { | 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { |
| 136 | if (!loaded_ || layout.tlas) return false; | 136 | if (!loaded_ || layout.tlas || !layout.size || !dst || !scratch) return false; |
| 137 | std::uint64_t total = 0; | ||
| 138 | for (const auto& geo : geometries) { | ||
| 139 | total += geo.triangle_count; | ||
| 140 | if (total > layout.elements) return false; | ||
| 141 | } | ||
| 142 | if (total != layout.elements) return false; | ||
| 137 | Push p = base(layout, dst, scratch); | 143 | Push p = base(layout, dst, scratch); |
| 138 | if (pair && !update_from) p.flags |= flag_pair; | 144 | if (pair && !update_from) p.flags |= flag_pair; |
| 139 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 145 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -155,7 +161,6 @@ public: | |||
| 155 | dispatch(cb, t, t.count); | 161 | dispatch(cb, t, t.count); |
| 156 | first += geo.triangle_count; | 162 | first += geo.triangle_count; |
| 157 | } | 163 | } |
| 158 | if (first != layout.elements) return false; | ||
| 159 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); | 164 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); |
| 160 | return true; | 165 | return true; |
| 161 | } | 166 | } |
| @@ -164,7 +169,8 @@ public: | |||
| 164 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. | 169 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. |
| 165 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, | 170 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, |
| 166 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { | 171 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { |
| 167 | if (!loaded_ || !layout.tlas) return false; | 172 | if (!loaded_ || !layout.tlas || !layout.size || !dst || !scratch || (layout.elements && !instances)) |
| 173 | return false; | ||
| 168 | Push p = base(layout, dst, scratch); | 174 | Push p = base(layout, dst, scratch); |
| 169 | p.bias = split(bias); | 175 | p.bias = split(bias); |
| 170 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 176 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -341,7 +347,7 @@ private: | |||
| 341 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). | 347 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). |
| 342 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { | 348 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { |
| 343 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); | 349 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); |
| 344 | vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); | 350 | vk_.vkCmdDispatch(cb, std::uint32_t((std::uint64_t(threads) + 63u) / 64u), 1, 1); |
| 345 | if (!barrier) return; | 351 | if (!barrier) return; |
| 346 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 352 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 347 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | 353 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; |
diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h index b44ce0372..3798b0fe7 100644 --- a/runtime/src/xdxr_descs.h +++ b/runtime/src/xdxr_descs.h | |||
| @@ -99,12 +99,11 @@ constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10; | |||
| 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping | 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping |
| 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. | 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. |
| 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { | 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { |
| 102 | if (desc.size_in_bytes == 0 || desc.stream == nullptr) | 102 | if (desc.size_in_bytes < sizeof(StreamRecord) || desc.stream == nullptr) |
| 103 | return nullptr; | 103 | return nullptr; |
| 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); | 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); |
| 105 | const auto* end = reinterpret_cast<const StreamRecord*>(static_cast<const uint8_t*>(desc.stream) + | 105 | const uint64_t count = desc.size_in_bytes / sizeof(StreamRecord); |
| 106 | desc.size_in_bytes); | 106 | for (uint64_t i = 0; i < count; ++i, ++record) { |
| 107 | for (; record < end; ++record) { | ||
| 108 | if (record->type == type) | 107 | if (record->type == type) |
| 109 | return record; | 108 | return record; |
| 110 | if (record->type > 2) | 109 | if (record->type > 2) |