diff options
| author | Rafael <rafaelalvesp2005@gmail.com> | 2026-11-23 15:36:26 -0300 |
|---|---|---|
| committer | Rafael <rafaelalvesp2005@gmail.com> | 2026-11-23 15:36:26 -0300 |
| commit | 63f0e0dea3a9d44201db408c4e2c3f2f5b2b94d6 (patch) | |
| tree | 86f0dcad8070e2a3a693ef4897aa83950cfeb224 /runtime/src/vulkan_backend.h | |
| parent | f78f7d6a2a9364cb128c03ac539fe540d5c70df1 (diff) | |
| parent | 6dda0630bd6fc0514baadb94fb98e36bd7d64c0b (diff) | |
Merge main into fix/walk-bink_names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/vulkan_backend.h')
| -rw-r--r-- | runtime/src/vulkan_backend.h | 1071 |
1 files changed, 901 insertions, 170 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index d247b8cb0..e659a762d 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -46,6 +46,15 @@ | |||
| 46 | 46 | ||
| 47 | namespace leonida { | 47 | namespace leonida { |
| 48 | 48 | ||
| 49 | // A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes. | ||
| 50 | // Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame. | ||
| 51 | struct KhrInstanceStage { | ||
| 52 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 53 | VkDeviceMemory memory = VK_NULL_HANDLE; | ||
| 54 | VkDeviceAddress address = 0; | ||
| 55 | std::uint64_t size = 0; // bytes available in buffer, so a larger later list can be refused for a new stage | ||
| 56 | }; | ||
| 57 | |||
| 49 | // VK_EXT_debug_utils labels: an instance extension, so a device has them only when its instance enabled it. | 58 | // VK_EXT_debug_utils labels: an instance extension, so a device has them only when its instance enabled it. |
| 50 | struct DebugLabelFunctions { | 59 | struct DebugLabelFunctions { |
| 51 | PFN_vkCmdInsertDebugUtilsLabelEXT cmd_insert = nullptr; | 60 | PFN_vkCmdInsertDebugUtilsLabelEXT cmd_insert = nullptr; |
| @@ -85,16 +94,19 @@ struct VulkanDeviceFunctions { | |||
| 85 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ | 94 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ |
| 86 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ | 95 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ |
| 87 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ | 96 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ |
| 88 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \ | 97 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ |
| 89 | X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ | 98 | X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ |
| 90 | X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) | 99 | X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ |
| 100 | X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ | ||
| 101 | X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) | ||
| 91 | #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; | 102 | #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; |
| 92 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) | 103 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) |
| 93 | #undef LEONIDA_VK_MEMBER | 104 | #undef LEONIDA_VK_MEMBER |
| 94 | 105 | ||
| 95 | // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering) when the | 106 | // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering, mesh |
| 96 | // extension is not enabled, and the query functions are optional (a list that uses queries without them is | 107 | // shaders) when the extension is not enabled, and the query functions are optional (a list that uses queries |
| 97 | // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. | 108 | // without them is unsupported). The compute and descriptor functions are needed for normalized or summed |
| 109 | // occlusion results. | ||
| 98 | bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { | 110 | bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { |
| 99 | #define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name)); | 111 | #define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name)); |
| 100 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) | 112 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) |
| @@ -200,7 +212,8 @@ public: | |||
| 200 | write.pBufferInfo = &storage; | 212 | write.pBufferInfo = &storage; |
| 201 | vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr); | 213 | vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr); |
| 202 | 214 | ||
| 203 | const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(std::uint32_t)}; | 215 | // The count, and for statistics_sum.comp whether the segments are mesh-pool results. |
| 216 | const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, 2 * sizeof(std::uint32_t)}; | ||
| 204 | VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | 217 | VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; |
| 205 | layout.setLayoutCount = 1; | 218 | layout.setLayoutCount = 1; |
| 206 | layout.pSetLayouts = &set_layout_; | 219 | layout.pSetLayouts = &set_layout_; |
| @@ -220,21 +233,28 @@ public: | |||
| 220 | create_pipeline(statistics_sum_spirv, statistics_pipeline_)); | 233 | create_pipeline(statistics_sum_spirv, statistics_pipeline_)); |
| 221 | } | 234 | } |
| 222 | 235 | ||
| 223 | // Adds `count` pipeline-statistics results (11 counters each) into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at | 236 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the |
| 224 | // dst + offset: the segments of a statistics query that was split around helper dispatches (D3D-162). | 237 | // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). |
| 225 | void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, | 238 | // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see |
| 226 | VkBuffer dst, VkDeviceSize offset) const { | 239 | // statistics_sum.comp), otherwise in `queries` (all eleven). |
| 240 | void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh, | ||
| 241 | std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { | ||
| 227 | constexpr VkDeviceSize result = statistics_counters * word_size; | 242 | constexpr VkDeviceSize result = statistics_counters * word_size; |
| 243 | constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes | ||
| 228 | begin_scratch_write(cb); | 244 | begin_scratch_write(cb); |
| 229 | vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); | 245 | vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); |
| 230 | bind(cb, statistics_pipeline_); | 246 | bind(cb, statistics_pipeline_); |
| 231 | while (count) { | 247 | while (count) { |
| 232 | const auto chunk = std::min(count, statistics_capacity); | 248 | const bool in_mesh = mesh && mesh[first]; |
| 233 | vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, result, result, | 249 | std::uint32_t chunk = 1; |
| 250 | while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) | ||
| 251 | ++chunk; | ||
| 252 | vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, | ||
| 253 | result + (in_mesh ? mesh_slot : 0), result, | ||
| 234 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | 254 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); |
| 235 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, | 255 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, |
| 236 | shader_access); | 256 | shader_access); |
| 237 | dispatch(cb, chunk, 1); | 257 | dispatch(cb, chunk, 1, in_mesh); |
| 238 | first += chunk; | 258 | first += chunk; |
| 239 | count -= chunk; | 259 | count -= chunk; |
| 240 | if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); | 260 | if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); |
| @@ -328,8 +348,9 @@ private: | |||
| 328 | vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); | 348 | vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); |
| 329 | } | 349 | } |
| 330 | 350 | ||
| 331 | void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups) const { | 351 | void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups, bool mesh = false) const { |
| 332 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(chunk), &chunk); | 352 | const std::uint32_t range[2] = {chunk, mesh ? 1u : 0u}; |
| 353 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(range), range); | ||
| 333 | vk_.vkCmdDispatch(cb, groups, 1, 1); | 354 | vk_.vkCmdDispatch(cb, groups, 1, 1); |
| 334 | } | 355 | } |
| 335 | 356 | ||
| @@ -381,6 +402,8 @@ private: | |||
| 381 | VkPipeline statistics_pipeline_ = VK_NULL_HANDLE; | 402 | VkPipeline statistics_pipeline_ = VK_NULL_HANDLE; |
| 382 | }; | 403 | }; |
| 383 | 404 | ||
| 405 | struct SparseResource; | ||
| 406 | |||
| 384 | // Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. | 407 | // Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. |
| 385 | class DeferredDeletionQueue { | 408 | class DeferredDeletionQueue { |
| 386 | public: | 409 | public: |
| @@ -388,9 +411,11 @@ public: | |||
| 388 | bindless_slot, | 411 | bindless_slot, |
| 389 | image_view, | 412 | image_view, |
| 390 | image, | 413 | image, |
| 414 | sparse_resource, | ||
| 391 | buffer, | 415 | buffer, |
| 392 | device_memory, | 416 | device_memory, |
| 393 | acceleration_structure, | 417 | acceleration_structure, |
| 418 | framebuffer, | ||
| 394 | }; | 419 | }; |
| 395 | 420 | ||
| 396 | struct Item { | 421 | struct Item { |
| @@ -464,6 +489,10 @@ public: | |||
| 464 | case Kind::image: | 489 | case Kind::image: |
| 465 | vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); | 490 | vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); |
| 466 | break; | 491 | break; |
| 492 | case Kind::sparse_resource: | ||
| 493 | // Releases the resource and its page backing together after outstanding submissions. | ||
| 494 | delete reinterpret_cast<std::shared_ptr<SparseResource>*>(item.handle); | ||
| 495 | break; | ||
| 467 | case Kind::buffer: | 496 | case Kind::buffer: |
| 468 | vk.vkDestroyBuffer(device, reinterpret_cast<VkBuffer>(item.handle), nullptr); | 497 | vk.vkDestroyBuffer(device, reinterpret_cast<VkBuffer>(item.handle), nullptr); |
| 469 | break; | 498 | break; |
| @@ -475,6 +504,9 @@ public: | |||
| 475 | vk.vkDestroyAccelerationStructureKHR( | 504 | vk.vkDestroyAccelerationStructureKHR( |
| 476 | device, reinterpret_cast<VkAccelerationStructureKHR>(item.handle), nullptr); | 505 | device, reinterpret_cast<VkAccelerationStructureKHR>(item.handle), nullptr); |
| 477 | break; | 506 | break; |
| 507 | case Kind::framebuffer: | ||
| 508 | vk.vkDestroyFramebuffer(device, reinterpret_cast<VkFramebuffer>(item.handle), nullptr); | ||
| 509 | break; | ||
| 478 | } | 510 | } |
| 479 | } | 511 | } |
| 480 | } | 512 | } |
| @@ -507,6 +539,20 @@ public: | |||
| 507 | std::function<void()> callback; | 539 | std::function<void()> callback; |
| 508 | }; | 540 | }; |
| 509 | 541 | ||
| 542 | // A dispatch runs outside mutex_. Each entry in a ready batch gets its own slot: a callback may re-entrantly | ||
| 543 | // call cancel() for a later entry in the same batch, which marks that entry cancelled so it is skipped before | ||
| 544 | // it can use the semaphore. A callback running on another thread must still be waited for. | ||
| 545 | // A cancelled entry still in pending_ is dispatched by cancel() itself (callback and bookkeeping both run); | ||
| 546 | // one already in a ready batch is skipped and only its event is signalled. The held Signal op's count is | ||
| 547 | // therefore not decremented for a skipped batch entry. That is safe because only ~Fence cancels a wait, but | ||
| 548 | // keep it in mind if cancel() gains other callers. | ||
| 549 | struct DispatchSlot { | ||
| 550 | VkSemaphore semaphore = VK_NULL_HANDLE; | ||
| 551 | std::thread::id owner; | ||
| 552 | bool active = false; // guarded by mutex_ | ||
| 553 | bool cancelled = false; // guarded by mutex_ | ||
| 554 | }; | ||
| 555 | |||
| 510 | using SignalEventFn = void (*)(void* event_handle); | 556 | using SignalEventFn = void (*)(void* event_handle); |
| 511 | 557 | ||
| 512 | // Longest single vkWaitSemaphores call in run(): bounds how long the thread can sit in an uninterruptible wait. | 558 | // Longest single vkWaitSemaphores call in run(): bounds how long the thread can sit in an uninterruptible wait. |
| @@ -587,7 +633,8 @@ public: | |||
| 587 | } | 633 | } |
| 588 | 634 | ||
| 589 | // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and | 635 | // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and |
| 590 | // blocks until any in-flight vkWaitSemaphores releases `sem` before the caller destroys the VkSemaphore. | 636 | // blocks until both a vkWaitSemaphores on `sem` and any callback already dispatched for it have finished, before |
| 637 | // the caller destroys the VkSemaphore. | ||
| 591 | void cancel(VkSemaphore sem) { | 638 | void cancel(VkSemaphore sem) { |
| 592 | if (!sem) return; | 639 | if (!sem) return; |
| 593 | std::vector<Entry> cancelled; | 640 | std::vector<Entry> cancelled; |
| @@ -605,10 +652,18 @@ public: | |||
| 605 | } | 652 | } |
| 606 | } | 653 | } |
| 607 | pending_.resize(write); | 654 | pending_.resize(write); |
| 608 | if (thread_.joinable() && waiting_) { | 655 | // Entries already taken out of pending_ but not yet started belong to a live ready batch. Mark them |
| 656 | // cancelled so dispatch skips them; this is how a re-entrant cancel() from another callback in the | ||
| 657 | // same batch is completed without waiting on the callback that is already on this thread's stack. | ||
| 658 | for (const auto& slot : dispatching_) { | ||
| 659 | if (slot->semaphore == sem && !slot->active) slot->cancelled = true; | ||
| 660 | } | ||
| 661 | if (thread_.joinable() && (waiting_ || callback_on_other_thread(sem))) { | ||
| 609 | const std::uint64_t target_epoch = epoch_ + 1; | 662 | const std::uint64_t target_epoch = epoch_ + 1; |
| 610 | signal_wakeup_locked(); | 663 | signal_wakeup_locked(); |
| 611 | epoch_cv_.wait(lock, [this, target_epoch] { return !waiting_ || epoch_ >= target_epoch; }); | 664 | epoch_cv_.wait(lock, [this, sem, target_epoch] { |
| 665 | return (!waiting_ || epoch_ >= target_epoch) && !callback_on_other_thread(sem); | ||
| 666 | }); | ||
| 612 | } | 667 | } |
| 613 | } | 668 | } |
| 614 | dispatch_entries(cancelled, fn); | 669 | dispatch_entries(cancelled, fn); |
| @@ -633,6 +688,63 @@ private: | |||
| 633 | } | 688 | } |
| 634 | } | 689 | } |
| 635 | 690 | ||
| 691 | // True only for a callback already running on another thread. A slot that has not started yet is cancelled by | ||
| 692 | // cancel() and skipped, so it never uses a destroyed semaphore and must not hold up the cancelling caller. | ||
| 693 | bool callback_on_other_thread(VkSemaphore sem) const { | ||
| 694 | const std::thread::id me = std::this_thread::get_id(); | ||
| 695 | return std::any_of(dispatching_.begin(), dispatching_.end(), [&](const auto& d) { | ||
| 696 | return d->semaphore == sem && d->active && d->owner != me; | ||
| 697 | }); | ||
| 698 | } | ||
| 699 | |||
| 700 | // mutex_ is held on entry and again on return. Recording every entry before unlocking closes the window where | ||
| 701 | // run() has taken them out of pending_ but has not started the callback, yet cancel() can return and let the | ||
| 702 | // caller destroy the semaphore. Each entry has its own slot so a cancel() for a later entry in the same batch | ||
| 703 | // skips that entry instead of being mistaken for the callback already on the cancelling thread's stack. | ||
| 704 | void dispatch_outside_lock(std::unique_lock<std::mutex>& lock, std::vector<Entry>& entries, SignalEventFn fn) { | ||
| 705 | const std::thread::id me = std::this_thread::get_id(); | ||
| 706 | std::vector<std::shared_ptr<DispatchSlot>> slots; | ||
| 707 | slots.reserve(entries.size()); | ||
| 708 | for (const Entry& e : entries) { | ||
| 709 | auto slot = std::make_shared<DispatchSlot>(); | ||
| 710 | slot->semaphore = e.semaphore; | ||
| 711 | slot->owner = me; | ||
| 712 | slots.push_back(slot); | ||
| 713 | dispatching_.push_back(slot); | ||
| 714 | } | ||
| 715 | lock.unlock(); | ||
| 716 | for (std::size_t i = 0; i < entries.size(); ++i) { | ||
| 717 | Entry& e = entries[i]; | ||
| 718 | DispatchSlot& slot = *slots[i]; | ||
| 719 | bool skip = false; | ||
| 720 | { | ||
| 721 | std::lock_guard guard(mutex_); | ||
| 722 | skip = slot.cancelled; | ||
| 723 | if (!skip) slot.active = true; | ||
| 724 | } | ||
| 725 | if (skip) { | ||
| 726 | // A re-entrant cancel() removed this wait; still complete its event so no waiter is left behind. | ||
| 727 | if (fn && e.event_handle) fn(e.event_handle); | ||
| 728 | continue; | ||
| 729 | } | ||
| 730 | if (e.callback) e.callback(); | ||
| 731 | else if (fn && e.event_handle) fn(e.event_handle); | ||
| 732 | { | ||
| 733 | std::lock_guard guard(mutex_); | ||
| 734 | slot.active = false; | ||
| 735 | const auto it = std::find(dispatching_.begin(), dispatching_.end(), slots[i]); | ||
| 736 | if (it != dispatching_.end()) dispatching_.erase(it); | ||
| 737 | } | ||
| 738 | epoch_cv_.notify_all(); | ||
| 739 | } | ||
| 740 | lock.lock(); | ||
| 741 | for (const auto& slot : slots) { | ||
| 742 | const auto it = std::find(dispatching_.begin(), dispatching_.end(), slot); | ||
| 743 | if (it != dispatching_.end()) dispatching_.erase(it); | ||
| 744 | } | ||
| 745 | epoch_cv_.notify_all(); | ||
| 746 | } | ||
| 747 | |||
| 636 | // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1, | 748 | // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1, |
| 637 | // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. Keep signaling even if | 749 | // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. Keep signaling even if |
| 638 | // device_lost_ is already set so a blocked vkWaitSemaphores wakes cleanly for cancel()/stop(). | 750 | // device_lost_ is already set so a blocked vkWaitSemaphores wakes cleanly for cancel()/stop(). |
| @@ -652,9 +764,7 @@ private: | |||
| 652 | if (device_lost_.load(std::memory_order_acquire)) { | 764 | if (device_lost_.load(std::memory_order_acquire)) { |
| 653 | std::vector<Entry> drained = std::move(pending_); | 765 | std::vector<Entry> drained = std::move(pending_); |
| 654 | pending_.clear(); | 766 | pending_.clear(); |
| 655 | const SignalEventFn fn = signal_event_; | 767 | dispatch_outside_lock(lock, drained, signal_event_); |
| 656 | lock.unlock(); | ||
| 657 | dispatch_entries(drained, fn); | ||
| 658 | return; | 768 | return; |
| 659 | } | 769 | } |
| 660 | if (stop_) return; | 770 | if (stop_) return; |
| @@ -692,9 +802,7 @@ private: | |||
| 692 | device_lost_.store(true, std::memory_order_release); | 802 | device_lost_.store(true, std::memory_order_release); |
| 693 | std::vector<Entry> drained = std::move(pending_); | 803 | std::vector<Entry> drained = std::move(pending_); |
| 694 | pending_.clear(); | 804 | pending_.clear(); |
| 695 | const SignalEventFn fn = signal_event_; | 805 | dispatch_outside_lock(lock, drained, signal_event_); |
| 696 | lock.unlock(); | ||
| 697 | dispatch_entries(drained, fn); | ||
| 698 | return; | 806 | return; |
| 699 | } | 807 | } |
| 700 | if (stop_) return; | 808 | if (stop_) return; |
| @@ -722,17 +830,12 @@ private: | |||
| 722 | for (Entry& e : pending_) ready.push_back(std::move(e)); | 830 | for (Entry& e : pending_) ready.push_back(std::move(e)); |
| 723 | pending_.clear(); | 831 | pending_.clear(); |
| 724 | device_lost_.store(true, std::memory_order_release); | 832 | device_lost_.store(true, std::memory_order_release); |
| 725 | const SignalEventFn fn = signal_event_; | 833 | dispatch_outside_lock(lock, ready, signal_event_); |
| 726 | lock.unlock(); | ||
| 727 | dispatch_entries(ready, fn); | ||
| 728 | return; | 834 | return; |
| 729 | } | 835 | } |
| 730 | pending_.resize(write); | 836 | pending_.resize(write); |
| 731 | if (!ready.empty()) { | 837 | if (!ready.empty()) { |
| 732 | const SignalEventFn fn = signal_event_; | 838 | dispatch_outside_lock(lock, ready, signal_event_); |
| 733 | lock.unlock(); | ||
| 734 | dispatch_entries(ready, fn); | ||
| 735 | lock.lock(); | ||
| 736 | if (stop_) return; | 839 | if (stop_) return; |
| 737 | } | 840 | } |
| 738 | } | 841 | } |
| @@ -749,6 +852,7 @@ private: | |||
| 749 | std::condition_variable cv_; | 852 | std::condition_variable cv_; |
| 750 | std::condition_variable epoch_cv_; | 853 | std::condition_variable epoch_cv_; |
| 751 | std::vector<Entry> pending_; | 854 | std::vector<Entry> pending_; |
| 855 | std::vector<std::shared_ptr<DispatchSlot>> dispatching_; // ready-batch callbacks outside mutex_ | ||
| 752 | std::vector<VkSemaphore> semaphores_; | 856 | std::vector<VkSemaphore> semaphores_; |
| 753 | std::vector<std::uint64_t> values_; | 857 | std::vector<std::uint64_t> values_; |
| 754 | std::uint64_t epoch_ = 0; | 858 | std::uint64_t epoch_ = 0; |
| @@ -765,34 +869,39 @@ struct TileHeapAllocation { | |||
| 765 | std::uint32_t memory_type = 0; | 869 | std::uint32_t memory_type = 0; |
| 766 | }; | 870 | }; |
| 767 | 871 | ||
| 768 | struct BufferTile { | 872 | struct TileMapping { |
| 769 | std::shared_ptr<const TileHeapAllocation> heap; | 873 | std::shared_ptr<const TileHeapAllocation> heap; |
| 770 | VkDeviceSize offset = 0; | 874 | VkDeviceSize offset = 0; |
| 771 | bool operator==(const BufferTile&) const = default; | 875 | bool operator==(const TileMapping&) const = default; |
| 772 | }; | 876 | }; |
| 773 | 877 | ||
| 774 | struct SparseBuffer { | 878 | struct SparseResource { |
| 775 | SparseBuffer(VkDevice device, PFN_vkDestroyBuffer destroy) : device(device), destroy(destroy) {} | 879 | SparseResource(VkDevice device, const VulkanDeviceFunctions& vk) : device(device), vk(vk) {} |
| 776 | SparseBuffer(const SparseBuffer&) = delete; | 880 | SparseResource(const SparseResource&) = delete; |
| 777 | SparseBuffer& operator=(const SparseBuffer&) = delete; | 881 | SparseResource& operator=(const SparseResource&) = delete; |
| 778 | ~SparseBuffer() { if (buffer) destroy(device, buffer, nullptr); } | 882 | ~SparseResource() { |
| 883 | if (image) vk.vkDestroyImage(device, image, nullptr); | ||
| 884 | if (buffer) vk.vkDestroyBuffer(device, buffer, nullptr); | ||
| 885 | } | ||
| 779 | 886 | ||
| 780 | VkDevice device; | 887 | VkDevice device; |
| 781 | PFN_vkDestroyBuffer destroy; | 888 | const VulkanDeviceFunctions& vk; |
| 782 | VkBuffer buffer = VK_NULL_HANDLE; | 889 | VkBuffer buffer = VK_NULL_HANDLE; |
| 890 | VkImage image = VK_NULL_HANDLE; | ||
| 891 | VkExtent2D image_extent{}; | ||
| 783 | std::uint64_t tile_count = 0; | 892 | std::uint64_t tile_count = 0; |
| 784 | std::uint32_t memory_types = 0; | 893 | std::uint32_t memory_types = 0; |
| 785 | std::map<std::uint64_t, BufferTile> mapped; | 894 | std::map<std::uint64_t, TileMapping> mapped; |
| 786 | }; | 895 | }; |
| 787 | 896 | ||
| 788 | struct BufferTileRegion { | 897 | struct TileRegion { |
| 789 | std::uint64_t first = 0; | 898 | std::uint64_t first = 0; |
| 790 | std::uint64_t count = 0; | 899 | std::uint64_t count = 0; |
| 791 | }; | 900 | }; |
| 792 | 901 | ||
| 793 | enum class TileRangeMode { sequential, unmap, skip, reuse }; | 902 | enum class TileRangeMode { sequential, unmap, skip, reuse }; |
| 794 | 903 | ||
| 795 | struct BufferTileRange { | 904 | struct TileRange { |
| 796 | TileRangeMode mode; | 905 | TileRangeMode mode; |
| 797 | std::uint64_t first; | 906 | std::uint64_t first; |
| 798 | std::uint64_t count; | 907 | std::uint64_t count; |
| @@ -857,6 +966,7 @@ public: | |||
| 857 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; | 966 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; |
| 858 | replay_.set_blend_constants = vk.vkCmdSetBlendConstants; | 967 | replay_.set_blend_constants = vk.vkCmdSetBlendConstants; |
| 859 | replay_.draw = vk.vkCmdDraw; | 968 | replay_.draw = vk.vkCmdDraw; |
| 969 | replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled | ||
| 860 | replay_.draw_indexed = vk.vkCmdDrawIndexed; | 970 | replay_.draw_indexed = vk.vkCmdDrawIndexed; |
| 861 | replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { | 971 | replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { |
| 862 | const auto it = graphics_pipelines_.find(id); | 972 | const auto it = graphics_pipelines_.find(id); |
| @@ -876,20 +986,37 @@ public: | |||
| 876 | size = std::min<std::uint64_t>(size, b->size - (va - b->va)); | 986 | size = std::min<std::uint64_t>(size, b->size - (va - b->va)); |
| 877 | return true; | 987 | return true; |
| 878 | }; | 988 | }; |
| 989 | // Host reads of small CPU-written inputs. Unlike buffer_at, the whole range must be in one CPU-writable | ||
| 990 | // mapping: a partial read would see bytes the application has not written through the D3D12 API. The | ||
| 991 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. | ||
| 992 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { | ||
| 993 | BufferVaIndex<ResourceId>::Hit hit{}; | ||
| 994 | if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; | ||
| 995 | const ResourceBinding* b = resolve(hit.id); | ||
| 996 | if (!b) return HostReadStatus::absent; | ||
| 997 | if (!b->host) return HostReadStatus::not_cpu_written; | ||
| 998 | const std::uint64_t offset = va - b->va; | ||
| 999 | if (offset > b->size || bytes > b->size - offset) return HostReadStatus::absent; | ||
| 1000 | host = b->host + offset; | ||
| 1001 | return HostReadStatus::ok; | ||
| 1002 | }; | ||
| 879 | if (xdxr && loaded_) { | 1003 | if (xdxr && loaded_) { |
| 880 | xdxr_ = std::make_unique<XdxrBuilder>(get, device); | 1004 | xdxr_ = std::make_unique<XdxrBuilder>(get, device); |
| 881 | if (xdxr_->loaded()) { | 1005 | if (xdxr_->loaded()) { |
| 882 | replay_.xdxr_check = [](const BuildAccelerationStructure& b) { | 1006 | replay_.xdxr_check = [](const BuildAccelerationStructure& b) { |
| 883 | XdxrLayout layout; | 1007 | XdxrLayout layout; |
| 884 | return xdxr_inputs(b, nullptr, 0) && layout.compute(xdxr_elements(b), b.is_tlas) && b.dst_va && | 1008 | // An update needs ALLOW_UPDATE (D3D12 requires it on the build and the update): a structure |
| 885 | b.scratch_va && (!b.is_tlas || !b.instance_count || b.instances_va); | 1009 | // built without it may have paired leaves, which a refit would rewrite as wrong geometry. |
| 1010 | return xdxr_inputs(b, nullptr, 0) && layout.compute(xdxr_elements(b), b.is_tlas, xdxr_box16(b)) && | ||
| 1011 | b.dst_va && b.scratch_va && (!b.is_tlas || !b.instance_count || b.instances_va) && | ||
| 1012 | (!b.update || (b.build_flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR) != 0); | ||
| 886 | }; | 1013 | }; |
| 887 | replay_.xdxr_record = [this](VkCommandBuffer cb, const BuildAccelerationStructure& b) { | 1014 | replay_.xdxr_record = [this](VkCommandBuffer cb, const BuildAccelerationStructure& b) { |
| 888 | // Every address is a console VA in the GPU address arena: the device address is heap_base + VA, | 1015 | // Every address is a console VA in the GPU address arena: the device address is heap_base + VA, |
| 889 | // and the BLAS addresses in instance descs get the same bias. | 1016 | // and the BLAS addresses in instance descs get the same bias. |
| 890 | const std::uint64_t base = replay_.heap_base; | 1017 | const std::uint64_t base = replay_.heap_base; |
| 891 | XdxrLayout layout; | 1018 | XdxrLayout layout; |
| 892 | layout.compute(xdxr_elements(b), b.is_tlas); | 1019 | layout.compute(xdxr_elements(b), b.is_tlas, xdxr_box16(b)); |
| 893 | // PERFORM_UPDATE refits the source (the destination itself when no source is given, as D3D12 | 1020 | // PERFORM_UPDATE refits the source (the destination itself when no source is given, as D3D12 |
| 894 | // allows for an in-place update); a full build otherwise. | 1021 | // allows for an in-place update); a full build otherwise. |
| 895 | const std::uint64_t from = b.update ? base + (b.src_va ? b.src_va : b.dst_va) : 0; | 1022 | const std::uint64_t from = b.update ? base + (b.src_va ? b.src_va : b.dst_va) : 0; |
| @@ -899,7 +1026,8 @@ public: | |||
| 899 | } else { | 1026 | } else { |
| 900 | std::vector<XdxrTriangles> geometries; | 1027 | std::vector<XdxrTriangles> geometries; |
| 901 | xdxr_inputs(b, &geometries, base); | 1028 | xdxr_inputs(b, &geometries, base); |
| 902 | xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va, from); | 1029 | xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va, from, |
| 1030 | xdxr_pair(b)); | ||
| 903 | } | 1031 | } |
| 904 | }; | 1032 | }; |
| 905 | replay_.xdxr_copy = [this](VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst, std::uint64_t bytes) { | 1033 | replay_.xdxr_copy = [this](VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst, std::uint64_t bytes) { |
| @@ -924,6 +1052,18 @@ public: | |||
| 924 | replay_.image_view = [this](const ResourceBinding& r, const VkImageSubresourceRange& range) { | 1052 | replay_.image_view = [this](const ResourceBinding& r, const VkImageSubresourceRange& range) { |
| 925 | return view(r, range); | 1053 | return view(r, range); |
| 926 | }; | 1054 | }; |
| 1055 | if (vk.vkCreateRenderPass2 && vk.vkDestroyRenderPass && vk.vkCreateFramebuffer && vk.vkDestroyFramebuffer && | ||
| 1056 | vk.vkCmdBeginRenderPass && vk.vkCmdEndRenderPass) { | ||
| 1057 | replay_.begin_render_pass = vk.vkCmdBeginRenderPass; | ||
| 1058 | replay_.end_render_pass = vk.vkCmdEndRenderPass; | ||
| 1059 | replay_.depth_resolve_framebuffer = [this](const ResourceBinding& source, VkImageView from, | ||
| 1060 | VkImageLayout from_layout, const ResourceBinding& target, | ||
| 1061 | VkImageView to, VkImageLayout to_layout, | ||
| 1062 | VkResolveModeFlagBits mode, VkExtent2D extent, | ||
| 1063 | VkRenderPass& pass) { | ||
| 1064 | return depth_resolve_framebuffer(source, from, from_layout, target, to, to_layout, mode, extent, pass); | ||
| 1065 | }; | ||
| 1066 | } | ||
| 927 | replay_.query_pool = [this](QueryHeapId id) -> QueryPool* { // called with resource_mutex_ held | 1067 | replay_.query_pool = [this](QueryHeapId id) -> QueryPool* { // called with resource_mutex_ held |
| 928 | const auto it = query_pools_.find(id); | 1068 | const auto it = query_pools_.find(id); |
| 929 | return it == query_pools_.end() ? nullptr : &it->second; | 1069 | return it == query_pools_.end() ? nullptr : &it->second; |
| @@ -937,6 +1077,9 @@ public: | |||
| 937 | ~VulkanContext() { | 1077 | ~VulkanContext() { |
| 938 | fence_dispatcher_.reset(); | 1078 | fence_dispatcher_.reset(); |
| 939 | deletion_queue_.drain(UINT64_MAX, device_, vk); | 1079 | deletion_queue_.drain(UINT64_MAX, device_, vk); |
| 1080 | for (const auto& [key, framebuffer] : resolve_framebuffers_) | ||
| 1081 | vk.vkDestroyFramebuffer(device_, framebuffer, nullptr); | ||
| 1082 | for (const auto& [key, pass] : resolve_passes_) vk.vkDestroyRenderPass(device_, pass, nullptr); | ||
| 940 | for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); | 1083 | for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); |
| 941 | } | 1084 | } |
| 942 | 1085 | ||
| @@ -990,11 +1133,9 @@ public: | |||
| 990 | } | 1133 | } |
| 991 | } | 1134 | } |
| 992 | 1135 | ||
| 993 | // An image that got a storage (unordered-access) view. A shader can write it before any command names it, so the | 1136 | // A shader can access a storage image or an initially unbound sparse image before any command names it. |
| 994 | // layer would not know it was used and the first barrier or copy that does would zero-fill it (vulkan_replay.h, | 1137 | // The first shader submission moves it to GENERAL, the descriptor's layout, ahead of its lists. |
| 995 | // initialize). The next submission therefore moves each such image to GENERAL, the layout its descriptor names, | 1138 | void note_shader_image(ResourceId id) { |
| 996 | // zero-filled, ahead of its lists. An image already tracked beyond UNDEFINED is left as it is. | ||
| 997 | void note_storage_image(ResourceId id) { | ||
| 998 | std::lock_guard lock(storage_mutex_); | 1139 | std::lock_guard lock(storage_mutex_); |
| 999 | storage_pending_.insert(id); | 1140 | storage_pending_.insert(id); |
| 1000 | } | 1141 | } |
| @@ -1007,14 +1148,19 @@ public: | |||
| 1007 | zero_pending_.push_back({id, buffer}); | 1148 | zero_pending_.push_back({id, buffer}); |
| 1008 | } | 1149 | } |
| 1009 | 1150 | ||
| 1010 | void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { | 1151 | void add_sparse_resource(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseResource> sparse) { |
| 1011 | std::unique_lock lock(resource_mutex_); | 1152 | std::unique_lock lock(resource_mutex_); |
| 1012 | set_resource_locked(id, binding); | 1153 | set_resource_locked(id, binding); |
| 1013 | sparse_buffers_.emplace(id, std::move(buffer)); | 1154 | sparse_resources_.emplace(id, std::move(sparse)); |
| 1155 | if (binding.image) { | ||
| 1156 | std::lock_guard tlock(tracker_mutex_); | ||
| 1157 | tracker_.track(id, binding, VK_IMAGE_LAYOUT_UNDEFINED); | ||
| 1158 | } | ||
| 1014 | } | 1159 | } |
| 1015 | 1160 | ||
| 1016 | void remove_resource(ResourceId id) { | 1161 | void remove_resource(ResourceId id) { |
| 1017 | VkImage img = VK_NULL_HANDLE; | 1162 | VkImage img = VK_NULL_HANDLE; |
| 1163 | std::shared_ptr<SparseResource> sparse_resource; | ||
| 1018 | { | 1164 | { |
| 1019 | std::unique_lock rlock(resource_mutex_); | 1165 | std::unique_lock rlock(resource_mutex_); |
| 1020 | const auto it = resources_.find(id); | 1166 | const auto it = resources_.find(id); |
| @@ -1022,7 +1168,10 @@ public: | |||
| 1022 | img = it->second.image; | 1168 | img = it->second.image; |
| 1023 | unindex_buffer(id, it->second); | 1169 | unindex_buffer(id, it->second); |
| 1024 | resources_.erase(it); | 1170 | resources_.erase(it); |
| 1025 | sparse_buffers_.erase(id); | 1171 | if (auto sparse = sparse_resources_.find(id); sparse != sparse_resources_.end()) { |
| 1172 | sparse_resource = std::move(sparse->second); | ||
| 1173 | sparse_resources_.erase(sparse); | ||
| 1174 | } | ||
| 1026 | } | 1175 | } |
| 1027 | { | 1176 | { |
| 1028 | std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled | 1177 | std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled |
| @@ -1030,6 +1179,14 @@ public: | |||
| 1030 | } | 1179 | } |
| 1031 | if (img) { | 1180 | if (img) { |
| 1032 | std::lock_guard vlock(views_mutex_); | 1181 | std::lock_guard vlock(views_mutex_); |
| 1182 | for (auto f = resolve_framebuffers_.begin(); f != resolve_framebuffers_.end();) { | ||
| 1183 | if (std::get<0>(f->first) == img || std::get<1>(f->first) == img) { | ||
| 1184 | defer_destroy(DeferredDeletionQueue::Kind::framebuffer, f->second); | ||
| 1185 | f = resolve_framebuffers_.erase(f); | ||
| 1186 | } else { | ||
| 1187 | ++f; | ||
| 1188 | } | ||
| 1189 | } | ||
| 1033 | for (auto v = views_.begin(); v != views_.end();) { | 1190 | for (auto v = views_.begin(); v != views_.end();) { |
| 1034 | if (std::get<0>(v->first) == img) { | 1191 | if (std::get<0>(v->first) == img) { |
| 1035 | defer_destroy(DeferredDeletionQueue::Kind::image_view, v->second); | 1192 | defer_destroy(DeferredDeletionQueue::Kind::image_view, v->second); |
| @@ -1039,6 +1196,9 @@ public: | |||
| 1039 | } | 1196 | } |
| 1040 | } | 1197 | } |
| 1041 | } | 1198 | } |
| 1199 | if (sparse_resource) | ||
| 1200 | defer_destroy(DeferredDeletionQueue::Kind::sparse_resource, | ||
| 1201 | new std::shared_ptr<SparseResource>(std::move(sparse_resource))); | ||
| 1042 | std::lock_guard tlock(tracker_mutex_); | 1202 | std::lock_guard tlock(tracker_mutex_); |
| 1043 | tracker_.forget(id); | 1203 | tracker_.forget(id); |
| 1044 | } | 1204 | } |
| @@ -1130,6 +1290,22 @@ public: | |||
| 1130 | bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } | 1290 | bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } |
| 1131 | bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } | 1291 | bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } |
| 1132 | 1292 | ||
| 1293 | // Whether a build's inner nodes are BOX16 (64 bytes, half boxes rounded outward) instead of BOX32: bottom-level | ||
| 1294 | // builds with MINIMIZE_MEMORY (VK LOW_MEMORY). A top-level build keeps BOX32: it is in world space, where half | ||
| 1295 | // precision would make boxes metres too large a few kilometres from the origin. The flags of an update must match | ||
| 1296 | // its build's (D3D12), so prebuild info, the build and its refits agree. WARNING: an update that breaks that rule | ||
| 1297 | // (MINIMIZE_MEMORY on one and not the other) is refitted with the wrong layout and writes past the structure; it | ||
| 1298 | // cannot be detected when the command is recorded. | ||
| 1299 | static bool xdxr_box16(const BuildAccelerationStructure& b) { | ||
| 1300 | return !b.is_tlas && (b.build_flags & VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR) != 0; | ||
| 1301 | } | ||
| 1302 | // Whether a bottom-level build pairs sibling triangles into TRI0/TRI1 leaves: not when the structure may be | ||
| 1303 | // updated (ALLOW_UPDATE), since a refit rewrites the leaves one triangle each and would leave every TRI1 child | ||
| 1304 | // reading wrong vertices. xdxr_check refuses an update without ALLOW_UPDATE for that reason. Pairing changes | ||
| 1305 | // neither the layout nor the tree, so prebuild info does not depend on it. | ||
| 1306 | static bool xdxr_pair(const BuildAccelerationStructure& b) { | ||
| 1307 | return !b.is_tlas && !b.update && (b.build_flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR) == 0; | ||
| 1308 | } | ||
| 1133 | // Triangles (BLAS) or instances (TLAS) a build has: what XdxrLayout is computed from, for the build and for | 1309 | // Triangles (BLAS) or instances (TLAS) a build has: what XdxrLayout is computed from, for the build and for |
| 1134 | // GetRaytracingAccelerationStructurePrebuildInfo. | 1310 | // GetRaytracingAccelerationStructurePrebuildInfo. |
| 1135 | static std::uint32_t xdxr_elements(const BuildAccelerationStructure& b) { | 1311 | static std::uint32_t xdxr_elements(const BuildAccelerationStructure& b) { |
| @@ -1222,10 +1398,23 @@ public: | |||
| 1222 | bindless_commit_ = std::move(commit); | 1398 | bindless_commit_ = std::move(commit); |
| 1223 | } | 1399 | } |
| 1224 | 1400 | ||
| 1401 | // The set 0 the commands of this ExecuteCommandLists bind, read after `prepare` succeeded and under the same | ||
| 1402 | // locks (a flush may have made a new set). Without it the pipelines' own set is bound. | ||
| 1403 | void set_bindless_current(std::function<VkDescriptorSet()> current) { | ||
| 1404 | std::unique_lock lock(resource_mutex_); | ||
| 1405 | bindless_current_ = std::move(current); | ||
| 1406 | } | ||
| 1407 | |||
| 1225 | void set_bindless_release(DeferredDeletionQueue::BindlessReleaseFn fn, void* user) { | 1408 | void set_bindless_release(DeferredDeletionQueue::BindlessReleaseFn fn, void* user) { |
| 1226 | deletion_queue_.set_bindless_release(fn, user); | 1409 | deletion_queue_.set_bindless_release(fn, user); |
| 1227 | } | 1410 | } |
| 1228 | 1411 | ||
| 1412 | // The ticket of the latest submission: everything submitted so far is at or below it, and a resource that any | ||
| 1413 | // of that work may use can be freed once completed_retire_ticket() has reached it. Tickets run over all queues, | ||
| 1414 | // each recorded with its queue's timeline value, so this waits for every queue's timeline to pass what was | ||
| 1415 | // submitted to it, and never makes a queue wait. | ||
| 1416 | std::uint64_t submitted_retire_ticket() const { return submitted_ticket_.load(std::memory_order_acquire); } | ||
| 1417 | |||
| 1229 | template<typename VkHandle> | 1418 | template<typename VkHandle> |
| 1230 | void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { | 1419 | void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { |
| 1231 | const auto raw = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(handle)); | 1420 | const auto raw = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(handle)); |
| @@ -1242,6 +1431,36 @@ public: | |||
| 1242 | deletion_queue_.push(safe_ticket, kind, raw_handle); | 1431 | deletion_queue_.push(safe_ticket, kind, raw_handle); |
| 1243 | } | 1432 | } |
| 1244 | 1433 | ||
| 1434 | // Waits (not for the device: for the queues' timelines) until every submission up to `ticket` is done, then | ||
| 1435 | // returns the completed ticket. For a caller whose list of retired objects has grown past what it will hold. | ||
| 1436 | std::uint64_t wait_retire_ticket(std::uint64_t ticket) { | ||
| 1437 | std::vector<std::pair<VkSemaphore, std::uint64_t>> pending; | ||
| 1438 | { | ||
| 1439 | std::lock_guard lock(submit_mutex_); | ||
| 1440 | if (is_device_lost()) return 0; | ||
| 1441 | pending = retire_tickets_.pending_through(ticket); | ||
| 1442 | } | ||
| 1443 | if (!pending.empty()) { | ||
| 1444 | std::vector<VkSemaphore> semaphores; | ||
| 1445 | std::vector<std::uint64_t> values; | ||
| 1446 | for (const auto& [semaphore, value] : pending) { | ||
| 1447 | semaphores.push_back(semaphore); | ||
| 1448 | values.push_back(value); | ||
| 1449 | } | ||
| 1450 | VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; | ||
| 1451 | wait.semaphoreCount = std::uint32_t(semaphores.size()); | ||
| 1452 | wait.pSemaphores = semaphores.data(); | ||
| 1453 | wait.pValues = values.data(); | ||
| 1454 | vk.vkWaitSemaphores(device_, &wait, UINT64_MAX); // outside submit_mutex_: a signal may need it | ||
| 1455 | } | ||
| 1456 | return completed_retire_ticket(); | ||
| 1457 | } | ||
| 1458 | |||
| 1459 | // The bindless flush of this ExecuteCommandLists started a new set generation, whose table upload is in its | ||
| 1460 | // command buffer: called from the `prepare` callback (tracker_mutex_ held), so execute() makes every other | ||
| 1461 | // queue's next submission wait for this one, which binds the new set. | ||
| 1462 | void note_bindless_upload() { bindless_upload_pending_ = true; } | ||
| 1463 | |||
| 1245 | std::uint64_t completed_retire_ticket() { | 1464 | std::uint64_t completed_retire_ticket() { |
| 1246 | std::lock_guard lock(submit_mutex_); | 1465 | std::lock_guard lock(submit_mutex_); |
| 1247 | if (is_device_lost()) return 0; | 1466 | if (is_device_lost()) return 0; |
| @@ -1331,7 +1550,7 @@ private: | |||
| 1331 | if (const auto it = views_.find(key); it != views_.end()) return it->second; | 1550 | if (const auto it = views_.find(key); it != views_.end()) return it->second; |
| 1332 | VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | 1551 | VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; |
| 1333 | info.image = r.image; | 1552 | info.image = r.image; |
| 1334 | info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; | 1553 | info.viewType = r.line ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_2D_ARRAY; // 1D images take no 2D view |
| 1335 | info.format = r.format; | 1554 | info.format = r.format; |
| 1336 | info.subresourceRange = range; | 1555 | info.subresourceRange = range; |
| 1337 | // Attachment views need only color-attachment usage. Inheriting STORAGE usage from a mutable/extended | 1556 | // Attachment views need only color-attachment usage. Inheriting STORAGE usage from a mutable/extended |
| @@ -1346,6 +1565,68 @@ private: | |||
| 1346 | return view; | 1565 | return view; |
| 1347 | } | 1566 | } |
| 1348 | 1567 | ||
| 1568 | // The render pass and framebuffer that resolve one layer of a depth-only multisampled image into one layer of | ||
| 1569 | // another: views `from` and `to` (from view()), in the layouts given. Used where the dynamic-rendering resolve | ||
| 1570 | // reads the wrong source layer (D3D-417; vulkan_replay.h says when). Both objects are cached: a pass by what it | ||
| 1571 | // describes, a framebuffer by its images and views, until remove_resource retires either image. | ||
| 1572 | VkFramebuffer depth_resolve_framebuffer(const ResourceBinding& source, VkImageView from, VkImageLayout from_layout, | ||
| 1573 | const ResourceBinding& target, VkImageView to, VkImageLayout to_layout, | ||
| 1574 | VkResolveModeFlagBits mode, VkExtent2D extent, VkRenderPass& pass) { | ||
| 1575 | std::lock_guard lock(views_mutex_); | ||
| 1576 | const auto pass_key = std::make_tuple(source.format, source.samples, from_layout, to_layout, mode); | ||
| 1577 | if (const auto it = resolve_passes_.find(pass_key); it != resolve_passes_.end()) { | ||
| 1578 | pass = it->second; | ||
| 1579 | } else { | ||
| 1580 | VkAttachmentDescription2 attachments[2]{}; | ||
| 1581 | for (auto& attachment : attachments) { | ||
| 1582 | attachment.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2; | ||
| 1583 | attachment.format = source.format; | ||
| 1584 | attachment.samples = VK_SAMPLE_COUNT_1_BIT; | ||
| 1585 | attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // the source is read; the destination keeps | ||
| 1586 | attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // what is outside the render area | ||
| 1587 | attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // depth-only formats | ||
| 1588 | attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; | ||
| 1589 | } | ||
| 1590 | attachments[0].samples = static_cast<VkSampleCountFlagBits>(source.samples); | ||
| 1591 | attachments[0].initialLayout = attachments[0].finalLayout = from_layout; | ||
| 1592 | attachments[1].initialLayout = attachments[1].finalLayout = to_layout; | ||
| 1593 | const VkAttachmentReference2 from_reference{VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, 0, | ||
| 1594 | from_layout, VK_IMAGE_ASPECT_DEPTH_BIT}; | ||
| 1595 | const VkAttachmentReference2 to_reference{VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, 1, to_layout, | ||
| 1596 | VK_IMAGE_ASPECT_DEPTH_BIT}; | ||
| 1597 | VkSubpassDescriptionDepthStencilResolve resolve{ | ||
| 1598 | VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE}; | ||
| 1599 | resolve.depthResolveMode = mode; | ||
| 1600 | resolve.stencilResolveMode = VK_RESOLVE_MODE_NONE; | ||
| 1601 | resolve.pDepthStencilResolveAttachment = &to_reference; | ||
| 1602 | VkSubpassDescription2 subpass{VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2}; | ||
| 1603 | subpass.pNext = &resolve; | ||
| 1604 | subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; | ||
| 1605 | subpass.pDepthStencilAttachment = &from_reference; | ||
| 1606 | VkRenderPassCreateInfo2 info{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2}; | ||
| 1607 | info.attachmentCount = 2; | ||
| 1608 | info.pAttachments = attachments; | ||
| 1609 | info.subpassCount = 1; | ||
| 1610 | info.pSubpasses = &subpass; | ||
| 1611 | if (vk.vkCreateRenderPass2(device_, &info, nullptr, &pass) != VK_SUCCESS) return VK_NULL_HANDLE; | ||
| 1612 | resolve_passes_[pass_key] = pass; | ||
| 1613 | } | ||
| 1614 | const auto key = std::make_tuple(source.image, target.image, from, to, pass); | ||
| 1615 | if (const auto it = resolve_framebuffers_.find(key); it != resolve_framebuffers_.end()) return it->second; | ||
| 1616 | const VkImageView views[] = {from, to}; | ||
| 1617 | VkFramebufferCreateInfo info{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; | ||
| 1618 | info.renderPass = pass; | ||
| 1619 | info.attachmentCount = 2; | ||
| 1620 | info.pAttachments = views; | ||
| 1621 | info.width = extent.width; | ||
| 1622 | info.height = extent.height; | ||
| 1623 | info.layers = 1; | ||
| 1624 | VkFramebuffer framebuffer = VK_NULL_HANDLE; | ||
| 1625 | if (vk.vkCreateFramebuffer(device_, &info, nullptr, &framebuffer) != VK_SUCCESS) return VK_NULL_HANDLE; | ||
| 1626 | resolve_framebuffers_[key] = framebuffer; | ||
| 1627 | return framebuffer; | ||
| 1628 | } | ||
| 1629 | |||
| 1349 | VkDevice device_; | 1630 | VkDevice device_; |
| 1350 | bool loaded_ = false; | 1631 | bool loaded_ = false; |
| 1351 | bool ray_tracing_ = false; | 1632 | bool ray_tracing_ = false; |
| @@ -1362,7 +1643,7 @@ private: | |||
| 1362 | QueueHolds<VkSemaphore> holds_; | 1643 | QueueHolds<VkSemaphore> holds_; |
| 1363 | std::unordered_map<ResourceId, ResourceBinding> resources_; | 1644 | std::unordered_map<ResourceId, ResourceBinding> resources_; |
| 1364 | BufferVaIndex<ResourceId> buffer_vas_; // the addressable buffers of resources_, by VA range (buffer_at) | 1645 | BufferVaIndex<ResourceId> buffer_vas_; // the addressable buffers of resources_, by VA range (buffer_at) |
| 1365 | std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_; | 1646 | std::unordered_map<ResourceId, std::shared_ptr<SparseResource>> sparse_resources_; |
| 1366 | std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; | 1647 | std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; |
| 1367 | std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; | 1648 | std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; |
| 1368 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; | 1649 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; |
| @@ -1381,7 +1662,18 @@ private: | |||
| 1381 | std::uint64_t storage_init_value_ = 0; | 1662 | std::uint64_t storage_init_value_ = 0; |
| 1382 | std::uint64_t storage_init_version_ = 0; | 1663 | std::uint64_t storage_init_version_ = 0; |
| 1383 | std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_; | 1664 | std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_; |
| 1665 | // depth_resolve_framebuffer's caches, under views_mutex_ like views_. | ||
| 1666 | std::map<std::tuple<VkFormat, std::uint32_t, VkImageLayout, VkImageLayout, VkResolveModeFlagBits>, VkRenderPass> | ||
| 1667 | resolve_passes_; | ||
| 1668 | std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; | ||
| 1384 | std::function<bool(VkCommandBuffer)> bindless_prepare_; | 1669 | std::function<bool(VkCommandBuffer)> bindless_prepare_; |
| 1670 | std::function<VkDescriptorSet()> bindless_current_; | ||
| 1671 | bool bindless_upload_pending_ = false; // tracker_mutex_ | ||
| 1672 | // The last submission that carried a new generation's table upload (its queue's progress semaphore and value), and | ||
| 1673 | // a counter that says which one: every other queue's next submission waits for it (storage_mutex_). | ||
| 1674 | VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; | ||
| 1675 | std::uint64_t bindless_upload_value_ = 0; | ||
| 1676 | std::uint64_t bindless_upload_version_ = 0; | ||
| 1385 | std::unique_ptr<Depth24Converter> depth24_; | 1677 | std::unique_ptr<Depth24Converter> depth24_; |
| 1386 | std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour) | 1678 | std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour) |
| 1387 | std::function<void(bool)> bindless_commit_; | 1679 | std::function<void(bool)> bindless_commit_; |
| @@ -1424,19 +1716,33 @@ public: | |||
| 1424 | VkSemaphore semaphore() const { return semaphore_; } | 1716 | VkSemaphore semaphore() const { return semaphore_; } |
| 1425 | 1717 | ||
| 1426 | std::uint64_t completed() const { | 1718 | std::uint64_t completed() const { |
| 1719 | if (context_.is_device_lost()) return UINT64_MAX; | ||
| 1427 | std::uint64_t value = 0; | 1720 | std::uint64_t value = 0; |
| 1428 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); | 1721 | const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); |
| 1722 | if (result == VK_ERROR_DEVICE_LOST) { | ||
| 1723 | context_.mark_device_lost(); | ||
| 1724 | return UINT64_MAX; | ||
| 1725 | } | ||
| 1726 | if (result != VK_SUCCESS) return 0; | ||
| 1429 | return value; | 1727 | return value; |
| 1430 | } | 1728 | } |
| 1431 | 1729 | ||
| 1432 | // ID3D12Fence::Signal from the CPU. Vulkan timelines only increase: a value at or below the current one is | 1730 | // ID3D12Fence::Signal from the CPU. Vulkan timelines only increase: a value at or below the current one is |
| 1433 | // ignored (D3D12 would set it), and the caller is told. | 1731 | // ignored (D3D12 would set it), and the caller is told. |
| 1434 | bool signal(std::uint64_t value) { | 1732 | bool signal(std::uint64_t value) { |
| 1435 | if (value <= completed()) return false; | 1733 | // The dispatcher may be testing a failed counter query. Do not call completed() here: |
| 1734 | // it marks the context lost on a query error and prevents the dispatcher from waking. | ||
| 1735 | if (context_.is_device_lost()) return false; | ||
| 1736 | std::uint64_t current = 0; | ||
| 1737 | if (context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, ¤t) == VK_SUCCESS && | ||
| 1738 | value <= current) | ||
| 1739 | return false; | ||
| 1436 | VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; | 1740 | VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; |
| 1437 | info.semaphore = semaphore_; | 1741 | info.semaphore = semaphore_; |
| 1438 | info.value = value; | 1742 | info.value = value; |
| 1439 | if (context_.vk.vkSignalSemaphore(context_.device(), &info) != VK_SUCCESS) return false; | 1743 | const VkResult result = context_.vk.vkSignalSemaphore(context_.device(), &info); |
| 1744 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); | ||
| 1745 | if (result != VK_SUCCESS) return false; | ||
| 1440 | context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now | 1746 | context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now |
| 1441 | context_.holds().pump_ready(); | 1747 | context_.holds().pump_ready(); |
| 1442 | return true; | 1748 | return true; |
| @@ -1448,7 +1754,9 @@ public: | |||
| 1448 | info.semaphoreCount = 1; | 1754 | info.semaphoreCount = 1; |
| 1449 | info.pSemaphores = &semaphore_; | 1755 | info.pSemaphores = &semaphore_; |
| 1450 | info.pValues = &value; | 1756 | info.pValues = &value; |
| 1451 | return context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns) == VK_SUCCESS; | 1757 | const VkResult result = context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns); |
| 1758 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); | ||
| 1759 | return result == VK_SUCCESS; | ||
| 1452 | } | 1760 | } |
| 1453 | 1761 | ||
| 1454 | private: | 1762 | private: |
| @@ -1469,6 +1777,13 @@ class VulkanQueue : private QueueHolds<VkSemaphore>::Holder { | |||
| 1469 | public: | 1777 | public: |
| 1470 | enum class QueueKind : std::uint8_t { direct, compute, copy }; | 1778 | enum class QueueKind : std::uint8_t { direct, compute, copy }; |
| 1471 | 1779 | ||
| 1780 | // The most command buffers a queue holds at once. At that many, a caller that outruns the GPU waits for the oldest | ||
| 1781 | // submitted one to finish (before taking any context lock, see wait_for_room) instead of allocating without bound. The | ||
| 1782 | // cap holds while the GPU is slow too: a wait that times out is retried, in kQueuedWaitNs slices so a device lost | ||
| 1783 | // meanwhile ends it, and a device lost makes execute() submit nothing. | ||
| 1784 | static constexpr std::size_t kMaxQueuedCommandBuffers = 64; | ||
| 1785 | static constexpr std::uint64_t kQueuedWaitNs = 5'000'000'000; | ||
| 1786 | |||
| 1472 | static constexpr VkPipelineStageFlags2 queue_supported_stages(QueueKind kind) noexcept { | 1787 | static constexpr VkPipelineStageFlags2 queue_supported_stages(QueueKind kind) noexcept { |
| 1473 | switch (kind) { | 1788 | switch (kind) { |
| 1474 | case QueueKind::copy: | 1789 | case QueueKind::copy: |
| @@ -1501,6 +1816,7 @@ public: | |||
| 1501 | auto& vk = context_.vk; | 1816 | auto& vk = context_.vk; |
| 1502 | context_.holds().detach(this); // no thread releases into this queue from here on | 1817 | context_.holds().detach(this); // no thread releases into this queue from here on |
| 1503 | report_held_at_teardown(); | 1818 | report_held_at_teardown(); |
| 1819 | context_.holds().pump_ready(); // presents queued behind what was just dropped can run | ||
| 1504 | if (queue_) { | 1820 | if (queue_) { |
| 1505 | std::lock_guard lock(context_.submit_mutex()); | 1821 | std::lock_guard lock(context_.submit_mutex()); |
| 1506 | for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); | 1822 | for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); |
| @@ -1524,7 +1840,11 @@ public: | |||
| 1524 | } | 1840 | } |
| 1525 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); | 1841 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); |
| 1526 | if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); | 1842 | if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); |
| 1527 | for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); | 1843 | destroy_khr_stages(khr_stage_pool_); |
| 1844 | for (auto& slot : buffers_) { | ||
| 1845 | destroy_khr_stages(slot.khr_instances); | ||
| 1846 | free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); | ||
| 1847 | } | ||
| 1528 | for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr); | 1848 | for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr); |
| 1529 | } | 1849 | } |
| 1530 | 1850 | ||
| @@ -1533,19 +1853,23 @@ public: | |||
| 1533 | 1853 | ||
| 1534 | bool ok() const { return ok_; } | 1854 | bool ok() const { return ok_; } |
| 1535 | 1855 | ||
| 1856 | // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage, | ||
| 1857 | // not work the next submission will replay (vk_queue_test checks both halves of that contract). | ||
| 1858 | std::size_t prepared_entries() const { return prepared_.size(); } | ||
| 1859 | |||
| 1536 | template<typename GetHeap> | 1860 | template<typename GetHeap> |
| 1537 | bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions, | 1861 | bool update_tiles(ResourceId id, std::span<const TileRegion> regions, |
| 1538 | std::span<const BufferTileRange> ranges, GetHeap&& get_heap) { | 1862 | std::span<const TileRange> ranges, GetHeap&& get_heap) { |
| 1539 | std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads | 1863 | std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads |
| 1540 | std::unique_lock lock(context_.resource_mutex_); | 1864 | std::unique_lock lock(context_.resource_mutex_); |
| 1541 | const auto it = context_.sparse_buffers_.find(id); | 1865 | const auto it = context_.sparse_resources_.find(id); |
| 1542 | if (it == context_.sparse_buffers_.end()) return false; | 1866 | if (it == context_.sparse_resources_.end()) return false; |
| 1543 | const auto& buffer = it->second; | 1867 | const auto& sparse = it->second; |
| 1544 | for (const auto& region : regions) | 1868 | for (const auto& region : regions) |
| 1545 | if (!valid_tiles(*buffer, region)) return false; | 1869 | if (!valid_tiles(*sparse, region)) return false; |
| 1546 | const auto heap = get_heap(); | 1870 | const auto heap = get_heap(sparse->image != VK_NULL_HANDLE, sparse->memory_types); |
| 1547 | 1871 | ||
| 1548 | std::map<std::uint64_t, BufferTile> changes; | 1872 | std::map<std::uint64_t, TileMapping> changes; |
| 1549 | std::size_t region_index = 0; | 1873 | std::size_t region_index = 0; |
| 1550 | std::uint64_t consumed = 0; | 1874 | std::uint64_t consumed = 0; |
| 1551 | for (const auto& range : ranges) { | 1875 | for (const auto& range : ranges) { |
| @@ -1560,7 +1884,7 @@ public: | |||
| 1560 | const auto first = region.first + consumed; | 1884 | const auto first = region.first + consumed; |
| 1561 | if (range.mode == TileRangeMode::unmap) { | 1885 | if (range.mode == TileRangeMode::unmap) { |
| 1562 | const auto end = first + count; | 1886 | const auto end = first + count; |
| 1563 | for (auto old = buffer->mapped.lower_bound(first); old != buffer->mapped.end() && old->first < end; ++old) | 1887 | for (auto old = sparse->mapped.lower_bound(first); old != sparse->mapped.end() && old->first < end; ++old) |
| 1564 | changes[old->first] = {}; | 1888 | changes[old->first] = {}; |
| 1565 | for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change) | 1889 | for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change) |
| 1566 | change->second = {}; | 1890 | change->second = {}; |
| @@ -1578,33 +1902,46 @@ public: | |||
| 1578 | } | 1902 | } |
| 1579 | } | 1903 | } |
| 1580 | } | 1904 | } |
| 1581 | return region_index == regions.size() && bind_tiles(buffer, changes); | 1905 | return region_index == regions.size() && bind_tiles(id, sparse, changes); |
| 1582 | } | 1906 | } |
| 1583 | 1907 | ||
| 1584 | bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) { | 1908 | bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src, |
| 1909 | std::span<const TileRegion> src_regions) { | ||
| 1585 | std::lock_guard state(state_mutex_); | 1910 | std::lock_guard state(state_mutex_); |
| 1586 | std::unique_lock lock(context_.resource_mutex_); | 1911 | std::unique_lock lock(context_.resource_mutex_); |
| 1587 | const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst); | 1912 | const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); |
| 1588 | if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() || | 1913 | if (source == context_.sparse_resources_.end() || target == context_.sparse_resources_.end() || |
| 1589 | !valid_tiles(*source->second, src_region) || | 1914 | bool(source->second->image) != bool(target->second->image) || src_regions.size() != dst_regions.size()) |
| 1590 | !valid_tiles(*target->second, {dst_first, src_region.count})) return false; | 1915 | return false; |
| 1591 | // Read the complete source mapping before changing any destination slot, including copies within one buffer. | 1916 | // Read the complete source mapping before changing any destination slot, including copies within one resource. |
| 1592 | std::map<std::uint64_t, BufferTile> changes; | 1917 | std::map<std::uint64_t, TileMapping> changes; |
| 1593 | for (std::uint64_t i = 0; i < src_region.count; ++i) { | 1918 | for (std::size_t row = 0; row < src_regions.size(); ++row) { |
| 1594 | const auto page = source->second->mapped.find(src_region.first + i); | 1919 | const auto from = src_regions[row], to = dst_regions[row]; |
| 1595 | changes.emplace(dst_first + i, page == source->second->mapped.end() ? BufferTile{} : page->second); | 1920 | if (!valid_tiles(*source->second, from) || !valid_tiles(*target->second, to) || from.count != to.count) |
| 1921 | return false; | ||
| 1922 | for (std::uint64_t i = 0; i < from.count; ++i) { | ||
| 1923 | const auto page = source->second->mapped.find(from.first + i); | ||
| 1924 | changes.emplace(to.first + i, page == source->second->mapped.end() ? TileMapping{} : page->second); | ||
| 1925 | } | ||
| 1596 | } | 1926 | } |
| 1597 | return bind_tiles(target->second, changes); | 1927 | return bind_tiles(dst, target->second, changes); |
| 1598 | } | 1928 | } |
| 1599 | 1929 | ||
| 1600 | // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves | 1930 | // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves |
| 1601 | // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an | 1931 | // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an |
| 1602 | // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and | 1932 | // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and |
| 1603 | // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU | 1933 | // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU |
| 1604 | // Signal), which is also where its errors are reported. | 1934 | // Signal), which is also where its errors are reported (stderr, and take_held_failure()). |
| 1605 | ReplayResult execute(std::span<const CommandList* const> lists) { | 1935 | // |
| 1936 | // `pin`, called only when the batch is held, returns what has to stay alive until the batch has run: the COM layer | ||
| 1937 | // passes the pipeline states and root signatures the lists named (the application may release them and Reset | ||
| 1938 | // the lists as soon as the call returns). | ||
| 1939 | using PinFn = std::function<std::shared_ptr<void>()>; | ||
| 1940 | |||
| 1941 | ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { | ||
| 1606 | ReplayResult result = ReplayResult::success; | 1942 | ReplayResult result = ReplayResult::success; |
| 1607 | bool held = false; | 1943 | bool held = false; |
| 1944 | std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released | ||
| 1608 | { | 1945 | { |
| 1609 | std::lock_guard state(state_mutex_); | 1946 | std::lock_guard state(state_mutex_); |
| 1610 | if (!must_hold()) { | 1947 | if (!must_hold()) { |
| @@ -1616,18 +1953,23 @@ public: | |||
| 1616 | op.kind = Deferred::Kind::batch; | 1953 | op.kind = Deferred::Kind::batch; |
| 1617 | op.lists.reserve(lists.size()); | 1954 | op.lists.reserve(lists.size()); |
| 1618 | for (const CommandList* list : lists) op.lists.push_back(*list); | 1955 | for (const CommandList* list : lists) op.lists.push_back(*list); |
| 1956 | if (pin) op.pins.push_back(pin()); | ||
| 1619 | hold(std::move(op)); | 1957 | hold(std::move(op)); |
| 1620 | held = true; | 1958 | held = true; |
| 1621 | } | 1959 | } |
| 1960 | drain_pins(retired); | ||
| 1622 | } | 1961 | } |
| 1962 | retired.clear(); | ||
| 1623 | if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check | 1963 | if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check |
| 1624 | return result; | 1964 | return result; |
| 1625 | } | 1965 | } |
| 1626 | 1966 | ||
| 1627 | // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier | 1967 | // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier |
| 1628 | // held operations, so the fence does not run ahead of the work it follows. | 1968 | // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is |
| 1629 | bool signal(VkSemaphore fence, std::uint64_t value) { | 1969 | // held) keeps the fence object alive until it has been submitted, as D3D12 does. |
| 1970 | bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { | ||
| 1630 | bool ok = true; | 1971 | bool ok = true; |
| 1972 | std::vector<std::shared_ptr<void>> retired; | ||
| 1631 | { | 1973 | { |
| 1632 | std::lock_guard state(state_mutex_); | 1974 | std::lock_guard state(state_mutex_); |
| 1633 | if (must_hold()) { | 1975 | if (must_hold()) { |
| @@ -1635,27 +1977,45 @@ public: | |||
| 1635 | op.kind = Deferred::Kind::signal; | 1977 | op.kind = Deferred::Kind::signal; |
| 1636 | op.fence = fence; | 1978 | op.fence = fence; |
| 1637 | op.value = value; | 1979 | op.value = value; |
| 1980 | if (pin) op.pins.push_back(pin()); | ||
| 1638 | hold(std::move(op)); | 1981 | hold(std::move(op)); |
| 1639 | } else { | 1982 | } else { |
| 1640 | ok = submit(VK_NULL_HANDLE, fence, value); | 1983 | ok = submit(VK_NULL_HANDLE, fence, value); |
| 1641 | } | 1984 | } |
| 1985 | drain_pins(retired); | ||
| 1642 | } | 1986 | } |
| 1987 | retired.clear(); | ||
| 1643 | context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready | 1988 | context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready |
| 1644 | return ok; | 1989 | return ok; |
| 1645 | } | 1990 | } |
| 1646 | 1991 | ||
| 1647 | // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that | 1992 | // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that |
| 1648 | // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). | 1993 | // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). |
| 1649 | void wait(VkSemaphore fence, std::uint64_t value) { | 1994 | // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). |
| 1650 | std::lock_guard state(state_mutex_); | 1995 | void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { |
| 1651 | waits_.push_back(fence); | 1996 | std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked |
| 1652 | wait_values_.push_back(value); | 1997 | { |
| 1998 | std::lock_guard state(state_mutex_); | ||
| 1999 | waits_.push_back(fence); | ||
| 2000 | wait_values_.push_back(value); | ||
| 2001 | if (pin) wait_pins_.push_back(pin()); | ||
| 2002 | drain_pins(retired); | ||
| 2003 | } | ||
| 2004 | } | ||
| 2005 | |||
| 2006 | // The first failure of a held ExecuteCommandLists since the last call (what the call would have returned had it | ||
| 2007 | // not been held), or success. A Signal behind a failed batch still signals, as when the failure is not held: the | ||
| 2008 | // work did not run, the application is told here and on stderr, and nothing waits forever. | ||
| 2009 | ReplayResult take_held_failure() { | ||
| 2010 | return static_cast<ReplayResult>(held_failure_.exchange(static_cast<int>(ReplayResult::success))); | ||
| 1653 | } | 2011 | } |
| 1654 | 2012 | ||
| 1655 | // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end | 2013 | // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end |
| 1656 | // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. | 2014 | // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. |
| 1657 | void marker(DebugMarker::Kind kind, const char* label) { | 2015 | void marker(DebugMarker::Kind kind, const char* label) { |
| 2016 | std::vector<std::shared_ptr<void>> retired; | ||
| 1658 | std::lock_guard state(state_mutex_); | 2017 | std::lock_guard state(state_mutex_); |
| 2018 | drain_pins(retired); // destroyed after the lock (reverse declaration order) | ||
| 1659 | if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too | 2019 | if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too |
| 1660 | Deferred op; | 2020 | Deferred op; |
| 1661 | op.kind = Deferred::Kind::marker; | 2021 | op.kind = Deferred::Kind::marker; |
| @@ -1673,8 +2033,127 @@ public: | |||
| 1673 | } | 2033 | } |
| 1674 | 2034 | ||
| 1675 | private: | 2035 | private: |
| 2036 | // Completed stages, reused by later ARRAY_OF_POINTERS builds. Only execute_now() touches the pool, and it holds | ||
| 2037 | // state_mutex_ (including the deferred/held release paths), so no extra lock is needed. | ||
| 2038 | std::vector<KhrInstanceStage> khr_stage_pool_; | ||
| 2039 | |||
| 2040 | void destroy_khr_stages(std::vector<KhrInstanceStage>& stages) { | ||
| 2041 | for (const auto& stage : stages) { | ||
| 2042 | if (stage.memory) context_.vk.vkFreeMemory(context_.device(), stage.memory, nullptr); | ||
| 2043 | if (stage.buffer) context_.vk.vkDestroyBuffer(context_.device(), stage.buffer, nullptr); | ||
| 2044 | } | ||
| 2045 | stages.clear(); | ||
| 2046 | } | ||
| 2047 | |||
| 2048 | // A stage returns to the pool only after its submission has completed, so rewriting it cannot race the GPU. | ||
| 2049 | void recycle_khr_stages(std::vector<KhrInstanceStage>& stages) { | ||
| 2050 | for (auto& stage : stages) khr_stage_pool_.push_back(std::move(stage)); | ||
| 2051 | stages.clear(); | ||
| 2052 | } | ||
| 2053 | |||
| 2054 | // A KHR TLAS built with D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS holds console VAs in its pointer list; Vulkan | ||
| 2055 | // reads those 8-byte entries as device addresses. Stage a translated copy in our own host-visible buffer instead | ||
| 2056 | // of editing the guest's input. The caller keeps the stage until the submission that builds with it completes. | ||
| 2057 | ReplayResult stage_khr_instances(const ReplayFunctions& vk, const BuildAccelerationStructure& build, | ||
| 2058 | std::vector<KhrInstanceStage>& stages, VkDeviceAddress& address) { | ||
| 2059 | const auto& funcs = context_.vk; | ||
| 2060 | if (!funcs.vkCreateBuffer || !funcs.vkDestroyBuffer || !funcs.vkGetBufferMemoryRequirements || | ||
| 2061 | !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || | ||
| 2062 | !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || | ||
| 2063 | !build.instance_count) | ||
| 2064 | return ReplayResult::unsupported; | ||
| 2065 | const std::uint64_t bytes = 8ull * build.instance_count; | ||
| 2066 | const std::uint8_t* guest = nullptr; | ||
| 2067 | const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); | ||
| 2068 | if (status == HostReadStatus::not_cpu_written) return ReplayResult::unsupported; | ||
| 2069 | if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; | ||
| 2070 | |||
| 2071 | KhrInstanceStage stage{}; | ||
| 2072 | const auto discard = [&] { | ||
| 2073 | if (stage.memory) funcs.vkFreeMemory(context_.device(), stage.memory, nullptr); | ||
| 2074 | if (stage.buffer) funcs.vkDestroyBuffer(context_.device(), stage.buffer, nullptr); | ||
| 2075 | }; | ||
| 2076 | // Reuse a completed stage that is already large enough. A per-frame TLAS rebuild then reuses the same buffer | ||
| 2077 | // and memory instead of making a new vkAllocateMemory call every frame. | ||
| 2078 | for (auto it = khr_stage_pool_.begin(); it != khr_stage_pool_.end(); ++it) { | ||
| 2079 | if (it->size >= bytes) { | ||
| 2080 | stage = std::move(*it); | ||
| 2081 | khr_stage_pool_.erase(it); | ||
| 2082 | break; | ||
| 2083 | } | ||
| 2084 | } | ||
| 2085 | if (!stage.buffer) { | ||
| 2086 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; | ||
| 2087 | info.size = bytes; | ||
| 2088 | info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | | ||
| 2089 | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; | ||
| 2090 | if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) | ||
| 2091 | return ReplayResult::unsupported; | ||
| 2092 | VkMemoryRequirements requirements{}; | ||
| 2093 | funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); | ||
| 2094 | const auto& memory = context_.occlusion_resolve_memory_; | ||
| 2095 | constexpr VkMemoryPropertyFlags host_flags = | ||
| 2096 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; | ||
| 2097 | std::uint32_t type = memory.memoryTypeCount; | ||
| 2098 | for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { | ||
| 2099 | if (!(requirements.memoryTypeBits & (1u << i))) continue; | ||
| 2100 | if ((memory.memoryTypes[i].propertyFlags & host_flags) == host_flags) { | ||
| 2101 | type = i; | ||
| 2102 | break; | ||
| 2103 | } | ||
| 2104 | } | ||
| 2105 | if (type == memory.memoryTypeCount) { | ||
| 2106 | discard(); | ||
| 2107 | return ReplayResult::unsupported; | ||
| 2108 | } | ||
| 2109 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; | ||
| 2110 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; | ||
| 2111 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; | ||
| 2112 | allocation.allocationSize = requirements.size; | ||
| 2113 | allocation.memoryTypeIndex = type; | ||
| 2114 | if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || | ||
| 2115 | funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { | ||
| 2116 | discard(); | ||
| 2117 | return ReplayResult::unsupported; | ||
| 2118 | } | ||
| 2119 | stage.size = bytes; | ||
| 2120 | } | ||
| 2121 | |||
| 2122 | void* mapped = nullptr; | ||
| 2123 | if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { | ||
| 2124 | discard(); | ||
| 2125 | return ReplayResult::unsupported; | ||
| 2126 | } | ||
| 2127 | // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. | ||
| 2128 | for (std::uint32_t i = 0; i < build.instance_count; ++i) { | ||
| 2129 | std::uint64_t va = 0; | ||
| 2130 | std::memcpy(&va, guest + 8ull * i, sizeof(va)); | ||
| 2131 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 2132 | VkDeviceSize offset = 0; | ||
| 2133 | std::uint64_t room = 64; // one D3D12_RAYTRACING_INSTANCE_DESC | ||
| 2134 | if (!va || !vk.buffer_at(va, room, buffer, offset) || room < 64 || va > UINT64_MAX - vk.heap_base) { | ||
| 2135 | funcs.vkUnmapMemory(context_.device(), stage.memory); | ||
| 2136 | discard(); | ||
| 2137 | return ReplayResult::invalid_copy; | ||
| 2138 | } | ||
| 2139 | const std::uint64_t device_address = vk.heap_base + va; | ||
| 2140 | std::memcpy(static_cast<std::uint8_t*>(mapped) + 8ull * i, &device_address, sizeof(device_address)); | ||
| 2141 | } | ||
| 2142 | funcs.vkUnmapMemory(context_.device(), stage.memory); | ||
| 2143 | VkBufferDeviceAddressInfo device_address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | ||
| 2144 | device_address.buffer = stage.buffer; | ||
| 2145 | stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); | ||
| 2146 | if (!stage.address) { | ||
| 2147 | discard(); | ||
| 2148 | return ReplayResult::unsupported; | ||
| 2149 | } | ||
| 2150 | stages.push_back(std::move(stage)); | ||
| 2151 | address = stages.back().address; | ||
| 2152 | return ReplayResult::success; | ||
| 2153 | } | ||
| 2154 | |||
| 1676 | ReplayResult execute_now(std::span<const CommandList* const> lists) { | 2155 | ReplayResult execute_now(std::span<const CommandList* const> lists) { |
| 1677 | if (context_.is_device_lost()) return ReplayResult::unsupported; | 2156 | if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; |
| 1678 | if (kind_ != QueueKind::direct) | 2157 | if (kind_ != QueueKind::direct) |
| 1679 | for (const auto* list : lists) | 2158 | for (const auto* list : lists) |
| 1680 | for (const auto& command : list->commands()) | 2159 | for (const auto& command : list->commands()) |
| @@ -1682,6 +2161,11 @@ private: | |||
| 1682 | std::holds_alternative<ClearDepthStencil>(command)) | 2161 | std::holds_alternative<ClearDepthStencil>(command)) |
| 1683 | return ReplayResult::unsupported; | 2162 | return ReplayResult::unsupported; |
| 1684 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; | 2163 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; |
| 2164 | struct KhrGuard { | ||
| 2165 | VulkanQueue* queue; | ||
| 2166 | std::vector<KhrInstanceStage> stages; | ||
| 2167 | ~KhrGuard() { queue->recycle_khr_stages(stages); } | ||
| 2168 | } khr_guard{this}; | ||
| 1685 | std::function<void(bool)> bindless_commit; | 2169 | std::function<void(bool)> bindless_commit; |
| 1686 | // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. | 2170 | // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. |
| 1687 | // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during | 2171 | // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during |
| @@ -1712,11 +2196,18 @@ private: | |||
| 1712 | // Kept between executions: prepare refills each list's entries in the storage the last execution left, where | 2196 | // Kept between executions: prepare refills each list's entries in the storage the last execution left, where |
| 1713 | // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). | 2197 | // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). |
| 1714 | auto& prepared = prepared_; | 2198 | auto& prepared = prepared_; |
| 1715 | prepared.resize(lists.size()); | 2199 | // Keep the storage from a larger batch. resize() down would destroy the unused entries and their vectors, so |
| 2200 | // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below | ||
| 2201 | // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. | ||
| 2202 | if (prepared.size() < lists.size()) prepared.resize(lists.size()); | ||
| 1716 | ReplayFunctions replay = context_.replay_; | 2203 | ReplayFunctions replay = context_.replay_; |
| 1717 | replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy | 2204 | replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy |
| 1718 | : kind_ == QueueKind::compute ? detail::queue_stages_compute | 2205 | : kind_ == QueueKind::compute ? detail::queue_stages_compute |
| 1719 | : 0; | 2206 | : 0; |
| 2207 | replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, | ||
| 2208 | VkDeviceAddress& address) { | ||
| 2209 | return stage_khr_instances(replay, build, khr_guard.stages, address); | ||
| 2210 | }; | ||
| 1720 | std::uint64_t captures = 0; | 2211 | std::uint64_t captures = 0; |
| 1721 | for (const auto* list : lists) | 2212 | for (const auto* list : lists) |
| 1722 | for (const auto& command : list->commands()) | 2213 | for (const auto& command : list->commands()) |
| @@ -1796,9 +2287,10 @@ private: | |||
| 1796 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 2287 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { |
| 1797 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); | 2288 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); |
| 1798 | }; | 2289 | }; |
| 1799 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 2290 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, |
| 1800 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 2291 | const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, |
| 1801 | occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset); | 2292 | VkBuffer dst, VkDeviceSize offset) { |
| 2293 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset); | ||
| 1802 | }; | 2294 | }; |
| 1803 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 2295 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, |
| 1804 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 2296 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { |
| @@ -1834,17 +2326,39 @@ private: | |||
| 1834 | }; | 2326 | }; |
| 1835 | std::shared_ptr<OcclusionSegmentPool> physical, statistics; | 2327 | std::shared_ptr<OcclusionSegmentPool> physical, statistics; |
| 1836 | if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; | 2328 | if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; |
| 1837 | // Without the compute helper a split query could not be summed: leave statistics queries whole, as before. | 2329 | // Without the compute helper a split query could not be summed: leave statistics queries whole, as before |
| 1838 | if (statistics_segments && can_resolve_occlusion && | 2330 | // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). |
| 1839 | !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) | 2331 | if (statistics_segments && can_resolve_occlusion) { |
| 1840 | return ReplayResult::unsupported; | 2332 | if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) |
| 2333 | return ReplayResult::unsupported; | ||
| 2334 | for (const auto& list : prepared) | ||
| 2335 | statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), | ||
| 2336 | list.statistics_mesh.end()); | ||
| 2337 | if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { | ||
| 2338 | statistics->mesh.clear(); | ||
| 2339 | } else { | ||
| 2340 | // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping | ||
| 2341 | // invocations and primitives, fragment and compute invocations (D3D-291). | ||
| 2342 | VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; | ||
| 2343 | info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; | ||
| 2344 | info.queryCount = statistics_segments; | ||
| 2345 | info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | | ||
| 2346 | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT | | ||
| 2347 | VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | | ||
| 2348 | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT; | ||
| 2349 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != | ||
| 2350 | VK_SUCCESS) | ||
| 2351 | return ReplayResult::unsupported; | ||
| 2352 | } | ||
| 2353 | } | ||
| 1841 | // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after | 2354 | // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after |
| 1842 | // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues | 2355 | // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues |
| 1843 | // see submission-order query state and remove_query_pool() waits until commit finishes. | 2356 | // see submission-order query state and remove_query_pool() waits until commit finishes. |
| 1844 | if (has_queries && !tracker_lock.owns_lock()) tracker_lock.lock(); | 2357 | if (has_queries && !tracker_lock.owns_lock()) tracker_lock.lock(); |
| 1845 | QueryReplay queries; | 2358 | QueryReplay queries; |
| 1846 | std::uint32_t base = 0, statistics_base = 0; | 2359 | std::uint32_t base = 0, statistics_base = 0; |
| 1847 | for (auto& list : prepared) { | 2360 | for (std::size_t i = 0; i < lists.size(); ++i) { |
| 2361 | auto& list = prepared[i]; | ||
| 1848 | const auto result = queries.plan(list, physical, base, can_resolve_occlusion, statistics, statistics_base); | 2362 | const auto result = queries.plan(list, physical, base, can_resolve_occlusion, statistics, statistics_base); |
| 1849 | if (result != ReplayResult::success) return result; | 2363 | if (result != ReplayResult::success) return result; |
| 1850 | base += list.segment_count; | 2364 | base += list.segment_count; |
| @@ -1863,6 +2377,8 @@ private: | |||
| 1863 | 2377 | ||
| 1864 | CommandSlot* slot = acquire(); | 2378 | CommandSlot* slot = acquire(); |
| 1865 | if (!slot) return ReplayResult::unsupported; | 2379 | if (!slot) return ReplayResult::unsupported; |
| 2380 | slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused | ||
| 2381 | khr_guard.stages.clear(); | ||
| 1866 | command_buffer = slot->buffer; | 2382 | command_buffer = slot->buffer; |
| 1867 | // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders | 2383 | // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders |
| 1868 | // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6). | 2384 | // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6). |
| @@ -1905,13 +2421,15 @@ private: | |||
| 1905 | context_.scratch_->retire(progress_, 0); | 2421 | context_.scratch_->retire(progress_, 0); |
| 1906 | scratch_guard.active = false; | 2422 | scratch_guard.active = false; |
| 1907 | } | 2423 | } |
| 1908 | tracker_lock.unlock(); | ||
| 1909 | if (bindless_commit) bindless_commit(submitted); | 2424 | if (bindless_commit) bindless_commit(submitted); |
| 2425 | tracker_lock.unlock(); | ||
| 1910 | return ReplayResult::unsupported; | 2426 | return ReplayResult::unsupported; |
| 1911 | } | 2427 | } |
| 2428 | replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; | ||
| 2429 | const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); | ||
| 1912 | auto next_tracker = context_.tracker_; | 2430 | auto next_tracker = context_.tracker_; |
| 1913 | // Images with a UAV view are moved to GENERAL (zeroed) by the first submission that can use a shader on them: | 2431 | // Bindless images that may already be visible to shaders are initialized on a submission that runs shaders. |
| 1914 | // not a copy queue (its family may not clear images), and one whose lists dispatch or draw. | 2432 | // initialize() zeroes committed storage images and only transitions sparse images. |
| 1915 | bool runs_shaders = false; | 2433 | bool runs_shaders = false; |
| 1916 | for (const CommandList* list : lists) | 2434 | for (const CommandList* list : lists) |
| 1917 | for (const auto& command : list->commands()) | 2435 | for (const auto& command : list->commands()) |
| @@ -1927,6 +2445,15 @@ private: | |||
| 1927 | wait_values_.push_back(context_.storage_init_value_); | 2445 | wait_values_.push_back(context_.storage_init_value_); |
| 1928 | storage_init_seen_ = context_.storage_init_version_; | 2446 | storage_init_seen_ = context_.storage_init_version_; |
| 1929 | } | 2447 | } |
| 2448 | // The set this submission binds may be a new generation whose table another queue's submission uploads: | ||
| 2449 | // wait for that one, as for the storage images (the table's buffers are used by one queue family only: | ||
| 2450 | // every D3D12 queue of the device is made in info.queue_family). | ||
| 2451 | if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && | ||
| 2452 | context_.bindless_upload_version_ != bindless_upload_seen_) { | ||
| 2453 | waits_.push_back(context_.bindless_upload_semaphore_); | ||
| 2454 | wait_values_.push_back(context_.bindless_upload_value_); | ||
| 2455 | } | ||
| 2456 | bindless_upload_seen_ = context_.bindless_upload_version_; | ||
| 1930 | if (kind_ != QueueKind::copy && runs_shaders) | 2457 | if (kind_ != QueueKind::copy && runs_shaders) |
| 1931 | storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); | 2458 | storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); |
| 1932 | if (!storage_images.empty()) context_.storage_pending_.clear(); | 2459 | if (!storage_images.empty()) context_.storage_pending_.clear(); |
| @@ -1951,7 +2478,8 @@ private: | |||
| 1951 | bool wrote_readback = false; | 2478 | bool wrote_readback = false; |
| 1952 | VkPipelineStageFlags2 readback_stages = 0; | 2479 | VkPipelineStageFlags2 readback_stages = 0; |
| 1953 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists | 2480 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists |
| 1954 | for (const auto& list : prepared) { | 2481 | for (std::size_t i = 0; i < lists.size(); ++i) { |
| 2482 | const auto& list = prepared[i]; | ||
| 1955 | emit(list, command_buffer, replay, &next_tracker, &open_labels); | 2483 | emit(list, command_buffer, replay, &next_tracker, &open_labels); |
| 1956 | wrote_readback |= list.wrote_readback; | 2484 | wrote_readback |= list.wrote_readback; |
| 1957 | readback_stages |= list.readback_src_stages; | 2485 | readback_stages |= list.readback_src_stages; |
| @@ -2008,6 +2536,13 @@ private: | |||
| 2008 | ++context_.storage_init_version_; | 2536 | ++context_.storage_init_version_; |
| 2009 | storage_init_seen_ = context_.storage_init_version_; | 2537 | storage_init_seen_ = context_.storage_init_version_; |
| 2010 | } | 2538 | } |
| 2539 | if (submitted && bindless_uploaded) { | ||
| 2540 | std::lock_guard lock(context_.storage_mutex_); | ||
| 2541 | context_.bindless_upload_semaphore_ = progress_; | ||
| 2542 | context_.bindless_upload_value_ = submitted_; | ||
| 2543 | ++context_.bindless_upload_version_; | ||
| 2544 | bindless_upload_seen_ = context_.bindless_upload_version_; | ||
| 2545 | } | ||
| 2011 | if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one | 2546 | if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one |
| 2012 | waits_.pop_back(); | 2547 | waits_.pop_back(); |
| 2013 | wait_values_.pop_back(); | 2548 | wait_values_.pop_back(); |
| @@ -2030,8 +2565,10 @@ private: | |||
| 2030 | context_.scratch_->retire(progress_, submitted ? submitted_ : 0); | 2565 | context_.scratch_->retire(progress_, submitted ? submitted_ : 0); |
| 2031 | scratch_guard.active = false; | 2566 | scratch_guard.active = false; |
| 2032 | } | 2567 | } |
| 2033 | tracker_lock.unlock(); | 2568 | // Under tracker_mutex_, so no other flush comes between this submit and the set's note of whether it reached |
| 2569 | // the queue (it keeps a single upload obligation). | ||
| 2034 | if (bindless_commit) bindless_commit(submitted); | 2570 | if (bindless_commit) bindless_commit(submitted); |
| 2571 | tracker_lock.unlock(); | ||
| 2035 | return submitted ? ReplayResult::success : ReplayResult::unsupported; | 2572 | return submitted ? ReplayResult::success : ReplayResult::unsupported; |
| 2036 | } | 2573 | } |
| 2037 | 2574 | ||
| @@ -2059,6 +2596,7 @@ private: | |||
| 2059 | struct Deferred { | 2596 | struct Deferred { |
| 2060 | enum class Kind : std::uint8_t { batch, signal, marker }; | 2597 | enum class Kind : std::uint8_t { batch, signal, marker }; |
| 2061 | Kind kind = Kind::batch; | 2598 | Kind kind = Kind::batch; |
| 2599 | std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues | ||
| 2062 | std::vector<VkSemaphore> waits; | 2600 | std::vector<VkSemaphore> waits; |
| 2063 | std::vector<std::uint64_t> wait_values; | 2601 | std::vector<std::uint64_t> wait_values; |
| 2064 | std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call | 2602 | std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call |
| @@ -2066,6 +2604,10 @@ private: | |||
| 2066 | std::uint64_t value = 0; | 2604 | std::uint64_t value = 0; |
| 2067 | DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker | 2605 | DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker |
| 2068 | std::string label; | 2606 | std::string label; |
| 2607 | // Alive until the operation has run: the fences it waits on and signals, the pipeline states and root | ||
| 2608 | // signatures of the lists (the application may release them right after the call). | ||
| 2609 | std::vector<std::shared_ptr<void>> pins; | ||
| 2610 | std::vector<std::shared_ptr<void>> wait_pins; // the fences of `waits` | ||
| 2069 | }; | 2611 | }; |
| 2070 | 2612 | ||
| 2071 | bool waits_pending(const std::vector<VkSemaphore>& semaphores, const std::vector<std::uint64_t>& values) const { | 2613 | bool waits_pending(const std::vector<VkSemaphore>& semaphores, const std::vector<std::uint64_t>& values) const { |
| @@ -2078,32 +2620,75 @@ private: | |||
| 2078 | // has no submitted Signal yet. Called with state_mutex_ held. | 2620 | // has no submitted Signal yet. Called with state_mutex_ held. |
| 2079 | bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); } | 2621 | bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); } |
| 2080 | 2622 | ||
| 2623 | // The waits are consumed: submitted as `ticket` (0: dropped on device loss). What the application may release | ||
| 2624 | // (the fences they named) is kept until that submission has completed on the GPU, as a D3D12 queue does: | ||
| 2625 | // destroying a semaphore a pending submission uses is a validation error. Retired pins are destroyed by the | ||
| 2626 | // caller after state_mutex_ is released (drain_pins): the last release of a fence waits for a running release, | ||
| 2627 | // which must not be waiting for this lock. | ||
| 2628 | void clear_waits(std::uint64_t ticket = 0) { | ||
| 2629 | waits_.clear(); | ||
| 2630 | wait_values_.clear(); | ||
| 2631 | retire_pins(wait_pins_, ticket); | ||
| 2632 | } | ||
| 2633 | |||
| 2634 | void retire_pins(std::vector<std::shared_ptr<void>>& pins, std::uint64_t ticket) { | ||
| 2635 | for (auto& pin : pins) { | ||
| 2636 | if (ticket) pin_queue_.push_back({ticket, std::move(pin)}); | ||
| 2637 | else retired_pins_.push_back(std::move(pin)); | ||
| 2638 | } | ||
| 2639 | pins.clear(); | ||
| 2640 | } | ||
| 2641 | |||
| 2642 | // Moves the pins whose submission has completed (and the ones retired outright) to `out`. state_mutex_ held. | ||
| 2643 | void drain_pins(std::vector<std::shared_ptr<void>>& out) { | ||
| 2644 | out.swap(retired_pins_); | ||
| 2645 | if (pin_queue_.empty()) return; | ||
| 2646 | const std::uint64_t done = completed(); | ||
| 2647 | while (!pin_queue_.empty() && pin_queue_.front().ticket <= done) { | ||
| 2648 | out.push_back(std::move(pin_queue_.front().pin)); | ||
| 2649 | pin_queue_.pop_front(); | ||
| 2650 | } | ||
| 2651 | } | ||
| 2652 | |||
| 2081 | // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. | 2653 | // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. |
| 2082 | void hold(Deferred&& op) { | 2654 | void hold(Deferred&& op) { |
| 2655 | op.seq = context_.holds().next_seq(); | ||
| 2083 | if (op.kind != Deferred::Kind::marker) { | 2656 | if (op.kind != Deferred::Kind::marker) { |
| 2084 | op.waits = std::move(waits_); | 2657 | op.waits = std::move(waits_); |
| 2085 | op.wait_values = std::move(wait_values_); | 2658 | op.wait_values = std::move(wait_values_); |
| 2659 | op.wait_pins = std::move(wait_pins_); | ||
| 2086 | waits_.clear(); | 2660 | waits_.clear(); |
| 2087 | wait_values_.clear(); | 2661 | wait_values_.clear(); |
| 2662 | wait_pins_.clear(); | ||
| 2088 | } | 2663 | } |
| 2089 | held_.push_back(std::move(op)); | 2664 | held_.push_back(std::move(op)); |
| 2090 | context_.holds().held_changed(1); | 2665 | context_.holds().held_changed(1); |
| 2091 | } | 2666 | } |
| 2092 | 2667 | ||
| 2093 | // Runs one held operation as the call would have, with its own waits and none of the ones queued since. | 2668 | // Runs one held operation as the call would have, with its own waits and none of the ones queued since. |
| 2669 | // A submission that fails leaves its waits for the next one, as when the call is not held (a transient | ||
| 2670 | // vkQueueSubmit failure is retried by the application's next call), ahead of the waits asked for since. | ||
| 2094 | void run(Deferred& op) { | 2671 | void run(Deferred& op) { |
| 2095 | auto later_waits = std::move(waits_); | 2672 | auto later_waits = std::move(waits_); |
| 2096 | auto later_values = std::move(wait_values_); | 2673 | auto later_values = std::move(wait_values_); |
| 2674 | auto later_pins = std::move(wait_pins_); | ||
| 2097 | waits_ = std::move(op.waits); | 2675 | waits_ = std::move(op.waits); |
| 2098 | wait_values_ = std::move(op.wait_values); | 2676 | wait_values_ = std::move(op.wait_values); |
| 2677 | wait_pins_ = std::move(op.wait_pins); // the fences stay alive until the submission has consumed their waits | ||
| 2099 | switch (op.kind) { | 2678 | switch (op.kind) { |
| 2100 | case Deferred::Kind::batch: { | 2679 | case Deferred::Kind::batch: { |
| 2101 | std::vector<const CommandList*> lists; | 2680 | std::vector<const CommandList*> lists; |
| 2102 | for (const CommandList& list : op.lists) lists.push_back(&list); | 2681 | for (const CommandList& list : op.lists) lists.push_back(&list); |
| 2682 | // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until | ||
| 2683 | // the batch has been recorded and then, with the fences, until its submission has completed (below). | ||
| 2103 | const ReplayResult result = execute_now(lists); | 2684 | const ReplayResult result = execute_now(lists); |
| 2104 | if (result != ReplayResult::success) | 2685 | if (result != ReplayResult::success) { |
| 2686 | int none = static_cast<int>(ReplayResult::success); | ||
| 2687 | held_failure_.compare_exchange_strong(none, static_cast<int>(result)); | ||
| 2105 | std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); " | 2688 | std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); " |
| 2106 | "nothing was submitted\n", static_cast<int>(result)); | 2689 | "nothing was submitted for it, and a Signal behind it still signals\n", |
| 2690 | static_cast<int>(result)); | ||
| 2691 | } | ||
| 2107 | break; | 2692 | break; |
| 2108 | } | 2693 | } |
| 2109 | case Deferred::Kind::signal: | 2694 | case Deferred::Kind::signal: |
| @@ -2114,55 +2699,83 @@ private: | |||
| 2114 | marker_now(op.marker_kind, op.label.c_str()); | 2699 | marker_now(op.marker_kind, op.label.c_str()); |
| 2115 | break; | 2700 | break; |
| 2116 | } | 2701 | } |
| 2117 | waits_ = std::move(later_waits); // a failed submission leaves its waits behind: drop them with the batch | 2702 | retire_pins(op.pins, submitted_); // the fence it signals, the pipeline states: until its submission is done |
| 2118 | wait_values_ = std::move(later_values); | 2703 | waits_.insert(waits_.end(), later_waits.begin(), later_waits.end()); |
| 2704 | wait_values_.insert(wait_values_.end(), later_values.begin(), later_values.end()); | ||
| 2705 | for (auto& pin : later_pins) wait_pins_.push_back(std::move(pin)); | ||
| 2119 | } | 2706 | } |
| 2120 | 2707 | ||
| 2121 | bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } | 2708 | bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } |
| 2122 | 2709 | ||
| 2123 | // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). | 2710 | // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). |
| 2124 | bool release_ready() override { | 2711 | bool release_ready() override { |
| 2125 | std::lock_guard state(state_mutex_); | 2712 | std::vector<std::shared_ptr<void>> retired; |
| 2126 | bool released = false; | 2713 | bool released = false; |
| 2127 | while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { | 2714 | { |
| 2128 | Deferred op = std::move(held_.front()); | 2715 | std::lock_guard state(state_mutex_); |
| 2129 | held_.pop_front(); | 2716 | while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { |
| 2130 | context_.holds().held_changed(-1); | 2717 | Deferred op = std::move(held_.front()); |
| 2131 | if (!context_.is_device_lost()) run(op); | 2718 | held_.pop_front(); |
| 2132 | released = true; | 2719 | context_.holds().held_changed(-1); |
| 2720 | if (!context_.is_device_lost()) run(op); | ||
| 2721 | released = true; | ||
| 2722 | } | ||
| 2723 | drain_pins(retired); | ||
| 2133 | } | 2724 | } |
| 2134 | return released; | 2725 | return released; |
| 2135 | } | 2726 | } |
| 2136 | 2727 | ||
| 2137 | // Holder: the fence is released, so what waits on it can never run. | 2728 | // Holder: the fence is released, so what waits on it can never run. |
| 2138 | void discard_waiting_on(VkSemaphore semaphore) override { | 2729 | void discard_waiting_on(VkSemaphore semaphore) override { |
| 2139 | std::lock_guard state(state_mutex_); | 2730 | std::vector<Deferred> dropped; |
| 2140 | for (auto it = held_.begin(); it != held_.end();) { | 2731 | { |
| 2141 | if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end()) { | 2732 | std::lock_guard state(state_mutex_); |
| 2142 | ++it; | 2733 | for (auto it = held_.begin(); it != held_.end();) { |
| 2143 | continue; | 2734 | if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end() && |
| 2735 | !(it->kind == Deferred::Kind::signal && it->fence == semaphore)) { | ||
| 2736 | ++it; | ||
| 2737 | continue; | ||
| 2738 | } | ||
| 2739 | std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work that names it; " | ||
| 2740 | "that work is dropped\n"); | ||
| 2741 | dropped.push_back(std::move(*it)); | ||
| 2742 | it = held_.erase(it); | ||
| 2743 | context_.holds().held_changed(-1); | ||
| 2144 | } | 2744 | } |
| 2145 | std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work waiting on it; " | ||
| 2146 | "that work is dropped\n"); | ||
| 2147 | it = held_.erase(it); | ||
| 2148 | context_.holds().held_changed(-1); | ||
| 2149 | } | 2745 | } |
| 2150 | } | 2746 | } |
| 2151 | 2747 | ||
| 2152 | // A queue destroyed with held work: the fence it waits on was never signaled. Reported, not waited for; nothing | 2748 | // Holder: the sequence number of the oldest held operation. |
| 2153 | // was submitted for it, so the VkQueue is idle and the destructor goes on. | 2749 | std::uint64_t oldest_held_seq() override { |
| 2154 | void report_held_at_teardown() { | ||
| 2155 | std::lock_guard state(state_mutex_); | 2750 | std::lock_guard state(state_mutex_); |
| 2156 | if (held_.empty()) return; | 2751 | return held_.empty() ? 0 : held_.front().seq; |
| 2157 | std::uint64_t value = 0; | 2752 | } |
| 2158 | for (const Deferred& op : held_) | 2753 | |
| 2159 | for (std::size_t i = 0; i < op.waits.size() && !value; ++i) | 2754 | // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is |
| 2160 | if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i]; | 2755 | // idle and the destructor goes on. The fences of held Signals will never reach their values, so what is waiting |
| 2161 | std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a " | 2756 | // for them on the CPU (SetEventOnCompletion, as a released fence completes them) is woken, and the batches |
| 2162 | "fence value (%llu) that no Signal reached; the fence was never signaled\n", | 2757 | // that wait for them on other queues stay held (and are reported when those queues are destroyed). |
| 2163 | held_.size(), static_cast<unsigned long long>(value)); | 2758 | void report_held_at_teardown() { |
| 2164 | context_.holds().held_changed(-static_cast<std::int64_t>(held_.size())); | 2759 | std::deque<Deferred> dropped; |
| 2165 | held_.clear(); | 2760 | { |
| 2761 | std::lock_guard state(state_mutex_); | ||
| 2762 | if (held_.empty()) return; | ||
| 2763 | std::uint64_t value = 0; | ||
| 2764 | for (const Deferred& op : held_) | ||
| 2765 | for (std::size_t i = 0; i < op.waits.size() && !value; ++i) | ||
| 2766 | if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i]; | ||
| 2767 | std::size_t signals = 0; | ||
| 2768 | for (const Deferred& op : held_) signals += op.kind == Deferred::Kind::signal; | ||
| 2769 | std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a " | ||
| 2770 | "fence value (%llu) that no Signal reached; the fence was never signaled%s\n", | ||
| 2771 | held_.size(), static_cast<unsigned long long>(value), | ||
| 2772 | signals ? "; CPU waits on the fences of its held Signals are completed" : ""); | ||
| 2773 | for (const Deferred& op : held_) | ||
| 2774 | if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); | ||
| 2775 | context_.holds().held_changed(-static_cast<std::int64_t>(held_.size())); | ||
| 2776 | dropped.swap(held_); | ||
| 2777 | } | ||
| 2778 | // The pins (fences, pipeline states) are released here, outside the lock. | ||
| 2166 | } | 2779 | } |
| 2167 | 2780 | ||
| 2168 | struct CommandSlot { | 2781 | struct CommandSlot { |
| @@ -2173,36 +2786,77 @@ private: | |||
| 2173 | std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; | 2786 | std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; |
| 2174 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_dispatch; | 2787 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_dispatch; |
| 2175 | std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes | 2788 | std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes |
| 2789 | std::vector<KhrInstanceStage> khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime | ||
| 2176 | }; | 2790 | }; |
| 2177 | 2791 | ||
| 2178 | struct PendingBindings { | 2792 | struct PendingBindings { |
| 2179 | std::uint64_t ticket = 0; | 2793 | std::uint64_t ticket = 0; |
| 2180 | // Vulkan needs the buffer until the bind completes and the previous allocation until it is unmapped. | 2794 | // Vulkan needs the resource until the bind completes and the previous allocation until it is unmapped. |
| 2181 | std::vector<std::shared_ptr<const TileHeapAllocation>> old_heaps; | 2795 | std::vector<std::shared_ptr<const TileHeapAllocation>> old_heaps; |
| 2182 | std::shared_ptr<SparseBuffer> buffer; | 2796 | std::shared_ptr<SparseResource> resource; |
| 2183 | }; | 2797 | }; |
| 2184 | 2798 | ||
| 2185 | static bool valid_tiles(const SparseBuffer& buffer, BufferTileRegion region) { | 2799 | static bool valid_tiles(const SparseResource& resource, TileRegion region) { |
| 2186 | return region.count && region.first < buffer.tile_count && region.count <= buffer.tile_count - region.first; | 2800 | return region.count && region.first < resource.tile_count && region.count <= resource.tile_count - region.first; |
| 2801 | } | ||
| 2802 | |||
| 2803 | bool initialize_sparse_image_layout(ResourceId id) { | ||
| 2804 | std::lock_guard lock(context_.tracker_mutex_); | ||
| 2805 | if (context_.tracker_.layout(id, 0) != VK_IMAGE_LAYOUT_UNDEFINED) return true; | ||
| 2806 | auto* slot = acquire(); | ||
| 2807 | if (!slot) return false; | ||
| 2808 | const VkCommandBuffer command_buffer = slot->buffer; | ||
| 2809 | auto& vk = context_.vk; | ||
| 2810 | VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | ||
| 2811 | begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; | ||
| 2812 | if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { | ||
| 2813 | slot->ticket = 0; | ||
| 2814 | return false; | ||
| 2815 | } | ||
| 2816 | // Transition while the image is still unbound. Doing this after binding could discard another image's | ||
| 2817 | // contents in an aliased page. Subsequent uses keep the image in GENERAL. | ||
| 2818 | constexpr VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 2819 | detail::image_barrier(context_.replay_, command_buffer, context_.resources_.at(id), range, | ||
| 2820 | VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, 0, | ||
| 2821 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, | ||
| 2822 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | ||
| 2823 | if (vk.vkEndCommandBuffer(command_buffer) != VK_SUCCESS || !submit(command_buffer, VK_NULL_HANDLE, 0)) { | ||
| 2824 | slot->ticket = 0; | ||
| 2825 | return false; | ||
| 2826 | } | ||
| 2827 | context_.tracker_.set(id, range, VK_IMAGE_LAYOUT_GENERAL); | ||
| 2828 | return true; | ||
| 2187 | } | 2829 | } |
| 2188 | 2830 | ||
| 2189 | bool bind_tiles(const std::shared_ptr<SparseBuffer>& buffer, | 2831 | bool bind_tiles(ResourceId id, const std::shared_ptr<SparseResource>& resource, |
| 2190 | std::map<std::uint64_t, BufferTile>& changes) { | 2832 | std::map<std::uint64_t, TileMapping>& changes) { |
| 2191 | auto& vk = context_.vk; | 2833 | auto& vk = context_.vk; |
| 2192 | if (!vk.vkQueueBindSparse || context_.is_device_lost()) return false; | 2834 | if (!vk.vkQueueBindSparse || context_.is_device_lost()) return false; |
| 2193 | const auto ticket = submitted_ + 1; | 2835 | PendingBindings pending{0, {}, resource}; |
| 2194 | PendingBindings pending{ticket, {}, buffer}; | ||
| 2195 | std::vector<VkSparseMemoryBind> binds; | 2836 | std::vector<VkSparseMemoryBind> binds; |
| 2837 | std::vector<VkSparseImageMemoryBind> image_binds; | ||
| 2196 | for (const auto& [index, page] : changes) { | 2838 | for (const auto& [index, page] : changes) { |
| 2197 | const auto old = buffer->mapped.find(index); | 2839 | const auto old = resource->mapped.find(index); |
| 2198 | if (old != buffer->mapped.end()) { | 2840 | if (old != resource->mapped.end()) { |
| 2199 | if (old->second == page) continue; | 2841 | if (old->second == page) continue; |
| 2200 | pending.old_heaps.push_back(old->second.heap); | 2842 | pending.old_heaps.push_back(old->second.heap); |
| 2201 | } else if (!page.heap) { | 2843 | } else if (!page.heap) { |
| 2202 | continue; | 2844 | continue; |
| 2203 | } | 2845 | } |
| 2204 | if (page.heap && !(buffer->memory_types & (1u << page.heap->memory_type))) return false; | 2846 | if (page.heap && !(resource->memory_types & (1u << page.heap->memory_type))) return false; |
| 2205 | const VkDeviceMemory memory = page.heap ? page.heap->memory : VK_NULL_HANDLE; | 2847 | const VkDeviceMemory memory = page.heap ? page.heap->memory : VK_NULL_HANDLE; |
| 2848 | if (resource->image) { | ||
| 2849 | constexpr auto shape = element_tile_shape(false, 4); | ||
| 2850 | const auto extent = resource->image_extent; | ||
| 2851 | const auto columns = 1 + (extent.width - 1) / shape.width; | ||
| 2852 | const auto x = std::uint32_t(index % columns) * shape.width; | ||
| 2853 | const auto y = std::uint32_t(index / columns) * shape.height; | ||
| 2854 | image_binds.push_back({ | ||
| 2855 | {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0}, {std::int32_t(x), std::int32_t(y), 0}, | ||
| 2856 | {std::min(shape.width, extent.width - x), std::min(shape.height, extent.height - y), 1}, | ||
| 2857 | memory, page.offset, 0}); | ||
| 2858 | continue; | ||
| 2859 | } | ||
| 2206 | const VkDeviceSize resource_offset = index * tile_size_in_bytes; | 2860 | const VkDeviceSize resource_offset = index * tile_size_in_bytes; |
| 2207 | if (!binds.empty()) { | 2861 | if (!binds.empty()) { |
| 2208 | auto& previous = binds.back(); | 2862 | auto& previous = binds.back(); |
| @@ -2214,7 +2868,10 @@ private: | |||
| 2214 | } | 2868 | } |
| 2215 | binds.push_back({resource_offset, tile_size_in_bytes, memory, page.offset, 0}); | 2869 | binds.push_back({resource_offset, tile_size_in_bytes, memory, page.offset, 0}); |
| 2216 | } | 2870 | } |
| 2217 | if (binds.empty()) return true; | 2871 | if (binds.empty() && image_binds.empty()) return true; |
| 2872 | if (!image_binds.empty() && !initialize_sparse_image_layout(id)) return false; | ||
| 2873 | const auto ticket = submitted_ + 1; | ||
| 2874 | pending.ticket = ticket; | ||
| 2218 | collect_bindings(completed()); | 2875 | collect_bindings(completed()); |
| 2219 | auto semaphores = waits_; | 2876 | auto semaphores = waits_; |
| 2220 | auto values = wait_values_; | 2877 | auto values = wait_values_; |
| @@ -2228,12 +2885,20 @@ private: | |||
| 2228 | tickets.pWaitSemaphoreValues = values.data(); | 2885 | tickets.pWaitSemaphoreValues = values.data(); |
| 2229 | tickets.signalSemaphoreValueCount = 1; | 2886 | tickets.signalSemaphoreValueCount = 1; |
| 2230 | tickets.pSignalSemaphoreValues = &ticket; | 2887 | tickets.pSignalSemaphoreValues = &ticket; |
| 2231 | const VkSparseBufferMemoryBindInfo buffer_bind{buffer->buffer, std::uint32_t(binds.size()), binds.data()}; | 2888 | const VkSparseBufferMemoryBindInfo buffer_bind{resource->buffer, std::uint32_t(binds.size()), binds.data()}; |
| 2889 | const VkSparseImageMemoryBindInfo image_bind{ | ||
| 2890 | resource->image, std::uint32_t(image_binds.size()), image_binds.data()}; | ||
| 2232 | VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &tickets}; | 2891 | VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &tickets}; |
| 2233 | info.waitSemaphoreCount = std::uint32_t(semaphores.size()); | 2892 | info.waitSemaphoreCount = std::uint32_t(semaphores.size()); |
| 2234 | info.pWaitSemaphores = semaphores.data(); | 2893 | info.pWaitSemaphores = semaphores.data(); |
| 2235 | info.bufferBindCount = 1; | 2894 | if (!binds.empty()) { |
| 2236 | info.pBufferBinds = &buffer_bind; | 2895 | info.bufferBindCount = 1; |
| 2896 | info.pBufferBinds = &buffer_bind; | ||
| 2897 | } | ||
| 2898 | if (!image_binds.empty()) { | ||
| 2899 | info.imageBindCount = 1; | ||
| 2900 | info.pImageBinds = &image_bind; | ||
| 2901 | } | ||
| 2237 | info.signalSemaphoreCount = 1; | 2902 | info.signalSemaphoreCount = 1; |
| 2238 | info.pSignalSemaphores = &progress_; | 2903 | info.pSignalSemaphores = &progress_; |
| 2239 | pending_bindings_.push_back(std::move(pending)); | 2904 | pending_bindings_.push_back(std::move(pending)); |
| @@ -2248,21 +2913,23 @@ private: | |||
| 2248 | context_.record_submit_locked(progress_, ticket); | 2913 | context_.record_submit_locked(progress_, ticket); |
| 2249 | } | 2914 | } |
| 2250 | submitted_ = last_sparse_ = ticket; | 2915 | submitted_ = last_sparse_ = ticket; |
| 2251 | waits_.clear(); | 2916 | clear_waits(ticket); |
| 2252 | wait_values_.clear(); | ||
| 2253 | for (auto it = changes.begin(); it != changes.end();) { | 2917 | for (auto it = changes.begin(); it != changes.end();) { |
| 2254 | buffer->mapped.erase(it->first); | 2918 | resource->mapped.erase(it->first); |
| 2255 | if (it->second.heap) ++it; | 2919 | if (it->second.heap) ++it; |
| 2256 | else it = changes.erase(it); | 2920 | else it = changes.erase(it); |
| 2257 | } | 2921 | } |
| 2258 | buffer->mapped.merge(changes); | 2922 | resource->mapped.merge(changes); |
| 2259 | return true; | 2923 | return true; |
| 2260 | } | 2924 | } |
| 2261 | 2925 | ||
| 2262 | std::uint64_t completed() const { | 2926 | std::uint64_t completed() const { |
| 2927 | if (context_.is_device_lost()) return 0; | ||
| 2263 | std::uint64_t done = 0; | 2928 | std::uint64_t done = 0; |
| 2264 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); | 2929 | const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); |
| 2265 | return done; | 2930 | if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); |
| 2931 | // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. | ||
| 2932 | return result == VK_SUCCESS ? done : 0; | ||
| 2266 | } | 2933 | } |
| 2267 | 2934 | ||
| 2268 | void collect_bindings(std::uint64_t done) { | 2935 | void collect_bindings(std::uint64_t done) { |
| @@ -2271,21 +2938,68 @@ private: | |||
| 2271 | if (last_sparse_ <= done) last_sparse_ = 0; | 2938 | if (last_sparse_ <= done) last_sparse_ = 0; |
| 2272 | } | 2939 | } |
| 2273 | 2940 | ||
| 2274 | CommandSlot* acquire() { | 2941 | // Releases what every finished command buffer holds; the first of them, or null when none has finished. |
| 2275 | if (context_.is_device_lost()) return nullptr; | 2942 | CommandSlot* recycle_finished() { |
| 2276 | context_.drain_deleted_resources(context_.completed_retire_ticket()); | ||
| 2277 | const auto done = completed(); | 2943 | const auto done = completed(); |
| 2944 | if (context_.is_device_lost()) return nullptr; | ||
| 2278 | collect_bindings(done); | 2945 | collect_bindings(done); |
| 2279 | CommandSlot* reuse = nullptr; | 2946 | CommandSlot* reuse = nullptr; |
| 2280 | for (auto& slot : buffers_) { | 2947 | for (auto& slot : buffers_) { |
| 2281 | if (slot.ticket > done) continue; | 2948 | if (slot.ticket > done) continue; |
| 2282 | slot.segments.clear(); | 2949 | slot.segments.clear(); |
| 2950 | recycle_khr_stages(slot.khr_instances); | ||
| 2283 | for (VkEvent event : slot.events) | 2951 | for (VkEvent event : slot.events) |
| 2284 | if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event); | 2952 | if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event); |
| 2285 | else context_.vk.vkDestroyEvent(context_.device(), event, nullptr); | 2953 | else context_.vk.vkDestroyEvent(context_.device(), event, nullptr); |
| 2286 | slot.events.clear(); | 2954 | slot.events.clear(); |
| 2287 | if (!reuse) reuse = &slot; | 2955 | if (!reuse) reuse = &slot; |
| 2288 | } | 2956 | } |
| 2957 | return reuse; | ||
| 2958 | } | ||
| 2959 | |||
| 2960 | // A queue at the cap with nothing finished waits here for its oldest submission. execute_now() calls it before it | ||
| 2961 | // takes resource_mutex_ or tracker_mutex_: the submission waited for may itself wait on another queue's work, and | ||
| 2962 | // that queue needs those locks to submit it. One execute runs at a time on a queue, so buffers_ is this caller's. | ||
| 2963 | // A timeout only means the GPU is slow: wait again rather than allocate past the cap. False when the device is lost | ||
| 2964 | // (now or while waiting), so the caller submits nothing. | ||
| 2965 | bool wait_for_room() { | ||
| 2966 | for (;;) { | ||
| 2967 | if (context_.is_device_lost()) return false; | ||
| 2968 | if (buffers_.size() < kMaxQueuedCommandBuffers) return true; | ||
| 2969 | const auto done = completed(); | ||
| 2970 | for (const auto& slot : buffers_) | ||
| 2971 | if (slot.ticket <= done) return true; | ||
| 2972 | switch (wait_oldest_submitted()) { | ||
| 2973 | case VK_SUCCESS: | ||
| 2974 | return true; | ||
| 2975 | case VK_TIMEOUT: | ||
| 2976 | continue; | ||
| 2977 | case VK_ERROR_DEVICE_LOST: | ||
| 2978 | context_.mark_device_lost(); | ||
| 2979 | return false; | ||
| 2980 | default: | ||
| 2981 | return true; // nothing submitted to wait for (or a host error): no wait can make room, allocate | ||
| 2982 | } | ||
| 2983 | } | ||
| 2984 | } | ||
| 2985 | |||
| 2986 | // Waits up to kQueuedWaitNs for the oldest submitted command buffer. VK_INCOMPLETE when none is submitted yet. | ||
| 2987 | VkResult wait_oldest_submitted() { | ||
| 2988 | std::uint64_t oldest = UINT64_MAX; | ||
| 2989 | for (const auto& slot : buffers_) | ||
| 2990 | if (slot.ticket < oldest) oldest = slot.ticket; | ||
| 2991 | if (oldest == UINT64_MAX) return VK_INCOMPLETE; // all still being recorded | ||
| 2992 | VkSemaphoreWaitInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; | ||
| 2993 | info.semaphoreCount = 1; | ||
| 2994 | info.pSemaphores = &progress_; | ||
| 2995 | info.pValues = &oldest; | ||
| 2996 | return context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs); | ||
| 2997 | } | ||
| 2998 | |||
| 2999 | CommandSlot* acquire() { | ||
| 3000 | if (context_.is_device_lost()) return nullptr; | ||
| 3001 | context_.drain_deleted_resources(context_.completed_retire_ticket()); | ||
| 3002 | CommandSlot* reuse = recycle_finished(); | ||
| 2289 | if (reuse) { | 3003 | if (reuse) { |
| 2290 | if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; | 3004 | if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; |
| 2291 | reuse->predicate.reset(); | 3005 | reuse->predicate.reset(); |
| @@ -2322,7 +3036,10 @@ private: | |||
| 2322 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { | 3036 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { |
| 2323 | if (context_.is_device_lost()) return false; | 3037 | if (context_.is_device_lost()) return false; |
| 2324 | const std::uint64_t ticket = submitted_ + 1; | 3038 | const std::uint64_t ticket = submitted_ + 1; |
| 2325 | if (last_sparse_) collect_bindings(completed()); | 3039 | if (last_sparse_) { |
| 3040 | collect_bindings(completed()); | ||
| 3041 | if (context_.is_device_lost()) return false; | ||
| 3042 | } | ||
| 2326 | std::span<const VkSemaphore> semaphores = waits_; | 3043 | std::span<const VkSemaphore> semaphores = waits_; |
| 2327 | std::span<const std::uint64_t> values = wait_values_; | 3044 | std::span<const std::uint64_t> values = wait_values_; |
| 2328 | std::vector<VkSemaphore> sparse_waits; | 3045 | std::vector<VkSemaphore> sparse_waits; |
| @@ -2342,7 +3059,12 @@ private: | |||
| 2342 | VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; | 3059 | VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; |
| 2343 | std::uint64_t signal_values[2]{ticket, 0}; | 3060 | std::uint64_t signal_values[2]{ticket, 0}; |
| 2344 | std::uint32_t signal_count = 1; | 3061 | std::uint32_t signal_count = 1; |
| 2345 | if (fence) { | 3062 | // Decided under the submit lock, so the order of the checks is the order of the submissions. A Signal |
| 3063 | // that is not above what was already submitted for this fence (a held Signal(F, 2) released after an | ||
| 3064 | // unheld Signal(F, 3)) leaves the Vulkan signal out: the timeline cannot go down, and waits for 2 pass. | ||
| 3065 | // The value counts as submitted only after the submit succeeded (below). | ||
| 3066 | const bool signals_fence = fence && context_.holds().would_signal(fence, value); | ||
| 3067 | if (signals_fence) { | ||
| 2346 | signals[signal_count] = fence; | 3068 | signals[signal_count] = fence; |
| 2347 | signal_values[signal_count] = value; | 3069 | signal_values[signal_count] = value; |
| 2348 | ++signal_count; | 3070 | ++signal_count; |
| @@ -2361,20 +3083,20 @@ private: | |||
| 2361 | submit.signalSemaphoreCount = signal_count; | 3083 | submit.signalSemaphoreCount = signal_count; |
| 2362 | submit.pSignalSemaphores = signals; | 3084 | submit.pSignalSemaphores = signals; |
| 2363 | res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); | 3085 | res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); |
| 2364 | if (res == VK_SUCCESS) context_.record_submit_locked(progress_, ticket); | 3086 | if (res == VK_SUCCESS) { |
| 3087 | context_.record_submit_locked(progress_, ticket); | ||
| 3088 | if (signals_fence) context_.holds().signaled(fence, value); | ||
| 3089 | } | ||
| 2365 | } | 3090 | } |
| 2366 | if (res == VK_ERROR_DEVICE_LOST) { | 3091 | if (res == VK_ERROR_DEVICE_LOST) { |
| 2367 | context_.mark_device_lost(); | 3092 | context_.mark_device_lost(); |
| 2368 | waits_.clear(); | 3093 | clear_waits(); |
| 2369 | wait_values_.clear(); | ||
| 2370 | return false; | 3094 | return false; |
| 2371 | } | 3095 | } |
| 2372 | const bool ok = (res == VK_SUCCESS); | 3096 | const bool ok = (res == VK_SUCCESS); |
| 2373 | if (ok) { | 3097 | if (ok) { |
| 2374 | if (fence) context_.holds().signaled(fence, value); // held batches waiting for it: the caller pumps | ||
| 2375 | submitted_ = ticket; | 3098 | submitted_ = ticket; |
| 2376 | waits_.clear(); | 3099 | clear_waits(ticket); |
| 2377 | wait_values_.clear(); | ||
| 2378 | for (auto& slot : buffers_) | 3100 | for (auto& slot : buffers_) |
| 2379 | if (slot.buffer == command_buffer) slot.ticket = ticket; | 3101 | if (slot.buffer == command_buffer) slot.ticket = ticket; |
| 2380 | } | 3102 | } |
| @@ -2392,6 +3114,7 @@ private: | |||
| 2392 | std::vector<VkEvent> free_events_; // unsignaled, for order_timestamp_copy | 3114 | std::vector<VkEvent> free_events_; // unsignaled, for order_timestamp_copy |
| 2393 | std::unique_ptr<OcclusionResolve> occlusion_resolve_; | 3115 | std::unique_ptr<OcclusionResolve> occlusion_resolve_; |
| 2394 | std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for | 3116 | std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for |
| 3117 | std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for | ||
| 2395 | std::uint64_t last_sparse_ = 0; | 3118 | std::uint64_t last_sparse_ = 0; |
| 2396 | std::deque<PendingBindings> pending_bindings_; | 3119 | std::deque<PendingBindings> pending_bindings_; |
| 2397 | std::vector<VkSemaphore> waits_; | 3120 | std::vector<VkSemaphore> waits_; |
| @@ -2405,6 +3128,14 @@ private: | |||
| 2405 | // guards the members above that execute, signal, wait and marker touch. | 3128 | // guards the members above that execute, signal, wait and marker touch. |
| 2406 | std::mutex state_mutex_; | 3129 | std::mutex state_mutex_; |
| 2407 | std::deque<Deferred> held_; | 3130 | std::deque<Deferred> held_; |
| 3131 | std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive | ||
| 3132 | std::vector<std::shared_ptr<void>> retired_pins_; // released by the caller once state_mutex_ is dropped | ||
| 3133 | struct TicketedPin { | ||
| 3134 | std::uint64_t ticket; | ||
| 3135 | std::shared_ptr<void> pin; | ||
| 3136 | }; | ||
| 3137 | std::deque<TicketedPin> pin_queue_; // released once progress_ reaches the ticket | ||
| 3138 | std::atomic<int> held_failure_{0}; // a ReplayResult: the first held batch that failed | ||
| 2408 | }; | 3139 | }; |
| 2409 | 3140 | ||
| 2410 | } // namespace leonida | 3141 | } // namespace leonida |