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:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
commit154e4ec034902deffa4b89b2cbca9a949f38baec (patch)
tree1b2ef5656de42c172291bc6009efa4c510650815 /runtime/src/vulkan_bindless.h
parenteb6a08cd359d98b5777e70d54d0ae8a75879495a (diff)
parent8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (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/vulkan_bindless.h')
-rw-r--r--runtime/src/vulkan_bindless.h331
1 files changed, 261 insertions, 70 deletions
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).
213inline constexpr std::uint32_t max_2d_images = 65536; 223inline constexpr std::uint32_t max_2d_images = 65536;
224// The other single-sample dimensions: a title streams far more cube maps and texture arrays (and 1D lookup
225// textures) than the 1024 and 256 of the defaults, each distinct T# of one taking its own index.
214inline constexpr std::uint32_t max_2d_array_images = 16384; 226inline constexpr std::uint32_t max_2d_array_images = 16384;
227inline constexpr std::uint32_t max_3d_images = 4096;
228inline constexpr std::uint32_t max_1d_images = 4096;
215inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images 229inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images
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
337class BindlessSet { 356class BindlessSet {
338public: 357public:
358 // `descriptor_hash` is the finalizer the shaders of this device probe the table with (descriptor_table.h); it is
359 // handed to the table before its first key is inserted, so every insert, lookup and rehash agrees with them.
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
576private: 666private:
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.