upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/console_heap_gpu.h
diff options
context:
space:
mode:
authorTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
committerTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
commitbeffaa9a476ca1b3dfd9cfa55e39eafbb1f5eec6 (patch)
tree32877805bf4eb46d9a89d5753db6b5a2b06dc845 /runtime/src/console_heap_gpu.h
parentf29ca7bacae9507f83e8c56abdb604bd4efb4cf1 (diff)
parenta73a57e1339be072baf5522351c8ec7f1482b56b (diff)
Merge main into fix/null-descriptor-generated-dir
Diffstat (limited to 'runtime/src/console_heap_gpu.h')
-rw-r--r--runtime/src/console_heap_gpu.h1058
1 files changed, 1058 insertions, 0 deletions
diff --git a/runtime/src/console_heap_gpu.h b/runtime/src/console_heap_gpu.h
new file mode 100644
index 000000000..b3a4c0ba4
--- /dev/null
+++ b/runtime/src/console_heap_gpu.h
@@ -0,0 +1,1058 @@
1// Console descriptor heap translation on the GPU (LEONIDA_CONSOLE_HEAP_GPU=1): the buffer V#s the title writes into
2// its console descriptor heaps are rebased by a compute pass (console_heap_fix.comp) at the start of the submission
3// that reads them, instead of one by one on the submitting thread (DeviceState::fix_console_slot).
4//
5// What stays on the CPU (shims/d3d12_vulkan_device.cpp): finding the changed slots (the heap's ShadowPages and a
6// compare against the bytes each slot was last made from), registering the T#s (they are copied as they are; shaders
7// find them by their words), and every lookup that can make something: a V# the pass cannot answer is written with no
8// records and recorded in the pass's miss list; once the submission is done the CPU resolves its words with
9// vsharp_address (which may make a geometry copy), enters the answer in the key table, and queues the slot again.
10//
11// The pass answers a V# half from four tables, in vsharp_address's order:
12// - the range table: the title-VA ranges of the alias table (src/title_va_alias.h), sorted, each with the shader VA
13// of its copy and whether the CPU found that copy backed. Rebuilt when the alias table or the backings change;
14// - the backed table: the shader-VA spans of the live GPU allocations (DeviceState's gpu_backings, merged) and of
15// the geometry copies' blocks. A base already inside one (a V# our API wrote, or the title copied) is left as it
16// is, as vsharp_address's backed() leaves it. Merged neighbours make it a superset of what backed() accepts, but
17// never of memory that is not there;
18// - the key table: the exact 16 bytes of a V# half and what vsharp_address answered for them (a shader VA, or no
19// backing), open addressed with up to kProbes slots per key (FNV-1a and fmix32). The CPU keeps the
20// mirror below; its changes reach the GPU as updates the pass applies first, so the table changes in GPU order;
21// - the ask table: the title's memory and its GPU windows. A base outside them that nothing above answered gets no
22// records (vsharp_address could only answer 0); one inside them is a miss, for the CPU.
23// When a backing or an alias range goes, every key entry whose answer falls in its shader VAs is dropped and every V#
24// slot of the heap is translated again.
25//
26// ConsoleHeapKeys and console_heap_translate_slot are the CPU reference of the pass (vk_console_heap_gpu_test checks
27// the GPU against them); ConsoleHeapGpu records the pass.
28#pragma once
29#ifndef VK_NO_PROTOTYPES
30#define VK_NO_PROTOTYPES
31#endif
32#include <vulkan/vulkan.h>
33
34#include <algorithm>
35#include <array>
36#include <cstdint>
37#include <cstring>
38#include <map>
39#include <memory>
40#include <mutex>
41#include <utility>
42#include <vector>
43
44#include "console_heap_fix_spv.h"
45#include "vulkan_aftermath.h"
46#include "vulkan_memory.h"
47
48namespace leonida {
49
50struct ConsoleHeapRange {
51 std::uint64_t title_va = 0, end = 0, shader_va = 0;
52 bool checked = false; // the whole [shader_va, shader_va + end - title_va) is backed
53};
54
55// Sorted, disjoint [start, end) spans: the backed and ask tables.
56using ConsoleHeapSpans = std::vector<std::pair<std::uint64_t, std::uint64_t>>;
57
58// Sorts and merges spans (overlapping or touching ones become one); empty and wrapping ones are dropped.
59inline void merge_console_heap_spans(ConsoleHeapSpans& spans) {
60 std::erase_if(spans, [](const auto& s) { return s.second <= s.first; });
61 std::sort(spans.begin(), spans.end());
62 std::size_t out = 0;
63 for (std::size_t i = 0; i < spans.size(); ++i) {
64 if (out && spans[i].first <= spans[out - 1].second) spans[out - 1].second = std::max(spans[out - 1].second, spans[i].second);
65 else spans[out++] = spans[i];
66 }
67 spans.resize(out);
68}
69
70// [v, v + bytes) inside one span (bytes 0 counts as 1).
71inline bool console_heap_spans_hold(const ConsoleHeapSpans& spans, std::uint64_t v, std::uint64_t bytes) {
72 auto it = std::upper_bound(spans.begin(), spans.end(), v,
73 [](std::uint64_t x, const auto& s) { return x < s.first; });
74 if (it == spans.begin()) return false;
75 --it;
76 const std::uint64_t n = std::max<std::uint64_t>(bytes, 1);
77 return v < it->second && n <= it->second - v;
78}
79
80// What the reference (and the pass) answers from, besides the key table.
81struct ConsoleHeapTables {
82 std::vector<ConsoleHeapRange> ranges;
83 ConsoleHeapSpans backed;
84 ConsoleHeapSpans ask;
85 bool use_ask = false; // without it every unanswered half is a miss
86 bool signed_offsets = false; // LEONIDA_IMPORT_BELOW_ARENA: a base with bit 47 set is a negative offset
87};
88
89// The key table's CPU mirror. An entry's GPU form is 8 dwords: the key, the answer's low 32 bits, its bits 32-47 and
90// the flags in bits 16-31 of the sixth, two pad dwords.
91class ConsoleHeapKeys {
92public:
93 using Key = std::array<std::uint32_t, 4>;
94 static constexpr std::uint32_t kProbes = 16;
95 static constexpr std::uint32_t kUsed = 1, kNone = 2;
96 static constexpr std::uint32_t kEntryWords = 8, kUpdateWords = 12;
97
98 explicit ConsoleHeapKeys(std::uint32_t log2_entries = 20)
99 : mask_((1u << std::min<std::uint32_t>(log2_entries, 26)) - 1), entries_(std::size_t(mask_) + 1),
100 dirty_flag_(std::size_t(mask_) + 1, 0) {}
101
102 // FNV-1a over the four dwords, then MurmurHash3's fmix32 (console_heap_fix.comp key_hash): the finalizer makes
103 // the low bits, which index the table, depend on every bit of the key. Bare FNV-1a put every V# whose base
104 // differed only above bit 20 into one probe chain, and the 17th of them found no slot.
105 static std::uint32_t hash(const Key& k) {
106 std::uint32_t h = 2166136261u;
107 for (const std::uint32_t w : k) h = (h ^ w) * 16777619u;
108 h ^= h >> 16;
109 h *= 0x85EBCA6Bu;
110 h ^= h >> 13;
111 h *= 0xC2B2AE35u;
112 h ^= h >> 16;
113 return h;
114 }
115
116 std::uint32_t mask() const { return mask_; }
117 std::size_t size() const { return used_; }
118 std::size_t capacity() const { return entries_.size(); }
119
120 // The entry's index, or -1.
121 std::int64_t find(const Key& k) const {
122 const std::uint32_t h = hash(k);
123 for (std::uint32_t p = 0; p < kProbes; ++p) {
124 const std::uint32_t at = (h + p) & mask_;
125 if (entries_[at].flags & kUsed && entries_[at].key == k) return at;
126 }
127 return -1;
128 }
129 // True with the answer when the key is entered: `none` for no backing.
130 bool lookup(const Key& k, std::uint64_t& to, bool& none) const {
131 const std::int64_t at = find(k);
132 if (at < 0) return false;
133 to = entries_[std::size_t(at)].to;
134 none = entries_[std::size_t(at)].flags & kNone;
135 return true;
136 }
137
138 // Enters (or replaces) the answer for `k`: the shader VA `to` reaching `span` bytes, or no backing. False when all
139 // of the key's probe slots hold other keys.
140 bool put(const Key& k, std::uint64_t to, std::uint64_t span, bool none) {
141 std::int64_t at = find(k);
142 if (at < 0) {
143 const std::uint32_t h = hash(k);
144 for (std::uint32_t p = 0; p < kProbes && at < 0; ++p)
145 if (!(entries_[(h + p) & mask_].flags & kUsed)) at = (h + p) & mask_;
146 if (at < 0) return false;
147 ++used_;
148 } else {
149 unindex(std::uint32_t(at));
150 }
151 Entry& e = entries_[std::size_t(at)];
152 e.key = k;
153 e.to = to;
154 e.span = span;
155 e.flags = kUsed | (none ? kNone : 0);
156 if (!none) {
157 by_to_.emplace(to, std::uint32_t(at));
158 longest_ = std::max(longest_, span);
159 }
160 touch(std::uint32_t(at));
161 return true;
162 }
163
164 bool erase(const Key& k) {
165 const std::int64_t at = find(k);
166 if (at < 0) return false;
167 erase_at(std::uint32_t(at));
168 return true;
169 }
170
171 // Every answer reaching into [start, end) of the shader VAs: dropped. Returns how many.
172 std::size_t erase_overlapping(std::uint64_t start, std::uint64_t end) {
173 if (end <= start || by_to_.empty()) return 0;
174 const std::uint64_t from = start > longest_ ? start - longest_ : 0;
175 std::vector<std::uint32_t> gone;
176 for (auto it = by_to_.lower_bound(from); it != by_to_.end() && it->first < end; ++it) {
177 const Entry& e = entries_[it->second];
178 if (e.to + std::max<std::uint64_t>(e.span, 1) > start) gone.push_back(it->second);
179 }
180 for (const std::uint32_t at : gone) erase_at(at);
181 return gone.size();
182 }
183
184 // Every "no backing" answer, for a caller that asks again after something changed: their keys.
185 void take_none(std::vector<Key>& out, std::size_t at_most) {
186 out.clear();
187 for (std::uint32_t at = 0; at < entries_.size() && out.size() < at_most; ++at) {
188 if ((entries_[at].flags & (kUsed | kNone)) != (kUsed | kNone)) continue;
189 out.push_back(entries_[at].key);
190 erase_at(at);
191 }
192 }
193
194 void clear() {
195 for (std::uint32_t at = 0; at < entries_.size(); ++at)
196 if (entries_[at].flags & kUsed) erase_at(at);
197 by_to_.clear();
198 longest_ = 0;
199 }
200 // Everything gone with no updates: for a GPU table that is cleared as a whole (ConsoleHeapGpu::reset_keys).
201 void clear_silent() {
202 std::fill(entries_.begin(), entries_.end(), Entry{});
203 for (const std::uint32_t at : dirty_) dirty_flag_[at] = 0;
204 dirty_.clear();
205 by_to_.clear();
206 used_ = 0;
207 longest_ = 0;
208 }
209
210 void gpu_words(std::uint32_t at, std::uint32_t out[kEntryWords]) const {
211 const Entry& e = entries_[at];
212 std::memset(out, 0, kEntryWords * 4);
213 if (!(e.flags & kUsed)) return;
214 for (int i = 0; i < 4; ++i) out[i] = e.key[i];
215 out[4] = std::uint32_t(e.to);
216 out[5] = std::uint32_t((e.to >> 32) & 0xffffu) | (std::uint32_t(e.flags) << 16);
217 }
218
219 // The entries changed since the last take, as update records (index, 3 pad dwords, the entry's 8 dwords).
220 void take_updates(std::vector<std::uint32_t>& out) {
221 out.clear();
222 out.reserve(dirty_.size() * kUpdateWords);
223 for (const std::uint32_t at : dirty_) {
224 dirty_flag_[at] = 0;
225 const std::size_t base = out.size();
226 out.resize(base + kUpdateWords, 0);
227 out[base] = at;
228 gpu_words(at, out.data() + base + 4);
229 }
230 dirty_.clear();
231 }
232 bool has_updates() const { return !dirty_.empty(); }
233 // Every entry again (a new GPU table, or updates that never reached the GPU).
234 void touch_all() {
235 for (std::uint32_t at = 0; at < entries_.size(); ++at)
236 if (entries_[at].flags & kUsed) touch(at);
237 }
238 void touch(std::uint32_t at) {
239 if (!dirty_flag_[at]) {
240 dirty_flag_[at] = 1;
241 dirty_.push_back(at);
242 }
243 }
244
245private:
246 struct Entry {
247 Key key{};
248 std::uint64_t to = 0;
249 std::uint64_t span = 0;
250 std::uint32_t flags = 0;
251 };
252 void unindex(std::uint32_t at) {
253 const Entry& e = entries_[at];
254 if (!(e.flags & kUsed) || (e.flags & kNone)) return;
255 auto [lo, hi] = by_to_.equal_range(e.to);
256 for (auto it = lo; it != hi; ++it)
257 if (it->second == at) {
258 by_to_.erase(it);
259 break;
260 }
261 }
262 void erase_at(std::uint32_t at) {
263 if (!(entries_[at].flags & kUsed)) return;
264 unindex(at);
265 entries_[at] = Entry{};
266 --used_;
267 touch(at);
268 }
269
270 std::uint32_t mask_;
271 std::vector<Entry> entries_;
272 std::size_t used_ = 0;
273 std::multimap<std::uint64_t, std::uint32_t> by_to_; // positive answers by shader VA
274 std::uint64_t longest_ = 0;
275 std::vector<std::uint32_t> dirty_;
276 std::vector<std::uint8_t> dirty_flag_;
277};
278
279// What the pass does to one V# half (console_heap_fix.comp translate()): 0 left as it is, 1 answered by a table
280// (rebased, written with no records, or left as it is), 2 missed (written with no records).
281inline unsigned console_heap_translate_half(std::uint32_t k[4], const ConsoleHeapTables& t,
282 const ConsoleHeapKeys& keys) {
283 if ((k[3] >> 30) || !k[2]) return 0;
284 const auto no_records = [k] { k[0] = k[1] = k[2] = 0; };
285 const auto rebase = [k](std::uint64_t to) {
286 k[0] = std::uint32_t(to);
287 k[1] = (k[1] & 0xffff0000u) | std::uint32_t((to >> 32) & 0xffffu);
288 };
289 const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffffu) << 32);
290 if (!base) return no_records(), 1;
291 const std::uint32_t stride = (k[1] >> 16) & 0x3fffu;
292 const std::uint64_t span = std::uint64_t(k[2]) * (stride ? stride : 1);
293 auto it = std::upper_bound(t.ranges.begin(), t.ranges.end(), base,
294 [](std::uint64_t va, const ConsoleHeapRange& r) { return va < r.title_va; });
295 if (it != t.ranges.begin()) {
296 const ConsoleHeapRange& r = *std::prev(it);
297 if (base < r.end && r.checked) {
298 if (r.end - base < span) no_records();
299 else rebase(r.shader_va + (base - r.title_va));
300 return 1;
301 }
302 }
303 std::uint64_t offset = base;
304 if (t.signed_offsets && (base & (1ull << 47))) offset |= ~((1ull << 48) - 1);
305 if (console_heap_spans_hold(t.backed, offset, span)) return 1;
306 const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]};
307 std::uint64_t to = 0;
308 bool none = false;
309 if (keys.lookup(key, to, none)) {
310 if (none) no_records();
311 else rebase(to);
312 return 1;
313 }
314 no_records();
315 if (t.use_ask && !console_heap_spans_hold(t.ask, base, 1)) return 1;
316 return 2;
317}
318
319// One 32-byte slot as the pass writes it; the bit of each half that missed (1: dwords 0-3, 2: dwords 4-7).
320// `zero_first`: the work item's bit 31 (ConsoleHeapGpu::kZeroFirst).
321inline unsigned console_heap_translate_slot(std::uint32_t w[8], const ConsoleHeapTables& t,
322 const ConsoleHeapKeys& keys, bool zero_first = false) {
323 if (w[3] >> 30) {
324 if (zero_first) w[0] = w[1] = w[2] = w[3] = 0;
325 else return 0;
326 }
327 unsigned missed = 0;
328 if (console_heap_translate_half(w, t, keys) == 2) missed |= 1;
329 if (console_heap_translate_half(w + 4, t, keys) == 2) missed |= 2;
330 return missed;
331}
332
333// The pass itself: the key table on the GPU, the range table's versions, the slots to translate per heap, and the
334// passes in flight with their miss lists. Every method takes the object's own lock (a leaf: it takes no other).
335class ConsoleHeapGpu {
336public:
337 static constexpr unsigned kMaxHeaps = 8;
338 // A queued slot's bit 31: the slot is neither a buffer pair nor a T# the CPU could decode, and the pass writes its
339 // dwords 0-3 as zeros. The last queue() of a slot before a pass decides it.
340 static constexpr std::uint32_t kZeroFirst = 0x80000000u;
341 static constexpr std::uint32_t kMissCapacity = 1u << 16;
342 static constexpr std::uint32_t kMissHeader = 4;
343
344 struct Stats {
345 std::uint64_t passes = 0, slots = 0, updates = 0, misses = 0, overflows = 0, tables = 0, resets = 0;
346 std::uint64_t rescanned = 0; // slots of rescan() dispatches
347 std::uint64_t filtered = 0; // slots of rescan_filtered() dispatches
348 std::uint64_t copies = 0, copy_bytes = 0; // queue_copy()
349 std::uint64_t failed = 0; // passes whose submission did not reach the queue (their work went back)
350 };
351 enum TableKind : unsigned { range_table, backed_table, ask_table, change_shader_table, change_title_table, table_count };
352
353 ConsoleHeapGpu(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
354 std::uint32_t log2_keys = 20)
355 : get_(get), device_(device), memory_(memory), keys_(log2_keys) {}
356 ~ConsoleHeapGpu() {
357 std::lock_guard lock(mutex_);
358 for (auto& pass : in_flight_) free_buffer(pass.buffer);
359 for (Heap& h : heaps_) free_buffer(h.meta);
360 for (auto& b : retired_) free_buffer(b);
361 for (auto& buffer : pool_) free_buffer(buffer);
362 for (Table& t : tables_) {
363 for (auto& [version, buffer] : t.old) free_buffer(buffer);
364 for (auto& buffer : t.pool) free_buffer(buffer);
365 if (t.current) free_buffer(*t.current);
366 }
367 free_buffer(key_table_);
368 if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr);
369 if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr);
370 }
371 ConsoleHeapGpu(const ConsoleHeapGpu&) = delete;
372 ConsoleHeapGpu& operator=(const ConsoleHeapGpu&) = delete;
373
374 // The pipeline and the GPU key table (device-local, zeroed by the first pass). False: the pass cannot run.
375 bool init() {
376 std::lock_guard lock(mutex_);
377 if (pipeline_) return true;
378 if (!make_pipeline()) return false;
379 const VkDeviceSize bytes = VkDeviceSize(keys_.capacity()) * ConsoleHeapKeys::kEntryWords * 4;
380 if (!make_buffer(bytes, false, key_table_)) return false;
381 clear_keys_ = true;
382 return true;
383 }
384
385 // A heap the pass writes: its title bytes (`input`) and the copy shaders read (`copy`), `slots` 32-byte slots.
386 // -1 when there is no room.
387 // Each heap also gets device-local metadata, 32 bytes a slot (what the pass last made of each V# half), which
388 // lets a filtered rescan pass over the slots no change touches without reading their words (rescan_filtered).
389 int add_heap(VkDeviceAddress input, VkDeviceAddress copy, std::uint32_t slots) {
390 std::lock_guard lock(mutex_);
391 for (unsigned i = 0; i < kMaxHeaps; ++i) {
392 if (heaps_[i].slots) continue;
393 Heap& h = heaps_[i];
394 h = Heap{};
395 h.input = input;
396 h.copy = copy;
397 h.slots = slots;
398 h.queued.assign(slots, 0);
399 if (make_buffer(VkDeviceSize(slots) * 32, false, h.meta)) h.meta_clear = true;
400 return int(i);
401 }
402 return -1;
403 }
404 void remove_heap(int heap) {
405 std::lock_guard lock(mutex_);
406 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
407 if (heaps_[heap].meta.buffer) retired_.push_back(heaps_[heap].meta); // a pass in flight may still write it
408 heaps_[heap] = Heap{};
409 }
410
411 void queue(int heap, std::uint32_t slot) {
412 std::lock_guard lock(mutex_);
413 queue_locked(heap, slot);
414 }
415 // A buffer copy for the start of the next pass, before the heap translation (LEONIDA_SHADOW_GPU: a slot-133 shadow's
416 // pages copied from an import of the title's pages). `keep` (the source import) lives until that pass retires.
417 void queue_copy(VkBuffer src, VkDeviceSize src_offset, VkBuffer dst, VkDeviceSize dst_offset, VkDeviceSize bytes,
418 std::shared_ptr<void> keep) {
419 std::lock_guard lock(mutex_);
420 copies_.push_back({src, dst, {src_offset, dst_offset, bytes}});
421 if (keep) keeps_.push_back(std::move(keep));
422 }
423
424 // Queued copies into `dst` dropped (its buffer is about to go); copies already recorded stay with their pass.
425 void drop_copies_to(VkBuffer dst) {
426 std::lock_guard lock(mutex_);
427 std::erase_if(copies_, [dst](const Copy& c) { return c.dst == dst; });
428 }
429
430 // Every buffer pair of slots [0, slots) translated again by the next pass: one dispatch over the range, no list
431 // (the pass reads each slot's words and leaves the slots that hold no pair as they are).
432 void rescan(int heap, std::uint32_t slots) {
433 std::lock_guard lock(mutex_);
434 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
435 heaps_[heap].rescan = std::max(heaps_[heap].rescan, std::min(slots, heaps_[heap].slots));
436 }
437 // Like rescan(), but only the slots whose metadata meets a change span: `shader` spans of shader VAs (backings and
438 // alias copies that went: a half whose title base or result reaches into one) and `title` spans of title VAs
439 // (alias ranges that went, words answered since: a half whose title base is in one). Without metadata, every
440 // slot of the range, as rescan().
441 void rescan_filtered(int heap, std::uint32_t slots, const ConsoleHeapSpans& shader, const ConsoleHeapSpans& title) {
442 std::lock_guard lock(mutex_);
443 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
444 heaps_[heap].rescan_filtered = std::max(heaps_[heap].rescan_filtered, std::min(slots, heaps_[heap].slots));
445 change_shader_.insert(change_shader_.end(), shader.begin(), shader.end());
446 change_title_.insert(change_title_.end(), title.begin(), title.end());
447 }
448 template <class It>
449 void queue(int heap, It first, It last) {
450 std::lock_guard lock(mutex_);
451 for (; first != last; ++first) queue_locked(heap, *first);
452 }
453
454 // A new range table for the next pass (sorted by title VA, not overlapping).
455 void set_ranges(const std::vector<ConsoleHeapRange>& ranges) {
456 std::lock_guard lock(mutex_);
457 Table& t = tables_[range_table];
458 t.words.clear();
459 for (const ConsoleHeapRange& r : ranges)
460 t.words.insert(t.words.end(), {std::uint32_t(r.title_va), std::uint32_t(r.title_va >> 32),
461 std::uint32_t(r.end), std::uint32_t(r.end >> 32),
462 std::uint32_t(r.shader_va), std::uint32_t(r.shader_va >> 32),
463 r.checked ? 1u : 0u, 0u});
464 t.count = std::uint32_t(ranges.size());
465 t.dirty = true;
466 }
467 // New backed or ask spans (merged) for the next pass.
468 void set_spans(TableKind kind, const ConsoleHeapSpans& spans) {
469 std::lock_guard lock(mutex_);
470 spans_locked(kind, spans);
471 }
472 void spans_locked(TableKind kind, const ConsoleHeapSpans& spans) {
473 Table& t = tables_[kind];
474 t.words.clear();
475 for (const auto& [start, end] : spans)
476 t.words.insert(t.words.end(), {std::uint32_t(start), std::uint32_t(start >> 32), std::uint32_t(end),
477 std::uint32_t(end >> 32)});
478 t.count = std::uint32_t(spans.size());
479 t.dirty = true;
480 if (kind == ask_table) use_ask_ = true;
481 }
482 void set_signed_offsets(bool on) {
483 std::lock_guard lock(mutex_);
484 signed_offsets_ = on;
485 }
486 // Every key entry gone at once (the GPU table is cleared by the next pass), for a table filling up.
487 void reset_keys() {
488 std::lock_guard lock(mutex_);
489 keys_.clear_silent();
490 clear_keys_ = true;
491 ++stats_.resets;
492 }
493
494 template <class F>
495 auto with_keys(F&& f) {
496 std::lock_guard lock(mutex_);
497 return f(keys_);
498 }
499
500 bool pending() {
501 std::lock_guard lock(mutex_);
502 return pending_locked();
503 }
504
505 // Records the pass into `cb`, ahead of the submission's lists: the key table updates, then each heap's queued
506 // slots, between barriers that order it after earlier work on the queue and before everything after it (and the
507 // host's read of the miss list). True when something was recorded; commit() must follow the submit.
508 bool record(VkCommandBuffer cb) {
509 std::lock_guard lock(mutex_);
510 if (!pipeline_ || !pending_locked() || in_flight_.size() >= 64) return false;
511 if (clear_keys_) keys_.touch_all();
512 std::vector<std::uint32_t> updates;
513 keys_.take_updates(updates);
514 const std::uint32_t update_count = std::uint32_t(updates.size() / ConsoleHeapKeys::kUpdateWords);
515 std::size_t work = 0;
516 for (const Heap& h : heaps_) work += h.work.size();
517 const VkDeviceSize bytes = VkDeviceSize(kMissHeader + kMissCapacity) * 4 + VkDeviceSize(work) * 4 +
518 VkDeviceSize(updates.size()) * 4 + 64;
519 Pass pass{};
520 if (!acquire_buffer(bytes, pass.buffer)) {
521 for (std::size_t i = 0; i < updates.size(); i += ConsoleHeapKeys::kUpdateWords) keys_.touch(updates[i]);
522 return false;
523 }
524 // A filtered rescan's change spans, merged, as this pass's change tables.
525 bool filtered = false;
526 for (const Heap& h : heaps_) filtered |= h.rescan_filtered && !h.rescan;
527 ConsoleHeapSpans change_shader, change_title;
528 if (filtered) {
529 change_shader = change_shader_;
530 change_title = change_title_;
531 merge_console_heap_spans(change_shader);
532 merge_console_heap_spans(change_title);
533 spans_locked(change_shader_table, change_shader);
534 spans_locked(change_title_table, change_title);
535 }
536 for (unsigned kind = 0; kind < table_count; ++kind) {
537 if (tables_[kind].dirty && !publish(tables_[kind], kind == range_table ? 32 : 16)) {
538 pool_.push_back(pass.buffer);
539 for (std::size_t i = 0; i < updates.size(); i += ConsoleHeapKeys::kUpdateWords) keys_.touch(updates[i]);
540 return false;
541 }
542 pass.versions[kind] = tables_[kind].version;
543 }
544 auto* words = static_cast<std::uint32_t*>(pass.buffer.mapped);
545 words[0] = 0;
546 words[1] = kMissCapacity;
547 words[2] = 0;
548 words[3] = 0;
549 std::size_t at = kMissHeader + kMissCapacity;
550 const VkDeviceAddress base = pass.buffer.address;
551 const VkDeviceAddress update_address = base + at * 4;
552 if (!updates.empty()) std::memcpy(words + at, updates.data(), updates.size() * 4);
553 at += updates.size();
554 const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
555 const auto dispatch = fn<PFN_vkCmdDispatch>("vkCmdDispatch");
556 const auto push = fn<PFN_vkCmdPushConstants>("vkCmdPushConstants");
557 // The copies first (another kind of work in the same prelude), then what reads their destinations may run.
558 if (!copies_.empty()) {
559 std::sort(copies_.begin(), copies_.end(), [](const Copy& a, const Copy& b) {
560 return a.src != b.src ? a.src < b.src : a.dst < b.dst;
561 });
562 std::vector<VkBufferCopy> regions;
563 const auto copy = fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
564 for (std::size_t i = 0; i < copies_.size();) {
565 std::size_t j = i;
566 regions.clear();
567 while (j < copies_.size() && copies_[j].src == copies_[i].src && copies_[j].dst == copies_[i].dst) {
568 regions.push_back(copies_[j].region);
569 stats_.copy_bytes += copies_[j].region.size;
570 ++j;
571 }
572 copy(cb, copies_[i].src, copies_[i].dst, std::uint32_t(regions.size()), regions.data());
573 stats_.copies += regions.size();
574 i = j;
575 }
576 VkMemoryBarrier copied{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
577 copied.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
578 copied.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
579 barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &copied, 0, nullptr, 0,
580 nullptr);
581 pass.copies = std::move(copies_);
582 pass.keeps = std::move(keeps_);
583 copies_.clear();
584 keeps_.clear();
585 }
586 // No barrier against the queue's earlier work: one from ALL_COMMANDS made every submission wait for the one
587 // before it to finish.
588 // The pass may then rewrite a slot an earlier submission still reads, as the CPU path's memcpy into the copy
589 // always could.
590 fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
591 Push p{};
592 const auto address = [&](TableKind kind) { return tables_[kind].current ? tables_[kind].current->address : 0; };
593 p.ranges = address(range_table);
594 p.backed = address(backed_table);
595 p.ask = address(ask_table);
596 p.keys = key_table_.address;
597 p.misses = base;
598 p.range_count = tables_[range_table].current ? tables_[range_table].count : 0;
599 p.backed_count = tables_[backed_table].current ? tables_[backed_table].count : 0;
600 p.ask_count = tables_[ask_table].current ? tables_[ask_table].count : 0;
601 p.flags = (signed_offsets_ ? 1u : 0u) | (use_ask_ ? 2u : 0u);
602 p.key_mask = keys_.mask();
603 if (clear_keys_) {
604 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, key_table_.buffer, 0, VK_WHOLE_SIZE, 0);
605 VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
606 filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
607 filled.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
608 barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0,
609 nullptr, 0, nullptr);
610 }
611 // New heaps' metadata starts at zero (no half known).
612 bool meta_filled = false;
613 for (Heap& h : heaps_)
614 if (h.meta_clear && h.meta.buffer) {
615 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, h.meta.buffer, 0, VK_WHOLE_SIZE, 0);
616 h.meta_clear = false;
617 meta_filled = true;
618 pass.filled.push_back(int(&h - heaps_.data()));
619 }
620 if (meta_filled) {
621 VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
622 filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
623 filled.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
624 barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0,
625 nullptr, 0, nullptr);
626 }
627 if (update_count) {
628 p.work = update_address; // MODE_UPDATE's records
629 p.count = update_count;
630 p.mode = 1;
631 push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p);
632 dispatch(cb, (update_count + 63) / 64, 1, 1);
633 VkMemoryBarrier written{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
634 written.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
635 written.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
636 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &written, 0,
637 nullptr, 0, nullptr);
638 }
639 p.mode = 0;
640 p.cshader = filtered ? address(change_shader_table) : 0;
641 p.ctitle = filtered ? address(change_title_table) : 0;
642 p.cshader_count = filtered && tables_[change_shader_table].current ? tables_[change_shader_table].count : 0;
643 p.ctitle_count = filtered && tables_[change_title_table].current ? tables_[change_title_table].count : 0;
644 for (unsigned i = 0; i < kMaxHeaps; ++i) {
645 Heap& h = heaps_[i];
646 const bool full = h.rescan != 0;
647 const std::uint32_t slots = full ? std::max(h.rescan, h.rescan_filtered) : h.rescan_filtered;
648 if (!slots) continue;
649 // Before the listed slots, so a slot both rewritten and rescanned ends with its listed (newer) form.
650 p.input_slots = h.input;
651 p.copy_slots = h.copy;
652 p.meta = h.meta.address;
653 p.heap = i;
654 const std::uint32_t flags = p.flags;
655 p.flags |= 4u; // FLAG_RANGE
656 if (!full) p.flags |= 8u; // FLAG_FILTER
657 for (std::uint32_t first = 0; first < slots; first += 65535u * 64u) {
658 const std::uint32_t n = std::min<std::uint32_t>(slots - first, 65535u * 64u);
659 p.work = first;
660 p.count = n;
661 push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p);
662 dispatch(cb, (n + 63) / 64, 1, 1);
663 (full ? stats_.rescanned : stats_.filtered) += n;
664 }
665 p.flags = flags;
666 pass.rescans.push_back({int(i), slots, !full});
667 h.rescan = h.rescan_filtered = 0;
668 }
669 if (filtered) {
670 pass.change_shader = std::move(change_shader);
671 pass.change_title = std::move(change_title);
672 }
673 change_shader_.clear();
674 change_title_.clear();
675 if (!pass.rescans.empty()) { // the listed slots' writes land after the rescan's
676 VkMemoryBarrier rescanned{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
677 rescanned.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
678 rescanned.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
679 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &rescanned,
680 0, nullptr, 0, nullptr);
681 }
682 for (unsigned i = 0; i < kMaxHeaps; ++i) {
683 Heap& h = heaps_[i];
684 if (h.work.empty()) continue;
685 std::memcpy(words + at, h.work.data(), h.work.size() * 4);
686 pass.work.push_back({int(i), std::move(h.work)});
687 const auto& list = pass.work.back().second;
688 for (const std::uint32_t item : list) h.queued[item & ~kZeroFirst] = 0;
689 h.work.clear();
690 p.input_slots = h.input;
691 p.copy_slots = h.copy;
692 p.meta = h.meta.address;
693 p.heap = i;
694 // At most 65535 groups a dispatch (the guaranteed limit).
695 for (std::size_t first = 0; first < list.size(); first += 65535ull * 64) {
696 const std::uint32_t n = std::uint32_t(std::min<std::size_t>(list.size() - first, 65535ull * 64));
697 p.work = base + (at + first) * 4;
698 p.count = n;
699 push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p);
700 dispatch(cb, (n + 63) / 64, 1, 1);
701 stats_.slots += n;
702 }
703 at += list.size();
704 }
705 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
706 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
707 after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_READ_BIT;
708 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
709 0, 1, &after, 0, nullptr, 0, nullptr);
710 pass.updates = std::move(updates);
711 pass.cleared = clear_keys_;
712 clear_keys_ = false;
713 stats_.updates += update_count;
714 ++stats_.passes;
715 in_flight_.push_back(std::move(pass));
716 return true;
717 }
718
719 // After the submit of the command buffer record() wrote into: `ticket` is a retire ticket at or after that
720 // submission. Not submitted: its slots and updates are queued again.
721 void commit(bool submitted, std::uint64_t ticket) {
722 std::lock_guard lock(mutex_);
723 for (auto it = in_flight_.rbegin(); it != in_flight_.rend(); ++it) {
724 if (it->committed) continue;
725 if (submitted) {
726 it->committed = true;
727 it->ticket = ticket;
728 return;
729 }
730 ++stats_.failed;
731 for (const auto& [heap, list] : it->work)
732 if (heaps_[heap].slots)
733 for (const std::uint32_t item : list) queue_locked(heap, item);
734 for (const auto& r : it->rescans) {
735 if (!heaps_[r.heap].slots) continue;
736 auto& to = r.filtered ? heaps_[r.heap].rescan_filtered : heaps_[r.heap].rescan;
737 to = std::max(to, r.slots);
738 }
739 change_shader_.insert(change_shader_.end(), it->change_shader.begin(), it->change_shader.end());
740 change_title_.insert(change_title_.end(), it->change_title.begin(), it->change_title.end());
741 for (const int heap : it->filled)
742 if (heaps_[heap].slots) heaps_[heap].meta_clear = true;
743 copies_.insert(copies_.end(), it->copies.begin(), it->copies.end());
744 keeps_.insert(keeps_.end(), it->keeps.begin(), it->keeps.end());
745 for (std::size_t i = 0; i < it->updates.size(); i += ConsoleHeapKeys::kUpdateWords)
746 keys_.touch(it->updates[i]);
747 if (it->cleared) clear_keys_ = true;
748 pool_.push_back(it->buffer);
749 in_flight_.erase(std::next(it).base());
750 return;
751 }
752 }
753
754 // The passes done by `completed` (a completed retire ticket): `miss(heap, slot, half)` for each V# half they
755 // could not answer, `overflow(heap)` for a heap whose misses ran past the list (-1: every heap).
756 template <class Miss, class Overflow>
757 void drain(std::uint64_t completed, Miss&& miss, Overflow&& overflow) {
758 std::vector<Pass> done;
759 {
760 std::lock_guard lock(mutex_);
761 for (auto it = in_flight_.begin(); it != in_flight_.end();) {
762 if (!it->committed || it->ticket > completed) {
763 ++it;
764 continue;
765 }
766 done.push_back(std::move(*it));
767 it = in_flight_.erase(it);
768 }
769 // Tables no pass in flight still reads go back to their pool.
770 for (unsigned kind = 0; kind < table_count; ++kind) {
771 Table& t = tables_[kind];
772 std::uint64_t oldest = t.version;
773 for (const Pass& pass : in_flight_) oldest = std::min(oldest, pass.versions[kind]);
774 for (auto it = t.old.begin(); it != t.old.end();) {
775 if (it->first < oldest) {
776 if (t.pool.size() < 8) t.pool.push_back(it->second);
777 else free_buffer(it->second);
778 it = t.old.erase(it);
779 } else {
780 ++it;
781 }
782 }
783 }
784 }
785 for (Pass& pass : done) {
786 const auto* words = static_cast<const std::uint32_t*>(pass.buffer.mapped);
787 const std::uint32_t count = std::min(words[0], kMissCapacity);
788 for (std::uint32_t i = 0; i < count; ++i) {
789 const std::uint32_t code = words[kMissHeader + i];
790 miss(int(code >> 29), (code >> 1) & ((1u << 28) - 1), code & 1u);
791 }
792 if (words[2]) overflow(-1);
793 std::lock_guard lock(mutex_);
794 stats_.misses += count;
795 stats_.overflows += words[2] ? 1 : 0;
796 pool_.push_back(pass.buffer);
797 }
798 }
799
800 std::size_t in_flight() {
801 std::lock_guard lock(mutex_);
802 return in_flight_.size();
803 }
804 // A pass recorded and not yet committed: its command buffer is on its way to the queue.
805 bool uncommitted() {
806 std::lock_guard lock(mutex_);
807 return std::any_of(in_flight_.begin(), in_flight_.end(), [](const Pass& p) { return !p.committed; });
808 }
809 Stats take_stats() {
810 std::lock_guard lock(mutex_);
811 return std::exchange(stats_, Stats{});
812 }
813
814private:
815 struct Buffer {
816 VkBuffer buffer = VK_NULL_HANDLE;
817 VkDeviceMemory memory = VK_NULL_HANDLE;
818 VkDeviceAddress address = 0;
819 VkDeviceSize size = 0;
820 void* mapped = nullptr;
821 };
822 struct Heap {
823 VkDeviceAddress input = 0, copy = 0;
824 std::uint32_t slots = 0;
825 std::vector<std::uint32_t> work;
826 std::vector<std::uint32_t> queued; // per slot: its position in `work` + 1, 0 when not queued
827 std::uint32_t rescan = 0; // slots [0, rescan) to translate again (rescan())
828 std::uint32_t rescan_filtered = 0; // the same, filtered by the change spans (rescan_filtered())
829 Buffer meta; // device-local, 32 bytes a slot (console_heap_fix.comp meta_of)
830 bool meta_clear = false;
831 };
832 struct Copy {
833 VkBuffer src, dst;
834 VkBufferCopy region;
835 };
836 struct Pass {
837 Buffer buffer;
838 std::array<std::uint64_t, table_count> versions{};
839 struct Rescan {
840 int heap;
841 std::uint32_t slots;
842 bool filtered;
843 };
844 std::vector<Rescan> rescans;
845 ConsoleHeapSpans change_shader, change_title;
846 std::vector<int> filled; // heaps whose metadata this pass zeroed
847 std::vector<Copy> copies;
848 std::vector<std::shared_ptr<void>> keeps;
849 std::vector<std::pair<int, std::vector<std::uint32_t>>> work;
850 std::vector<std::uint32_t> updates;
851 bool cleared = false, committed = false;
852 std::uint64_t ticket = 0;
853 };
854 struct Push {
855 VkDeviceAddress input_slots, copy_slots, work, ranges, keys, misses, backed, ask, meta, cshader, ctitle;
856 std::uint32_t count, range_count, key_mask, mode, heap, backed_count, ask_count, flags, cshader_count,
857 ctitle_count;
858 };
859 static_assert(sizeof(Push) == 128); // the guaranteed maxPushConstantsSize
860 // A table the CPU rebuilds whole (range, backed, ask): each version is its own buffer, kept until no pass in
861 // flight reads it, then reused.
862 struct Table {
863 std::vector<std::uint32_t> words;
864 std::uint32_t count = 0;
865 bool dirty = false;
866 std::unique_ptr<Buffer> current;
867 std::uint64_t version = 0;
868 std::vector<std::pair<std::uint64_t, Buffer>> old;
869 std::vector<Buffer> pool;
870 };
871
872 template <typename T>
873 T fn(const char* name) const {
874 return reinterpret_cast<T>(get_(device_, name));
875 }
876
877 void queue_locked(int heap, std::uint32_t item) {
878 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
879 Heap& h = heaps_[heap];
880 const std::uint32_t slot = item & ~kZeroFirst;
881 if (slot >= h.slots) return;
882 if (const std::uint32_t at = h.queued[slot]) {
883 h.work[at - 1] = item;
884 return;
885 }
886 h.work.push_back(item);
887 h.queued[slot] = std::uint32_t(h.work.size());
888 }
889 bool pending_locked() const {
890 if (keys_.has_updates() || clear_keys_ || !copies_.empty()) return true;
891 for (const Heap& h : heaps_)
892 if (!h.work.empty() || h.rescan || h.rescan_filtered) return true;
893 return false;
894 }
895
896 bool publish(Table& t, std::size_t entry_bytes) {
897 Buffer table{};
898 if (t.count) {
899 // A version no pass reads any more, when one is big enough: the tables change at most submissions.
900 const VkDeviceSize bytes = VkDeviceSize(t.count) * entry_bytes;
901 for (auto it = t.pool.begin(); it != t.pool.end(); ++it)
902 if (it->size >= bytes) {
903 table = *it;
904 t.pool.erase(it);
905 break;
906 }
907 // Device-local and host-visible where there is such memory: the pass's binary searches read it a few
908 // dozen times per slot, and from system memory each step was a trip over the bus.
909 if (!table.buffer && !make_buffer(std::max<VkDeviceSize>(bytes + bytes / 2, 64 * 1024), true, table, true))
910 return false;
911 std::memcpy(table.mapped, t.words.data(), t.words.size() * 4);
912 }
913 if (t.current) t.old.emplace_back(t.version, *t.current);
914 t.current.reset();
915 if (table.buffer) t.current = std::make_unique<Buffer>(table);
916 ++t.version;
917 t.dirty = false;
918 ++stats_.tables;
919 return true;
920 }
921
922 bool acquire_buffer(VkDeviceSize bytes, Buffer& out) {
923 for (auto it = pool_.begin(); it != pool_.end(); ++it) {
924 if (it->size < bytes) continue;
925 out = *it;
926 pool_.erase(it);
927 return true;
928 }
929 // Room to grow: the next pass of about this size reuses it.
930 return make_buffer(std::max<VkDeviceSize>(bytes + bytes / 2, 1 << 20), true, out);
931 }
932
933 bool make_buffer(VkDeviceSize bytes, bool host, Buffer& out, bool host_device_local = false) {
934 out = {};
935 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
936 info.size = bytes;
937 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
938 VK_BUFFER_USAGE_TRANSFER_DST_BIT;
939 if (fn<PFN_vkCreateBuffer>("vkCreateBuffer")(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false;
940 VkMemoryRequirements requirements{};
941 fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(device_, out.buffer, &requirements);
942 const VkMemoryPropertyFlags required =
943 host ? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT : 0;
944 const VkMemoryPropertyFlags preferred = host ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
945 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
946 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
947 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
948 allocate.allocationSize = requirements.size;
949 // Host-visible: system memory first (not the ReBAR heap the title's windows need).
950 std::vector<std::uint32_t> order;
951 if (host && host_device_local) {
952 order = memory_type_order(memory_, requirements.memoryTypeBits, required | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
953 0, requirements.size);
954 for (const std::uint32_t t : memory_type_order(memory_, requirements.memoryTypeBits, required, 0,
955 requirements.size))
956 if (std::find(order.begin(), order.end(), t) == order.end()) order.push_back(t);
957 } else if (host) {
958 order = memory_type_order(memory_, requirements.memoryTypeBits, required | VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
959 0, requirements.size);
960 for (const std::uint32_t t : memory_type_order(memory_, requirements.memoryTypeBits, required, 0,
961 requirements.size))
962 if (std::find(order.begin(), order.end(), t) == order.end()) order.push_back(t);
963 } else {
964 order = memory_type_order(memory_, requirements.memoryTypeBits, required, preferred, requirements.size);
965 }
966 const auto allocate_memory = fn<PFN_vkAllocateMemory>("vkAllocateMemory");
967 for (const std::uint32_t type : order) {
968 allocate.memoryTypeIndex = type;
969 if (allocate_memory(device_, &allocate, nullptr, &out.memory) == VK_SUCCESS) break;
970 out.memory = VK_NULL_HANDLE;
971 }
972 if (!out.memory ||
973 fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(device_, out.buffer, out.memory, 0) != VK_SUCCESS ||
974 (host && fn<PFN_vkMapMemory>("vkMapMemory")(device_, out.memory, 0, VK_WHOLE_SIZE, 0, &out.mapped) !=
975 VK_SUCCESS)) {
976 free_buffer(out);
977 return false;
978 }
979 VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
980 address.buffer = out.buffer;
981 out.address = fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress")(device_, &address);
982 out.size = bytes;
983 if (!out.address) {
984 free_buffer(out);
985 return false;
986 }
987 return true;
988 }
989 void free_buffer(Buffer& b) {
990 if (b.buffer) fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(device_, b.buffer, nullptr);
991 if (b.memory) fn<PFN_vkFreeMemory>("vkFreeMemory")(device_, b.memory, nullptr); // unmaps
992 b = {};
993 }
994
995 bool make_pipeline() {
996 for (const char* name :
997 {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", "vkFreeMemory",
998 "vkBindBufferMemory", "vkMapMemory", "vkGetBufferDeviceAddress", "vkCreateShaderModule",
999 "vkDestroyShaderModule", "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines",
1000 "vkDestroyPipeline", "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch",
1001 "vkCmdFillBuffer", "vkCmdCopyBuffer"})
1002 if (!get_(device_, name)) return false;
1003 VkShaderModule module = VK_NULL_HANDLE;
1004 VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
1005 shader.codeSize = sizeof(console_heap_fix_spirv);
1006 shader.pCode = console_heap_fix_spirv;
1007 const aftermath::ShaderName aftermath_name("(runtime) console_heap_fix");
1008 bool ok =
1009 fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS;
1010 const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push)};
1011 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
1012 layout_info.pushConstantRangeCount = 1;
1013 layout_info.pPushConstantRanges = &range;
1014 VkPipelineLayout layout = VK_NULL_HANDLE;
1015 VkPipeline pipeline = VK_NULL_HANDLE;
1016 ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) ==
1017 VK_SUCCESS;
1018 VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
1019 info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
1020 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
1021 info.stage.module = module;
1022 info.stage.pName = "main";
1023 info.layout = layout;
1024 ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info,
1025 nullptr, &pipeline) == VK_SUCCESS;
1026 if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr);
1027 if (!ok) {
1028 if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr);
1029 if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr);
1030 return false;
1031 }
1032 layout_ = layout;
1033 pipeline_ = pipeline;
1034 return true;
1035 }
1036
1037 PFN_vkGetDeviceProcAddr get_;
1038 VkDevice device_;
1039 VkPhysicalDeviceMemoryProperties memory_;
1040 std::mutex mutex_;
1041 VkPipelineLayout layout_ = VK_NULL_HANDLE;
1042 VkPipeline pipeline_ = VK_NULL_HANDLE;
1043 ConsoleHeapKeys keys_;
1044 Buffer key_table_;
1045 bool clear_keys_ = false;
1046 std::array<Heap, kMaxHeaps> heaps_{};
1047 std::array<Table, table_count> tables_{};
1048 bool use_ask_ = false, signed_offsets_ = false;
1049 std::vector<Pass> in_flight_;
1050 std::vector<Buffer> pool_;
1051 std::vector<Copy> copies_;
1052 std::vector<std::shared_ptr<void>> keeps_;
1053 ConsoleHeapSpans change_shader_, change_title_; // pending rescan_filtered() spans
1054 std::vector<Buffer> retired_; // removed heaps' metadata
1055 Stats stats_;
1056};
1057
1058} // namespace leonida