upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_backend.h
diff options
context:
space:
mode:
authorEmma <47298336+zzEmmazz@users.noreply.github.com>2026-11-23 00:40:34 +0200
committerEmma <47298336+zzEmmazz@users.noreply.github.com>2026-11-23 00:40:34 +0200
commitd2e6b31db24e7ca93a34f0b53b063d32ff944070 (patch)
tree85b3b6de8fd34420002210fc541f7daccef5267c /runtime/src/vulkan_backend.h
parent9d36ec83ce3b72c77e72753903cea9e73f5c0d91 (diff)
parentaa2988cc555bad7ecd508b48a702adbb32fe7c95 (diff)
Merge commit 'aa2988cc' into d3d-417-msaa-depth-array-slices
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h298
1 files changed, 262 insertions, 36 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index dd412d64e..24a2155c5 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -10,7 +10,9 @@
10#define VK_NO_PROTOTYPES 10#define VK_NO_PROTOTYPES
11#endif 11#endif
12#include "binary_occlusion_spirv.h" 12#include "binary_occlusion_spirv.h"
13#include "buffer_va_index.h"
13#include "occlusion_sum_spirv.h" 14#include "occlusion_sum_spirv.h"
15#include "queue_holds.h"
14#include "retire_tickets.h" 16#include "retire_tickets.h"
15#include "statistics_sum_spirv.h" 17#include "statistics_sum_spirv.h"
16#include "vulkan13_features.h" 18#include "vulkan13_features.h"
@@ -35,6 +37,7 @@
35#include <unordered_set> 37#include <unordered_set>
36#include <shared_mutex> 38#include <shared_mutex>
37#include <span> 39#include <span>
40#include <string>
38#include <thread> 41#include <thread>
39#include <tuple> 42#include <tuple>
40#include <unordered_map> 43#include <unordered_map>
@@ -510,6 +513,9 @@ public:
510 513
511 using SignalEventFn = void (*)(void* event_handle); 514 using SignalEventFn = void (*)(void* event_handle);
512 515
516 // Longest single vkWaitSemaphores call in run(): bounds how long the thread can sit in an uninterruptible wait.
517 static constexpr std::uint64_t kWaitSliceNs = 100'000'000; // 100 ms
518
513 FenceWaitDispatcher(VkDevice device, const VulkanDeviceFunctions& vk, std::atomic<bool>& device_lost) 519 FenceWaitDispatcher(VkDevice device, const VulkanDeviceFunctions& vk, std::atomic<bool>& device_lost)
514 : device_(device), vk_(vk), device_lost_(device_lost) { 520 : device_(device), vk_(vk), device_lost_(device_lost) {
515 VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; 521 VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO};
@@ -674,7 +680,12 @@ private:
674 wi.semaphoreCount = static_cast<std::uint32_t>(semaphores_.size()); 680 wi.semaphoreCount = static_cast<std::uint32_t>(semaphores_.size());
675 wi.pSemaphores = semaphores_.data(); 681 wi.pSemaphores = semaphores_.data();
676 wi.pValues = values_.data(); 682 wi.pValues = values_.data();
677 const VkResult res = vk_.vkWaitSemaphores(device_, &wi, UINT64_MAX); 683 // A bounded slice, not UINT64_MAX. Under GPU paravirtualization (measured in Windows Sandbox on an
684 // RTX 5060 Ti) this wait is a kernel wait the OS cannot interrupt: a process that exits while a wait
685 // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes
686 // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the
687 // same wait; completions still wake it at once through the ANY wait.
688 const VkResult res = vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs);
678 689
679 lock.lock(); 690 lock.lock();
680 waiting_ = false; 691 waiting_ = false;
@@ -855,18 +866,19 @@ public:
855 const auto it = graphics_pipelines_.find(id); 866 const auto it = graphics_pipelines_.find(id);
856 return it == graphics_pipelines_.end() ? nullptr : &it->second; 867 return it == graphics_pipelines_.end() ? nullptr : &it->second;
857 }; 868 };
858 // Called with resource_mutex_ held. A linear search: fine for the first frames, an interval map when it shows. 869 // Called with resource_mutex_ held. A binary search of the buffers' VA ranges (buffer_va_index.h), kept in step
870 // with resources_ by set_resource_locked and remove_resource.
859 // A range that runs past its buffer is cut at the buffer's end (`size` is updated): D3D12 reads past a view's 871 // A range that runs past its buffer is cut at the buffer's end (`size` is updated): D3D12 reads past a view's
860 // buffer as out of bounds, which is no reason to drop the submission. 872 // buffer as out of bounds, which is no reason to drop the submission.
861 replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { 873 replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) {
862 for (const auto& [id, b] : resources_) { 874 BufferVaIndex<ResourceId>::Hit hit{};
863 if (b.image || !b.buffer || !b.va || va < b.va || va - b.va >= b.size) continue; 875 if (!buffer_vas_.find(va, hit)) return false;
864 buffer = b.buffer; 876 const ResourceBinding* b = resolve(hit.id);
865 offset = b.buffer_offset + (va - b.va); 877 if (!b) return false;
866 size = std::min<std::uint64_t>(size, b.size - (va - b.va)); 878 buffer = b->buffer;
867 return true; 879 offset = b->buffer_offset + (va - b->va);
868 } 880 size = std::min<std::uint64_t>(size, b->size - (va - b->va));
869 return false; 881 return true;
870 }; 882 };
871 if (xdxr && loaded_) { 883 if (xdxr && loaded_) {
872 xdxr_ = std::make_unique<XdxrBuilder>(get, device); 884 xdxr_ = std::make_unique<XdxrBuilder>(get, device);
@@ -979,11 +991,11 @@ public:
979 // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation. 991 // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation.
980 void add_resource(ResourceId id, const ResourceBinding& binding) { 992 void add_resource(ResourceId id, const ResourceBinding& binding) {
981 std::unique_lock lock(resource_mutex_); 993 std::unique_lock lock(resource_mutex_);
982 resources_[id] = binding; 994 set_resource_locked(id, binding);
983 } 995 }
984 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { 996 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) {
985 std::unique_lock rlock(resource_mutex_); 997 std::unique_lock rlock(resource_mutex_);
986 resources_[id] = binding; 998 set_resource_locked(id, binding);
987 if (binding.image) { 999 if (binding.image) {
988 std::lock_guard tlock(tracker_mutex_); 1000 std::lock_guard tlock(tracker_mutex_);
989 tracker_.track(id, binding, current_layout); 1001 tracker_.track(id, binding, current_layout);
@@ -1001,7 +1013,7 @@ public:
1001 1013
1002 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { 1014 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) {
1003 std::unique_lock lock(resource_mutex_); 1015 std::unique_lock lock(resource_mutex_);
1004 resources_[id] = binding; 1016 set_resource_locked(id, binding);
1005 sparse_buffers_.emplace(id, std::move(buffer)); 1017 sparse_buffers_.emplace(id, std::move(buffer));
1006 } 1018 }
1007 1019
@@ -1012,6 +1024,7 @@ public:
1012 const auto it = resources_.find(id); 1024 const auto it = resources_.find(id);
1013 if (it == resources_.end()) return; 1025 if (it == resources_.end()) return;
1014 img = it->second.image; 1026 img = it->second.image;
1027 unindex_buffer(id, it->second);
1015 resources_.erase(it); 1028 resources_.erase(it);
1016 sparse_buffers_.erase(id); 1029 sparse_buffers_.erase(id);
1017 } 1030 }
@@ -1289,10 +1302,30 @@ public:
1289 if (fence_dispatcher_) fence_dispatcher_->cancel(sem); 1302 if (fence_dispatcher_) fence_dispatcher_->cancel(sem);
1290 } 1303 }
1291 1304
1305 // Cross-queue Wait-before-Signal: per fence, the highest value a Signal was submitted for, and the queues that
1306 // hold batches until one is (queue_holds.h).
1307 QueueHolds<VkSemaphore>& holds() { return holds_; }
1308
1292private: 1309private:
1293 friend class VulkanQueue; 1310 friend class VulkanQueue;
1294 friend class VulkanPresenter; 1311 friend class VulkanPresenter;
1295 1312
1313 // buffer_at finds a buffer by VA: one with no image, a VkBuffer, a VA and bytes (what the linear search it replaced
1314 // accepted). Both are called with resource_mutex_ held uniquely.
1315 static bool addressable(const ResourceBinding& b) { return !b.image && b.buffer && b.va && b.size; }
1316 void unindex_buffer(ResourceId id, const ResourceBinding& b) {
1317 if (addressable(b)) buffer_vas_.erase(b.va, id);
1318 }
1319 // resources_[id] = binding, with the VA index kept in step (a re-registered ID drops its old range first).
1320 void set_resource_locked(ResourceId id, const ResourceBinding& binding) {
1321 auto [it, inserted] = resources_.try_emplace(id, binding);
1322 if (!inserted) {
1323 unindex_buffer(id, it->second);
1324 it->second = binding;
1325 }
1326 if (addressable(binding)) buffer_vas_.insert(binding.va, binding.size, id);
1327 }
1328
1296 const ResourceBinding* resolve(ResourceId id) const { 1329 const ResourceBinding* resolve(ResourceId id) const {
1297 const auto it = resources_.find(id); 1330 const auto it = resources_.find(id);
1298 return it == resources_.end() ? nullptr : &it->second; 1331 return it == resources_.end() ? nullptr : &it->second;
@@ -1396,7 +1429,9 @@ private:
1396 std::atomic<std::uint64_t> submitted_ticket_{0}; 1429 std::atomic<std::uint64_t> submitted_ticket_{0};
1397 DeferredDeletionQueue deletion_queue_; 1430 DeferredDeletionQueue deletion_queue_;
1398 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; 1431 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_;
1432 QueueHolds<VkSemaphore> holds_;
1399 std::unordered_map<ResourceId, ResourceBinding> resources_; 1433 std::unordered_map<ResourceId, ResourceBinding> resources_;
1434 BufferVaIndex<ResourceId> buffer_vas_; // the addressable buffers of resources_, by VA range (buffer_at)
1400 std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_; 1435 std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_;
1401 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 1436 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
1402 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1437 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
@@ -1444,9 +1479,12 @@ public:
1444 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; 1479 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type};
1445 if (context.vk.vkCreateSemaphore(context.device(), &info, nullptr, &semaphore_) != VK_SUCCESS) 1480 if (context.vk.vkCreateSemaphore(context.device(), &info, nullptr, &semaphore_) != VK_SUCCESS)
1446 semaphore_ = VK_NULL_HANDLE; 1481 semaphore_ = VK_NULL_HANDLE;
1482 if (semaphore_) context.holds().add_fence(semaphore_, initial);
1447 } 1483 }
1448 ~VulkanFence() { 1484 ~VulkanFence() {
1449 if (semaphore_) context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); 1485 if (!semaphore_) return;
1486 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported
1487 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr);
1450 } 1488 }
1451 VulkanFence(const VulkanFence&) = delete; 1489 VulkanFence(const VulkanFence&) = delete;
1452 VulkanFence& operator=(const VulkanFence&) = delete; 1490 VulkanFence& operator=(const VulkanFence&) = delete;
@@ -1466,7 +1504,10 @@ public:
1466 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 1504 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
1467 info.semaphore = semaphore_; 1505 info.semaphore = semaphore_;
1468 info.value = value; 1506 info.value = value;
1469 return context_.vk.vkSignalSemaphore(context_.device(), &info) == VK_SUCCESS; 1507 if (context_.vk.vkSignalSemaphore(context_.device(), &info) != VK_SUCCESS) return false;
1508 context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now
1509 context_.holds().pump_ready();
1510 return true;
1470 } 1511 }
1471 1512
1472 // true when the value was reached within the timeout. 1513 // true when the value was reached within the timeout.
@@ -1483,9 +1524,16 @@ private:
1483 VkSemaphore semaphore_ = VK_NULL_HANDLE; 1524 VkSemaphore semaphore_ = VK_NULL_HANDLE;
1484}; 1525};
1485 1526
1486// One D3D12 command queue on one VkQueue. Not thread-safe by itself: D3D12 lets one thread use a queue at a time 1527// One D3D12 command queue on one VkQueue. D3D12 lets one thread use a queue at a time per call and the COM wrapper
1487// per call, and the COM wrapper serialises its calls. 1528// serialises its calls; state_mutex_ additionally serialises them against the thread that releases a held batch
1488class VulkanQueue { 1529// (Wait-before-Signal, queue_holds.h), the only other thread that touches a queue.
1530//
1531// A Wait on a fence value no Signal has been submitted for yet holds the next batch (ExecuteCommandLists or Signal)
1532// on the CPU, with everything the queue is asked to do after it, instead of replaying it against layouts from before
1533// the work it waits for: Vulkan itself would accept the wait (timeline semaphores allow wait-before-signal), but the
1534// layout tracker follows replay order. Holding on the CPU also keeps a Wait and the Signal that satisfies it from
1535// landing on one VkQueue in the wrong order, which would never make progress on the GPU.
1536class VulkanQueue : private QueueHolds<VkSemaphore>::Holder {
1489public: 1537public:
1490 enum class QueueKind : std::uint8_t { direct, compute, copy }; 1538 enum class QueueKind : std::uint8_t { direct, compute, copy };
1491 1539
@@ -1514,10 +1562,13 @@ public:
1514 type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; 1562 type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
1515 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; 1563 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type};
1516 ok_ = ok_ && vk.vkCreateSemaphore(context.device(), &info, nullptr, &progress_) == VK_SUCCESS; 1564 ok_ = ok_ && vk.vkCreateSemaphore(context.device(), &info, nullptr, &progress_) == VK_SUCCESS;
1565 context_.holds().attach(this);
1517 } 1566 }
1518 1567
1519 ~VulkanQueue() { 1568 ~VulkanQueue() {
1520 auto& vk = context_.vk; 1569 auto& vk = context_.vk;
1570 context_.holds().detach(this); // no thread releases into this queue from here on
1571 report_held_at_teardown();
1521 if (queue_) { 1572 if (queue_) {
1522 std::lock_guard lock(context_.submit_mutex()); 1573 std::lock_guard lock(context_.submit_mutex());
1523 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 1574 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
@@ -1547,6 +1598,7 @@ public:
1547 template<typename GetHeap> 1598 template<typename GetHeap>
1548 bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions, 1599 bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions,
1549 std::span<const BufferTileRange> ranges, GetHeap&& get_heap) { 1600 std::span<const BufferTileRange> ranges, GetHeap&& get_heap) {
1601 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads
1550 std::unique_lock lock(context_.resource_mutex_); 1602 std::unique_lock lock(context_.resource_mutex_);
1551 const auto it = context_.sparse_buffers_.find(id); 1603 const auto it = context_.sparse_buffers_.find(id);
1552 if (it == context_.sparse_buffers_.end()) return false; 1604 if (it == context_.sparse_buffers_.end()) return false;
@@ -1592,6 +1644,7 @@ public:
1592 } 1644 }
1593 1645
1594 bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) { 1646 bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) {
1647 std::lock_guard state(state_mutex_);
1595 std::unique_lock lock(context_.resource_mutex_); 1648 std::unique_lock lock(context_.resource_mutex_);
1596 const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst); 1649 const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst);
1597 if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() || 1650 if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() ||
@@ -1607,8 +1660,82 @@ public:
1607 } 1660 }
1608 1661
1609 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves 1662 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves
1610 // the layout tracker as it was. Pending Wait()s are attached to this submission. 1663 // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an
1664 // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and
1665 // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU
1666 // Signal), which is also where its errors are reported.
1611 ReplayResult execute(std::span<const CommandList* const> lists) { 1667 ReplayResult execute(std::span<const CommandList* const> lists) {
1668 ReplayResult result = ReplayResult::success;
1669 bool held = false;
1670 {
1671 std::lock_guard state(state_mutex_);
1672 if (!must_hold()) {
1673 result = execute_now(lists);
1674 } else if (context_.is_device_lost()) {
1675 result = ReplayResult::unsupported;
1676 } else {
1677 Deferred op;
1678 op.kind = Deferred::Kind::batch;
1679 op.lists.reserve(lists.size());
1680 for (const CommandList* list : lists) op.lists.push_back(*list);
1681 hold(std::move(op));
1682 held = true;
1683 }
1684 }
1685 if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check
1686 return result;
1687 }
1688
1689 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier
1690 // held operations, so the fence does not run ahead of the work it follows.
1691 bool signal(VkSemaphore fence, std::uint64_t value) {
1692 bool ok = true;
1693 {
1694 std::lock_guard state(state_mutex_);
1695 if (must_hold()) {
1696 Deferred op;
1697 op.kind = Deferred::Kind::signal;
1698 op.fence = fence;
1699 op.value = value;
1700 hold(std::move(op));
1701 } else {
1702 ok = submit(VK_NULL_HANDLE, fence, value);
1703 }
1704 }
1705 context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready
1706 return ok;
1707 }
1708
1709 // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that
1710 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet).
1711 void wait(VkSemaphore fence, std::uint64_t value) {
1712 std::lock_guard state(state_mutex_);
1713 waits_.push_back(fence);
1714 wait_values_.push_back(value);
1715 }
1716
1717 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
1718 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
1719 void marker(DebugMarker::Kind kind, const char* label) {
1720 std::lock_guard state(state_mutex_);
1721 if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too
1722 Deferred op;
1723 op.kind = Deferred::Kind::marker;
1724 op.marker_kind = kind;
1725 op.label = label ? label : "";
1726 hold(std::move(op));
1727 return;
1728 }
1729 marker_now(kind, label);
1730 }
1731
1732 bool idle() {
1733 std::lock_guard lock(context_.submit_mutex());
1734 return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS;
1735 }
1736
1737private:
1738 ReplayResult execute_now(std::span<const CommandList* const> lists) {
1612 if (context_.is_device_lost()) return ReplayResult::unsupported; 1739 if (context_.is_device_lost()) return ReplayResult::unsupported;
1613 if (kind_ != QueueKind::direct) 1740 if (kind_ != QueueKind::direct)
1614 for (const auto* list : lists) 1741 for (const auto* list : lists)
@@ -1942,19 +2069,7 @@ public:
1942 return submitted ? ReplayResult::success : ReplayResult::unsupported; 2069 return submitted ? ReplayResult::success : ReplayResult::unsupported;
1943 } 2070 }
1944 2071
1945 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. 2072 void marker_now(DebugMarker::Kind kind, const char* label) {
1946 bool signal(VkSemaphore fence, std::uint64_t value) { return submit(VK_NULL_HANDLE, fence, value); }
1947
1948 // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that
1949 // batch, so it is kept and attached to the next submission.
1950 void wait(VkSemaphore fence, std::uint64_t value) {
1951 waits_.push_back(fence);
1952 wait_values_.push_back(value);
1953 }
1954
1955 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
1956 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
1957 void marker(DebugMarker::Kind kind, const char* label) {
1958 const DebugLabelFunctions& f = context_.labels_; 2073 const DebugLabelFunctions& f = context_.labels_;
1959 if (!f.complete()) return; 2074 if (!f.complete()) return;
1960 if (kind == DebugMarker::Kind::end && !open_labels_) return; 2075 if (kind == DebugMarker::Kind::end && !open_labels_) return;
@@ -1972,12 +2087,118 @@ public:
1972 } 2087 }
1973 } 2088 }
1974 2089
1975 bool idle() { 2090 // ---- Wait-before-Signal: operations held on the CPU (queue_holds.h) ----
1976 std::lock_guard lock(context_.submit_mutex()); 2091
1977 return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; 2092 // One held operation, with the waits that were pending when it was asked for.
2093 struct Deferred {
2094 enum class Kind : std::uint8_t { batch, signal, marker };
2095 Kind kind = Kind::batch;
2096 std::vector<VkSemaphore> waits;
2097 std::vector<std::uint64_t> wait_values;
2098 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call
2099 VkSemaphore fence = VK_NULL_HANDLE; // signal
2100 std::uint64_t value = 0;
2101 DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker
2102 std::string label;
2103 };
2104
2105 bool waits_pending(const std::vector<VkSemaphore>& semaphores, const std::vector<std::uint64_t>& values) const {
2106 for (std::size_t i = 0; i < semaphores.size(); ++i)
2107 if (context_.holds().pending(semaphores[i], values[i])) return true;
2108 return false;
2109 }
2110
2111 // The next batch or Signal has to be held: something is held ahead of it (queue order), or a Wait it carries
2112 // has no submitted Signal yet. Called with state_mutex_ held.
2113 bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); }
2114
2115 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held.
2116 void hold(Deferred&& op) {
2117 if (op.kind != Deferred::Kind::marker) {
2118 op.waits = std::move(waits_);
2119 op.wait_values = std::move(wait_values_);
2120 waits_.clear();
2121 wait_values_.clear();
2122 }
2123 held_.push_back(std::move(op));
2124 context_.holds().held_changed(1);
2125 }
2126
2127 // Runs one held operation as the call would have, with its own waits and none of the ones queued since.
2128 void run(Deferred& op) {
2129 auto later_waits = std::move(waits_);
2130 auto later_values = std::move(wait_values_);
2131 waits_ = std::move(op.waits);
2132 wait_values_ = std::move(op.wait_values);
2133 switch (op.kind) {
2134 case Deferred::Kind::batch: {
2135 std::vector<const CommandList*> lists;
2136 for (const CommandList& list : op.lists) lists.push_back(&list);
2137 const ReplayResult result = execute_now(lists);
2138 if (result != ReplayResult::success)
2139 std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); "
2140 "nothing was submitted\n", static_cast<int>(result));
2141 break;
2142 }
2143 case Deferred::Kind::signal:
2144 if (!submit(VK_NULL_HANDLE, op.fence, op.value))
2145 std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n");
2146 break;
2147 case Deferred::Kind::marker:
2148 marker_now(op.marker_kind, op.label.c_str());
2149 break;
2150 }
2151 waits_ = std::move(later_waits); // a failed submission leaves its waits behind: drop them with the batch
2152 wait_values_ = std::move(later_values);
2153 }
2154
2155 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); }
2156
2157 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held).
2158 bool release_ready() override {
2159 std::lock_guard state(state_mutex_);
2160 bool released = false;
2161 while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) {
2162 Deferred op = std::move(held_.front());
2163 held_.pop_front();
2164 context_.holds().held_changed(-1);
2165 if (!context_.is_device_lost()) run(op);
2166 released = true;
2167 }
2168 return released;
2169 }
2170
2171 // Holder: the fence is released, so what waits on it can never run.
2172 void discard_waiting_on(VkSemaphore semaphore) override {
2173 std::lock_guard state(state_mutex_);
2174 for (auto it = held_.begin(); it != held_.end();) {
2175 if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end()) {
2176 ++it;
2177 continue;
2178 }
2179 std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work waiting on it; "
2180 "that work is dropped\n");
2181 it = held_.erase(it);
2182 context_.holds().held_changed(-1);
2183 }
2184 }
2185
2186 // A queue destroyed with held work: the fence it waits on was never signaled. Reported, not waited for; nothing
2187 // was submitted for it, so the VkQueue is idle and the destructor goes on.
2188 void report_held_at_teardown() {
2189 std::lock_guard state(state_mutex_);
2190 if (held_.empty()) return;
2191 std::uint64_t value = 0;
2192 for (const Deferred& op : held_)
2193 for (std::size_t i = 0; i < op.waits.size() && !value; ++i)
2194 if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i];
2195 std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a "
2196 "fence value (%llu) that no Signal reached; the fence was never signaled\n",
2197 held_.size(), static_cast<unsigned long long>(value));
2198 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size()));
2199 held_.clear();
1978 } 2200 }
1979 2201
1980private:
1981 struct CommandSlot { 2202 struct CommandSlot {
1982 VkCommandBuffer buffer; 2203 VkCommandBuffer buffer;
1983 std::uint64_t ticket; 2204 std::uint64_t ticket;
@@ -2182,6 +2403,7 @@ private:
2182 } 2403 }
2183 const bool ok = (res == VK_SUCCESS); 2404 const bool ok = (res == VK_SUCCESS);
2184 if (ok) { 2405 if (ok) {
2406 if (fence) context_.holds().signaled(fence, value); // held batches waiting for it: the caller pumps
2185 submitted_ = ticket; 2407 submitted_ = ticket;
2186 waits_.clear(); 2408 waits_.clear();
2187 wait_values_.clear(); 2409 wait_values_.clear();
@@ -2211,6 +2433,10 @@ private:
2211 std::vector<PreparedList> prepared_; 2433 std::vector<PreparedList> prepared_;
2212 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 2434 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
2213 bool ok_ = false; 2435 bool ok_ = false;
2436 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and
2437 // guards the members above that execute, signal, wait and marker touch.
2438 std::mutex state_mutex_;
2439 std::deque<Deferred> held_;
2214}; 2440};
2215 2441
2216} // namespace leonida 2442} // namespace leonida