upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_bindless.h
diff options
context:
space:
mode:
authoraslan2142 <jan.trencansky@protonmail.com>2026-11-25 02:37:19 +0100
committerGitHub <noreply@github.com>2026-11-25 02:37:19 +0100
commit18a22c1aefa227fd2eda047bab3385147d569f9d (patch)
tree74ad707a670f980da61b5b9e0bc9241dfd6ef181 /runtime/src/vulkan_bindless.h
parent5a5df8e0b6bff458814c934e18f4216e69c40d36 (diff)
parent71a783e56fb6eb591849b5c9fb6618ed3af3f595 (diff)
Merge pull request #984 from Moriz82/integration/proton-story-load
[integration] Linux/Proton and native Windows: boot through the story load (RT-PROTON-STORY-LOAD)
Diffstat (limited to 'runtime/src/vulkan_bindless.h')
-rw-r--r--runtime/src/vulkan_bindless.h325
1 files changed, 260 insertions, 65 deletions
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index cb5b61f65..179ba12e9 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -11,8 +11,9 @@
11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. 11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint.
12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). 12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs).
13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. 13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes.
14// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays 14// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the sampled arrays of every
15// from the device's limits instead; the shaders declare runtime arrays, so any count works for them. 15// single-sample dimension, the samplers and the storage arrays from the device's limits instead; the shaders declare
16// runtime arrays, so any count works for them.
16// 17//
17// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in 18// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in
18// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage 19// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage
@@ -37,6 +38,15 @@
37// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped 38// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped
38// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush. 39// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush.
39// 40//
41// When device-local memory runs out (a title that fills VRAM), a new generation's table goes to HOST_VISIBLE memory
42// instead: slower lookups beat no table. Released generations are kept as spares (at most max_spares) and reused,
43// pool and buffers, by the next replacing flush, so steady churn allocates nothing. If a generation still cannot be
44// made, flush() rewrites the current table in place when every submission that could read it is done, and otherwise
45// degrades: the descriptors are written, the table keeps its last uploaded contents (keys added since find the
46// fallback, index 0; keys rebound since keep their previous index, whose views stay alive; removed indices are not
47// given out again meanwhile) and the change waits for a later flush. A flush never fails the submission for want of
48// memory (last_flush_degraded(), degraded_flushes()).
49//
40// Not thread-safe: the owner serialises calls. 50// Not thread-safe: the owner serialises calls.
41 51
42#ifndef VK_NO_PROTOTYPES 52#ifndef VK_NO_PROTOTYPES
@@ -196,8 +206,13 @@ struct SetLayout {
196}; 206};
197 207
198// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then 208// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then
199// 3-6 MiB (93793 descriptors on an RTX 5070). 209// 5-10 MiB (about 160000 descriptors on an RTX 5070).
200inline constexpr std::uint32_t max_2d_images = 65536; 210inline constexpr std::uint32_t max_2d_images = 65536;
211// The other single-sample dimensions: a title streams far more cube maps and texture arrays (and 1D lookup
212// textures) than the 1024 and 256 of the defaults, each distinct T# of one taking its own index.
213inline constexpr std::uint32_t max_2d_array_images = 16384;
214inline constexpr std::uint32_t max_3d_images = 4096;
215inline constexpr std::uint32_t max_1d_images = 4096;
201inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images 216inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images
202// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can 217// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can
203// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. 218// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set.
@@ -212,8 +227,9 @@ inline constexpr std::uint32_t growth_headroom = 64;
212// standalone samplers do not, though they count in an update-after-bind pool. 227// standalone samplers do not, though they count in an update-after-bind pool.
213// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. 228// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images.
214// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). 229// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off).
215// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says 230// 3. Growth towards the maximums above, in the same order, then the 2D-array, 3D and 1D images, within
216// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. 231// maxPerSetDescriptors. That limit only says what is sure to work (vkGetDescriptorSetLayoutSupport may allow
232// more), so it never shrinks step 1.
217// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a 233// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a
218// storage view an index past the sampled array. The other bindings keep their default counts. 234// storage view an index past the sampled array. The other bindings keep their default counts.
219// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: 235// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument:
@@ -243,10 +259,16 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
243 auto& counts = features.counts; 259 auto& counts = features.counts;
244 counts = default_counts(); 260 counts = default_counts();
245 std::uint32_t images = 1, samplers = 1, storage = 1; 261 std::uint32_t images = 1, samplers = 1, storage = 1;
262 std::uint32_t arrays = counts[sampled_binding(ImageDimension::dim_2d_array)];
263 std::uint32_t volumes = counts[sampled_binding(ImageDimension::dim_3d)];
264 std::uint32_t lines = counts[sampled_binding(ImageDimension::dim_1d)];
246 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only 265 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only
247 // take descriptors away. 266 // take descriptors away.
248 const auto apply = [&](bool final) { 267 const auto apply = [&](bool final) {
249 counts[sampled_binding(ImageDimension::dim_2d)] = images; 268 counts[sampled_binding(ImageDimension::dim_2d)] = images;
269 counts[sampled_binding(ImageDimension::dim_2d_array)] = arrays;
270 counts[sampled_binding(ImageDimension::dim_3d)] = volumes;
271 counts[sampled_binding(ImageDimension::dim_1d)] = lines;
250 counts[sampler_binding] = samplers; 272 counts[sampler_binding] = samplers;
251 for (std::uint32_t d = 0; d < 4; ++d) { 273 for (std::uint32_t d = 0; d < 4; ++d) {
252 const auto dimension = ImageDimension(d); 274 const auto dimension = ImageDimension(d);
@@ -305,6 +327,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
305 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); 327 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit);
306 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); 328 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit);
307 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); 329 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit);
330 grow(arrays, std::max(arrays, max_2d_array_images), growth_headroom, set_limit);
331 grow(volumes, std::max(volumes, max_3d_images), growth_headroom, set_limit);
332 grow(lines, std::max(lines, max_1d_images), growth_headroom, set_limit);
308 apply(true); 333 apply(true);
309 return full; 334 return full;
310} 335}
@@ -313,14 +338,18 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
313 338
314class BindlessSet { 339class BindlessSet {
315public: 340public:
341 // `descriptor_hash` is the finalizer the shaders of this device probe the table with (descriptor_table.h); it is
342 // handed to the table before its first key is inserted, so every insert, lookup and rehash agrees with them.
316 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, 343 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
317 BindlessFeatures features = {}) 344 BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a)
318 : device_(device), memory_(memory), features_(features) { 345 : device_(device), memory_(memory), features_(features), table_(64, descriptor_hash) {
319 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); 346 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill();
320 } 347 }
321 348
322 ~BindlessSet() { 349 ~BindlessSet() {
323 release_retired(); 350 release_retired();
351 for (Generation& spare : spares_) destroy(spare);
352 spares_.clear();
324 destroy(table_buffers_); 353 destroy(table_buffers_);
325 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); 354 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr);
326 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); 355 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr);
@@ -414,16 +443,20 @@ public:
414 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, 443 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout,
415 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 444 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) {
416 const auto& used = image_used_[std::uint32_t(dimension)]; 445 const auto& used = image_used_[std::uint32_t(dimension)];
417 if (index && index < used.size() && used[index]) 446 if (index && index < used.size() && used[index] == in_use)
418 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); 447 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class);
419 } 448 }
420 449
421 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. 450 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first.
451 // While the table has changes the GPU's copy lacks (an erased key may still name the index there), the index is
452 // held until a flush has brought the table up to date (one that did not degrade), so that no new image answers
453 // that key; otherwise it is free at once.
422 void remove_image(ImageDimension dimension, std::uint32_t index) { 454 void remove_image(ImageDimension dimension, std::uint32_t index) {
423 auto& used = image_used_[std::uint32_t(dimension)]; 455 auto& used = image_used_[std::uint32_t(dimension)];
424 if (!index || index >= used.size() || !used[index]) return; 456 if (!index || index >= used.size() || used[index] != in_use) return;
425 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); 457 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0);
426 used[index] = 0; 458 used[index] = table_dirty_ ? held : 0;
459 if (table_dirty_) held_images_.push_back({dimension, index});
427 } 460 }
428 461
429 // 0 when the sampler array is full. 462 // 0 when the sampler array is full.
@@ -434,9 +467,10 @@ public:
434 } 467 }
435 468
436 void remove_sampler(std::uint32_t index) { 469 void remove_sampler(std::uint32_t index) {
437 if (!index || index >= sampler_used_.size() || !sampler_used_[index]) return; 470 if (!index || index >= sampler_used_.size() || sampler_used_[index] != in_use) return;
438 write_sampler(index, fallback_sampler_); 471 write_sampler(index, fallback_sampler_);
439 sampler_used_[index] = 0; 472 sampler_used_[index] = table_dirty_ ? held : 0;
473 if (table_dirty_) held_samplers_.push_back(index);
440 } 474 }
441 475
442 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders 476 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders
@@ -479,7 +513,10 @@ public:
479 void table_upload_result(bool submitted) { 513 void table_upload_result(bool submitted) {
480 if (!upload_in_flight_) return; 514 if (!upload_in_flight_) return;
481 upload_in_flight_ = false; 515 upload_in_flight_ = false;
482 if (submitted) return; 516 if (submitted) {
517 table_on_gpu_ = true; // the current buffers hold a table the GPU was given
518 return;
519 }
483 table_dirty_ = true; 520 table_dirty_ = true;
484 force_full_upload_ = true; 521 force_full_upload_ = true;
485 } 522 }
@@ -488,17 +525,42 @@ public:
488 // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table 525 // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table
489 // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire 526 // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire
490 // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired() 527 // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired()
491 // compares with what has completed. False when the new generation cannot be made: the set then still has the 528 // compares with what has completed.
492 // table as of the last flush. 529 // When the new generation cannot be made (no memory for its buffers or descriptor pool) and `completed_ticket` is
493 bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0) { 530 // given, it is asked what has completed: the generations retired up to there are released (to the spares) and
531 // the generation is tried again; when everything up to `retire_ticket` is done, nothing reads the current table
532 // and it is rewritten in place if it is large enough. Failing both, the flush degrades instead of failing: the
533 // descriptors are written in place, as on a flush that does not replace the table (add_image writes new indices,
534 // which no key of the GPU's table reaches; remove_image writes the fallback, and the index stays held until a
535 // flush that does not degrade), the table keeps what it had, and its changes wait for a later flush
536 // (last_flush_degraded()). False only without a command buffer, when nothing can be recorded.
537 bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0,
538 const std::function<std::uint64_t()>& completed_ticket = {}) {
539 if (!command_buffer) return false;
494 bool replaced = false; 540 bool replaced = false;
495 bool written = true; 541 bool written = true;
496 const bool must_replace = flush_replaces_table(); 542 const bool must_replace = flush_replaces_table();
543 last_flush_degraded_ = false;
497 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced); 544 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced);
545 if (!written && must_replace && completed_ticket) {
546 const std::uint64_t completed = completed_ticket();
547 if (!retired_.empty()) {
548 release_retired(completed);
549 written = upload_table(command_buffer, retire_ticket, replaced);
550 }
551 if (!written && completed >= retire_ticket) written = rewrite_table_in_place(command_buffer);
552 }
498 last_flush_replaced_ = replaced; 553 last_flush_replaced_ = replaced;
499 // The new generation could not be made: the current set is the one running work reads, so its descriptors are 554 // Degrading keeps what the current buffers hold, so only once they hold a table that reached the queue: a
500 // not written in place either. The pending writes and the table's changes stay for the next flush. 555 // first flush under full memory, or one after a failed submission of the only upload, has nothing on the GPU
501 if (!written && must_replace) return false; 556 // (word 0 is the probe mask) and refuses as before (review of #64).
557 if (!written && must_replace && !table_on_gpu_) return false;
558 if (!written && must_replace) {
559 // The current set is the one running work reads, and the table's changes may move or rebind live keys:
560 // they stay for a later flush, and keys added since find the fallback until then.
561 ++degraded_flushes_;
562 last_flush_degraded_ = true;
563 }
502 for (const Pending& pending : pending_) { 564 for (const Pending& pending : pending_) {
503 if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue; 565 if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue;
504 shadow_[pending.binding][pending.index] = pending.info; 566 shadow_[pending.binding][pending.index] = pending.info;
@@ -521,17 +583,29 @@ public:
521 } 583 }
522 pending_.clear(); 584 pending_.clear();
523 pending_slots_.clear(); 585 pending_slots_.clear();
524 return written; 586 if (!last_flush_degraded_) {
587 // The table this flush leaves on the GPU names no removed index any more: they can be given out again.
588 for (const auto& [dimension, index] : held_images_) image_used_[std::uint32_t(dimension)][index] = 0;
589 for (const std::uint32_t index : held_samplers_) sampler_used_[index] = 0;
590 held_images_.clear();
591 held_samplers_.clear();
592 }
593 return true;
525 } 594 }
526 595
527 // Frees the generations (table buffers and descriptor set) that flush() retired with a ticket up to `completed`. 596 // Releases the generations (table buffers and descriptor set) that flush() retired with a ticket up to
528 // The default frees all of them: when nothing submitted before the last flush() still runs. 597 // `completed`: up to max_spares of them, large enough for the table, are kept for the next replacing flush to
598 // reuse; the others are freed. The default releases all of them: when nothing submitted before the last flush()
599 // still runs.
529 void release_retired(std::uint64_t completed = UINT64_MAX) { 600 void release_retired(std::uint64_t completed = UINT64_MAX) {
530 std::size_t kept = 0; 601 std::size_t kept = 0;
531 for (auto& generation : retired_) { 602 for (auto& generation : retired_) {
532 if (generation.ticket <= completed) { 603 if (generation.ticket <= completed) {
533 destroy(generation.buffers); 604 if (spares_.size() < max_spares && generation.pool && generation.buffers.staging.mapped &&
534 if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); 605 generation.buffers.table.size >= table_.size_bytes())
606 spares_.push_back(generation);
607 else
608 destroy(generation);
535 } else { 609 } else {
536 retired_[kept++] = generation; 610 retired_[kept++] = generation;
537 } 611 }
@@ -548,11 +622,32 @@ public:
548 std::uint64_t generations_made() const { return generations_made_; } 622 std::uint64_t generations_made() const { return generations_made_; }
549 std::size_t retired_count() const { return retired_.size(); } 623 std::size_t retired_count() const { return retired_.size(); }
550 624
625 // Released generations kept for reuse, and how many replacing flushes reused one instead of allocating. One: the
626 // current generation and a spare are the two a replacing flush has at its peak anyway (the new one, and the one
627 // retired until its work completes), and a grown table can be large (64 MiB at a million slots).
628 static constexpr std::size_t max_spares = 1;
629 std::size_t spare_count() const { return spares_.size(); }
630 std::uint64_t spares_reused() const { return spares_reused_; }
631 // Flushes that could not make the generation they needed and kept the previous table (see flush()), and whether
632 // the last one did; flushes that rewrote the table in place instead, every submission being done.
633 std::uint64_t degraded_flushes() const { return degraded_flushes_; }
634 bool last_flush_degraded() const { return last_flush_degraded_; }
635 std::uint64_t in_place_rewrites() const { return in_place_rewrites_; }
636 // Table buffers placed in HOST_VISIBLE memory because the DEVICE_LOCAL allocation failed.
637 std::uint64_t table_host_fallbacks() const { return table_host_fallbacks_; }
638 // What the last generation that could not be made failed to get: "table buffer", "staging buffer" or
639 // "descriptor set" (nullptr before any failure), and the Vulkan result of that call.
640 const char* last_failure() const { return last_failure_; }
641 VkResult last_failure_result() const { return last_failure_result_; }
642 // Bytes of the current table buffer (the table grows by doubling its slots: size_bytes() of table()).
643 std::size_t table_buffer_bytes() const { return table_buffers_.table.size; }
644
551private: 645private:
552 struct Functions { 646 struct Functions {
553#define LEONIDA_BINDLESS_FUNCTIONS(X) \ 647#define LEONIDA_BINDLESS_FUNCTIONS(X) \
554 X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ 648 X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \
555 X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) \ 649 X(vkDestroyDescriptorPool) X(vkResetDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \
650 X(vkCreateBuffer) \
556 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ 651 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \
557 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ 652 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \
558 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ 653 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \
@@ -583,6 +678,7 @@ private:
583 VkDeviceMemory memory = VK_NULL_HANDLE; 678 VkDeviceMemory memory = VK_NULL_HANDLE;
584 void* mapped = nullptr; 679 void* mapped = nullptr;
585 std::size_t size = 0; 680 std::size_t size = 0;
681 bool device_local = false; // the memory is DEVICE_LOCAL
586 }; 682 };
587 683
588 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes. 684 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes.
@@ -591,6 +687,13 @@ private:
591 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT 687 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT
592 }; 688 };
593 689
690 struct Generation { // what a replaced table leaves for release_retired()
691 TableBuffers buffers;
692 VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set
693 VkDescriptorSet set = VK_NULL_HANDLE;
694 std::uint64_t ticket = 0;
695 };
696
594 struct Pending { 697 struct Pending {
595 std::uint32_t binding; 698 std::uint32_t binding;
596 std::uint32_t index; 699 std::uint32_t index;
@@ -598,6 +701,9 @@ private:
598 }; 701 };
599 702
600 static constexpr std::uint32_t dimensions = 6, classes = 3; 703 static constexpr std::uint32_t dimensions = 6, classes = 3;
704 // image_used_ and sampler_used_: 0 free, in_use, or held (removed while the table was dirty: free after the next
705 // flush that does not degrade).
706 static constexpr std::uint8_t in_use = 1, held = 2;
601 707
602 // The first free index in [begin, end), marked used; 0 when there is none. 708 // The first free index in [begin, end), marked used; 0 when there is none.
603 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) { 709 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) {
@@ -645,21 +751,35 @@ private:
645 pool_info.maxSets = 1; 751 pool_info.maxSets = 1;
646 pool_info.poolSizeCount = pool_size_count_; 752 pool_info.poolSizeCount = pool_size_count_;
647 pool_info.pPoolSizes = pool_sizes_.data(); 753 pool_info.pPoolSizes = pool_sizes_.data();
648 if (vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool) != VK_SUCCESS) { 754 if (const VkResult result = vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool);
755 result != VK_SUCCESS) {
649 pool = VK_NULL_HANDLE; 756 pool = VK_NULL_HANDLE;
757 note_failure("descriptor set", result);
650 return false; 758 return false;
651 } 759 }
760 if (allocate_set(pool, set)) return true;
761 vk_.vkDestroyDescriptorPool(device_, pool, nullptr);
762 pool = VK_NULL_HANDLE;
763 return false;
764 }
765
766 bool allocate_set(VkDescriptorPool pool, VkDescriptorSet& set) const {
652 VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; 767 VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
653 set_info.descriptorPool = pool; 768 set_info.descriptorPool = pool;
654 set_info.descriptorSetCount = 1; 769 set_info.descriptorSetCount = 1;
655 set_info.pSetLayouts = &layout_; 770 set_info.pSetLayouts = &layout_;
656 if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set) == VK_SUCCESS) return true; 771 const VkResult result = vk_.vkAllocateDescriptorSets(device_, &set_info, &set);
657 vk_.vkDestroyDescriptorPool(device_, pool, nullptr); 772 if (result == VK_SUCCESS) return true;
658 pool = VK_NULL_HANDLE;
659 set = VK_NULL_HANDLE; 773 set = VK_NULL_HANDLE;
774 note_failure("descriptor set", result);
660 return false; 775 return false;
661 } 776 }
662 777
778 void note_failure(const char* what, VkResult result) const {
779 last_failure_ = what;
780 last_failure_result_ = result;
781 }
782
663 // Writes every descriptor written so far (the shadow) into the current set, one update per run of written 783 // Writes every descriptor written so far (the shadow) into the current set, one update per run of written
664 // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows. 784 // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows.
665 void write_shadow() const { 785 void write_shadow() const {
@@ -753,36 +873,53 @@ private:
753 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; 873 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS;
754 } 874 }
755 875
756 bool create(TableBuffer& out, std::size_t bytes, bool device_local, bool* got_device_local = nullptr) const { 876 // device_local: the table (DEVICE_LOCAL, else HOST_VISIBLE when the device has no such type or that heap is out
877 // of memory); otherwise the mapped staging buffer (HOST_VISIBLE | HOST_COHERENT).
878 bool create(TableBuffer& out, std::size_t bytes, bool device_local) {
879 constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
880 const char* what = device_local ? "table buffer" : "staging buffer";
757 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 881 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
758 info.size = bytes; 882 info.size = bytes;
759 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | 883 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
760 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); 884 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
761 TableBuffer made; 885 TableBuffer made;
762 made.size = bytes; 886 made.size = bytes;
763 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; 887 if (const VkResult result = vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer); result != VK_SUCCESS) {
888 made.buffer = VK_NULL_HANDLE;
889 note_failure(what, result);
890 return false;
891 }
764 VkMemoryRequirements requirements{}; 892 VkMemoryRequirements requirements{};
765 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); 893 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements);
766 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; 894 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
767 allocation.allocationSize = requirements.size; 895 allocation.allocationSize = requirements.size;
768 allocation.memoryTypeIndex = 896 const auto allocate = [&](std::uint32_t type) {
769 device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) 897 if (type == 0xffffffffu) return VK_ERROR_OUT_OF_DEVICE_MEMORY;
770 : memory_type(requirements.memoryTypeBits, 898 allocation.memoryTypeIndex = type;
771 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 899 const VkResult result = vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory);
772 if (device_local && allocation.memoryTypeIndex == 0xffffffffu) 900 if (result != VK_SUCCESS) made.memory = VK_NULL_HANDLE;
773 allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, 901 return result;
774 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | 902 };
775 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 903 const std::uint32_t local = device_local
776 if (got_device_local) 904 ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
777 *got_device_local = allocation.memoryTypeIndex != 0xffffffffu && 905 : 0xffffffffu;
778 (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags & 906 VkResult result = device_local ? allocate(local) : allocate(memory_type(requirements.memoryTypeBits, host));
907 if (result != VK_SUCCESS && device_local) {
908 const std::uint32_t fallback = memory_type(requirements.memoryTypeBits, host);
909 if (fallback != local) {
910 result = allocate(fallback);
911 if (result == VK_SUCCESS && local != 0xffffffffu) ++table_host_fallbacks_;
912 }
913 }
914 if (result == VK_SUCCESS) {
915 made.device_local = (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags &
779 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; 916 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0;
780 bool ready = allocation.memoryTypeIndex != 0xffffffffu && 917 result = vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0);
781 vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && 918 }
782 vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS; 919 if (result == VK_SUCCESS && !device_local)
783 if (ready && !device_local) 920 result = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped);
784 ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; 921 if (result != VK_SUCCESS) {
785 if (!ready) { 922 note_failure(what, result);
786 destroy(made); 923 destroy(made);
787 return false; 924 return false;
788 } 925 }
@@ -801,17 +938,55 @@ private:
801 destroy(buffers.table); 938 destroy(buffers.table);
802 } 939 }
803 940
941 void destroy(Generation& generation) const {
942 destroy(generation.buffers);
943 if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); // frees the set
944 generation.pool = VK_NULL_HANDLE;
945 generation.set = VK_NULL_HANDLE;
946 }
947
948 // A generation for a table of `bytes`: a spare when one is large enough (its pool reset for a fresh set), else
949 // new buffers and a new pool. Spares too small for the table are freed: the table never shrinks.
950 bool make_generation(std::size_t bytes, TableBuffers& buffers, VkDescriptorPool& pool, VkDescriptorSet& set) {
951 std::size_t kept = 0;
952 bool found = false;
953 for (Generation& spare : spares_) {
954 if (spare.buffers.table.size < bytes || spare.buffers.staging.size < bytes) {
955 destroy(spare);
956 continue;
957 }
958 if (!found && vk_.vkResetDescriptorPool(device_, spare.pool, 0) == VK_SUCCESS &&
959 allocate_set(spare.pool, set)) {
960 buffers = spare.buffers;
961 pool = spare.pool;
962 found = true;
963 ++spares_reused_;
964 continue;
965 }
966 spares_[kept++] = spare;
967 }
968 spares_.resize(kept);
969 if (found) return true;
970 TableBuffers made;
971 if (!create(made.table, bytes, true) || !create(made.staging, bytes, false) || !make_set(pool, set)) {
972 destroy(made);
973 return false;
974 }
975 buffers = made;
976 return true;
977 }
978
804 bool create_table_buffers() { 979 bool create_table_buffers() {
805 const std::size_t bytes = table_.size_bytes(); 980 const std::size_t bytes = table_.size_bytes();
806 TableBuffers made; 981 TableBuffers made;
807 bool device_local = false; 982 if (!create(made.table, bytes, true) || !create(made.staging, bytes, false)) {
808 if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) {
809 destroy(made); 983 destroy(made);
810 return false; 984 return false;
811 } 985 }
812 table_buffers_ = made; 986 table_buffers_ = made;
813 table_device_local_ = device_local; 987 table_device_local_ = made.table.device_local;
814 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it 988 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it
989 table_on_gpu_ = false;
815 table_dirty_ = existing_entries_changed_ = false; 990 table_dirty_ = existing_entries_changed_ = false;
816 return true; 991 return true;
817 } 992 }
@@ -829,15 +1004,11 @@ private:
829 TableBuffers larger; 1004 TableBuffers larger;
830 VkDescriptorPool pool = VK_NULL_HANDLE; 1005 VkDescriptorPool pool = VK_NULL_HANDLE;
831 VkDescriptorSet set = VK_NULL_HANDLE; 1006 VkDescriptorSet set = VK_NULL_HANDLE;
832 bool device_local = false; 1007 if (!make_generation(bytes, larger, pool, set)) return false;
833 if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false) || 1008 table_device_local_ = larger.table.device_local;
834 !make_set(pool, set)) {
835 destroy(larger);
836 return false;
837 }
838 table_device_local_ = device_local;
839 retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); 1009 retired_.push_back({table_buffers_, pool_, set_, retire_ticket});
840 table_buffers_ = larger; 1010 table_buffers_ = larger;
1011 table_on_gpu_ = false; // until this generation's upload is submitted (table_upload_result)
841 pool_ = pool; 1012 pool_ = pool;
842 set_ = set; 1013 set_ = set;
843 write_table_binding(table_buffers_.table.buffer); 1014 write_table_binding(table_buffers_.table.buffer);
@@ -893,6 +1064,25 @@ private:
893 return true; 1064 return true;
894 } 1065 }
895 1066
1067 // The whole table into the current generation's buffers, for a flush whose new generation could not be made,
1068 // once every submission that could read the current table is done (flush()). False when the table outgrew them.
1069 bool rewrite_table_in_place(VkCommandBuffer command_buffer) {
1070 const std::size_t bytes = table_.size_bytes();
1071 if (bytes > table_buffers_.table.size || bytes > table_buffers_.staging.size || !table_buffers_.staging.mapped)
1072 return false;
1073 table_.take_changes(); // all of it goes
1074 // Nothing still runs that copies from the staging buffer or reads the table.
1075 table_.write_to_buffer(table_buffers_.staging.mapped);
1076 copy_table_range(command_buffer, 0, bytes);
1077 record_table_barrier(command_buffer);
1078 upload_in_flight_ = true;
1079 table_dirty_ = existing_entries_changed_ = false;
1080 table_uploaded_ = true;
1081 force_full_upload_ = false;
1082 ++in_place_rewrites_;
1083 return true;
1084 }
1085
896 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging 1086 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging
897 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy. 1087 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy.
898 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data, 1088 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data,
@@ -1026,25 +1216,30 @@ private:
1026 bool fallbacks_ready_ = false; 1216 bool fallbacks_ready_ = false;
1027 std::array<std::vector<std::uint8_t>, dimensions> image_used_; 1217 std::array<std::vector<std::uint8_t>, dimensions> image_used_;
1028 std::vector<std::uint8_t> sampler_used_; 1218 std::vector<std::uint8_t> sampler_used_;
1219 std::vector<std::pair<ImageDimension, std::uint32_t>> held_images_; // removed, not yet free (remove_image)
1220 std::vector<std::uint32_t> held_samplers_;
1029 std::vector<Pending> pending_; 1221 std::vector<Pending> pending_;
1030 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_ 1222 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_
1031 DescriptorTable table_{64}; 1223 DescriptorTable table_; // 64 slots, and the device's hash kind, from the constructor
1032 TableBuffers table_buffers_; 1224 TableBuffers table_buffers_;
1033 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table 1225 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table
1226 bool table_on_gpu_ = false; // an upload into the current table buffers reached the queue (degrading is safe)
1034 bool table_device_local_ = false; 1227 bool table_device_local_ = false;
1035 bool table_dirty_ = false; // the table differs from the buffer 1228 bool table_dirty_ = false; // the table differs from the buffer
1036 bool existing_entries_changed_ = false; // ... and not only by entries added 1229 bool existing_entries_changed_ = false; // ... and not only by entries added
1037 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue 1230 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue
1038 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush 1231 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush
1039 struct Generation { // what a replaced table leaves for release_retired()
1040 TableBuffers buffers;
1041 VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set
1042 VkDescriptorSet set = VK_NULL_HANDLE;
1043 std::uint64_t ticket = 0;
1044 };
1045 std::vector<Generation> retired_; 1232 std::vector<Generation> retired_;
1233 std::vector<Generation> spares_; // released generations kept for reuse (release_retired)
1046 std::uint64_t generations_made_ = 0; 1234 std::uint64_t generations_made_ = 0;
1047 bool last_flush_replaced_ = false; 1235 bool last_flush_replaced_ = false;
1236 bool last_flush_degraded_ = false;
1237 std::uint64_t spares_reused_ = 0;
1238 std::uint64_t degraded_flushes_ = 0;
1239 std::uint64_t in_place_rewrites_ = 0;
1240 std::uint64_t table_host_fallbacks_ = 0;
1241 mutable const char* last_failure_ = nullptr;
1242 mutable VkResult last_failure_result_ = VK_SUCCESS;
1048 std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{}; 1243 std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{};
1049 std::uint32_t pool_size_count_ = 0; 1244 std::uint32_t pool_size_count_ = 0;
1050 // Every descriptor written to the set (the table's binding aside), to fill the next generation's set. 1245 // Every descriptor written to the set (the table's binding aside), to fill the next generation's set.