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:
authorAlxcBTW <187763517+AlxcBTW@users.noreply.github.com>2026-11-22 19:22:39 +0100
committerAlxcBTW <187763517+AlxcBTW@users.noreply.github.com>2026-11-22 19:22:39 +0100
commitfbc11e973d5a1de721f8b70cd5721a8fe709fc3c (patch)
treec541babd5f1994164514bf5ddaa212d1fe3b3c1c /runtime/src/vulkan_backend.h
parent49475796c226c8511b9470bf97a4daf57b8af323 (diff)
D3D12 queues: hold a batch that waits for a Signal not yet submitted, so layouts follow dependency order
A queue's ExecuteCommandLists is replayed against one LayoutTracker in call order, so a batch that waits (cross-queue) for a Signal submitted later was recorded against layouts from before the work it waits for. Track, per fence, the highest Signal value submitted (CPU Signal and the creation value count); a queue holds a batch, and what follows it, while a Wait names a higher value, and the thread that submits the satisfying Signal releases the held work in dependency order on its own VkQueue. Reports a queue destroyed with held work and a fence released under a waiter; nothing blocks. Adds d3d12_queue_handover_test (27 queue-type assignments x 6 submission orders, two producers, CPU Signal cases, never-signaled and released fences, byte-exact against the host runtime) and updates docs section 4.4 and the M4 row. Two existing tests that used an unsignaled Wait as a GPU gate or expected a synchronous submit failure under a pending Wait now declare the Signal first. 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.h244
1 files changed, 221 insertions, 23 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 93d7e5259..a3ecc964a 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -11,6 +11,7 @@
11#endif 11#endif
12#include "binary_occlusion_spirv.h" 12#include "binary_occlusion_spirv.h"
13#include "occlusion_sum_spirv.h" 13#include "occlusion_sum_spirv.h"
14#include "queue_holds.h"
14#include "retire_tickets.h" 15#include "retire_tickets.h"
15#include "statistics_sum_spirv.h" 16#include "statistics_sum_spirv.h"
16#include "vulkan13_features.h" 17#include "vulkan13_features.h"
@@ -34,6 +35,7 @@
34#include <unordered_set> 35#include <unordered_set>
35#include <shared_mutex> 36#include <shared_mutex>
36#include <span> 37#include <span>
38#include <string>
37#include <thread> 39#include <thread>
38#include <tuple> 40#include <tuple>
39#include <unordered_map> 41#include <unordered_map>
@@ -1217,6 +1219,10 @@ public:
1217 if (fence_dispatcher_) fence_dispatcher_->cancel(sem); 1219 if (fence_dispatcher_) fence_dispatcher_->cancel(sem);
1218 } 1220 }
1219 1221
1222 // Cross-queue Wait-before-Signal: per fence, the highest value a Signal was submitted for, and the queues that
1223 // hold batches until one is (queue_holds.h).
1224 QueueHolds<VkSemaphore>& holds() { return holds_; }
1225
1220private: 1226private:
1221 friend class VulkanQueue; 1227 friend class VulkanQueue;
1222 friend class VulkanPresenter; 1228 friend class VulkanPresenter;
@@ -1262,6 +1268,7 @@ private:
1262 std::atomic<std::uint64_t> submitted_ticket_{0}; 1268 std::atomic<std::uint64_t> submitted_ticket_{0};
1263 DeferredDeletionQueue deletion_queue_; 1269 DeferredDeletionQueue deletion_queue_;
1264 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; 1270 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_;
1271 QueueHolds<VkSemaphore> holds_;
1265 std::unordered_map<ResourceId, ResourceBinding> resources_; 1272 std::unordered_map<ResourceId, ResourceBinding> resources_;
1266 std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_; 1273 std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_;
1267 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 1274 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
@@ -1304,9 +1311,12 @@ public:
1304 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; 1311 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type};
1305 if (context.vk.vkCreateSemaphore(context.device(), &info, nullptr, &semaphore_) != VK_SUCCESS) 1312 if (context.vk.vkCreateSemaphore(context.device(), &info, nullptr, &semaphore_) != VK_SUCCESS)
1306 semaphore_ = VK_NULL_HANDLE; 1313 semaphore_ = VK_NULL_HANDLE;
1314 if (semaphore_) context.holds().add_fence(semaphore_, initial);
1307 } 1315 }
1308 ~VulkanFence() { 1316 ~VulkanFence() {
1309 if (semaphore_) context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); 1317 if (!semaphore_) return;
1318 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported
1319 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr);
1310 } 1320 }
1311 VulkanFence(const VulkanFence&) = delete; 1321 VulkanFence(const VulkanFence&) = delete;
1312 VulkanFence& operator=(const VulkanFence&) = delete; 1322 VulkanFence& operator=(const VulkanFence&) = delete;
@@ -1326,7 +1336,10 @@ public:
1326 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 1336 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
1327 info.semaphore = semaphore_; 1337 info.semaphore = semaphore_;
1328 info.value = value; 1338 info.value = value;
1329 return context_.vk.vkSignalSemaphore(context_.device(), &info) == VK_SUCCESS; 1339 if (context_.vk.vkSignalSemaphore(context_.device(), &info) != VK_SUCCESS) return false;
1340 context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now
1341 context_.holds().pump_ready();
1342 return true;
1330 } 1343 }
1331 1344
1332 // true when the value was reached within the timeout. 1345 // true when the value was reached within the timeout.
@@ -1343,9 +1356,16 @@ private:
1343 VkSemaphore semaphore_ = VK_NULL_HANDLE; 1356 VkSemaphore semaphore_ = VK_NULL_HANDLE;
1344}; 1357};
1345 1358
1346// One D3D12 command queue on one VkQueue. Not thread-safe by itself: D3D12 lets one thread use a queue at a time 1359// One D3D12 command queue on one VkQueue. D3D12 lets one thread use a queue at a time per call and the COM wrapper
1347// per call, and the COM wrapper serialises its calls. 1360// serialises its calls; state_mutex_ additionally serialises them against the thread that releases a held batch
1348class VulkanQueue { 1361// (Wait-before-Signal, queue_holds.h), the only other thread that touches a queue.
1362//
1363// A Wait on a fence value no Signal has been submitted for yet holds the next batch (ExecuteCommandLists or Signal)
1364// on the CPU, with everything the queue is asked to do after it, instead of replaying it against layouts from before
1365// the work it waits for: Vulkan itself would accept the wait (timeline semaphores allow wait-before-signal), but the
1366// layout tracker follows replay order. Holding on the CPU also keeps a Wait and the Signal that satisfies it from
1367// landing on one VkQueue in the wrong order, which would never make progress on the GPU.
1368class VulkanQueue : private QueueHolds<VkSemaphore>::Holder {
1349public: 1369public:
1350 enum class QueueKind : std::uint8_t { direct, compute, copy }; 1370 enum class QueueKind : std::uint8_t { direct, compute, copy };
1351 1371
@@ -1374,10 +1394,13 @@ public:
1374 type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; 1394 type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
1375 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; 1395 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type};
1376 ok_ = ok_ && vk.vkCreateSemaphore(context.device(), &info, nullptr, &progress_) == VK_SUCCESS; 1396 ok_ = ok_ && vk.vkCreateSemaphore(context.device(), &info, nullptr, &progress_) == VK_SUCCESS;
1397 context_.holds().attach(this);
1377 } 1398 }
1378 1399
1379 ~VulkanQueue() { 1400 ~VulkanQueue() {
1380 auto& vk = context_.vk; 1401 auto& vk = context_.vk;
1402 context_.holds().detach(this); // no thread releases into this queue from here on
1403 report_held_at_teardown();
1381 if (queue_) { 1404 if (queue_) {
1382 std::lock_guard lock(context_.submit_mutex()); 1405 std::lock_guard lock(context_.submit_mutex());
1383 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 1406 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
@@ -1405,6 +1428,7 @@ public:
1405 template<typename GetHeap> 1428 template<typename GetHeap>
1406 bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions, 1429 bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions,
1407 std::span<const BufferTileRange> ranges, GetHeap&& get_heap) { 1430 std::span<const BufferTileRange> ranges, GetHeap&& get_heap) {
1431 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads
1408 std::unique_lock lock(context_.resource_mutex_); 1432 std::unique_lock lock(context_.resource_mutex_);
1409 const auto it = context_.sparse_buffers_.find(id); 1433 const auto it = context_.sparse_buffers_.find(id);
1410 if (it == context_.sparse_buffers_.end()) return false; 1434 if (it == context_.sparse_buffers_.end()) return false;
@@ -1450,6 +1474,7 @@ public:
1450 } 1474 }
1451 1475
1452 bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) { 1476 bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) {
1477 std::lock_guard state(state_mutex_);
1453 std::unique_lock lock(context_.resource_mutex_); 1478 std::unique_lock lock(context_.resource_mutex_);
1454 const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst); 1479 const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst);
1455 if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() || 1480 if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() ||
@@ -1465,8 +1490,82 @@ public:
1465 } 1490 }
1466 1491
1467 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves 1492 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves
1468 // the layout tracker as it was. Pending Wait()s are attached to this submission. 1493 // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an
1494 // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and
1495 // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU
1496 // Signal), which is also where its errors are reported.
1469 ReplayResult execute(std::span<const CommandList* const> lists) { 1497 ReplayResult execute(std::span<const CommandList* const> lists) {
1498 ReplayResult result = ReplayResult::success;
1499 bool held = false;
1500 {
1501 std::lock_guard state(state_mutex_);
1502 if (!must_hold()) {
1503 result = execute_now(lists);
1504 } else if (context_.is_device_lost()) {
1505 result = ReplayResult::unsupported;
1506 } else {
1507 Deferred op;
1508 op.kind = Deferred::Kind::batch;
1509 op.lists.reserve(lists.size());
1510 for (const CommandList* list : lists) op.lists.push_back(*list);
1511 hold(std::move(op));
1512 held = true;
1513 }
1514 }
1515 if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check
1516 return result;
1517 }
1518
1519 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier
1520 // held operations, so the fence does not run ahead of the work it follows.
1521 bool signal(VkSemaphore fence, std::uint64_t value) {
1522 bool ok = true;
1523 {
1524 std::lock_guard state(state_mutex_);
1525 if (must_hold()) {
1526 Deferred op;
1527 op.kind = Deferred::Kind::signal;
1528 op.fence = fence;
1529 op.value = value;
1530 hold(std::move(op));
1531 } else {
1532 ok = submit(VK_NULL_HANDLE, fence, value);
1533 }
1534 }
1535 context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready
1536 return ok;
1537 }
1538
1539 // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that
1540 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet).
1541 void wait(VkSemaphore fence, std::uint64_t value) {
1542 std::lock_guard state(state_mutex_);
1543 waits_.push_back(fence);
1544 wait_values_.push_back(value);
1545 }
1546
1547 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
1548 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
1549 void marker(DebugMarker::Kind kind, const char* label) {
1550 std::lock_guard state(state_mutex_);
1551 if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too
1552 Deferred op;
1553 op.kind = Deferred::Kind::marker;
1554 op.marker_kind = kind;
1555 op.label = label ? label : "";
1556 hold(std::move(op));
1557 return;
1558 }
1559 marker_now(kind, label);
1560 }
1561
1562 bool idle() {
1563 std::lock_guard lock(context_.submit_mutex());
1564 return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS;
1565 }
1566
1567private:
1568 ReplayResult execute_now(std::span<const CommandList* const> lists) {
1470 if (context_.is_device_lost()) return ReplayResult::unsupported; 1569 if (context_.is_device_lost()) return ReplayResult::unsupported;
1471 VkCommandBuffer command_buffer = VK_NULL_HANDLE; 1570 VkCommandBuffer command_buffer = VK_NULL_HANDLE;
1472 std::function<void(bool)> bindless_commit; 1571 std::function<void(bool)> bindless_commit;
@@ -1758,19 +1857,7 @@ public:
1758 return submitted ? ReplayResult::success : ReplayResult::unsupported; 1857 return submitted ? ReplayResult::success : ReplayResult::unsupported;
1759 } 1858 }
1760 1859
1761 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. 1860 void marker_now(DebugMarker::Kind kind, const char* label) {
1762 bool signal(VkSemaphore fence, std::uint64_t value) { return submit(VK_NULL_HANDLE, fence, value); }
1763
1764 // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that
1765 // batch, so it is kept and attached to the next submission.
1766 void wait(VkSemaphore fence, std::uint64_t value) {
1767 waits_.push_back(fence);
1768 wait_values_.push_back(value);
1769 }
1770
1771 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
1772 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
1773 void marker(DebugMarker::Kind kind, const char* label) {
1774 const DebugLabelFunctions& f = context_.labels_; 1861 const DebugLabelFunctions& f = context_.labels_;
1775 if (!f.complete()) return; 1862 if (!f.complete()) return;
1776 if (kind == DebugMarker::Kind::end && !open_labels_) return; 1863 if (kind == DebugMarker::Kind::end && !open_labels_) return;
@@ -1788,12 +1875,118 @@ public:
1788 } 1875 }
1789 } 1876 }
1790 1877
1791 bool idle() { 1878 // ---- Wait-before-Signal: operations held on the CPU (queue_holds.h) ----
1792 std::lock_guard lock(context_.submit_mutex()); 1879
1793 return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; 1880 // One held operation, with the waits that were pending when it was asked for.
1881 struct Deferred {
1882 enum class Kind : std::uint8_t { batch, signal, marker };
1883 Kind kind = Kind::batch;
1884 std::vector<VkSemaphore> waits;
1885 std::vector<std::uint64_t> wait_values;
1886 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call
1887 VkSemaphore fence = VK_NULL_HANDLE; // signal
1888 std::uint64_t value = 0;
1889 DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker
1890 std::string label;
1891 };
1892
1893 bool waits_pending(const std::vector<VkSemaphore>& semaphores, const std::vector<std::uint64_t>& values) const {
1894 for (std::size_t i = 0; i < semaphores.size(); ++i)
1895 if (context_.holds().pending(semaphores[i], values[i])) return true;
1896 return false;
1897 }
1898
1899 // The next batch or Signal has to be held: something is held ahead of it (queue order), or a Wait it carries
1900 // has no submitted Signal yet. Called with state_mutex_ held.
1901 bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); }
1902
1903 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held.
1904 void hold(Deferred&& op) {
1905 if (op.kind != Deferred::Kind::marker) {
1906 op.waits = std::move(waits_);
1907 op.wait_values = std::move(wait_values_);
1908 waits_.clear();
1909 wait_values_.clear();
1910 }
1911 held_.push_back(std::move(op));
1912 context_.holds().held_changed(1);
1913 }
1914
1915 // Runs one held operation as the call would have, with its own waits and none of the ones queued since.
1916 void run(Deferred& op) {
1917 auto later_waits = std::move(waits_);
1918 auto later_values = std::move(wait_values_);
1919 waits_ = std::move(op.waits);
1920 wait_values_ = std::move(op.wait_values);
1921 switch (op.kind) {
1922 case Deferred::Kind::batch: {
1923 std::vector<const CommandList*> lists;
1924 for (const CommandList& list : op.lists) lists.push_back(&list);
1925 const ReplayResult result = execute_now(lists);
1926 if (result != ReplayResult::success)
1927 std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); "
1928 "nothing was submitted\n", static_cast<int>(result));
1929 break;
1930 }
1931 case Deferred::Kind::signal:
1932 if (!submit(VK_NULL_HANDLE, op.fence, op.value))
1933 std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n");
1934 break;
1935 case Deferred::Kind::marker:
1936 marker_now(op.marker_kind, op.label.c_str());
1937 break;
1938 }
1939 waits_ = std::move(later_waits); // a failed submission leaves its waits behind: drop them with the batch
1940 wait_values_ = std::move(later_values);
1941 }
1942
1943 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); }
1944
1945 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held).
1946 bool release_ready() override {
1947 std::lock_guard state(state_mutex_);
1948 bool released = false;
1949 while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) {
1950 Deferred op = std::move(held_.front());
1951 held_.pop_front();
1952 context_.holds().held_changed(-1);
1953 if (!context_.is_device_lost()) run(op);
1954 released = true;
1955 }
1956 return released;
1957 }
1958
1959 // Holder: the fence is released, so what waits on it can never run.
1960 void discard_waiting_on(VkSemaphore semaphore) override {
1961 std::lock_guard state(state_mutex_);
1962 for (auto it = held_.begin(); it != held_.end();) {
1963 if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end()) {
1964 ++it;
1965 continue;
1966 }
1967 std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work waiting on it; "
1968 "that work is dropped\n");
1969 it = held_.erase(it);
1970 context_.holds().held_changed(-1);
1971 }
1972 }
1973
1974 // A queue destroyed with held work: the fence it waits on was never signaled. Reported, not waited for; nothing
1975 // was submitted for it, so the VkQueue is idle and the destructor goes on.
1976 void report_held_at_teardown() {
1977 std::lock_guard state(state_mutex_);
1978 if (held_.empty()) return;
1979 std::uint64_t value = 0;
1980 for (const Deferred& op : held_)
1981 for (std::size_t i = 0; i < op.waits.size() && !value; ++i)
1982 if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i];
1983 std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a "
1984 "fence value (%llu) that no Signal reached; the fence was never signaled\n",
1985 held_.size(), static_cast<unsigned long long>(value));
1986 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size()));
1987 held_.clear();
1794 } 1988 }
1795 1989
1796private:
1797 struct CommandSlot { 1990 struct CommandSlot {
1798 VkCommandBuffer buffer; 1991 VkCommandBuffer buffer;
1799 std::uint64_t ticket; 1992 std::uint64_t ticket;
@@ -1979,6 +2172,7 @@ private:
1979 } 2172 }
1980 const bool ok = (res == VK_SUCCESS); 2173 const bool ok = (res == VK_SUCCESS);
1981 if (ok) { 2174 if (ok) {
2175 if (fence) context_.holds().signaled(fence, value); // held batches waiting for it: the caller pumps
1982 submitted_ = ticket; 2176 submitted_ = ticket;
1983 waits_.clear(); 2177 waits_.clear();
1984 wait_values_.clear(); 2178 wait_values_.clear();
@@ -2007,6 +2201,10 @@ private:
2007 std::vector<PreparedList> prepared_; 2201 std::vector<PreparedList> prepared_;
2008 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 2202 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
2009 bool ok_ = false; 2203 bool ok_ = false;
2204 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and
2205 // guards the members above that execute, signal, wait and marker touch.
2206 std::mutex state_mutex_;
2207 std::deque<Deferred> held_;
2010}; 2208};
2011 2209
2012} // namespace leonida 2210} // namespace leonida