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:
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h1149
1 files changed, 918 insertions, 231 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index ac84df7a4..4a4d9d485 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -30,6 +30,7 @@
30#include "resource_tiling.h" 30#include "resource_tiling.h"
31#include "pipeline_profile.h" 31#include "pipeline_profile.h"
32#include "submit_phases.h" 32#include "submit_phases.h"
33#include "pipeline_wait.h"
33#include "title_va_alias.h" 34#include "title_va_alias.h"
34#include "xdxr_build.h" 35#include "xdxr_build.h"
35 36
@@ -124,13 +125,14 @@ struct VulkanDeviceFunctions {
124 X(vkCmdPushConstants) X(vkCmdDispatch) \ 125 X(vkCmdPushConstants) X(vkCmdDispatch) \
125 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 126 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
126 X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ 127 X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \
127 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 128 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) X(vkCmdSetDepthBounds) \
128 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 129 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
129 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 130 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
130 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ 131 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \
131 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ 132 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \
132 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 133 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
133 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 134 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \
135 X(vkCmdBeginQueryIndexedEXT) X(vkCmdEndQueryIndexedEXT)
134#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 136#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
135 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 137 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
136#undef LEONIDA_VK_MEMBER 138#undef LEONIDA_VK_MEMBER
@@ -165,6 +167,9 @@ struct VulkanDeviceFunctions {
165 return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && 167 return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology &&
166 vkCmdSetPrimitiveRestartEnable; 168 vkCmdSetPrimitiveRestartEnable;
167 } 169 }
170 // VK_EXT_transform_feedback is enabled on the device: the indexed-query entry points are loaded, so an
171 // SO_STATISTICS heap can be a real transform-feedback pool (D3D-302).
172 bool transform_feedback = false;
168}; 173};
169 174
170// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. 175// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout.
@@ -618,6 +623,8 @@ inline Stats& stats(int kind) {
618 static Stats s[3]; 623 static Stats s[3];
619 return s[kind < 0 || kind > 2 ? 0 : kind]; 624 return s[kind < 0 || kind > 2 ? 0 : kind];
620} 625}
626inline void held_tick(int kind); // below: the held-operations line, due on the same 10 s
627
621inline void done(int kind, std::chrono::steady_clock::time_point submitted) { 628inline void done(int kind, std::chrono::steady_clock::time_point submitted) {
622 using clock = std::chrono::steady_clock; 629 using clock = std::chrono::steady_clock;
623 const auto now = clock::now(); 630 const auto now = clock::now();
@@ -641,36 +648,66 @@ inline void done(int kind, std::chrono::steady_clock::time_point submitted) {
641 s.sum_ms = s.max_ms = s.busy_ms = 0; 648 s.sum_ms = s.max_ms = s.busy_ms = 0;
642 s.since = now; 649 s.since = now;
643 } 650 }
651 held_tick(kind);
644} 652}
645// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run. 653// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run.
646inline void held(int kind, int op, std::chrono::steady_clock::time_point at) { 654// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run, and for
655// the longest one of the window the fence (semaphore handle) and value it waited for, so the slow signaller can be
656// named. The line is due every 10 s: held() prints it, and so does done() (held_tick), so a window with nothing
657// released still reports.
658struct HeldStats {
659 std::mutex mutex;
660 std::uint64_t count[3] = {};
661 double sum_ms = 0, max_ms = 0;
662 std::uint64_t max_fence = 0, max_value = 0;
663 int max_op = 0;
664 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now();
665};
666inline HeldStats& held_stats(int kind) {
667 static HeldStats h[3];
668 return h[kind < 0 || kind > 2 ? 0 : kind];
669}
670// held_stats(kind).mutex held.
671inline void held_report_locked(int kind, HeldStats& s, std::chrono::steady_clock::time_point now) {
672 if (now - s.since < std::chrono::seconds(10)) return;
673 const std::uint64_t all = s.count[0] + s.count[1] + s.count[2];
674 std::fprintf(stderr, "[rt] gpu latency (%s): %llu held operations released in %.0f s (%llu batches, %llu "
675 "signals, %llu markers), held %.2f ms on average, %.1f ms the longest",
676 kind == 0 ? "direct" : kind == 1 ? "compute" : "copy", static_cast<unsigned long long>(all),
677 std::chrono::duration<double>(now - s.since).count(), static_cast<unsigned long long>(s.count[0]),
678 static_cast<unsigned long long>(s.count[1]), static_cast<unsigned long long>(s.count[2]),
679 all ? s.sum_ms / double(all) : 0.0, s.max_ms);
680 if (all && s.max_fence)
681 std::fprintf(stderr, " (a %s waiting for fence 0x%llx value %llu)",
682 s.max_op == 0 ? "batch" : s.max_op == 1 ? "Signal" : "marker",
683 static_cast<unsigned long long>(s.max_fence), static_cast<unsigned long long>(s.max_value));
684 std::fputc('\n', stderr);
685 s.count[0] = s.count[1] = s.count[2] = 0;
686 s.sum_ms = s.max_ms = 0;
687 s.max_fence = s.max_value = 0;
688 s.since = now;
689}
690inline void held(int kind, int op, std::chrono::steady_clock::time_point at, std::uint64_t fence = 0,
691 std::uint64_t value = 0) {
647 using clock = std::chrono::steady_clock; 692 using clock = std::chrono::steady_clock;
648 struct Held { 693 HeldStats& s = held_stats(kind);
649 std::mutex mutex;
650 std::uint64_t count[3] = {};
651 double sum_ms = 0, max_ms = 0;
652 clock::time_point since = clock::now();
653 };
654 static Held h[3];
655 Held& s = h[kind < 0 || kind > 2 ? 0 : kind];
656 const auto now = clock::now(); 694 const auto now = clock::now();
657 const double ms = std::chrono::duration<double, std::milli>(now - at).count(); 695 const double ms = std::chrono::duration<double, std::milli>(now - at).count();
658 std::lock_guard lock(s.mutex); 696 std::lock_guard lock(s.mutex);
659 ++s.count[op < 0 || op > 2 ? 0 : op]; 697 ++s.count[op < 0 || op > 2 ? 0 : op];
660 s.sum_ms += ms; 698 s.sum_ms += ms;
661 s.max_ms = (std::max)(s.max_ms, ms); 699 if (ms > s.max_ms) {
662 if (now - s.since >= std::chrono::seconds(10)) { 700 s.max_ms = ms;
663 const std::uint64_t all = s.count[0] + s.count[1] + s.count[2]; 701 s.max_fence = fence;
664 std::fprintf(stderr, "[rt] gpu latency (%s): %llu held operations released in %.0f s (%llu batches, %llu " 702 s.max_value = value;
665 "signals, %llu markers), held %.2f ms on average, %.1f ms the longest\n", 703 s.max_op = op;
666 kind == 0 ? "direct" : kind == 1 ? "compute" : "copy", static_cast<unsigned long long>(all),
667 std::chrono::duration<double>(now - s.since).count(), static_cast<unsigned long long>(s.count[0]),
668 static_cast<unsigned long long>(s.count[1]), static_cast<unsigned long long>(s.count[2]),
669 all ? s.sum_ms / double(all) : 0.0, s.max_ms);
670 s.count[0] = s.count[1] = s.count[2] = 0;
671 s.sum_ms = s.max_ms = 0;
672 s.since = now;
673 } 704 }
705 held_report_locked(kind, s, now);
706}
707inline void held_tick(int kind) {
708 HeldStats& s = held_stats(kind);
709 std::lock_guard lock(s.mutex);
710 held_report_locked(kind, s, std::chrono::steady_clock::now());
674} 711}
675} // namespace gpu_latency 712} // namespace gpu_latency
676 713
@@ -1090,6 +1127,8 @@ public:
1090 GraphicsIndirectCapabilities indirect = {}) 1127 GraphicsIndirectCapabilities indirect = {})
1091 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { 1128 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) {
1092 loaded_ = vk.load(get, device); 1129 loaded_ = vk.load(get, device);
1130 // VK_EXT_transform_feedback: enabled on the device when its indexed-query entry points resolved (D3D-302).
1131 vk.transform_feedback = vk.vkCmdBeginQueryIndexedEXT && vk.vkCmdEndQueryIndexedEXT;
1093 if (loaded_ && gpu_labels_.initialize(device, get)) { 1132 if (loaded_ && gpu_labels_.initialize(device, get)) {
1094 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; 1133 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); };
1095 } 1134 }
@@ -1125,6 +1164,11 @@ public:
1125 replay_.reset_query_pool = vk.vkCmdResetQueryPool; 1164 replay_.reset_query_pool = vk.vkCmdResetQueryPool;
1126 replay_.begin_query = vk.vkCmdBeginQuery; 1165 replay_.begin_query = vk.vkCmdBeginQuery;
1127 replay_.end_query = vk.vkCmdEndQuery; 1166 replay_.end_query = vk.vkCmdEndQuery;
1167 // VK_EXT_transform_feedback (D3D-302), loaded when the device enabled it: indexed SO_STATISTICS queries.
1168 if (vk.transform_feedback) {
1169 replay_.begin_query_indexed = vk.vkCmdBeginQueryIndexedEXT;
1170 replay_.end_query_indexed = vk.vkCmdEndQueryIndexedEXT;
1171 }
1128 replay_.write_timestamp = vk.vkCmdWriteTimestamp; 1172 replay_.write_timestamp = vk.vkCmdWriteTimestamp;
1129 replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; 1173 replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults;
1130 replay_.bind_pipeline = vk.vkCmdBindPipeline; 1174 replay_.bind_pipeline = vk.vkCmdBindPipeline;
@@ -1148,8 +1192,11 @@ public:
1148 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; 1192 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable;
1149 replay_.set_stencil_reference = vk.vkCmdSetStencilReference; 1193 replay_.set_stencil_reference = vk.vkCmdSetStencilReference;
1150 replay_.set_blend_constants = vk.vkCmdSetBlendConstants; 1194 replay_.set_blend_constants = vk.vkCmdSetBlendConstants;
1195 replay_.set_depth_bounds = vk.vkCmdSetDepthBounds;
1151 replay_.draw = vk.vkCmdDraw; 1196 replay_.draw = vk.vkCmdDraw;
1152 replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled 1197 replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled
1198 replay_.draw_mesh_tasks_indirect = vk.vkCmdDrawMeshTasksIndirectEXT;
1199 replay_.draw_mesh_tasks_indirect_count = vk.vkCmdDrawMeshTasksIndirectCountEXT;
1153 replay_.draw_indexed = vk.vkCmdDrawIndexed; 1200 replay_.draw_indexed = vk.vkCmdDrawIndexed;
1154 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { 1201 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* {
1155 const auto it = graphics_pipelines_.find(id); 1202 const auto it = graphics_pipelines_.find(id);
@@ -1280,6 +1327,7 @@ public:
1280 1327
1281 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) { 1328 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) {
1282 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled); 1329 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled);
1330 device_fault_->set_submit_lock(&submit_mutex_);
1283 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get()); 1331 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get());
1284 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); }); 1332 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); });
1285 } 1333 }
@@ -1329,12 +1377,16 @@ public:
1329 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate, 1377 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate,
1330 std::vector<std::uint32_t> families = {}) { 1378 std::vector<std::uint32_t> families = {}) {
1331 std::unique_lock lock(resource_mutex_); 1379 std::unique_lock lock(resource_mutex_);
1380 // An enabled clamp is required: a call whose scratch preparation fails is refused (unsupported) instead of
1381 // reading the application's argument buffer, which may hold a record no compute pass wrote. Off, or on a
1382 // device the pass cannot run on, the replay keeps the application's buffer as before.
1332 replay_.require_indirect_clamp = indirect_clamp_enabled(); 1383 replay_.require_indirect_clamp = indirect_clamp_enabled();
1333 if (!replay_.require_indirect_clamp) return; 1384 if (!replay_.require_indirect_clamp) return;
1334 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate), 1385 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate),
1335 device_fault_.get(), std::move(families)); 1386 device_fault_.get(), std::move(families));
1336 if (!indirect_clamp_->loaded()) { 1387 if (!indirect_clamp_->loaded()) {
1337 indirect_clamp_.reset(); 1388 indirect_clamp_.reset();
1389 replay_.require_indirect_clamp = false;
1338 return; 1390 return;
1339 } 1391 }
1340 // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists 1392 // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists
@@ -1546,32 +1598,42 @@ public:
1546 } 1598 }
1547 1599
1548 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1600 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1601 // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block
1602 // resource registration or destruction on the render thread.
1549 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { 1603 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1550 std::unique_lock lock(resource_mutex_); 1604 std::unique_lock lock(pipeline_mutex_);
1551 pipelines_[id] = pipeline; 1605 pipelines_[id] = pipeline;
1552 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; 1606 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1553 } 1607 }
1554 void remove_pipeline(std::uintptr_t id) { 1608 void remove_pipeline(std::uintptr_t id) {
1555 std::unique_lock lock(resource_mutex_); 1609 std::unique_lock lock(pipeline_mutex_);
1556 pipelines_.erase(id); 1610 pipelines_.erase(id);
1557 graphics_pipelines_.erase(id); 1611 graphics_pipelines_.erase(id);
1558 if (device_fault_) device_fault_->pipeline_names.erase(id); 1612 if (device_fault_) device_fault_->pipeline_names.erase(id);
1559 } 1613 }
1560 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, 1614 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1561 const CheckpointShaders* shaders = nullptr) { 1615 const CheckpointShaders* shaders = nullptr) {
1562 std::unique_lock lock(resource_mutex_); 1616 std::unique_lock lock(pipeline_mutex_);
1563 graphics_pipelines_[id] = pipeline; 1617 graphics_pipelines_[id] = pipeline;
1564 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; 1618 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1565 } 1619 }
1566 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where 1620 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on
1567 // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the 1621 // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and
1568 // workers it had. 1622 // ends the workers it had.
1569 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { 1623 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) {
1570 std::unique_lock lock(resource_mutex_); 1624 std::unique_lock lock(pipeline_mutex_);
1571 pipeline_workers_.swap(workers); 1625 pipeline_workers_.swap(workers);
1572 } 1626 }
1627 // For the large pipelines of a submission: the memory they may use while they compile together
1628 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1629 // one after another.
1630 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1631 std::unique_lock lock(pipeline_mutex_);
1632 large_compile_budget_ = std::move(budget);
1633 large_compile_demand_ = std::move(demand);
1634 }
1573 PipelineWorkers::Stats pipeline_worker_stats() { 1635 PipelineWorkers::Stats pipeline_worker_stats() {
1574 std::shared_lock lock(resource_mutex_); 1636 std::shared_lock lock(pipeline_mutex_);
1575 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1637 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
1576 } 1638 }
1577 // Configure before queue creation, when the selected queue family supports compute. 1639 // Configure before queue creation, when the selected queue family supports compute.
@@ -1585,6 +1647,44 @@ public:
1585 return host_texture_stats_; 1647 return host_texture_stats_;
1586 } 1648 }
1587 1649
1650 // LOCAL FIX (deadlock on the first-run pages): the texture writes below used vkDeviceWaitIdle with the submit
1651 // lock held. The device is idle only once every queue has run all it was given, and a queue whose submitted
1652 // work waits on a value a later submission signals never gets there while this thread keeps the lock: a native
1653 // boot sat 270 s in vkDeviceWaitIdle (title staging), then lost the device. Instead: wait for the queue
1654 // timelines to pass what was submitted so far, at most `timeout`; on VK_TIMEOUT the caller skips this write (the
1655 // title-texture pass tries it again) rather than freeze the title. Not covered, unlike the device wait: present
1656 // and probe submissions, which have their own fences outside the retirement timelines (a present reading the
1657 // image). The staged write is ordered behind them anyway (same queue, an ALL_COMMANDS barrier); the host copy
1658 // is not, so a presented title texture can be written while a present still reads it (a torn frame, no fault).
1659 // With submit_mutex_ held.
1660 VkResult wait_submitted_locked(std::uint64_t timeout_ns, const char* what) {
1661 if (is_device_lost()) return VK_ERROR_DEVICE_LOST; // a queue's timeline may be gone already
1662 const auto pending = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire));
1663 if (pending.empty()) return VK_SUCCESS;
1664 std::vector<VkSemaphore> semaphores;
1665 std::vector<std::uint64_t> values;
1666 for (const auto& [semaphore, value] : pending) {
1667 semaphores.push_back(semaphore);
1668 values.push_back(value);
1669 }
1670 VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO};
1671 wait.semaphoreCount = std::uint32_t(semaphores.size());
1672 wait.pSemaphores = semaphores.data();
1673 wait.pValues = values.data();
1674 const VkResult r = observe_result(vk.vkWaitSemaphores(device_, &wait, timeout_ns), what);
1675 if (r == VK_TIMEOUT) {
1676 static std::atomic<std::uint64_t> timeouts{0};
1677 const std::uint64_t n = timeouts.fetch_add(1, std::memory_order_relaxed) + 1;
1678 if (!(n & (n - 1)))
1679 std::fprintf(stderr, "[rt] vulkan: %s: submitted work not done within %llu ms (%llu time(s)); the "
1680 "write is skipped this time\n", what,
1681 static_cast<unsigned long long>(timeout_ns / 1000000), static_cast<unsigned long long>(n));
1682 }
1683 return r;
1684 }
1685 // Short: a timeout is certain when the awaited work needs this thread's lock, and the write is only skipped.
1686 static constexpr std::uint64_t kTitleWriteWaitNs = 250'000'000; // 250 ms
1687
1588 // CPU writes to a title texture have no application fence. Prevent another queue from 1688 // CPU writes to a title texture have no application fence. Prevent another queue from
1589 // claiming a new layout or submitting work between the completion check and the host copy. 1689 // claiming a new layout or submitting work between the completion check and the host copy.
1590 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues. 1690 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues.
@@ -1595,7 +1695,13 @@ public:
1595 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY; 1695 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY;
1596 if (image_work_pending_) { 1696 if (image_work_pending_) {
1597 ++host_texture_stats_.waits; 1697 ++host_texture_stats_.waits;
1598 const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)"); 1698 // A device wait is a queue operation: it passes the compile gate, so it never waits in the driver behind a
1699 // long pipeline create (the starved wait that loses the device after 10 s).
1700 const SubmitMutex::SubmitTurn turn(submit_mutex_);
1701 const auto result = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title texture upload)");
1702 // Not done in time: VK_NOT_READY, so the caller takes its staged path (ordered on the queue) or tries
1703 // again later, and the skip is not counted as a failed fill.
1704 if (result == VK_TIMEOUT) return VK_NOT_READY;
1599 if (result != VK_SUCCESS) return result; 1705 if (result != VK_SUCCESS) return result;
1600 image_work_pending_ = false; 1706 image_work_pending_ = false;
1601 } 1707 }
@@ -1613,7 +1719,8 @@ public:
1613 LayoutPieces pieces; 1719 LayoutPieces pieces;
1614 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; 1720 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN;
1615 if (image_work_pending_) { 1721 if (image_work_pending_) {
1616 const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)"); 1722 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate (as above)
1723 const auto r = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title staging)");
1617 if (r != VK_SUCCESS) return r; 1724 if (r != VK_SUCCESS) return r;
1618 image_work_pending_ = false; 1725 image_work_pending_ = false;
1619 } 1726 }
@@ -1738,7 +1845,6 @@ public:
1738 // `before` is called at the start of every submission of command lists (a held batch: when it is released), 1845 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1739 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. 1846 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1740 // Set once, before the first queue exists. 1847 // Set once, before the first queue exists.
1741 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1742 1848
1743 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues. 1849 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues.
1744 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of 1850 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of
@@ -1775,11 +1881,22 @@ public:
1775 return true; 1881 return true;
1776 } 1882 }
1777 const char* diagnostic_compute_name(std::uintptr_t id) { 1883 const char* diagnostic_compute_name(std::uintptr_t id) {
1778 std::shared_lock lock(resource_mutex_); 1884 std::shared_lock lock(pipeline_mutex_);
1779 if (!device_fault_) return nullptr; 1885 if (!device_fault_) return nullptr;
1780 const auto it = device_fault_->pipeline_names.find(id); 1886 const auto it = device_fault_->pipeline_names.find(id);
1781 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; 1887 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
1782 } 1888 }
1889 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1890 // GPU work the lists of a submission depend on, recorded at the start of its command buffer by a queue that can
1891 // run compute (the console heap translation pass, src/console_heap_gpu.h): `record` returns true when it recorded
1892 // something, and `commit` follows that submit (true: it reached the queue; the ticket is a retire ticket at or
1893 // after it). Every other queue's next submission then waits for that one, as for a bindless table upload: a
1894 // queue that records nothing itself may run lists that read what the pass wrote. Called with tracker_mutex_
1895 // held, so passes and those waits follow submission order. Set once, before the first queue exists.
1896 void set_prelude(std::function<bool(VkCommandBuffer)> record, std::function<void(bool, std::uint64_t)> commit) {
1897 prelude_record_ = std::move(record);
1898 prelude_commit_ = std::move(commit);
1899 }
1783 1900
1784 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1901 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1785 std::unique_lock lock(resource_mutex_); 1902 std::unique_lock lock(resource_mutex_);
@@ -1934,7 +2051,14 @@ public:
1934 VulkanDeviceFunctions vk; 2051 VulkanDeviceFunctions vk;
1935 2052
1936 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 2053 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
1937 std::mutex& submit_mutex() { return submit_mutex_; } 2054 SubmitMutex& submit_mutex() { return submit_mutex_; }
2055
2056 // vkQueueSubmit through the compile gate (SubmitMutex::SubmitTurn): it waits here, not in the driver, while a
2057 // pipeline create is in the driver. Called with the submit lock held; the caller observes the result.
2058 VkResult queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) {
2059 const SubmitMutex::SubmitTurn turn(submit_mutex_);
2060 return vk.vkQueueSubmit(queue, count, submits, fence);
2061 }
1938 2062
1939 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept { 2063 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept {
1940 set_device_lost(device_lost_, where); 2064 set_device_lost(device_lost_, where);
@@ -2104,19 +2228,32 @@ private:
2104 using Watch = SubmissionProgressWatch; 2228 using Watch = SubmissionProgressWatch;
2105 Watch watch; 2229 Watch watch;
2106 std::uint64_t retired = 0; 2230 std::uint64_t retired = 0;
2231 std::int64_t reported_hold = -1;
2232 std::int64_t busy_since = -1;
2233 SubmitMutex::GateStats gate_logged;
2234 unsigned tick = 0;
2107 std::mutex timer_mutex; 2235 std::mutex timer_mutex;
2108 std::condition_variable_any timer; 2236 std::condition_variable_any timer;
2109 std::unique_lock timer_lock(timer_mutex); 2237 std::unique_lock timer_lock(timer_mutex);
2238 // LOCAL DIAGNOSTIC (post-load GPU hangs): with the device-fault report on, sample every 250 ms, so a loss the
2239 // driver has already reset is seen (and its checkpoints read) before a watchdog outside kills the process.
2240 const auto period = device_fault_ ? std::chrono::milliseconds(250) : std::chrono::milliseconds(1000);
2241 const unsigned per_10s = unsigned(std::chrono::seconds(10) / period);
2110 while (!stop.stop_requested()) { 2242 while (!stop.stop_requested()) {
2111 timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; }); 2243 timer.wait_for(timer_lock, stop, period, [] { return false; });
2112 if (stop.stop_requested() || is_device_lost()) break; 2244 if (stop.stop_requested() || is_device_lost()) break;
2113 auto state = Watch::State::submit_lock_busy; 2245 auto state = Watch::State::submit_lock_busy;
2114 VkResult result = VK_SUCCESS; 2246 VkResult result = VK_SUCCESS;
2115 std::uint64_t submitted; 2247 std::uint64_t submitted;
2116 { 2248 {
2117 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait 2249 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait
2118 // blocked inside the driver can hold this mutex indefinitely. 2250 // blocked inside the driver can hold this mutex indefinitely. Under heavy submission one try finds
2251 // it busy most of the time: a few more within a millisecond or two.
2119 std::unique_lock lock(submit_mutex_, std::try_to_lock); 2252 std::unique_lock lock(submit_mutex_, std::try_to_lock);
2253 for (int retry = 0; !lock.owns_lock() && retry < 20; ++retry) {
2254 std::this_thread::sleep_for(std::chrono::microseconds(100));
2255 if (lock.try_lock()) break;
2256 }
2120 submitted = submitted_retire_ticket(); 2257 submitted = submitted_retire_ticket();
2121 if (lock.owns_lock()) { 2258 if (lock.owns_lock()) {
2122 if (is_device_lost()) break; 2259 if (is_device_lost()) break;
@@ -2124,12 +2261,49 @@ private:
2124 state = retired < submitted ? Watch::State::pending : Watch::State::idle; 2261 state = retired < submitted ? Watch::State::pending : Watch::State::idle;
2125 } 2262 }
2126 } 2263 }
2264 // LOCAL DIAGNOSTIC (early device loss): a submission unfinished for 4 s dumps the recent submissions with
2265 // their semaphore counters (unreadable once the device is lost); a hold of the submit lock of 3 s names
2266 // its thread and prints its call chain, once per hold.
2267 // A vkQueueSubmit stuck in the driver (measured: 10 s, then VK_ERROR_DEVICE_LOST) also blocks
2268 // vkGetSemaphoreCounterValue, so with the lock busy the watch stays out of the driver: the holder report
2269 // samples stacks only, and the counters are read once the lock is free again.
2270 if (state == Watch::State::submit_lock_busy) {
2271 const std::uint32_t owner = submit_mutex_.owner();
2272 const std::int64_t since = submit_mutex_.since_ms();
2273 const std::int64_t held = diagnostic_ms() - since;
2274 if (owner && held >= 3000 && since != reported_hold) {
2275 reported_hold = since;
2276 device_fault_->report_submit_lock_holder(owner, held);
2277 }
2278 // Busy at every sample but changing hands: contended, not stuck. Only a hold that lasts (the same
2279 // holder since the same time) counts toward the 15 s stall report.
2280 if (since != busy_since) {
2281 busy_since = since;
2282 state = Watch::State::idle;
2283 }
2284 } else {
2285 device_fault_->check_submit_progress();
2286 }
2127 if (result == VK_ERROR_DEVICE_LOST) { 2287 if (result == VK_ERROR_DEVICE_LOST) {
2128 mark_device_lost(); 2288 mark_device_lost();
2129 break; 2289 break;
2130 } 2290 }
2131 // A failed counter query does not measure GPU progress. 2291 // A failed counter query does not measure GPU progress.
2132 if (result != VK_SUCCESS) state = Watch::State::idle; 2292 if (result != VK_SUCCESS) state = Watch::State::idle;
2293 // Every 10 s while it changes: what the compile gate has cost so far (SubmitMutex::CompileTurn).
2294 if (++tick % per_10s == 0) {
2295 const SubmitMutex::GateStats gate = submit_mutex_.gate_stats();
2296 if (gate.submits != gate_logged.submits || gate.creates != gate_logged.creates) {
2297 gate_logged = gate;
2298 std::fprintf(stderr, "[rt] compile-gate: t=%.0f s: %llu submissions waited for pipeline creates "
2299 "(%lld ms in all, longest %lld ms); %llu creates waited behind a submission "
2300 "(%lld ms in all, longest %lld ms)\n",
2301 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(gate.submits),
2302 static_cast<long long>(gate.submit_ms), static_cast<long long>(gate.submit_max_ms),
2303 static_cast<unsigned long long>(gate.creates), static_cast<long long>(gate.create_ms),
2304 static_cast<long long>(gate.create_max_ms));
2305 }
2306 }
2133 // LEONIDA_HANG_EXIT_S=<s> (for boots): work pending and retirement still for s seconds is a GPU hang 2307 // LEONIDA_HANG_EXIT_S=<s> (for boots): work pending and retirement still for s seconds is a GPU hang
2134 // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then 2308 // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then
2135 // waits forever, the window frozen). The stall is reported (with the checkpoints under 2309 // waits forever, the window frozen). The stall is reported (with the checkpoints under
@@ -2157,7 +2331,9 @@ private:
2157 } 2331 }
2158 if (watch.sample(state, retired, Watch::Clock::now())) 2332 if (watch.sample(state, retired, Watch::Clock::now()))
2159 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced" 2333 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced"
2160 : "could not sample the submit lock", 2334 : submit_mutex_.gate_waiter() && submit_mutex_.gate_waiter() == submit_mutex_.owner()
2335 ? "could not sample the submit lock (its holder waits at the compile gate)"
2336 : "could not sample the submit lock",
2161 submitted, retired); 2337 submitted, retired);
2162 } 2338 }
2163 } 2339 }
@@ -2167,10 +2343,17 @@ private:
2167 bool ray_tracing_ = false; 2343 bool ray_tracing_ = false;
2168 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records 2344 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records
2169 std::atomic<bool> device_lost_{false}; 2345 std::atomic<bool> device_lost_{false};
2346 alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers
2170 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove 2347 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove
2171 alignas(64) std::mutex tracker_mutex_; 2348 alignas(64) std::mutex tracker_mutex_;
2172 alignas(64) std::mutex views_mutex_; 2349 alignas(64) std::mutex views_mutex_;
2173 alignas(64) std::mutex submit_mutex_; 2350 // Lock hierarchy (see VulkanQueue::execute): resource_mutex_ -> tracker_mutex_ -> submit_mutex_. A PSO build
2351 // (shims/d3d12_vulkan_device.cpp, PipelineState::build_compute / build) holds its variants_mutex_ and the
2352 // static big_compile mutex while it waits for the submit lock (SubmitMutex::let_submit_finish) or at the compile
2353 // gate: variants_mutex_ -> big_compile -> submit_mutex_, and nothing holding submit_mutex_ takes either. The
2354 // gate's own mutex is a leaf; a submission waits at the gate with submit_mutex_ held, for creates already in the
2355 // driver only (SubmitMutex::CompileTurn).
2356 alignas(64) SubmitMutex submit_mutex_;
2174 bool image_work_pending_ = false; // under submit_mutex_ 2357 bool image_work_pending_ = false; // under submit_mutex_
2175 HostTextureStats host_texture_stats_; // under submit_mutex_ 2358 HostTextureStats host_texture_stats_; // under submit_mutex_
2176 RetireTickets<VkSemaphore> retire_tickets_; 2359 RetireTickets<VkSemaphore> retire_tickets_;
@@ -2186,6 +2369,8 @@ private:
2186 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2369 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2187 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2370 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2188 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2371 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2372 std::function<std::uint64_t()> large_compile_budget_;
2373 std::function<std::shared_ptr<void>()> large_compile_demand_;
2189 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2374 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2190 LayoutTracker tracker_; 2375 LayoutTracker tracker_;
2191 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2376 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -2220,6 +2405,11 @@ private:
2220 VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; 2405 VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE;
2221 std::uint64_t bindless_upload_value_ = 0; 2406 std::uint64_t bindless_upload_value_ = 0;
2222 std::uint64_t bindless_upload_version_ = 0; 2407 std::uint64_t bindless_upload_version_ = 0;
2408 std::function<bool(VkCommandBuffer)> prelude_record_;
2409 std::function<void(bool, std::uint64_t)> prelude_commit_;
2410 VkSemaphore prelude_semaphore_ = VK_NULL_HANDLE; // the queue whose submission recorded the last prelude
2411 std::uint64_t prelude_value_ = 0;
2412 std::uint64_t prelude_version_ = 0;
2223 std::unique_ptr<Depth24Converter> depth24_; 2413 std::unique_ptr<Depth24Converter> depth24_;
2224 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour) 2414 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour)
2225 std::function<void(bool)> bindless_commit_; 2415 std::function<void(bool)> bindless_commit_;
@@ -2257,7 +2447,19 @@ public:
2257 } 2447 }
2258 ~VulkanFence() { 2448 ~VulkanFence() {
2259 if (!semaphore_) return; 2449 if (!semaphore_) return;
2450 // LOCAL DIAGNOSTIC (early device loss): a fence released while a Signal the GPU has not run yet names it.
2451 if (!context_.is_device_lost()) {
2452 const std::uint64_t submitted = context_.holds().submitted_value(semaphore_);
2453 std::uint64_t reached = 0;
2454 if (submitted && context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &reached) == VK_SUCCESS &&
2455 reached < submitted)
2456 std::fprintf(stderr, "[rt] d3d12: fence semaphore %p destroyed with a Signal pending (submitted %llu, "
2457 "reached %llu) at t=%.3f s\n",
2458 static_cast<void*>(semaphore_), static_cast<unsigned long long>(submitted),
2459 static_cast<unsigned long long>(reached), double(diagnostic_ms()) / 1000.0);
2460 }
2260 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported 2461 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported
2462 if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(semaphore_); // no report reads it
2261 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); 2463 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr);
2262 } 2464 }
2263 VulkanFence(const VulkanFence&) = delete; 2465 VulkanFence(const VulkanFence&) = delete;
@@ -2391,16 +2593,24 @@ public:
2391 2593
2392 ~VulkanQueue() { 2594 ~VulkanQueue() {
2393 auto& vk = context_.vk; 2595 auto& vk = context_.vk;
2596 stop_async(); // LEONIDA_SUBMIT_ASYNC: what is queued runs first
2597 std::fprintf(stderr, "[rt] d3d12: queue %p (progress %p) destroyed at t=%.3f s\n", static_cast<void*>(queue_),
2598 static_cast<void*>(progress_), double(diagnostic_ms()) / 1000.0);
2394 context_.holds().detach(this); // no thread releases into this queue from here on 2599 context_.holds().detach(this); // no thread releases into this queue from here on
2395 report_held_at_teardown(); 2600 report_held_at_teardown();
2396 context_.holds().pump_ready(); // presents queued behind what was just dropped can run 2601 context_.holds().pump_ready(); // presents queued behind what was just dropped can run
2397 if (queue_) { 2602 if (queue_) {
2398 std::lock_guard lock(context_.submit_mutex()); 2603 std::lock_guard lock(context_.submit_mutex());
2604 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
2399 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 2605 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
2400 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); 2606 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle");
2401 if (idle_result == VK_SUCCESS) { 2607 if (idle_result == VK_SUCCESS) {
2402 if (progress_) context_.retire_queue_idle_locked(progress_); 2608 if (progress_) context_.retire_queue_idle_locked(progress_);
2403 } else { 2609 } else {
2610 // Any failure here makes every fence read ~0 from now on: say so when it is not a real loss.
2611 if (idle_result != VK_ERROR_DEVICE_LOST)
2612 std::fprintf(stderr, "[rt] d3d12: vkQueueWaitIdle at queue teardown returned %d; the device is "
2613 "treated as lost\n", int(idle_result));
2404 context_.mark_device_lost(); 2614 context_.mark_device_lost();
2405 } 2615 }
2406 } 2616 }
@@ -2415,9 +2625,15 @@ public:
2415 // finished: the next submission on another queue must not wait on a semaphore that is about to go. 2625 // finished: the next submission on another queue must not wait on a semaphore that is about to go.
2416 std::lock_guard lock(context_.storage_mutex_); 2626 std::lock_guard lock(context_.storage_mutex_);
2417 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; 2627 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE;
2628 // The same for the bindless table upload: a queue that had not seen its version yet would otherwise
2629 // wait on this destroyed semaphore in its next vkQueueSubmit.
2630 if (context_.bindless_upload_semaphore_ == progress_) context_.bindless_upload_semaphore_ = VK_NULL_HANDLE;
2418 } 2631 }
2419 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 2632 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
2420 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 2633 if (progress_) {
2634 if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(progress_); // no report reads it
2635 vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
2636 }
2421 destroy_khr_stages(khr_stage_pool_); 2637 destroy_khr_stages(khr_stage_pool_);
2422 destroy_khr_as_queries(khr_as_query_pool_); 2638 destroy_khr_as_queries(khr_as_query_pool_);
2423 for (auto& slot : buffers_) { 2639 for (auto& slot : buffers_) {
@@ -2432,6 +2648,8 @@ public:
2432 VulkanQueue& operator=(const VulkanQueue&) = delete; 2648 VulkanQueue& operator=(const VulkanQueue&) = delete;
2433 2649
2434 bool ok() const { return ok_; } 2650 bool ok() const { return ok_; }
2651 // A queue of the runtime's own whose caller waits for each call (a staging copy): never on a worker.
2652 void make_synchronous() { synchronous_ = true; }
2435 2653
2436 // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage, 2654 // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage,
2437 // not work the next submission will replay (vk_queue_test checks both halves of that contract). 2655 // not work the next submission will replay (vk_queue_test checks both halves of that contract).
@@ -2440,6 +2658,7 @@ public:
2440 template<typename GetHeap> 2658 template<typename GetHeap>
2441 bool update_tiles(ResourceId id, std::span<const TileRegion> regions, 2659 bool update_tiles(ResourceId id, std::span<const TileRegion> regions,
2442 std::span<const TileRange> ranges, GetHeap&& get_heap) { 2660 std::span<const TileRange> ranges, GetHeap&& get_heap) {
2661 flush_async(); // after the calls queued before it (LEONIDA_SUBMIT_ASYNC)
2443 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads 2662 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads
2444 std::unique_lock lock(context_.resource_mutex_); 2663 std::unique_lock lock(context_.resource_mutex_);
2445 const auto it = context_.sparse_resources_.find(id); 2664 const auto it = context_.sparse_resources_.find(id);
@@ -2487,6 +2706,7 @@ public:
2487 2706
2488 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src, 2707 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src,
2489 std::span<const TileRegion> src_regions) { 2708 std::span<const TileRegion> src_regions) {
2709 flush_async();
2490 std::lock_guard state(state_mutex_); 2710 std::lock_guard state(state_mutex_);
2491 std::unique_lock lock(context_.resource_mutex_); 2711 std::unique_lock lock(context_.resource_mutex_);
2492 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); 2712 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst);
@@ -2519,8 +2739,23 @@ public:
2519 using PinFn = std::function<std::shared_ptr<void>()>; 2739 using PinFn = std::function<std::shared_ptr<void>()>;
2520 2740
2521 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { 2741 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) {
2742 pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits
2522 auto* diagnostics = context_.device_fault(); 2743 auto* diagnostics = context_.device_fault();
2523 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; 2744 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0;
2745 if (async_on()) { // copied and queued: the worker replays it (a failure is reported as a held one's)
2746 Call call;
2747 call.kind = Call::Kind::execute;
2748 call.execute_call = execute_call;
2749 call.lists.reserve(lists.size());
2750 for (const CommandList* list : lists) call.lists.push_back(*list);
2751 if (pin) call.pin = pin();
2752 enqueue(std::move(call));
2753 return ReplayResult::success;
2754 }
2755 return execute_sync(lists, pin, execute_call);
2756 }
2757
2758 ReplayResult execute_sync(std::span<const CommandList* const> lists, const PinFn& pin, std::uint64_t execute_call) {
2524 ReplayResult result = ReplayResult::success; 2759 ReplayResult result = ReplayResult::success;
2525 bool held = false; 2760 bool held = false;
2526 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released 2761 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released
@@ -2551,6 +2786,19 @@ public:
2551 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is 2786 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is
2552 // held) keeps the fence object alive until it has been submitted, as D3D12 does. 2787 // held) keeps the fence object alive until it has been submitted, as D3D12 does.
2553 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { 2788 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
2789 if (async_on()) {
2790 Call call;
2791 call.kind = Call::Kind::signal;
2792 call.fence = fence;
2793 call.value = value;
2794 if (pin) call.pin = pin();
2795 enqueue(std::move(call));
2796 return true;
2797 }
2798 return signal_sync(fence, value, pin);
2799 }
2800
2801 bool signal_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) {
2554 bool ok = true; 2802 bool ok = true;
2555 std::vector<std::shared_ptr<void>> retired; 2803 std::vector<std::shared_ptr<void>> retired;
2556 { 2804 {
@@ -2564,6 +2812,10 @@ public:
2564 hold(std::move(op)); 2812 hold(std::move(op));
2565 } else { 2813 } else {
2566 ok = submit(VK_NULL_HANDLE, fence, value); 2814 ok = submit(VK_NULL_HANDLE, fence, value);
2815 // As for a held Signal (release_held): the fence object, and so its semaphore, stays alive until the
2816 // GPU has run the signal. Destroying a semaphore a pending submission signals is undefined
2817 // (VUID-vkDestroySemaphore-semaphore-05149), and a title may release a fence right after Signal.
2818 if (ok && pin) pin_queue_.push_back({submitted_, pin()});
2567 } 2819 }
2568 drain_pins(retired); 2820 drain_pins(retired);
2569 } 2821 }
@@ -2576,6 +2828,19 @@ public:
2576 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). 2828 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet).
2577 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). 2829 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences).
2578 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { 2830 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
2831 if (async_on()) {
2832 Call call;
2833 call.kind = Call::Kind::wait;
2834 call.fence = fence;
2835 call.value = value;
2836 if (pin) call.pin = pin();
2837 enqueue(std::move(call));
2838 return;
2839 }
2840 wait_sync(fence, value, pin);
2841 }
2842
2843 void wait_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) {
2579 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked 2844 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked
2580 { 2845 {
2581 std::lock_guard state(state_mutex_); 2846 std::lock_guard state(state_mutex_);
@@ -2596,6 +2861,18 @@ public:
2596 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end 2861 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
2597 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. 2862 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
2598 void marker(DebugMarker::Kind kind, const char* label) { 2863 void marker(DebugMarker::Kind kind, const char* label) {
2864 if (async_on()) {
2865 Call call;
2866 call.kind = Call::Kind::marker;
2867 call.marker_kind = kind;
2868 call.label = label ? label : "";
2869 enqueue(std::move(call));
2870 return;
2871 }
2872 marker_sync(kind, label);
2873 }
2874
2875 void marker_sync(DebugMarker::Kind kind, const char* label) {
2599 std::vector<std::shared_ptr<void>> retired; 2876 std::vector<std::shared_ptr<void>> retired;
2600 std::lock_guard state(state_mutex_); 2877 std::lock_guard state(state_mutex_);
2601 drain_pins(retired); // destroyed after the lock (reverse declaration order) 2878 drain_pins(retired); // destroyed after the lock (reverse declaration order)
@@ -2611,7 +2888,9 @@ public:
2611 } 2888 }
2612 2889
2613 bool idle() { 2890 bool idle() {
2891 flush_async();
2614 std::lock_guard lock(context_.submit_mutex()); 2892 std::lock_guard lock(context_.submit_mutex());
2893 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
2615 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; 2894 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS;
2616 } 2895 }
2617 2896
@@ -2900,11 +3179,15 @@ private:
2900 } 3179 }
2901 } khr_guard{this}; 3180 } khr_guard{this};
2902 std::function<void(bool)> bindless_commit; 3181 std::function<void(bool)> bindless_commit;
2903 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 3182 // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
2904 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during 3183 // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across
2905 // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before 3184 // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is
2906 // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. 3185 // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader
2907 std::shared_lock resource_lock(context_.resource_mutex_); 3186 // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and
3187 // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and
3188 // submissions stay in order.
3189 std::shared_lock pipeline_lock(context_.pipeline_mutex_);
3190 std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock);
2908 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 3191 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
2909 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools 3192 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools
2910 // with ticket 0 while tracker_lock is still held. 3193 // with ticket 0 while tracker_lock is still held.
@@ -2915,7 +3198,7 @@ private:
2915 ~Depth24Guard() { 3198 ~Depth24Guard() {
2916 if (active && d24) d24->retire(progress, 0); 3199 if (active && d24) d24->retire(progress, 0);
2917 } 3200 }
2918 } depth24_guard{context_.depth24_.get(), progress_, false}; 3201 } depth24_guard{nullptr, progress_, false};
2919 struct ScratchGuard { // the same for the copy scratch 3202 struct ScratchGuard { // the same for the copy scratch
2920 ScratchBuffers* scratch = nullptr; 3203 ScratchBuffers* scratch = nullptr;
2921 VkSemaphore progress = VK_NULL_HANDLE; 3204 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2923,7 +3206,7 @@ private:
2923 ~ScratchGuard() { 3206 ~ScratchGuard() {
2924 if (active && scratch) scratch->retire(progress, 0); 3207 if (active && scratch) scratch->retire(progress, 0);
2925 } 3208 }
2926 } scratch_guard{context_.scratch_.get(), progress_, false}; 3209 } scratch_guard{nullptr, progress_, false};
2927 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch 3210 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch
2928 IndirectArgumentClamp* clamp = nullptr; 3211 IndirectArgumentClamp* clamp = nullptr;
2929 VkSemaphore progress = VK_NULL_HANDLE; 3212 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2931,9 +3214,8 @@ private:
2931 ~ClampGuard() { 3214 ~ClampGuard() {
2932 if (active && clamp) clamp->retire(progress, 0); 3215 if (active && clamp) clamp->retire(progress, 0);
2933 } 3216 }
2934 } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; 3217 } clamp_guard{nullptr, progress_, false};
2935 const bool transfer_only = family_ == context_.transfer_only_family_; 3218 const bool transfer_only = family_ == context_.transfer_only_family_;
2936 if (!transfer_only) bindless_commit = context_.bindless_commit_;
2937 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 3219 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
2938 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 3220 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
2939 auto& prepared = prepared_; 3221 auto& prepared = prepared_;
@@ -2941,42 +3223,9 @@ private:
2941 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below 3223 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below
2942 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 3224 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2943 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 3225 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2944 ReplayFunctions replay = context_.replay_; 3226 ReplayFunctions replay{};
2945 unsigned mesh_draws = 0; 3227 unsigned mesh_draws = 0;
2946 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2947 std::vector<VulkanContext::GeometryUpload> geometry; 3228 std::vector<VulkanContext::GeometryUpload> geometry;
2948 if (context_.geometry_provider_) {
2949 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2950 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2951 for (const auto& upload : geometry) {
2952 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2953 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2954 return true;
2955 }
2956 VulkanContext::GeometryUpload upload;
2957 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2958 buffer=upload.buffer;offset=upload.offset;
2959 geometry.push_back(std::move(upload));
2960 return true;
2961 };
2962 }
2963 replay.graphics_family = family_ == context_.graphics_family_;
2964 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2965 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2966 : 0;
2967 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
2968 VkDeviceAddress& address) {
2969 return stage_khr_instances(replay, build, khr_guard.stages, address);
2970 };
2971 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2972 return stage_xdxr_table(khr_guard.stages, address, count);
2973 };
2974 if (replay.write_acceleration_structures_properties) {
2975 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
2976 std::uint32_t& first) {
2977 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
2978 };
2979 }
2980 std::uint64_t captures = 0; 3229 std::uint64_t captures = 0;
2981 for (const auto* list : lists) 3230 for (const auto* list : lists)
2982 for (const auto& command : list->commands()) 3231 for (const auto& command : list->commands())
@@ -2985,149 +3234,239 @@ private:
2985 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 3234 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
2986 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 3235 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2987 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; 3236 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch;
2988 if (captures) { 3237 const auto& occlusion_memory = context_.occlusion_resolve_memory_;
2989 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 3238 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0;
2990 return queue_unsupported(__LINE__); 3239 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
2991 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 3240 std::uint32_t segments = 0, statistics_segments = 0;
2992 // retaining main's resource -> tracker -> submit lock order through emit and submission. 3241 bool has_queries = false;
2993 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3242 const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) {
2994 batch = context_.predicate_reducer_->batch(captures); 3243 context_.pipeline_workers_->run(count, job);
2995 if (!batch) return queue_unsupported(__LINE__); 3244 };
2996 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 3245 PipelineCompiles prior_compiles;
2997 return batch->prepare(buffer, offset, out); 3246 bool has_prior_compiles = false;
3247 for (int pass = 0;; ++pass) {
3248 resource_lock.lock();
3249 bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{};
3250 replay = context_.replay_;
3251 mesh_draws = 0;
3252 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
3253 if (context_.geometry_provider_) {
3254 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
3255 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
3256 for (const auto& upload : geometry) {
3257 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
3258 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
3259 return true;
3260 }
3261 VulkanContext::GeometryUpload upload;
3262 if (!context_.geometry_provider_(va,bytes,upload)) return false;
3263 buffer=upload.buffer;offset=upload.offset;
3264 geometry.push_back(std::move(upload));
3265 return true;
3266 };
3267 }
3268 replay.graphics_family = family_ == context_.graphics_family_;
3269 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
3270 : kind_ == QueueKind::compute ? detail::queue_stages_compute
3271 : 0;
3272 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
3273 VkDeviceAddress& address) {
3274 return stage_khr_instances(replay, build, khr_guard.stages, address);
2998 }; 3275 };
2999 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { 3276 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
3000 context_.predicate_reducer_->capture(cb, p); 3277 return stage_xdxr_table(khr_guard.stages, address, count);
3001 }; 3278 };
3002 if (context_.predicated_copier_) { 3279 if (replay.write_acceleration_structures_properties) {
3003 copy_batch = context_.predicated_copier_->batch(); 3280 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
3004 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, 3281 std::uint32_t& first) {
3005 VkDeviceSize dst, VkDeviceSize size, 3282 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
3006 std::vector<PredicatedCopyDispatch>& out) {
3007 return copy_batch->prepare(source, destination, src, dst, size, out);
3008 };
3009 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3010 context_.predicated_copier_->emit(cb, jobs);
3011 }; 3283 };
3012 } 3284 }
3013 } 3285 if (captures) {
3014 if (context_.scratch_) { 3286 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
3015 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, 3287 return queue_unsupported(__LINE__);
3016 VkDeviceSize& offset) { 3288 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
3289 // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission.
3017 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3290 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3018 if (!scratch_guard.active) { 3291 batch = context_.predicate_reducer_->batch(captures);
3019 context_.scratch_->collect(); 3292 if (!batch) return queue_unsupported(__LINE__);
3020 scratch_guard.active = true; 3293 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
3294 return batch->prepare(buffer, offset, out);
3295 };
3296 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) {
3297 context_.predicate_reducer_->capture(cb, p);
3298 };
3299 if (context_.predicated_copier_) {
3300 copy_batch = context_.predicated_copier_->batch();
3301 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src,
3302 VkDeviceSize dst, VkDeviceSize size,
3303 std::vector<PredicatedCopyDispatch>& out) {
3304 return copy_batch->prepare(source, destination, src, dst, size, out);
3305 };
3306 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3307 context_.predicated_copier_->emit(cb, jobs);
3308 };
3021 } 3309 }
3022 return context_.scratch_->get(bytes, buffer, offset); 3310 }
3023 }; 3311 if (context_.scratch_) {
3024 } 3312 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
3025 if (kind_ != QueueKind::copy && context_.indirect_clamp_) { 3313 VkDeviceSize& offset) {
3026 // The record scratch belongs to this submission: collected here, retired below with its ticket. The 3314 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3027 // counter slots are read back once that ticket completes (the batch's destructor). 3315 if (!scratch_guard.active) {
3028 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( 3316 scratch_guard.scratch = context_.scratch_.get();
3029 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, 3317 context_.scratch_->collect();
3030 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, 3318 scratch_guard.active = true;
3031 std::uint32_t max_count, ClampedIndirect& out) { 3319 }
3032 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3320 return context_.scratch_->get(bytes, buffer, offset);
3033 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3321 };
3034 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); 3322 }
3035 if (!clamp_guard.active) { 3323 if (kind_ != QueueKind::copy && context_.indirect_clamp_) {
3036 context_.indirect_clamp_->collect(); 3324 // The record scratch belongs to this submission: collected here, retired below with its ticket. The
3037 clamp_guard.active = true; 3325 // counter slots are read back once that ticket completes (the batch's destructor).
3326 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard](
3327 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
3328 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride,
3329 std::uint32_t max_count, ClampedIndirect& out) {
3330 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3331 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3332 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch();
3333 if (!clamp_guard.active) {
3334 clamp_guard.clamp = context_.indirect_clamp_.get();
3335 context_.indirect_clamp_->collect();
3336 clamp_guard.active = true;
3337 }
3338 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride,
3339 max_count, out);
3340 };
3341 }
3342 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
3343 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
3344 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
3345 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
3346 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3347 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3348 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
3349 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3350 };
3351 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3352 context_.counted_dispatch_->emit(cb, job);
3353 };
3354 }
3355 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3356 replay.prepare_quad_indices = [this, &tracker_lock](
3357 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3358 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3359 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3360 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3361 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3362 scratch_offset, out);
3363 };
3364 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3365 context_.quad_indices_->emit(cb, job);
3366 };
3367 }
3368 if (context_.depth24_ && !transfer_only) {
3369 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3370 std::vector<Depth24Job>& parts) {
3371 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3372 if (!depth24_guard.active) {
3373 depth24_guard.d24 = context_.depth24_.get();
3374 context_.depth24_->collect();
3375 depth24_guard.active = true;
3376 }
3377 return context_.depth24_->prepare(job, parts);
3378 };
3379 }
3380 if (can_resolve_occlusion) {
3381 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3382 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3383 occlusion_resolve_->sum(cb, pool, first, count, dst, offset);
3384 };
3385 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3386 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3387 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
3388 };
3389 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
3390 VkQueryPool primitives_pool, const std::uint8_t* mesh,
3391 std::uint32_t first, std::uint32_t count, VkBuffer dst,
3392 VkDeviceSize offset) {
3393 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
3394 offset);
3395 };
3396 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3397 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3398 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
3399 };
3400 }
3401 segments = 0;
3402 statistics_segments = 0;
3403 has_queries = false;
3404 // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial).
3405 // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock
3406 // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and
3407 // workers stay alive), then re-prepare on pass 1 against current resources.
3408 PipelineCompiles compiles;
3409 replay.compiles = &compiles;
3410 ReplayResult prepare_result = ReplayResult::success;
3411 for (std::size_t i = 0; i < lists.size(); ++i) {
3412 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3413 if (result != ReplayResult::success) {
3414 prepare_result = result;
3415 break;
3038 } 3416 }
3039 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, 3417 if (prepared[i].segment_count > UINT32_MAX - segments ||
3040 out); 3418 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
3041 }; 3419 return queue_unsupported(__LINE__);
3042 } 3420 segments += prepared[i].segment_count;
3043 if (kind_ != QueueKind::copy && context_.counted_dispatch_) { 3421 statistics_segments += prepared[i].statistics_segment_count;
3044 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( 3422 has_queries = has_queries || !prepared[i].queries.empty();
3045 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, 3423 }
3046 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { 3424 if (pass == 0 && !compiles.empty()) {
3047 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3425 if (depth24_guard.active) {
3048 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3426 context_.depth24_->retire(progress_, 0);
3049 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); 3427 depth24_guard.active = false;
3050 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3051 };
3052 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3053 context_.counted_dispatch_->emit(cb, job);
3054 };
3055 }
3056 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3057 replay.prepare_quad_indices = [this, &tracker_lock](
3058 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3059 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3060 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3061 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3062 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3063 scratch_offset, out);
3064 };
3065 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3066 context_.quad_indices_->emit(cb, job);
3067 };
3068 }
3069 if (context_.depth24_ && !transfer_only) {
3070 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3071 std::vector<Depth24Job>& parts) {
3072 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3073 if (!depth24_guard.active) {
3074 context_.depth24_->collect();
3075 depth24_guard.active = true;
3076 } 3428 }
3077 return context_.depth24_->prepare(job, parts); 3429 if (scratch_guard.active) {
3078 }; 3430 context_.scratch_->retire(progress_, 0);
3079 } 3431 scratch_guard.active = false;
3080 const auto& occlusion_memory = context_.occlusion_resolve_memory_; 3432 }
3081 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; 3433 if (clamp_guard.active) {
3082 if (can_resolve_occlusion) { 3434 context_.indirect_clamp_->retire(progress_, 0);
3083 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3435 clamp_guard.active = false;
3084 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3436 }
3085 occlusion_resolve_->sum(cb, pool, first, count, dst, offset); 3437 batch.reset();
3086 }; 3438 copy_batch.reset();
3087 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3439 counted_batch.reset();
3088 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3440 clamp_batch.reset();
3089 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 3441 if (tracker_lock.owns_lock()) tracker_lock.unlock();
3090 }; 3442 resource_lock.unlock();
3091 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 3443 recycle_khr_stages(khr_guard.stages);
3092 VkQueryPool primitives_pool, const std::uint8_t* mesh, 3444 recycle_khr_as_queries(khr_guard.as_queries);
3093 std::uint32_t first, std::uint32_t count, VkBuffer dst, 3445 geometry.clear();
3094 VkDeviceSize offset) { 3446
3095 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, 3447 std::shared_ptr<void> demand;
3096 offset); 3448 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3097 }; 3449 if (context_.pipeline_workers_)
3098 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3450 compiles.build(run_compiles, context_.large_compile_budget_);
3099 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3451 else
3100 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); 3452 compiles.build_serial();
3101 }; 3453 demand.reset();
3102 } 3454 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3103 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 3455 if (compile_result != ReplayResult::success) return compile_result;
3104 std::uint32_t segments = 0, statistics_segments = 0; 3456 prior_compiles = std::move(compiles);
3105 bool has_queries = false; 3457 has_prior_compiles = true;
3106 // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of 3458 continue;
3107 // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline
3108 // states that own them alive (remove_pipeline takes it uniquely).
3109 PipelineCompiles compiles;
3110 if (context_.pipeline_workers_) replay.compiles = &compiles;
3111 ReplayResult prepare_result = ReplayResult::success;
3112 for (std::size_t i = 0; i < lists.size(); ++i) {
3113 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3114 if (result != ReplayResult::success) {
3115 prepare_result = result;
3116 break;
3117 } 3459 }
3118 if (prepared[i].segment_count > UINT32_MAX - segments || 3460 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3119 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 3461 prepare_result = context_.pipeline_workers_
3120 return queue_unsupported(__LINE__); 3462 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3121 segments += prepared[i].segment_count; 3463 run_compiles, context_.large_compile_budget_, prior)
3122 statistics_segments += prepared[i].statistics_segment_count; 3464 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3123 has_queries = has_queries || !prepared[i].queries.empty(); 3465 prepare_result, prior);
3124 } 3466 replay.compiles = nullptr;
3125 prepare_result = build_pipelines( 3467 if (prepare_result != ReplayResult::success) return prepare_result;
3126 compiles, std::span(prepared).first(lists.size()), prepare_result, 3468 break;
3127 [this](std::size_t count, const std::function<void(std::size_t)>& job) { 3469 }
3128 context_.pipeline_workers_->run(count, job);
3129 });
3130 if (prepare_result != ReplayResult::success) return prepare_result;
3131 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 3470 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
3132 std::shared_ptr<OcclusionSegmentPool>& out) { 3471 std::shared_ptr<OcclusionSegmentPool>& out) {
3133 const auto& vk = context_.vk; 3472 const auto& vk = context_.vk;
@@ -3254,6 +3593,7 @@ private:
3254 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3593 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3255 "vkEndCommandBuffer") == VK_SUCCESS; 3594 "vkEndCommandBuffer") == VK_SUCCESS;
3256 resource_lock.unlock(); 3595 resource_lock.unlock();
3596 pipeline_lock.unlock();
3257 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3597 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
3258 if (!submitted) discard(); 3598 if (!submitted) discard();
3259 if (depth24_guard.active) { 3599 if (depth24_guard.active) {
@@ -3331,6 +3671,25 @@ private:
3331 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); 3671 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED);
3332 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); 3672 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker);
3333 } 3673 }
3674 // The prelude (set_prelude): recorded here, after the set's upload and before the lists, and in either case
3675 // after the last submission of another queue that recorded one (its pass writes what these lists read, and
3676 // a pass here must not overtake it).
3677 const bool prelude = !transfer_only && context_.prelude_record_ && context_.prelude_record_(command_buffer);
3678 // LEONIDA_PRELUDE_QUEUE_WAIT=0 (an experiment): no wait for another queue's pass, so the queues do not
3679 // serialise on each other's whole submissions; a list may then read what that pass has not written yet.
3680 static const bool cross_wait = [] {
3681 const char* v = std::getenv("LEONIDA_PRELUDE_QUEUE_WAIT");
3682 return !(v && v[0] == '0' && v[1] == 0);
3683 }();
3684 {
3685 std::lock_guard lock(context_.storage_mutex_);
3686 if (cross_wait && context_.prelude_semaphore_ && context_.prelude_semaphore_ != progress_ &&
3687 context_.prelude_version_ != prelude_seen_) {
3688 waits_.push_back(context_.prelude_semaphore_);
3689 wait_values_.push_back(context_.prelude_value_);
3690 }
3691 prelude_seen_ = context_.prelude_version_;
3692 }
3334 bool wrote_readback = false; 3693 bool wrote_readback = false;
3335 VkPipelineStageFlags2 readback_stages = 0; 3694 VkPipelineStageFlags2 readback_stages = 0;
3336 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 3695 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
@@ -3387,7 +3746,8 @@ private:
3387 } 3746 }
3388 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3747 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3389 "vkEndCommandBuffer") == VK_SUCCESS; 3748 "vkEndCommandBuffer") == VK_SUCCESS;
3390 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3749 resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held
3750 pipeline_lock.unlock();
3391 const bool wait_previous = ordered_timestamps && submitted_; 3751 const bool wait_previous = ordered_timestamps && submitted_;
3392 if (wait_previous) { 3752 if (wait_previous) {
3393 waits_.push_back(progress_); 3753 waits_.push_back(progress_);
@@ -3418,6 +3778,16 @@ private:
3418 ++context_.bindless_upload_version_; 3778 ++context_.bindless_upload_version_;
3419 bindless_upload_seen_ = context_.bindless_upload_version_; 3779 bindless_upload_seen_ = context_.bindless_upload_version_;
3420 } 3780 }
3781 if (prelude) {
3782 if (submitted) {
3783 std::lock_guard lock(context_.storage_mutex_);
3784 context_.prelude_semaphore_ = progress_;
3785 context_.prelude_value_ = submitted_;
3786 ++context_.prelude_version_;
3787 prelude_seen_ = context_.prelude_version_;
3788 }
3789 if (context_.prelude_commit_) context_.prelude_commit_(submitted, context_.submitted_retire_ticket());
3790 }
3421 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one 3791 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one
3422 waits_.pop_back(); 3792 waits_.pop_back();
3423 wait_values_.pop_back(); 3793 wait_values_.pop_back();
@@ -3538,7 +3908,9 @@ private:
3538 3908
3539 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. 3909 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held.
3540 void hold(Deferred&& op) { 3910 void hold(Deferred&& op) {
3541 op.seq = context_.holds().next_seq(); 3911 // A call the worker runs (LEONIDA_SUBMIT_ASYNC) keeps the number it was queued with: what was registered
3912 // behind it (a Present) still waits for it.
3913 op.seq = async_seq_ ? async_seq_ : context_.holds().next_seq();
3542 if (op.kind != Deferred::Kind::marker) { 3914 if (op.kind != Deferred::Kind::marker) {
3543 op.waits = std::move(waits_); 3915 op.waits = std::move(waits_);
3544 op.wait_values = std::move(wait_values_); 3916 op.wait_values = std::move(wait_values_);
@@ -3549,6 +3921,7 @@ private:
3549 } 3921 }
3550 if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now(); 3922 if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now();
3551 held_.push_back(std::move(op)); 3923 held_.push_back(std::move(op));
3924 held_front_seq_.store(held_.front().seq, std::memory_order_release);
3552 context_.holds().held_changed(1); 3925 context_.holds().held_changed(1);
3553 } 3926 }
3554 3927
@@ -3595,7 +3968,21 @@ private:
3595 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } 3968 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); }
3596 3969
3597 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). 3970 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held).
3971 // With LEONIDA_SUBMIT_ASYNC another thread does not run this queue's held work: it asks the queue's worker,
3972 // which releases it and then pumps the holds itself (so a Present behind it still runs after it).
3598 bool release_ready() override { 3973 bool release_ready() override {
3974 if (async_started_.load(std::memory_order_acquire) && t_worker_of_ != this) {
3975 {
3976 std::lock_guard lock(inbox_mutex_);
3977 release_requested_ = true;
3978 }
3979 inbox_cv_.notify_one();
3980 return false;
3981 }
3982 return release_held();
3983 }
3984
3985 bool release_held() {
3599 std::vector<std::shared_ptr<void>> retired; 3986 std::vector<std::shared_ptr<void>> retired;
3600 bool released = false; 3987 bool released = false;
3601 { 3988 {
@@ -3604,8 +3991,19 @@ private:
3604 Deferred op = std::move(held_.front()); 3991 Deferred op = std::move(held_.front());
3605 held_.pop_front(); 3992 held_.pop_front();
3606 context_.holds().held_changed(-1); 3993 context_.holds().held_changed(-1);
3607 if (gpu_latency::enabled()) gpu_latency::held(int(kind_), int(op.kind), op.held_at); 3994 if (gpu_latency::enabled()) {
3995 // The wait that was pending when it was held: the fence whose Signal let it go.
3996 std::uint64_t fence = 0, value = 0;
3997 for (std::size_t i = 0; i < op.waits.size(); ++i)
3998 if (op.wait_values[i] > value) {
3999 fence = std::uint64_t(reinterpret_cast<std::uintptr_t>(op.waits[i]));
4000 value = op.wait_values[i];
4001 }
4002 gpu_latency::held(int(kind_), int(op.kind), op.held_at, fence, value);
4003 }
3608 if (!context_.is_device_lost()) run(op); 4004 if (!context_.is_device_lost()) run(op);
4005 // Only now: until it has run, the operation still counts as the oldest held one.
4006 held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release);
3609 released = true; 4007 released = true;
3610 } 4008 }
3611 drain_pins(retired); 4009 drain_pins(retired);
@@ -3630,13 +4028,22 @@ private:
3630 it = held_.erase(it); 4028 it = held_.erase(it);
3631 context_.holds().held_changed(-1); 4029 context_.holds().held_changed(-1);
3632 } 4030 }
4031 held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release);
3633 } 4032 }
3634 } 4033 }
3635 4034
3636 // Holder: the sequence number of the oldest held operation. 4035 // Holder: the sequence number of the oldest held operation.
3637 std::uint64_t oldest_held_seq() override { 4036 std::uint64_t oldest_held_seq() override {
3638 std::lock_guard state(state_mutex_); 4037 if (!async_on()) {
3639 return held_.empty() ? 0 : held_.front().seq; 4038 std::lock_guard state(state_mutex_);
4039 return held_.empty() ? 0 : held_.front().seq;
4040 }
4041 // Not under state_mutex_, which the worker holds while it replays: the front's number is kept apart.
4042 std::uint64_t oldest = held_front_seq_.load(std::memory_order_acquire);
4043 std::lock_guard lock(inbox_mutex_);
4044 const std::uint64_t queued = running_seq_ ? running_seq_ : inbox_.empty() ? 0 : inbox_.front().seq;
4045 if (queued && (!oldest || queued < oldest)) oldest = queued;
4046 return oldest;
3640 } 4047 }
3641 4048
3642 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is 4049 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is
@@ -3662,6 +4069,7 @@ private:
3662 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); 4069 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence);
3663 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size())); 4070 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size()));
3664 dropped.swap(held_); 4071 dropped.swap(held_);
4072 held_front_seq_.store(0, std::memory_order_release);
3665 } 4073 }
3666 // The pins (fences, pipeline states) are released here, outside the lock. 4074 // The pins (fences, pipeline states) are released here, outside the lock.
3667 } 4075 }
@@ -3796,8 +4204,12 @@ private:
3796 pending_bindings_.push_back(std::move(pending)); 4204 pending_bindings_.push_back(std::move(pending));
3797 { 4205 {
3798 std::lock_guard lock(context_.submit_mutex()); 4206 std::lock_guard lock(context_.submit_mutex());
3799 const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE), 4207 VkResult bound;
3800 "vkQueueBindSparse"); 4208 {
4209 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
4210 bound = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE);
4211 }
4212 const auto result = context_.observe_result(bound, "vkQueueBindSparse");
3801 if (result != VK_SUCCESS) { 4213 if (result != VK_SUCCESS) {
3802 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 4214 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3803 pending_bindings_.pop_back(); 4215 pending_bindings_.pop_back();
@@ -4021,10 +4433,32 @@ private:
4021 if (diagnostics) pass_trace(*diagnostics); 4433 if (diagnostics) pass_trace(*diagnostics);
4022 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. 4434 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss.
4023 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); 4435 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics));
4024 const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); 4436 DeviceFaultDiagnostics* const ring = context_.device_fault();
4025 res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence), 4437 std::size_t ring_at = 0;
4438 const std::int64_t submit_start = diagnostic_ms();
4439 if (ring) {
4440 SubmitRecord record;
4441 record.at_ms = submit_start;
4442 record.queue = queue_;
4443 record.kind = kind_ == QueueKind::direct ? "direct" : kind_ == QueueKind::compute ? "compute" : "copy";
4444 record.progress = progress_;
4445 record.ticket = ticket;
4446 record.buffers = submit.commandBufferCount;
4447 if (signals_fence) {
4448 record.fence = fence;
4449 record.fence_value = value;
4450 }
4451 record.waits = std::uint32_t(semaphores.size());
4452 for (std::size_t i = 0; i < semaphores.size() && i < SubmitRecord::max_waits; ++i) {
4453 record.wait_semaphores[i] = semaphores[i];
4454 record.wait_values[i] = values[i];
4455 }
4456 ring_at = ring->begin_submit(record);
4457 }
4458 res = context_.observe_result(context_.queue_submit(queue_, 1, &submit, context_.gpu_labels_.submit_fence(command_buffer)),
4026 "vkQueueSubmit"); 4459 "vkQueueSubmit");
4027 context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); 4460 context_.gpu_labels_.submitted(command_buffer, res == VK_SUCCESS);
4461 if (ring) ring->end_submit(ring_at, diagnostic_ms() - submit_start, res);
4028 if (res == VK_SUCCESS) { 4462 if (res == VK_SUCCESS) {
4029 context_.record_submit_locked(progress_, ticket); 4463 context_.record_submit_locked(progress_, ticket);
4030 if (signals_fence) context_.holds().signaled(fence, value); 4464 if (signals_fence) context_.holds().signaled(fence, value);
@@ -4063,6 +4497,7 @@ private:
4063 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 4497 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
4064 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for 4498 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
4065 std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for 4499 std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for
4500 std::uint64_t prelude_seen_ = 0; // the prelude_version_ this queue has waited for (or recorded)
4066 std::uint64_t last_sparse_ = 0; 4501 std::uint64_t last_sparse_ = 0;
4067 std::deque<PendingBindings> pending_bindings_; 4502 std::deque<PendingBindings> pending_bindings_;
4068 std::vector<VkSemaphore> waits_; 4503 std::vector<VkSemaphore> waits_;
@@ -4072,8 +4507,260 @@ private:
4072 std::vector<PreparedList> prepared_; 4507 std::vector<PreparedList> prepared_;
4073 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 4508 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
4074 bool ok_ = false; 4509 bool ok_ = false;
4075 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and 4510 // ---- LEONIDA_SUBMIT_ASYNC=<n>: the queue's calls run on a worker of its own -----------------------------------
4076 // guards the members above that execute, signal, wait and marker touch. 4511 // ExecuteCommandLists, Signal, Wait and the markers are queued in call order and return at once; one worker per
4512 // queue runs each through the synchronous path (execute_sync & co.), so the replay, the before-submission
4513 // refreshes and vkQueueSubmit leave the caller's thread and overlap with its next frame. At most n batches wait per
4514 // queue; the caller of the next one waits for room (the in-flight bound). A queued call counts as held work
4515 // (QueueHolds), numbered when it was called, so a Present behind it still waits for it and cross-queue order is
4516 // the call order. Calls that use the queue's state at once (tile mappings, idle, the destructor) first wait for
4517 // what is queued. A batch that fails is reported as a held one is (stderr, take_held_failure()). Off (0) by
4518 // default: every call runs on the caller's thread, as before.
4519 static unsigned async_depth() {
4520 static const unsigned depth = [] {
4521 const char* v = std::getenv("LEONIDA_SUBMIT_ASYNC");
4522 const int n = v && *v ? std::atoi(v) : 0;
4523 return n > 0 ? unsigned(n) : 0u;
4524 }();
4525 return depth;
4526 }
4527
4528 bool async_on() const { return async_depth() && !synchronous_; }
4529
4530 struct Call {
4531 enum class Kind : std::uint8_t { execute, signal, wait, marker };
4532 Kind kind = Kind::execute;
4533 std::uint64_t seq = 0, execute_call = 0, value = 0;
4534 std::vector<CommandList> lists; // copies: the application may Reset its lists after the call
4535 std::shared_ptr<void> pin; // the fence, or the lists' pipeline states and root signatures
4536 VkSemaphore fence = VK_NULL_HANDLE;
4537 DebugMarker::Kind marker_kind = DebugMarker::Kind::set;
4538 std::string label;
4539 std::chrono::steady_clock::time_point queued_at{};
4540 };
4541
4542 struct AsyncStats { // under inbox_mutex_, since the last line
4543 std::uint64_t calls = 0, batches = 0, room_waits = 0, room_wait_ns = 0, run_ns = 0, lag_ns = 0, lag_max_ns = 0;
4544 std::size_t depth_max = 0;
4545 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now();
4546 };
4547
4548 void enqueue(Call&& call) {
4549 const bool batch = call.kind == Call::Kind::execute;
4550 std::unique_lock lock(inbox_mutex_);
4551 if (!worker_.joinable()) {
4552 worker_ = std::thread([this] { async_worker(); });
4553 async_started_.store(true, std::memory_order_release);
4554 }
4555 // n batches, and 4n calls of any kind (a title that signals after every small job must not queue Signals
4556 // without bound). n = 1 makes each caller wait for the batch before it: n should be 2 or more.
4557 const auto room = [this, batch] {
4558 return async_stop_ ||
4559 ((!batch || inbox_batches_ < async_depth()) && inbox_.size() < 4 * std::size_t(async_depth()));
4560 };
4561 if (!room()) {
4562 const auto start = std::chrono::steady_clock::now();
4563 room_cv_.wait(lock, room);
4564 ++async_stats_.room_waits;
4565 async_stats_.room_wait_ns += std::uint64_t(
4566 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count());
4567 }
4568 if (batch) {
4569 ++inbox_batches_;
4570 ++async_stats_.batches;
4571 }
4572 ++async_stats_.calls;
4573 call.seq = context_.holds().next_seq();
4574 call.queued_at = std::chrono::steady_clock::now();
4575 context_.holds().held_changed(1);
4576 inbox_.push_back(std::move(call));
4577 async_stats_.depth_max = std::max(async_stats_.depth_max, inbox_.size());
4578 lock.unlock();
4579 inbox_cv_.notify_one();
4580 }
4581
4582 void async_worker() {
4583 t_worker_of_ = this;
4584 for (;;) {
4585 Call call;
4586 bool have = false, release = false;
4587 {
4588 std::unique_lock lock(inbox_mutex_);
4589 inbox_cv_.wait(lock, [this] { return !inbox_.empty() || release_requested_ || async_stop_; });
4590 release = std::exchange(release_requested_, false);
4591 if (!inbox_.empty()) {
4592 call = std::move(inbox_.front());
4593 inbox_.pop_front();
4594 running_seq_ = call.seq;
4595 have = true;
4596 } else if (!release) {
4597 return; // stopping, nothing queued
4598 }
4599 worker_busy_ = true;
4600 }
4601 if (release) release_held();
4602 std::uint64_t ran_ns = 0;
4603 if (have) {
4604 const auto start = std::chrono::steady_clock::now();
4605 run_call(call);
4606 const auto end = std::chrono::steady_clock::now();
4607 ran_ns = std::uint64_t(std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count());
4608 const auto lag = std::uint64_t(
4609 std::chrono::duration_cast<std::chrono::nanoseconds>(start - call.queued_at).count());
4610 std::lock_guard lock(inbox_mutex_);
4611 async_stats_.run_ns += ran_ns;
4612 async_stats_.lag_ns += lag;
4613 async_stats_.lag_max_ns = std::max(async_stats_.lag_max_ns, lag);
4614 }
4615 {
4616 std::lock_guard lock(inbox_mutex_);
4617 running_seq_ = 0;
4618 worker_busy_ = false;
4619 if (have && call.kind == Call::Kind::execute) --inbox_batches_;
4620 if (have) room_cv_.notify_all();
4621 idle_cv_.notify_all();
4622 report_async_locked();
4623 }
4624 if (have) context_.holds().held_changed(-1);
4625 call = Call{}; // the copies and pins go before the pump, outside the lock
4626 context_.holds().pump_ready();
4627 }
4628 }
4629
4630 // An exception on the worker would end the process (std::terminate) and leave the queue's callers waiting: it is
4631 // turned into a held failure and a lost device instead, as a failed submission would be, and the worker goes on
4632 // (each later call fails at once on the lost device).
4633 void run_call(Call& call) {
4634 try {
4635 run_call_unguarded(call);
4636 } catch (const std::exception& e) {
4637 worker_threw(call, e.what());
4638 } catch (...) {
4639 worker_threw(call, "not a std::exception");
4640 }
4641 async_seq_ = 0;
4642 }
4643
4644 void worker_threw(const Call& call, const char* what) {
4645 int none = static_cast<int>(ReplayResult::success);
4646 held_failure_.compare_exchange_strong(none, static_cast<int>(ReplayResult::unsupported));
4647 std::fprintf(stderr, "[rt] d3d12: the queue's worker caught an exception running a queued %s (%s); the device is "
4648 "marked lost\n",
4649 call.kind == Call::Kind::execute ? "ExecuteCommandLists"
4650 : call.kind == Call::Kind::signal ? "Signal"
4651 : call.kind == Call::Kind::wait ? "Wait"
4652 : "marker",
4653 what);
4654 context_.mark_device_lost();
4655 }
4656
4657 void run_call_unguarded(Call& call) {
4658 async_seq_ = call.seq;
4659 const PinFn pin = call.pin ? PinFn([&call] { return call.pin; }) : PinFn{};
4660 switch (call.kind) {
4661 case Call::Kind::execute: {
4662 std::vector<const CommandList*> lists;
4663 lists.reserve(call.lists.size());
4664 for (const CommandList& list : call.lists) lists.push_back(&list);
4665 const ReplayResult result = execute_sync(lists, pin, call.execute_call);
4666 if (result != ReplayResult::success) {
4667 int none = static_cast<int>(ReplayResult::success);
4668 held_failure_.compare_exchange_strong(none, static_cast<int>(result));
4669 std::fprintf(stderr, "[rt] d3d12: a queued ExecuteCommandLists failed on the queue's worker (result "
4670 "%d); nothing was submitted for it\n",
4671 static_cast<int>(result));
4672 }
4673 break;
4674 }
4675 case Call::Kind::signal:
4676 if (!signal_sync(call.fence, call.value, pin)) {
4677 int none = static_cast<int>(ReplayResult::success);
4678 held_failure_.compare_exchange_strong(none, static_cast<int>(ReplayResult::unsupported));
4679 std::fprintf(stderr, "[rt] d3d12: a queued Signal failed on the queue's worker\n");
4680 }
4681 break;
4682 case Call::Kind::wait: wait_sync(call.fence, call.value, pin); break;
4683 case Call::Kind::marker: marker_sync(call.marker_kind, call.label.c_str()); break;
4684 }
4685 if (call.pin && call.kind == Call::Kind::execute) {
4686 // The pipeline states stay alive until what was just submitted has completed (a held batch keeps its own).
4687 std::lock_guard state(state_mutex_);
4688 std::vector<std::shared_ptr<void>> pins{std::move(call.pin)};
4689 retire_pins(pins, submitted_);
4690 }
4691 }
4692
4693 // Every 10 s, per queue: what the worker did. Called with inbox_mutex_ held.
4694 void report_async_locked() {
4695 const auto now = std::chrono::steady_clock::now();
4696 const double s = std::chrono::duration<double>(now - async_stats_.since).count();
4697 if (s < 10.0) return;
4698 static constexpr const char* kinds[] = {"direct", "compute", "copy"};
4699 const AsyncStats& a = async_stats_;
4700 std::fprintf(stderr,
4701 "[rt] submit-async: %s queue %p: %.1f calls/s (%.1f batches/s), queued now %zu (max %zu), "
4702 "worker busy %.0f%%, call waited for the worker avg %.2f ms max %.2f ms, caller waited for "
4703 "room %llu times %.1f ms\n",
4704 kinds[int(kind_) < 3 ? int(kind_) : 0], static_cast<const void*>(this), double(a.calls) / s,
4705 double(a.batches) / s, inbox_.size(), a.depth_max, 100.0 * double(a.run_ns) / (s * 1e9),
4706 a.calls ? double(a.lag_ns) / double(a.calls) / 1e6 : 0.0, double(a.lag_max_ns) / 1e6,
4707 static_cast<unsigned long long>(a.room_waits), double(a.room_wait_ns) / 1e6);
4708 async_stats_ = AsyncStats{};
4709 }
4710
4711 // What was queued before this call has run (held work may stay held, as without the worker). A worker that does
4712 // not come back (a GPU hang inside wait_for_room, say) is reported every 10 s, and after 60 s the caller goes on
4713 // without it: false.
4714 bool flush_async() {
4715 if (!async_started_.load(std::memory_order_acquire) || t_worker_of_ == this) return true;
4716 std::unique_lock lock(inbox_mutex_);
4717 const auto idle = [this] { return inbox_.empty() && !worker_busy_; };
4718 for (int slice = 1; slice <= 6; ++slice) {
4719 if (idle_cv_.wait_for(lock, std::chrono::seconds(10), idle)) return true;
4720 std::fprintf(stderr, "[rt] d3d12: waited %d s for a queue's worker to finish what is queued (%zu calls, "
4721 "running call %llu)%s\n",
4722 slice * 10, inbox_.size(), static_cast<unsigned long long>(running_seq_),
4723 slice == 6 ? "; going on without it" : "");
4724 }
4725 return false;
4726 }
4727
4728 void stop_async() {
4729 if (!async_started_.load(std::memory_order_acquire)) return;
4730 const bool drained = flush_async();
4731 {
4732 std::lock_guard lock(inbox_mutex_);
4733 async_stop_ = true;
4734 }
4735 inbox_cv_.notify_all();
4736 room_cv_.notify_all();
4737 if (!worker_.joinable()) return;
4738 if (drained) {
4739 worker_.join();
4740 return;
4741 }
4742 // A worker stuck for a minute holds this queue's objects: it is left running rather than joined forever
4743 // (only at teardown; the process is ending or the device is gone).
4744 std::fprintf(stderr, "[rt] d3d12: a queue's worker did not finish; it is detached at the queue's destruction\n");
4745 worker_.detach();
4746 }
4747
4748 std::mutex inbox_mutex_;
4749 std::condition_variable inbox_cv_, room_cv_, idle_cv_;
4750 std::deque<Call> inbox_;
4751 std::size_t inbox_batches_ = 0;
4752 std::uint64_t running_seq_ = 0; // the call the worker runs now
4753 bool worker_busy_ = false, release_requested_ = false, async_stop_ = false;
4754 AsyncStats async_stats_;
4755 std::atomic<bool> async_started_{false};
4756 bool synchronous_ = false; // make_synchronous()
4757 std::thread worker_;
4758 static inline thread_local VulkanQueue* t_worker_of_ = nullptr; // the queue whose worker this thread is
4759 static inline thread_local std::uint64_t async_seq_ = 0; // the sequence number of the call being run
4760 std::atomic<std::uint64_t> held_front_seq_{0}; // held_.front().seq, 0 when empty; see release_held()
4761
4762 // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ ->
4763 // submit_mutex_) and guards the members above that execute, signal, wait and marker touch.
4077 std::mutex state_mutex_; 4764 std::mutex state_mutex_;
4078 std::deque<Deferred> held_; 4765 std::deque<Deferred> held_;
4079 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive 4766 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive