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:
authorTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
committerTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
commitbeffaa9a476ca1b3dfd9cfa55e39eafbb1f5eec6 (patch)
tree32877805bf4eb46d9a89d5753db6b5a2b06dc845 /runtime/src/vulkan_backend.h
parentf29ca7bacae9507f83e8c56abdb604bd4efb4cf1 (diff)
parenta73a57e1339be072baf5522351c8ec7f1482b56b (diff)
Merge main into fix/null-descriptor-generated-dir
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h1176
1 files changed, 941 insertions, 235 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 145fa11ee..9fdb29640 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);
@@ -1278,8 +1325,12 @@ public:
1278 1325
1279 bool loaded() const { return loaded_; } 1326 bool loaded() const { return loaded_; }
1280 1327
1281 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) { 1328 // `memory`: the physical device's memory types, for the AMD marker buffer (enabled.markers).
1282 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled); 1329 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled,
1330 const VkPhysicalDeviceMemoryProperties* memory = nullptr) {
1331 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled, memory,
1332 vk.vkCmdPipelineBarrier2 != nullptr);
1333 device_fault_->set_submit_lock(&submit_mutex_);
1283 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get()); 1334 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); }); 1335 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); });
1285 } 1336 }
@@ -1326,14 +1377,19 @@ public:
1326 // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the 1377 // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the
1327 // pass off at replay time. 1378 // pass off at replay time.
1328 void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, 1379 void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
1329 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate) { 1380 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate,
1381 std::vector<std::uint32_t> families = {}) {
1330 std::unique_lock lock(resource_mutex_); 1382 std::unique_lock lock(resource_mutex_);
1383 // An enabled clamp is required: a call whose scratch preparation fails is refused (unsupported) instead of
1384 // reading the application's argument buffer, which may hold a record no compute pass wrote. Off, or on a
1385 // device the pass cannot run on, the replay keeps the application's buffer as before.
1331 replay_.require_indirect_clamp = indirect_clamp_enabled(); 1386 replay_.require_indirect_clamp = indirect_clamp_enabled();
1332 if (!replay_.require_indirect_clamp) return; 1387 if (!replay_.require_indirect_clamp) return;
1333 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate), 1388 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate),
1334 device_fault_.get()); 1389 device_fault_.get(), std::move(families));
1335 if (!indirect_clamp_->loaded()) { 1390 if (!indirect_clamp_->loaded()) {
1336 indirect_clamp_.reset(); 1391 indirect_clamp_.reset();
1392 replay_.require_indirect_clamp = false;
1337 return; 1393 return;
1338 } 1394 }
1339 // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists 1395 // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists
@@ -1545,32 +1601,42 @@ public:
1545 } 1601 }
1546 1602
1547 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1603 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1604 // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block
1605 // resource registration or destruction on the render thread.
1548 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { 1606 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1549 std::unique_lock lock(resource_mutex_); 1607 std::unique_lock lock(pipeline_mutex_);
1550 pipelines_[id] = pipeline; 1608 pipelines_[id] = pipeline;
1551 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; 1609 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1552 } 1610 }
1553 void remove_pipeline(std::uintptr_t id) { 1611 void remove_pipeline(std::uintptr_t id) {
1554 std::unique_lock lock(resource_mutex_); 1612 std::unique_lock lock(pipeline_mutex_);
1555 pipelines_.erase(id); 1613 pipelines_.erase(id);
1556 graphics_pipelines_.erase(id); 1614 graphics_pipelines_.erase(id);
1557 if (device_fault_) device_fault_->pipeline_names.erase(id); 1615 if (device_fault_) device_fault_->pipeline_names.erase(id);
1558 } 1616 }
1559 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, 1617 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1560 const CheckpointShaders* shaders = nullptr) { 1618 const CheckpointShaders* shaders = nullptr) {
1561 std::unique_lock lock(resource_mutex_); 1619 std::unique_lock lock(pipeline_mutex_);
1562 graphics_pipelines_[id] = pipeline; 1620 graphics_pipelines_[id] = pipeline;
1563 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; 1621 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1564 } 1622 }
1565 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where 1623 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on
1566 // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the 1624 // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and
1567 // workers it had. 1625 // ends the workers it had.
1568 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { 1626 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) {
1569 std::unique_lock lock(resource_mutex_); 1627 std::unique_lock lock(pipeline_mutex_);
1570 pipeline_workers_.swap(workers); 1628 pipeline_workers_.swap(workers);
1571 } 1629 }
1630 // For the large pipelines of a submission: the memory they may use while they compile together
1631 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1632 // one after another.
1633 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1634 std::unique_lock lock(pipeline_mutex_);
1635 large_compile_budget_ = std::move(budget);
1636 large_compile_demand_ = std::move(demand);
1637 }
1572 PipelineWorkers::Stats pipeline_worker_stats() { 1638 PipelineWorkers::Stats pipeline_worker_stats() {
1573 std::shared_lock lock(resource_mutex_); 1639 std::shared_lock lock(pipeline_mutex_);
1574 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1640 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
1575 } 1641 }
1576 // Configure before queue creation, when the selected queue family supports compute. 1642 // Configure before queue creation, when the selected queue family supports compute.
@@ -1584,6 +1650,44 @@ public:
1584 return host_texture_stats_; 1650 return host_texture_stats_;
1585 } 1651 }
1586 1652
1653 // LOCAL FIX (deadlock on the first-run pages): the texture writes below used vkDeviceWaitIdle with the submit
1654 // lock held. The device is idle only once every queue has run all it was given, and a queue whose submitted
1655 // work waits on a value a later submission signals never gets there while this thread keeps the lock: a native
1656 // boot sat 270 s in vkDeviceWaitIdle (title staging), then lost the device. Instead: wait for the queue
1657 // timelines to pass what was submitted so far, at most `timeout`; on VK_TIMEOUT the caller skips this write (the
1658 // title-texture pass tries it again) rather than freeze the title. Not covered, unlike the device wait: present
1659 // and probe submissions, which have their own fences outside the retirement timelines (a present reading the
1660 // image). The staged write is ordered behind them anyway (same queue, an ALL_COMMANDS barrier); the host copy
1661 // is not, so a presented title texture can be written while a present still reads it (a torn frame, no fault).
1662 // With submit_mutex_ held.
1663 VkResult wait_submitted_locked(std::uint64_t timeout_ns, const char* what) {
1664 if (is_device_lost()) return VK_ERROR_DEVICE_LOST; // a queue's timeline may be gone already
1665 const auto pending = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire));
1666 if (pending.empty()) return VK_SUCCESS;
1667 std::vector<VkSemaphore> semaphores;
1668 std::vector<std::uint64_t> values;
1669 for (const auto& [semaphore, value] : pending) {
1670 semaphores.push_back(semaphore);
1671 values.push_back(value);
1672 }
1673 VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO};
1674 wait.semaphoreCount = std::uint32_t(semaphores.size());
1675 wait.pSemaphores = semaphores.data();
1676 wait.pValues = values.data();
1677 const VkResult r = observe_result(vk.vkWaitSemaphores(device_, &wait, timeout_ns), what);
1678 if (r == VK_TIMEOUT) {
1679 static std::atomic<std::uint64_t> timeouts{0};
1680 const std::uint64_t n = timeouts.fetch_add(1, std::memory_order_relaxed) + 1;
1681 if (!(n & (n - 1)))
1682 std::fprintf(stderr, "[rt] vulkan: %s: submitted work not done within %llu ms (%llu time(s)); the "
1683 "write is skipped this time\n", what,
1684 static_cast<unsigned long long>(timeout_ns / 1000000), static_cast<unsigned long long>(n));
1685 }
1686 return r;
1687 }
1688 // Short: a timeout is certain when the awaited work needs this thread's lock, and the write is only skipped.
1689 static constexpr std::uint64_t kTitleWriteWaitNs = 250'000'000; // 250 ms
1690
1587 // CPU writes to a title texture have no application fence. Prevent another queue from 1691 // CPU writes to a title texture have no application fence. Prevent another queue from
1588 // claiming a new layout or submitting work between the completion check and the host copy. 1692 // claiming a new layout or submitting work between the completion check and the host copy.
1589 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues. 1693 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues.
@@ -1594,7 +1698,13 @@ public:
1594 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY; 1698 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY;
1595 if (image_work_pending_) { 1699 if (image_work_pending_) {
1596 ++host_texture_stats_.waits; 1700 ++host_texture_stats_.waits;
1597 const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)"); 1701 // A device wait is a queue operation: it passes the compile gate, so it never waits in the driver behind a
1702 // long pipeline create (the starved wait that loses the device after 10 s).
1703 const SubmitMutex::SubmitTurn turn(submit_mutex_);
1704 const auto result = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title texture upload)");
1705 // Not done in time: VK_NOT_READY, so the caller takes its staged path (ordered on the queue) or tries
1706 // again later, and the skip is not counted as a failed fill.
1707 if (result == VK_TIMEOUT) return VK_NOT_READY;
1598 if (result != VK_SUCCESS) return result; 1708 if (result != VK_SUCCESS) return result;
1599 image_work_pending_ = false; 1709 image_work_pending_ = false;
1600 } 1710 }
@@ -1612,7 +1722,8 @@ public:
1612 LayoutPieces pieces; 1722 LayoutPieces pieces;
1613 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; 1723 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN;
1614 if (image_work_pending_) { 1724 if (image_work_pending_) {
1615 const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)"); 1725 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate (as above)
1726 const auto r = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title staging)");
1616 if (r != VK_SUCCESS) return r; 1727 if (r != VK_SUCCESS) return r;
1617 image_work_pending_ = false; 1728 image_work_pending_ = false;
1618 } 1729 }
@@ -1737,7 +1848,6 @@ public:
1737 // `before` is called at the start of every submission of command lists (a held batch: when it is released), 1848 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1738 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. 1849 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1739 // Set once, before the first queue exists. 1850 // Set once, before the first queue exists.
1740 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1741 1851
1742 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues. 1852 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues.
1743 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of 1853 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of
@@ -1774,11 +1884,25 @@ public:
1774 return true; 1884 return true;
1775 } 1885 }
1776 const char* diagnostic_compute_name(std::uintptr_t id) { 1886 const char* diagnostic_compute_name(std::uintptr_t id) {
1777 std::shared_lock lock(resource_mutex_); 1887 std::shared_lock lock(pipeline_mutex_);
1778 if (!device_fault_) return nullptr; 1888 if (!device_fault_) return nullptr;
1779 const auto it = device_fault_->pipeline_names.find(id); 1889 const auto it = device_fault_->pipeline_names.find(id);
1780 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; 1890 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
1781 } 1891 }
1892 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1893 // Called at the end of every ExecuteCommandLists replay that called before_execute_, however it returns: by then
1894 // the submissions it made are recorded, so submitted_retire_ticket() covers them.
1895 void set_after_execute(std::function<void()> after) { after_execute_ = std::move(after); }
1896 // GPU work the lists of a submission depend on, recorded at the start of its command buffer by a queue that can
1897 // run compute (the console heap translation pass, src/console_heap_gpu.h): `record` returns true when it recorded
1898 // something, and `commit` follows that submit (true: it reached the queue; the ticket is a retire ticket at or
1899 // after it). Every other queue's next submission then waits for that one, as for a bindless table upload: a
1900 // queue that records nothing itself may run lists that read what the pass wrote. Called with tracker_mutex_
1901 // held, so passes and those waits follow submission order. Set once, before the first queue exists.
1902 void set_prelude(std::function<bool(VkCommandBuffer)> record, std::function<void(bool, std::uint64_t)> commit) {
1903 prelude_record_ = std::move(record);
1904 prelude_commit_ = std::move(commit);
1905 }
1782 1906
1783 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1907 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1784 std::unique_lock lock(resource_mutex_); 1908 std::unique_lock lock(resource_mutex_);
@@ -1802,6 +1926,11 @@ public:
1802 }; 1926 };
1803 } 1927 }
1804 1928
1929 bool has_depth24() {
1930 std::shared_lock lock(resource_mutex_);
1931 return depth24_ != nullptr;
1932 }
1933
1805 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from 1934 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from
1806 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer 1935 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer
1807 // usage, for configure_quad_indices. 1936 // usage, for configure_quad_indices.
@@ -1933,7 +2062,14 @@ public:
1933 VulkanDeviceFunctions vk; 2062 VulkanDeviceFunctions vk;
1934 2063
1935 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 2064 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
1936 std::mutex& submit_mutex() { return submit_mutex_; } 2065 SubmitMutex& submit_mutex() { return submit_mutex_; }
2066
2067 // vkQueueSubmit through the compile gate (SubmitMutex::SubmitTurn): it waits here, not in the driver, while a
2068 // pipeline create is in the driver. Called with the submit lock held; the caller observes the result.
2069 VkResult queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) {
2070 const SubmitMutex::SubmitTurn turn(submit_mutex_);
2071 return vk.vkQueueSubmit(queue, count, submits, fence);
2072 }
1937 2073
1938 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept { 2074 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept {
1939 set_device_lost(device_lost_, where); 2075 set_device_lost(device_lost_, where);
@@ -2103,19 +2239,32 @@ private:
2103 using Watch = SubmissionProgressWatch; 2239 using Watch = SubmissionProgressWatch;
2104 Watch watch; 2240 Watch watch;
2105 std::uint64_t retired = 0; 2241 std::uint64_t retired = 0;
2242 std::int64_t reported_hold = -1;
2243 std::int64_t busy_since = -1;
2244 SubmitMutex::GateStats gate_logged;
2245 unsigned tick = 0;
2106 std::mutex timer_mutex; 2246 std::mutex timer_mutex;
2107 std::condition_variable_any timer; 2247 std::condition_variable_any timer;
2108 std::unique_lock timer_lock(timer_mutex); 2248 std::unique_lock timer_lock(timer_mutex);
2249 // LOCAL DIAGNOSTIC (post-load GPU hangs): with the device-fault report on, sample every 250 ms, so a loss the
2250 // driver has already reset is seen (and its checkpoints read) before a watchdog outside kills the process.
2251 const auto period = device_fault_ ? std::chrono::milliseconds(250) : std::chrono::milliseconds(1000);
2252 const unsigned per_10s = unsigned(std::chrono::seconds(10) / period);
2109 while (!stop.stop_requested()) { 2253 while (!stop.stop_requested()) {
2110 timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; }); 2254 timer.wait_for(timer_lock, stop, period, [] { return false; });
2111 if (stop.stop_requested() || is_device_lost()) break; 2255 if (stop.stop_requested() || is_device_lost()) break;
2112 auto state = Watch::State::submit_lock_busy; 2256 auto state = Watch::State::submit_lock_busy;
2113 VkResult result = VK_SUCCESS; 2257 VkResult result = VK_SUCCESS;
2114 std::uint64_t submitted; 2258 std::uint64_t submitted;
2115 { 2259 {
2116 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait 2260 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait
2117 // blocked inside the driver can hold this mutex indefinitely. 2261 // blocked inside the driver can hold this mutex indefinitely. Under heavy submission one try finds
2262 // it busy most of the time: a few more within a millisecond or two.
2118 std::unique_lock lock(submit_mutex_, std::try_to_lock); 2263 std::unique_lock lock(submit_mutex_, std::try_to_lock);
2264 for (int retry = 0; !lock.owns_lock() && retry < 20; ++retry) {
2265 std::this_thread::sleep_for(std::chrono::microseconds(100));
2266 if (lock.try_lock()) break;
2267 }
2119 submitted = submitted_retire_ticket(); 2268 submitted = submitted_retire_ticket();
2120 if (lock.owns_lock()) { 2269 if (lock.owns_lock()) {
2121 if (is_device_lost()) break; 2270 if (is_device_lost()) break;
@@ -2123,12 +2272,49 @@ private:
2123 state = retired < submitted ? Watch::State::pending : Watch::State::idle; 2272 state = retired < submitted ? Watch::State::pending : Watch::State::idle;
2124 } 2273 }
2125 } 2274 }
2275 // LOCAL DIAGNOSTIC (early device loss): a submission unfinished for 4 s dumps the recent submissions with
2276 // their semaphore counters (unreadable once the device is lost); a hold of the submit lock of 3 s names
2277 // its thread and prints its call chain, once per hold.
2278 // A vkQueueSubmit stuck in the driver (measured: 10 s, then VK_ERROR_DEVICE_LOST) also blocks
2279 // vkGetSemaphoreCounterValue, so with the lock busy the watch stays out of the driver: the holder report
2280 // samples stacks only, and the counters are read once the lock is free again.
2281 if (state == Watch::State::submit_lock_busy) {
2282 const std::uint32_t owner = submit_mutex_.owner();
2283 const std::int64_t since = submit_mutex_.since_ms();
2284 const std::int64_t held = diagnostic_ms() - since;
2285 if (owner && held >= 3000 && since != reported_hold) {
2286 reported_hold = since;
2287 device_fault_->report_submit_lock_holder(owner, held);
2288 }
2289 // Busy at every sample but changing hands: contended, not stuck. Only a hold that lasts (the same
2290 // holder since the same time) counts toward the 15 s stall report.
2291 if (since != busy_since) {
2292 busy_since = since;
2293 state = Watch::State::idle;
2294 }
2295 } else {
2296 device_fault_->check_submit_progress();
2297 }
2126 if (result == VK_ERROR_DEVICE_LOST) { 2298 if (result == VK_ERROR_DEVICE_LOST) {
2127 mark_device_lost(); 2299 mark_device_lost();
2128 break; 2300 break;
2129 } 2301 }
2130 // A failed counter query does not measure GPU progress. 2302 // A failed counter query does not measure GPU progress.
2131 if (result != VK_SUCCESS) state = Watch::State::idle; 2303 if (result != VK_SUCCESS) state = Watch::State::idle;
2304 // Every 10 s while it changes: what the compile gate has cost so far (SubmitMutex::CompileTurn).
2305 if (++tick % per_10s == 0) {
2306 const SubmitMutex::GateStats gate = submit_mutex_.gate_stats();
2307 if (gate.submits != gate_logged.submits || gate.creates != gate_logged.creates) {
2308 gate_logged = gate;
2309 std::fprintf(stderr, "[rt] compile-gate: t=%.0f s: %llu submissions waited for pipeline creates "
2310 "(%lld ms in all, longest %lld ms); %llu creates waited behind a submission "
2311 "(%lld ms in all, longest %lld ms)\n",
2312 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(gate.submits),
2313 static_cast<long long>(gate.submit_ms), static_cast<long long>(gate.submit_max_ms),
2314 static_cast<unsigned long long>(gate.creates), static_cast<long long>(gate.create_ms),
2315 static_cast<long long>(gate.create_max_ms));
2316 }
2317 }
2132 // LEONIDA_HANG_EXIT_S=<s> (for boots): work pending and retirement still for s seconds is a GPU hang 2318 // LEONIDA_HANG_EXIT_S=<s> (for boots): work pending and retirement still for s seconds is a GPU hang
2133 // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then 2319 // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then
2134 // waits forever, the window frozen). The stall is reported (with the checkpoints under 2320 // waits forever, the window frozen). The stall is reported (with the checkpoints under
@@ -2156,7 +2342,9 @@ private:
2156 } 2342 }
2157 if (watch.sample(state, retired, Watch::Clock::now())) 2343 if (watch.sample(state, retired, Watch::Clock::now()))
2158 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced" 2344 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced"
2159 : "could not sample the submit lock", 2345 : submit_mutex_.gate_waiter() && submit_mutex_.gate_waiter() == submit_mutex_.owner()
2346 ? "could not sample the submit lock (its holder waits at the compile gate)"
2347 : "could not sample the submit lock",
2160 submitted, retired); 2348 submitted, retired);
2161 } 2349 }
2162 } 2350 }
@@ -2166,10 +2354,17 @@ private:
2166 bool ray_tracing_ = false; 2354 bool ray_tracing_ = false;
2167 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records 2355 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records
2168 std::atomic<bool> device_lost_{false}; 2356 std::atomic<bool> device_lost_{false};
2357 alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers
2169 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove 2358 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove
2170 alignas(64) std::mutex tracker_mutex_; 2359 alignas(64) std::mutex tracker_mutex_;
2171 alignas(64) std::mutex views_mutex_; 2360 alignas(64) std::mutex views_mutex_;
2172 alignas(64) std::mutex submit_mutex_; 2361 // Lock hierarchy (see VulkanQueue::execute): resource_mutex_ -> tracker_mutex_ -> submit_mutex_. A PSO build
2362 // (shims/d3d12_vulkan_device.cpp, PipelineState::build_compute / build) holds its variants_mutex_ and the
2363 // static big_compile mutex while it waits for the submit lock (SubmitMutex::let_submit_finish) or at the compile
2364 // gate: variants_mutex_ -> big_compile -> submit_mutex_, and nothing holding submit_mutex_ takes either. The
2365 // gate's own mutex is a leaf; a submission waits at the gate with submit_mutex_ held, for creates already in the
2366 // driver only (SubmitMutex::CompileTurn).
2367 alignas(64) SubmitMutex submit_mutex_;
2173 bool image_work_pending_ = false; // under submit_mutex_ 2368 bool image_work_pending_ = false; // under submit_mutex_
2174 HostTextureStats host_texture_stats_; // under submit_mutex_ 2369 HostTextureStats host_texture_stats_; // under submit_mutex_
2175 RetireTickets<VkSemaphore> retire_tickets_; 2370 RetireTickets<VkSemaphore> retire_tickets_;
@@ -2185,6 +2380,8 @@ private:
2185 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2380 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2186 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2381 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2187 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2382 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2383 std::function<std::uint64_t()> large_compile_budget_;
2384 std::function<std::shared_ptr<void>()> large_compile_demand_;
2188 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2385 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2189 LayoutTracker tracker_; 2386 LayoutTracker tracker_;
2190 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2387 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -2206,6 +2403,7 @@ private:
2206 resolve_passes_; 2403 resolve_passes_;
2207 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; 2404 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_;
2208 std::function<void()> before_execute_; 2405 std::function<void()> before_execute_;
2406 std::function<void()> after_execute_;
2209 InputProbe input_probe_; 2407 InputProbe input_probe_;
2210 TableScanner table_scanner_; 2408 TableScanner table_scanner_;
2211 GeometryProvider geometry_provider_; 2409 GeometryProvider geometry_provider_;
@@ -2219,6 +2417,11 @@ private:
2219 VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; 2417 VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE;
2220 std::uint64_t bindless_upload_value_ = 0; 2418 std::uint64_t bindless_upload_value_ = 0;
2221 std::uint64_t bindless_upload_version_ = 0; 2419 std::uint64_t bindless_upload_version_ = 0;
2420 std::function<bool(VkCommandBuffer)> prelude_record_;
2421 std::function<void(bool, std::uint64_t)> prelude_commit_;
2422 VkSemaphore prelude_semaphore_ = VK_NULL_HANDLE; // the queue whose submission recorded the last prelude
2423 std::uint64_t prelude_value_ = 0;
2424 std::uint64_t prelude_version_ = 0;
2222 std::unique_ptr<Depth24Converter> depth24_; 2425 std::unique_ptr<Depth24Converter> depth24_;
2223 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour) 2426 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour)
2224 std::function<void(bool)> bindless_commit_; 2427 std::function<void(bool)> bindless_commit_;
@@ -2256,7 +2459,19 @@ public:
2256 } 2459 }
2257 ~VulkanFence() { 2460 ~VulkanFence() {
2258 if (!semaphore_) return; 2461 if (!semaphore_) return;
2462 // LOCAL DIAGNOSTIC (early device loss): a fence released while a Signal the GPU has not run yet names it.
2463 if (!context_.is_device_lost()) {
2464 const std::uint64_t submitted = context_.holds().submitted_value(semaphore_);
2465 std::uint64_t reached = 0;
2466 if (submitted && context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &reached) == VK_SUCCESS &&
2467 reached < submitted)
2468 std::fprintf(stderr, "[rt] d3d12: fence semaphore %p destroyed with a Signal pending (submitted %llu, "
2469 "reached %llu) at t=%.3f s\n",
2470 static_cast<void*>(semaphore_), static_cast<unsigned long long>(submitted),
2471 static_cast<unsigned long long>(reached), double(diagnostic_ms()) / 1000.0);
2472 }
2259 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported 2473 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported
2474 if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(semaphore_); // no report reads it
2260 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); 2475 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr);
2261 } 2476 }
2262 VulkanFence(const VulkanFence&) = delete; 2477 VulkanFence(const VulkanFence&) = delete;
@@ -2390,16 +2605,24 @@ public:
2390 2605
2391 ~VulkanQueue() { 2606 ~VulkanQueue() {
2392 auto& vk = context_.vk; 2607 auto& vk = context_.vk;
2608 stop_async(); // LEONIDA_SUBMIT_ASYNC: what is queued runs first
2609 std::fprintf(stderr, "[rt] d3d12: queue %p (progress %p) destroyed at t=%.3f s\n", static_cast<void*>(queue_),
2610 static_cast<void*>(progress_), double(diagnostic_ms()) / 1000.0);
2393 context_.holds().detach(this); // no thread releases into this queue from here on 2611 context_.holds().detach(this); // no thread releases into this queue from here on
2394 report_held_at_teardown(); 2612 report_held_at_teardown();
2395 context_.holds().pump_ready(); // presents queued behind what was just dropped can run 2613 context_.holds().pump_ready(); // presents queued behind what was just dropped can run
2396 if (queue_) { 2614 if (queue_) {
2397 std::lock_guard lock(context_.submit_mutex()); 2615 std::lock_guard lock(context_.submit_mutex());
2616 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
2398 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 2617 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
2399 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); 2618 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle");
2400 if (idle_result == VK_SUCCESS) { 2619 if (idle_result == VK_SUCCESS) {
2401 if (progress_) context_.retire_queue_idle_locked(progress_); 2620 if (progress_) context_.retire_queue_idle_locked(progress_);
2402 } else { 2621 } else {
2622 // Any failure here makes every fence read ~0 from now on: say so when it is not a real loss.
2623 if (idle_result != VK_ERROR_DEVICE_LOST)
2624 std::fprintf(stderr, "[rt] d3d12: vkQueueWaitIdle at queue teardown returned %d; the device is "
2625 "treated as lost\n", int(idle_result));
2403 context_.mark_device_lost(); 2626 context_.mark_device_lost();
2404 } 2627 }
2405 } 2628 }
@@ -2414,9 +2637,15 @@ public:
2414 // finished: the next submission on another queue must not wait on a semaphore that is about to go. 2637 // finished: the next submission on another queue must not wait on a semaphore that is about to go.
2415 std::lock_guard lock(context_.storage_mutex_); 2638 std::lock_guard lock(context_.storage_mutex_);
2416 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; 2639 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE;
2640 // The same for the bindless table upload: a queue that had not seen its version yet would otherwise
2641 // wait on this destroyed semaphore in its next vkQueueSubmit.
2642 if (context_.bindless_upload_semaphore_ == progress_) context_.bindless_upload_semaphore_ = VK_NULL_HANDLE;
2417 } 2643 }
2418 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 2644 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
2419 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 2645 if (progress_) {
2646 if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(progress_); // no report reads it
2647 vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
2648 }
2420 destroy_khr_stages(khr_stage_pool_); 2649 destroy_khr_stages(khr_stage_pool_);
2421 destroy_khr_as_queries(khr_as_query_pool_); 2650 destroy_khr_as_queries(khr_as_query_pool_);
2422 for (auto& slot : buffers_) { 2651 for (auto& slot : buffers_) {
@@ -2431,6 +2660,8 @@ public:
2431 VulkanQueue& operator=(const VulkanQueue&) = delete; 2660 VulkanQueue& operator=(const VulkanQueue&) = delete;
2432 2661
2433 bool ok() const { return ok_; } 2662 bool ok() const { return ok_; }
2663 // A queue of the runtime's own whose caller waits for each call (a staging copy): never on a worker.
2664 void make_synchronous() { synchronous_ = true; }
2434 2665
2435 // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage, 2666 // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage,
2436 // not work the next submission will replay (vk_queue_test checks both halves of that contract). 2667 // not work the next submission will replay (vk_queue_test checks both halves of that contract).
@@ -2439,6 +2670,7 @@ public:
2439 template<typename GetHeap> 2670 template<typename GetHeap>
2440 bool update_tiles(ResourceId id, std::span<const TileRegion> regions, 2671 bool update_tiles(ResourceId id, std::span<const TileRegion> regions,
2441 std::span<const TileRange> ranges, GetHeap&& get_heap) { 2672 std::span<const TileRange> ranges, GetHeap&& get_heap) {
2673 flush_async(); // after the calls queued before it (LEONIDA_SUBMIT_ASYNC)
2442 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads 2674 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads
2443 std::unique_lock lock(context_.resource_mutex_); 2675 std::unique_lock lock(context_.resource_mutex_);
2444 const auto it = context_.sparse_resources_.find(id); 2676 const auto it = context_.sparse_resources_.find(id);
@@ -2486,6 +2718,7 @@ public:
2486 2718
2487 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src, 2719 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src,
2488 std::span<const TileRegion> src_regions) { 2720 std::span<const TileRegion> src_regions) {
2721 flush_async();
2489 std::lock_guard state(state_mutex_); 2722 std::lock_guard state(state_mutex_);
2490 std::unique_lock lock(context_.resource_mutex_); 2723 std::unique_lock lock(context_.resource_mutex_);
2491 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); 2724 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst);
@@ -2518,8 +2751,23 @@ public:
2518 using PinFn = std::function<std::shared_ptr<void>()>; 2751 using PinFn = std::function<std::shared_ptr<void>()>;
2519 2752
2520 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { 2753 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) {
2754 pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits
2521 auto* diagnostics = context_.device_fault(); 2755 auto* diagnostics = context_.device_fault();
2522 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; 2756 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0;
2757 if (async_on()) { // copied and queued: the worker replays it (a failure is reported as a held one's)
2758 Call call;
2759 call.kind = Call::Kind::execute;
2760 call.execute_call = execute_call;
2761 call.lists.reserve(lists.size());
2762 for (const CommandList* list : lists) call.lists.push_back(*list);
2763 if (pin) call.pin = pin();
2764 enqueue(std::move(call));
2765 return ReplayResult::success;
2766 }
2767 return execute_sync(lists, pin, execute_call);
2768 }
2769
2770 ReplayResult execute_sync(std::span<const CommandList* const> lists, const PinFn& pin, std::uint64_t execute_call) {
2523 ReplayResult result = ReplayResult::success; 2771 ReplayResult result = ReplayResult::success;
2524 bool held = false; 2772 bool held = false;
2525 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released 2773 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released
@@ -2550,6 +2798,19 @@ public:
2550 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is 2798 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is
2551 // held) keeps the fence object alive until it has been submitted, as D3D12 does. 2799 // held) keeps the fence object alive until it has been submitted, as D3D12 does.
2552 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { 2800 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
2801 if (async_on()) {
2802 Call call;
2803 call.kind = Call::Kind::signal;
2804 call.fence = fence;
2805 call.value = value;
2806 if (pin) call.pin = pin();
2807 enqueue(std::move(call));
2808 return true;
2809 }
2810 return signal_sync(fence, value, pin);
2811 }
2812
2813 bool signal_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) {
2553 bool ok = true; 2814 bool ok = true;
2554 std::vector<std::shared_ptr<void>> retired; 2815 std::vector<std::shared_ptr<void>> retired;
2555 { 2816 {
@@ -2563,6 +2824,10 @@ public:
2563 hold(std::move(op)); 2824 hold(std::move(op));
2564 } else { 2825 } else {
2565 ok = submit(VK_NULL_HANDLE, fence, value); 2826 ok = submit(VK_NULL_HANDLE, fence, value);
2827 // As for a held Signal (release_held): the fence object, and so its semaphore, stays alive until the
2828 // GPU has run the signal. Destroying a semaphore a pending submission signals is undefined
2829 // (VUID-vkDestroySemaphore-semaphore-05149), and a title may release a fence right after Signal.
2830 if (ok && pin) pin_queue_.push_back({submitted_, pin()});
2566 } 2831 }
2567 drain_pins(retired); 2832 drain_pins(retired);
2568 } 2833 }
@@ -2575,6 +2840,19 @@ public:
2575 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). 2840 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet).
2576 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). 2841 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences).
2577 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { 2842 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
2843 if (async_on()) {
2844 Call call;
2845 call.kind = Call::Kind::wait;
2846 call.fence = fence;
2847 call.value = value;
2848 if (pin) call.pin = pin();
2849 enqueue(std::move(call));
2850 return;
2851 }
2852 wait_sync(fence, value, pin);
2853 }
2854
2855 void wait_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) {
2578 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked 2856 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked
2579 { 2857 {
2580 std::lock_guard state(state_mutex_); 2858 std::lock_guard state(state_mutex_);
@@ -2595,6 +2873,18 @@ public:
2595 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end 2873 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
2596 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. 2874 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
2597 void marker(DebugMarker::Kind kind, const char* label) { 2875 void marker(DebugMarker::Kind kind, const char* label) {
2876 if (async_on()) {
2877 Call call;
2878 call.kind = Call::Kind::marker;
2879 call.marker_kind = kind;
2880 call.label = label ? label : "";
2881 enqueue(std::move(call));
2882 return;
2883 }
2884 marker_sync(kind, label);
2885 }
2886
2887 void marker_sync(DebugMarker::Kind kind, const char* label) {
2598 std::vector<std::shared_ptr<void>> retired; 2888 std::vector<std::shared_ptr<void>> retired;
2599 std::lock_guard state(state_mutex_); 2889 std::lock_guard state(state_mutex_);
2600 drain_pins(retired); // destroyed after the lock (reverse declaration order) 2890 drain_pins(retired); // destroyed after the lock (reverse declaration order)
@@ -2610,7 +2900,9 @@ public:
2610 } 2900 }
2611 2901
2612 bool idle() { 2902 bool idle() {
2903 flush_async();
2613 std::lock_guard lock(context_.submit_mutex()); 2904 std::lock_guard lock(context_.submit_mutex());
2905 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
2614 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; 2906 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS;
2615 } 2907 }
2616 2908
@@ -2871,6 +3163,12 @@ private:
2871 if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__); 3163 if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__);
2872 } 3164 }
2873 if (context_.before_execute_) context_.before_execute_(); 3165 if (context_.before_execute_) context_.before_execute_();
3166 struct AfterExecute {
3167 VulkanContext& context;
3168 ~AfterExecute() {
3169 if (context.after_execute_) context.after_execute_();
3170 }
3171 } after_execute{context_};
2874 // The rest of this call is the replay phase; the submission is counted when it returns, however it returns. 3172 // The rest of this call is the replay phase; the submission is counted when it returns, however it returns.
2875 struct Replayed { 3173 struct Replayed {
2876 std::int64_t start = submit_phases::now_ns(); 3174 std::int64_t start = submit_phases::now_ns();
@@ -2899,11 +3197,15 @@ private:
2899 } 3197 }
2900 } khr_guard{this}; 3198 } khr_guard{this};
2901 std::function<void(bool)> bindless_commit; 3199 std::function<void(bool)> bindless_commit;
2902 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 3200 // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
2903 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during 3201 // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across
2904 // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before 3202 // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is
2905 // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. 3203 // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader
2906 std::shared_lock resource_lock(context_.resource_mutex_); 3204 // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and
3205 // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and
3206 // submissions stay in order.
3207 std::shared_lock pipeline_lock(context_.pipeline_mutex_);
3208 std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock);
2907 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 3209 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
2908 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools 3210 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools
2909 // with ticket 0 while tracker_lock is still held. 3211 // with ticket 0 while tracker_lock is still held.
@@ -2914,7 +3216,7 @@ private:
2914 ~Depth24Guard() { 3216 ~Depth24Guard() {
2915 if (active && d24) d24->retire(progress, 0); 3217 if (active && d24) d24->retire(progress, 0);
2916 } 3218 }
2917 } depth24_guard{context_.depth24_.get(), progress_, false}; 3219 } depth24_guard{nullptr, progress_, false};
2918 struct ScratchGuard { // the same for the copy scratch 3220 struct ScratchGuard { // the same for the copy scratch
2919 ScratchBuffers* scratch = nullptr; 3221 ScratchBuffers* scratch = nullptr;
2920 VkSemaphore progress = VK_NULL_HANDLE; 3222 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2922,7 +3224,7 @@ private:
2922 ~ScratchGuard() { 3224 ~ScratchGuard() {
2923 if (active && scratch) scratch->retire(progress, 0); 3225 if (active && scratch) scratch->retire(progress, 0);
2924 } 3226 }
2925 } scratch_guard{context_.scratch_.get(), progress_, false}; 3227 } scratch_guard{nullptr, progress_, false};
2926 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch 3228 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch
2927 IndirectArgumentClamp* clamp = nullptr; 3229 IndirectArgumentClamp* clamp = nullptr;
2928 VkSemaphore progress = VK_NULL_HANDLE; 3230 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2930,9 +3232,8 @@ private:
2930 ~ClampGuard() { 3232 ~ClampGuard() {
2931 if (active && clamp) clamp->retire(progress, 0); 3233 if (active && clamp) clamp->retire(progress, 0);
2932 } 3234 }
2933 } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; 3235 } clamp_guard{nullptr, progress_, false};
2934 const bool transfer_only = family_ == context_.transfer_only_family_; 3236 const bool transfer_only = family_ == context_.transfer_only_family_;
2935 if (!transfer_only) bindless_commit = context_.bindless_commit_;
2936 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 3237 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
2937 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 3238 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
2938 auto& prepared = prepared_; 3239 auto& prepared = prepared_;
@@ -2940,42 +3241,9 @@ private:
2940 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below 3241 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below
2941 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 3242 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2942 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 3243 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2943 ReplayFunctions replay = context_.replay_; 3244 ReplayFunctions replay{};
2944 unsigned mesh_draws = 0; 3245 unsigned mesh_draws = 0;
2945 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2946 std::vector<VulkanContext::GeometryUpload> geometry; 3246 std::vector<VulkanContext::GeometryUpload> geometry;
2947 if (context_.geometry_provider_) {
2948 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2949 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2950 for (const auto& upload : geometry) {
2951 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2952 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2953 return true;
2954 }
2955 VulkanContext::GeometryUpload upload;
2956 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2957 buffer=upload.buffer;offset=upload.offset;
2958 geometry.push_back(std::move(upload));
2959 return true;
2960 };
2961 }
2962 replay.graphics_family = family_ == context_.graphics_family_;
2963 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2964 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2965 : 0;
2966 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
2967 VkDeviceAddress& address) {
2968 return stage_khr_instances(replay, build, khr_guard.stages, address);
2969 };
2970 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2971 return stage_xdxr_table(khr_guard.stages, address, count);
2972 };
2973 if (replay.write_acceleration_structures_properties) {
2974 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
2975 std::uint32_t& first) {
2976 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
2977 };
2978 }
2979 std::uint64_t captures = 0; 3247 std::uint64_t captures = 0;
2980 for (const auto* list : lists) 3248 for (const auto* list : lists)
2981 for (const auto& command : list->commands()) 3249 for (const auto& command : list->commands())
@@ -2984,149 +3252,239 @@ private:
2984 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 3252 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
2985 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 3253 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2986 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; 3254 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch;
2987 if (captures) { 3255 const auto& occlusion_memory = context_.occlusion_resolve_memory_;
2988 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 3256 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0;
2989 return queue_unsupported(__LINE__); 3257 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
2990 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 3258 std::uint32_t segments = 0, statistics_segments = 0;
2991 // retaining main's resource -> tracker -> submit lock order through emit and submission. 3259 bool has_queries = false;
2992 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3260 const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) {
2993 batch = context_.predicate_reducer_->batch(captures); 3261 context_.pipeline_workers_->run(count, job);
2994 if (!batch) return queue_unsupported(__LINE__); 3262 };
2995 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 3263 PipelineCompiles prior_compiles;
2996 return batch->prepare(buffer, offset, out); 3264 bool has_prior_compiles = false;
3265 for (int pass = 0;; ++pass) {
3266 resource_lock.lock();
3267 bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{};
3268 replay = context_.replay_;
3269 mesh_draws = 0;
3270 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
3271 if (context_.geometry_provider_) {
3272 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
3273 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
3274 for (const auto& upload : geometry) {
3275 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
3276 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
3277 return true;
3278 }
3279 VulkanContext::GeometryUpload upload;
3280 if (!context_.geometry_provider_(va,bytes,upload)) return false;
3281 buffer=upload.buffer;offset=upload.offset;
3282 geometry.push_back(std::move(upload));
3283 return true;
3284 };
3285 }
3286 replay.graphics_family = family_ == context_.graphics_family_;
3287 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
3288 : kind_ == QueueKind::compute ? detail::queue_stages_compute
3289 : 0;
3290 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
3291 VkDeviceAddress& address) {
3292 return stage_khr_instances(replay, build, khr_guard.stages, address);
2997 }; 3293 };
2998 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { 3294 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2999 context_.predicate_reducer_->capture(cb, p); 3295 return stage_xdxr_table(khr_guard.stages, address, count);
3000 }; 3296 };
3001 if (context_.predicated_copier_) { 3297 if (replay.write_acceleration_structures_properties) {
3002 copy_batch = context_.predicated_copier_->batch(); 3298 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
3003 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, 3299 std::uint32_t& first) {
3004 VkDeviceSize dst, VkDeviceSize size, 3300 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
3005 std::vector<PredicatedCopyDispatch>& out) {
3006 return copy_batch->prepare(source, destination, src, dst, size, out);
3007 };
3008 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3009 context_.predicated_copier_->emit(cb, jobs);
3010 }; 3301 };
3011 } 3302 }
3012 } 3303 if (captures) {
3013 if (context_.scratch_) { 3304 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
3014 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, 3305 return queue_unsupported(__LINE__);
3015 VkDeviceSize& offset) { 3306 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
3307 // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission.
3016 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3308 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3017 if (!scratch_guard.active) { 3309 batch = context_.predicate_reducer_->batch(captures);
3018 context_.scratch_->collect(); 3310 if (!batch) return queue_unsupported(__LINE__);
3019 scratch_guard.active = true; 3311 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
3312 return batch->prepare(buffer, offset, out);
3313 };
3314 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) {
3315 context_.predicate_reducer_->capture(cb, p);
3316 };
3317 if (context_.predicated_copier_) {
3318 copy_batch = context_.predicated_copier_->batch();
3319 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src,
3320 VkDeviceSize dst, VkDeviceSize size,
3321 std::vector<PredicatedCopyDispatch>& out) {
3322 return copy_batch->prepare(source, destination, src, dst, size, out);
3323 };
3324 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3325 context_.predicated_copier_->emit(cb, jobs);
3326 };
3020 } 3327 }
3021 return context_.scratch_->get(bytes, buffer, offset); 3328 }
3022 }; 3329 if (context_.scratch_) {
3023 } 3330 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
3024 if (kind_ != QueueKind::copy && context_.indirect_clamp_) { 3331 VkDeviceSize& offset) {
3025 // The record scratch belongs to this submission: collected here, retired below with its ticket. The 3332 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3026 // counter slots are read back once that ticket completes (the batch's destructor). 3333 if (!scratch_guard.active) {
3027 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( 3334 scratch_guard.scratch = context_.scratch_.get();
3028 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, 3335 context_.scratch_->collect();
3029 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, 3336 scratch_guard.active = true;
3030 std::uint32_t max_count, ClampedIndirect& out) { 3337 }
3031 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3338 return context_.scratch_->get(bytes, buffer, offset);
3032 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3339 };
3033 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); 3340 }
3034 if (!clamp_guard.active) { 3341 if (kind_ != QueueKind::copy && context_.indirect_clamp_) {
3035 context_.indirect_clamp_->collect(); 3342 // The record scratch belongs to this submission: collected here, retired below with its ticket. The
3036 clamp_guard.active = true; 3343 // counter slots are read back once that ticket completes (the batch's destructor).
3344 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard](
3345 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
3346 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride,
3347 std::uint32_t max_count, ClampedIndirect& out) {
3348 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3349 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3350 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch();
3351 if (!clamp_guard.active) {
3352 clamp_guard.clamp = context_.indirect_clamp_.get();
3353 context_.indirect_clamp_->collect();
3354 clamp_guard.active = true;
3355 }
3356 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride,
3357 max_count, out);
3358 };
3359 }
3360 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
3361 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
3362 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
3363 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
3364 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3365 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3366 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
3367 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3368 };
3369 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3370 context_.counted_dispatch_->emit(cb, job);
3371 };
3372 }
3373 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3374 replay.prepare_quad_indices = [this, &tracker_lock](
3375 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3376 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3377 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3378 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3379 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3380 scratch_offset, out);
3381 };
3382 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3383 context_.quad_indices_->emit(cb, job);
3384 };
3385 }
3386 if (context_.depth24_ && !transfer_only) {
3387 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3388 std::vector<Depth24Job>& parts) {
3389 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3390 if (!depth24_guard.active) {
3391 depth24_guard.d24 = context_.depth24_.get();
3392 context_.depth24_->collect();
3393 depth24_guard.active = true;
3394 }
3395 return context_.depth24_->prepare(job, parts);
3396 };
3397 }
3398 if (can_resolve_occlusion) {
3399 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3400 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3401 occlusion_resolve_->sum(cb, pool, first, count, dst, offset);
3402 };
3403 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3404 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3405 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
3406 };
3407 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
3408 VkQueryPool primitives_pool, const std::uint8_t* mesh,
3409 std::uint32_t first, std::uint32_t count, VkBuffer dst,
3410 VkDeviceSize offset) {
3411 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
3412 offset);
3413 };
3414 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3415 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3416 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
3417 };
3418 }
3419 segments = 0;
3420 statistics_segments = 0;
3421 has_queries = false;
3422 // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial).
3423 // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock
3424 // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and
3425 // workers stay alive), then re-prepare on pass 1 against current resources.
3426 PipelineCompiles compiles;
3427 replay.compiles = &compiles;
3428 ReplayResult prepare_result = ReplayResult::success;
3429 for (std::size_t i = 0; i < lists.size(); ++i) {
3430 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3431 if (result != ReplayResult::success) {
3432 prepare_result = result;
3433 break;
3037 } 3434 }
3038 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, 3435 if (prepared[i].segment_count > UINT32_MAX - segments ||
3039 out); 3436 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
3040 }; 3437 return queue_unsupported(__LINE__);
3041 } 3438 segments += prepared[i].segment_count;
3042 if (kind_ != QueueKind::copy && context_.counted_dispatch_) { 3439 statistics_segments += prepared[i].statistics_segment_count;
3043 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( 3440 has_queries = has_queries || !prepared[i].queries.empty();
3044 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, 3441 }
3045 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { 3442 if (pass == 0 && !compiles.empty()) {
3046 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3443 if (depth24_guard.active) {
3047 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3444 context_.depth24_->retire(progress_, 0);
3048 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); 3445 depth24_guard.active = false;
3049 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3050 };
3051 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3052 context_.counted_dispatch_->emit(cb, job);
3053 };
3054 }
3055 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3056 replay.prepare_quad_indices = [this, &tracker_lock](
3057 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3058 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3059 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3060 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3061 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3062 scratch_offset, out);
3063 };
3064 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3065 context_.quad_indices_->emit(cb, job);
3066 };
3067 }
3068 if (context_.depth24_ && !transfer_only) {
3069 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3070 std::vector<Depth24Job>& parts) {
3071 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3072 if (!depth24_guard.active) {
3073 context_.depth24_->collect();
3074 depth24_guard.active = true;
3075 } 3446 }
3076 return context_.depth24_->prepare(job, parts); 3447 if (scratch_guard.active) {
3077 }; 3448 context_.scratch_->retire(progress_, 0);
3078 } 3449 scratch_guard.active = false;
3079 const auto& occlusion_memory = context_.occlusion_resolve_memory_; 3450 }
3080 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; 3451 if (clamp_guard.active) {
3081 if (can_resolve_occlusion) { 3452 context_.indirect_clamp_->retire(progress_, 0);
3082 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3453 clamp_guard.active = false;
3083 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3454 }
3084 occlusion_resolve_->sum(cb, pool, first, count, dst, offset); 3455 batch.reset();
3085 }; 3456 copy_batch.reset();
3086 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3457 counted_batch.reset();
3087 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3458 clamp_batch.reset();
3088 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 3459 if (tracker_lock.owns_lock()) tracker_lock.unlock();
3089 }; 3460 resource_lock.unlock();
3090 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 3461 recycle_khr_stages(khr_guard.stages);
3091 VkQueryPool primitives_pool, const std::uint8_t* mesh, 3462 recycle_khr_as_queries(khr_guard.as_queries);
3092 std::uint32_t first, std::uint32_t count, VkBuffer dst, 3463 geometry.clear();
3093 VkDeviceSize offset) { 3464
3094 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, 3465 std::shared_ptr<void> demand;
3095 offset); 3466 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3096 }; 3467 if (context_.pipeline_workers_)
3097 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3468 compiles.build(run_compiles, context_.large_compile_budget_);
3098 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3469 else
3099 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); 3470 compiles.build_serial();
3100 }; 3471 demand.reset();
3101 } 3472 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3102 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 3473 if (compile_result != ReplayResult::success) return compile_result;
3103 std::uint32_t segments = 0, statistics_segments = 0; 3474 prior_compiles = std::move(compiles);
3104 bool has_queries = false; 3475 has_prior_compiles = true;
3105 // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of 3476 continue;
3106 // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline
3107 // states that own them alive (remove_pipeline takes it uniquely).
3108 PipelineCompiles compiles;
3109 if (context_.pipeline_workers_) replay.compiles = &compiles;
3110 ReplayResult prepare_result = ReplayResult::success;
3111 for (std::size_t i = 0; i < lists.size(); ++i) {
3112 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3113 if (result != ReplayResult::success) {
3114 prepare_result = result;
3115 break;
3116 } 3477 }
3117 if (prepared[i].segment_count > UINT32_MAX - segments || 3478 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3118 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 3479 prepare_result = context_.pipeline_workers_
3119 return queue_unsupported(__LINE__); 3480 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3120 segments += prepared[i].segment_count; 3481 run_compiles, context_.large_compile_budget_, prior)
3121 statistics_segments += prepared[i].statistics_segment_count; 3482 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3122 has_queries = has_queries || !prepared[i].queries.empty(); 3483 prepare_result, prior);
3123 } 3484 replay.compiles = nullptr;
3124 prepare_result = build_pipelines( 3485 if (prepare_result != ReplayResult::success) return prepare_result;
3125 compiles, std::span(prepared).first(lists.size()), prepare_result, 3486 break;
3126 [this](std::size_t count, const std::function<void(std::size_t)>& job) { 3487 }
3127 context_.pipeline_workers_->run(count, job);
3128 });
3129 if (prepare_result != ReplayResult::success) return prepare_result;
3130 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 3488 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
3131 std::shared_ptr<OcclusionSegmentPool>& out) { 3489 std::shared_ptr<OcclusionSegmentPool>& out) {
3132 const auto& vk = context_.vk; 3490 const auto& vk = context_.vk;
@@ -3253,6 +3611,7 @@ private:
3253 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3611 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3254 "vkEndCommandBuffer") == VK_SUCCESS; 3612 "vkEndCommandBuffer") == VK_SUCCESS;
3255 resource_lock.unlock(); 3613 resource_lock.unlock();
3614 pipeline_lock.unlock();
3256 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3615 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
3257 if (!submitted) discard(); 3616 if (!submitted) discard();
3258 if (depth24_guard.active) { 3617 if (depth24_guard.active) {
@@ -3330,6 +3689,25 @@ private:
3330 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); 3689 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED);
3331 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); 3690 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker);
3332 } 3691 }
3692 // The prelude (set_prelude): recorded here, after the set's upload and before the lists, and in either case
3693 // after the last submission of another queue that recorded one (its pass writes what these lists read, and
3694 // a pass here must not overtake it).
3695 const bool prelude = !transfer_only && context_.prelude_record_ && context_.prelude_record_(command_buffer);
3696 // LEONIDA_PRELUDE_QUEUE_WAIT=0 (an experiment): no wait for another queue's pass, so the queues do not
3697 // serialise on each other's whole submissions; a list may then read what that pass has not written yet.
3698 static const bool cross_wait = [] {
3699 const char* v = std::getenv("LEONIDA_PRELUDE_QUEUE_WAIT");
3700 return !(v && v[0] == '0' && v[1] == 0);
3701 }();
3702 {
3703 std::lock_guard lock(context_.storage_mutex_);
3704 if (cross_wait && context_.prelude_semaphore_ && context_.prelude_semaphore_ != progress_ &&
3705 context_.prelude_version_ != prelude_seen_) {
3706 waits_.push_back(context_.prelude_semaphore_);
3707 wait_values_.push_back(context_.prelude_value_);
3708 }
3709 prelude_seen_ = context_.prelude_version_;
3710 }
3333 bool wrote_readback = false; 3711 bool wrote_readback = false;
3334 VkPipelineStageFlags2 readback_stages = 0; 3712 VkPipelineStageFlags2 readback_stages = 0;
3335 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 3713 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
@@ -3386,7 +3764,8 @@ private:
3386 } 3764 }
3387 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3765 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3388 "vkEndCommandBuffer") == VK_SUCCESS; 3766 "vkEndCommandBuffer") == VK_SUCCESS;
3389 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3767 resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held
3768 pipeline_lock.unlock();
3390 const bool wait_previous = ordered_timestamps && submitted_; 3769 const bool wait_previous = ordered_timestamps && submitted_;
3391 if (wait_previous) { 3770 if (wait_previous) {
3392 waits_.push_back(progress_); 3771 waits_.push_back(progress_);
@@ -3417,6 +3796,16 @@ private:
3417 ++context_.bindless_upload_version_; 3796 ++context_.bindless_upload_version_;
3418 bindless_upload_seen_ = context_.bindless_upload_version_; 3797 bindless_upload_seen_ = context_.bindless_upload_version_;
3419 } 3798 }
3799 if (prelude) {
3800 if (submitted) {
3801 std::lock_guard lock(context_.storage_mutex_);
3802 context_.prelude_semaphore_ = progress_;
3803 context_.prelude_value_ = submitted_;
3804 ++context_.prelude_version_;
3805 prelude_seen_ = context_.prelude_version_;
3806 }
3807 if (context_.prelude_commit_) context_.prelude_commit_(submitted, context_.submitted_retire_ticket());
3808 }
3420 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one 3809 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one
3421 waits_.pop_back(); 3810 waits_.pop_back();
3422 wait_values_.pop_back(); 3811 wait_values_.pop_back();
@@ -3537,7 +3926,9 @@ private:
3537 3926
3538 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. 3927 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held.
3539 void hold(Deferred&& op) { 3928 void hold(Deferred&& op) {
3540 op.seq = context_.holds().next_seq(); 3929 // A call the worker runs (LEONIDA_SUBMIT_ASYNC) keeps the number it was queued with: what was registered
3930 // behind it (a Present) still waits for it.
3931 op.seq = async_seq_ ? async_seq_ : context_.holds().next_seq();
3541 if (op.kind != Deferred::Kind::marker) { 3932 if (op.kind != Deferred::Kind::marker) {
3542 op.waits = std::move(waits_); 3933 op.waits = std::move(waits_);
3543 op.wait_values = std::move(wait_values_); 3934 op.wait_values = std::move(wait_values_);
@@ -3548,6 +3939,7 @@ private:
3548 } 3939 }
3549 if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now(); 3940 if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now();
3550 held_.push_back(std::move(op)); 3941 held_.push_back(std::move(op));
3942 held_front_seq_.store(held_.front().seq, std::memory_order_release);
3551 context_.holds().held_changed(1); 3943 context_.holds().held_changed(1);
3552 } 3944 }
3553 3945
@@ -3594,7 +3986,21 @@ private:
3594 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } 3986 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); }
3595 3987
3596 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). 3988 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held).
3989 // With LEONIDA_SUBMIT_ASYNC another thread does not run this queue's held work: it asks the queue's worker,
3990 // which releases it and then pumps the holds itself (so a Present behind it still runs after it).
3597 bool release_ready() override { 3991 bool release_ready() override {
3992 if (async_started_.load(std::memory_order_acquire) && t_worker_of_ != this) {
3993 {
3994 std::lock_guard lock(inbox_mutex_);
3995 release_requested_ = true;
3996 }
3997 inbox_cv_.notify_one();
3998 return false;
3999 }
4000 return release_held();
4001 }
4002
4003 bool release_held() {
3598 std::vector<std::shared_ptr<void>> retired; 4004 std::vector<std::shared_ptr<void>> retired;
3599 bool released = false; 4005 bool released = false;
3600 { 4006 {
@@ -3603,8 +4009,19 @@ private:
3603 Deferred op = std::move(held_.front()); 4009 Deferred op = std::move(held_.front());
3604 held_.pop_front(); 4010 held_.pop_front();
3605 context_.holds().held_changed(-1); 4011 context_.holds().held_changed(-1);
3606 if (gpu_latency::enabled()) gpu_latency::held(int(kind_), int(op.kind), op.held_at); 4012 if (gpu_latency::enabled()) {
4013 // The wait that was pending when it was held: the fence whose Signal let it go.
4014 std::uint64_t fence = 0, value = 0;
4015 for (std::size_t i = 0; i < op.waits.size(); ++i)
4016 if (op.wait_values[i] > value) {
4017 fence = std::uint64_t(reinterpret_cast<std::uintptr_t>(op.waits[i]));
4018 value = op.wait_values[i];
4019 }
4020 gpu_latency::held(int(kind_), int(op.kind), op.held_at, fence, value);
4021 }
3607 if (!context_.is_device_lost()) run(op); 4022 if (!context_.is_device_lost()) run(op);
4023 // Only now: until it has run, the operation still counts as the oldest held one.
4024 held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release);
3608 released = true; 4025 released = true;
3609 } 4026 }
3610 drain_pins(retired); 4027 drain_pins(retired);
@@ -3629,13 +4046,22 @@ private:
3629 it = held_.erase(it); 4046 it = held_.erase(it);
3630 context_.holds().held_changed(-1); 4047 context_.holds().held_changed(-1);
3631 } 4048 }
4049 held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release);
3632 } 4050 }
3633 } 4051 }
3634 4052
3635 // Holder: the sequence number of the oldest held operation. 4053 // Holder: the sequence number of the oldest held operation.
3636 std::uint64_t oldest_held_seq() override { 4054 std::uint64_t oldest_held_seq() override {
3637 std::lock_guard state(state_mutex_); 4055 if (!async_on()) {
3638 return held_.empty() ? 0 : held_.front().seq; 4056 std::lock_guard state(state_mutex_);
4057 return held_.empty() ? 0 : held_.front().seq;
4058 }
4059 // Not under state_mutex_, which the worker holds while it replays: the front's number is kept apart.
4060 std::uint64_t oldest = held_front_seq_.load(std::memory_order_acquire);
4061 std::lock_guard lock(inbox_mutex_);
4062 const std::uint64_t queued = running_seq_ ? running_seq_ : inbox_.empty() ? 0 : inbox_.front().seq;
4063 if (queued && (!oldest || queued < oldest)) oldest = queued;
4064 return oldest;
3639 } 4065 }
3640 4066
3641 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is 4067 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is
@@ -3661,6 +4087,7 @@ private:
3661 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); 4087 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence);
3662 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size())); 4088 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size()));
3663 dropped.swap(held_); 4089 dropped.swap(held_);
4090 held_front_seq_.store(0, std::memory_order_release);
3664 } 4091 }
3665 // The pins (fences, pipeline states) are released here, outside the lock. 4092 // The pins (fences, pipeline states) are released here, outside the lock.
3666 } 4093 }
@@ -3795,8 +4222,12 @@ private:
3795 pending_bindings_.push_back(std::move(pending)); 4222 pending_bindings_.push_back(std::move(pending));
3796 { 4223 {
3797 std::lock_guard lock(context_.submit_mutex()); 4224 std::lock_guard lock(context_.submit_mutex());
3798 const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE), 4225 VkResult bound;
3799 "vkQueueBindSparse"); 4226 {
4227 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
4228 bound = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE);
4229 }
4230 const auto result = context_.observe_result(bound, "vkQueueBindSparse");
3800 if (result != VK_SUCCESS) { 4231 if (result != VK_SUCCESS) {
3801 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 4232 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3802 pending_bindings_.pop_back(); 4233 pending_bindings_.pop_back();
@@ -4020,10 +4451,32 @@ private:
4020 if (diagnostics) pass_trace(*diagnostics); 4451 if (diagnostics) pass_trace(*diagnostics);
4021 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. 4452 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss.
4022 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); 4453 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics));
4023 const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); 4454 DeviceFaultDiagnostics* const ring = context_.device_fault();
4024 res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence), 4455 std::size_t ring_at = 0;
4456 const std::int64_t submit_start = diagnostic_ms();
4457 if (ring) {
4458 SubmitRecord record;
4459 record.at_ms = submit_start;
4460 record.queue = queue_;
4461 record.kind = kind_ == QueueKind::direct ? "direct" : kind_ == QueueKind::compute ? "compute" : "copy";
4462 record.progress = progress_;
4463 record.ticket = ticket;
4464 record.buffers = submit.commandBufferCount;
4465 if (signals_fence) {
4466 record.fence = fence;
4467 record.fence_value = value;
4468 }
4469 record.waits = std::uint32_t(semaphores.size());
4470 for (std::size_t i = 0; i < semaphores.size() && i < SubmitRecord::max_waits; ++i) {
4471 record.wait_semaphores[i] = semaphores[i];
4472 record.wait_values[i] = values[i];
4473 }
4474 ring_at = ring->begin_submit(record);
4475 }
4476 res = context_.observe_result(context_.queue_submit(queue_, 1, &submit, context_.gpu_labels_.submit_fence(command_buffer)),
4025 "vkQueueSubmit"); 4477 "vkQueueSubmit");
4026 context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); 4478 context_.gpu_labels_.submitted(command_buffer, res == VK_SUCCESS);
4479 if (ring) ring->end_submit(ring_at, diagnostic_ms() - submit_start, res);
4027 if (res == VK_SUCCESS) { 4480 if (res == VK_SUCCESS) {
4028 context_.record_submit_locked(progress_, ticket); 4481 context_.record_submit_locked(progress_, ticket);
4029 if (signals_fence) context_.holds().signaled(fence, value); 4482 if (signals_fence) context_.holds().signaled(fence, value);
@@ -4062,6 +4515,7 @@ private:
4062 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 4515 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
4063 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for 4516 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
4064 std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for 4517 std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for
4518 std::uint64_t prelude_seen_ = 0; // the prelude_version_ this queue has waited for (or recorded)
4065 std::uint64_t last_sparse_ = 0; 4519 std::uint64_t last_sparse_ = 0;
4066 std::deque<PendingBindings> pending_bindings_; 4520 std::deque<PendingBindings> pending_bindings_;
4067 std::vector<VkSemaphore> waits_; 4521 std::vector<VkSemaphore> waits_;
@@ -4071,8 +4525,260 @@ private:
4071 std::vector<PreparedList> prepared_; 4525 std::vector<PreparedList> prepared_;
4072 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 4526 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
4073 bool ok_ = false; 4527 bool ok_ = false;
4074 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and 4528 // ---- LEONIDA_SUBMIT_ASYNC=<n>: the queue's calls run on a worker of its own -----------------------------------
4075 // guards the members above that execute, signal, wait and marker touch. 4529 // ExecuteCommandLists, Signal, Wait and the markers are queued in call order and return at once; one worker per
4530 // queue runs each through the synchronous path (execute_sync & co.), so the replay, the before-submission
4531 // refreshes and vkQueueSubmit leave the caller's thread and overlap with its next frame. At most n batches wait per
4532 // queue; the caller of the next one waits for room (the in-flight bound). A queued call counts as held work
4533 // (QueueHolds), numbered when it was called, so a Present behind it still waits for it and cross-queue order is
4534 // the call order. Calls that use the queue's state at once (tile mappings, idle, the destructor) first wait for
4535 // what is queued. A batch that fails is reported as a held one is (stderr, take_held_failure()). Off (0) by
4536 // default: every call runs on the caller's thread, as before.
4537 static unsigned async_depth() {
4538 static const unsigned depth = [] {
4539 const char* v = std::getenv("LEONIDA_SUBMIT_ASYNC");
4540 const int n = v && *v ? std::atoi(v) : 0;
4541 return n > 0 ? unsigned(n) : 0u;
4542 }();
4543 return depth;
4544 }
4545
4546 bool async_on() const { return async_depth() && !synchronous_; }
4547
4548 struct Call {
4549 enum class Kind : std::uint8_t { execute, signal, wait, marker };
4550 Kind kind = Kind::execute;
4551 std::uint64_t seq = 0, execute_call = 0, value = 0;
4552 std::vector<CommandList> lists; // copies: the application may Reset its lists after the call
4553 std::shared_ptr<void> pin; // the fence, or the lists' pipeline states and root signatures
4554 VkSemaphore fence = VK_NULL_HANDLE;
4555 DebugMarker::Kind marker_kind = DebugMarker::Kind::set;
4556 std::string label;
4557 std::chrono::steady_clock::time_point queued_at{};
4558 };
4559
4560 struct AsyncStats { // under inbox_mutex_, since the last line
4561 std::uint64_t calls = 0, batches = 0, room_waits = 0, room_wait_ns = 0, run_ns = 0, lag_ns = 0, lag_max_ns = 0;
4562 std::size_t depth_max = 0;
4563 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now();
4564 };
4565
4566 void enqueue(Call&& call) {
4567 const bool batch = call.kind == Call::Kind::execute;
4568 std::unique_lock lock(inbox_mutex_);
4569 if (!worker_.joinable()) {
4570 worker_ = std::thread([this] { async_worker(); });
4571 async_started_.store(true, std::memory_order_release);
4572 }
4573 // n batches, and 4n calls of any kind (a title that signals after every small job must not queue Signals
4574 // without bound). n = 1 makes each caller wait for the batch before it: n should be 2 or more.
4575 const auto room = [this, batch] {
4576 return async_stop_ ||
4577 ((!batch || inbox_batches_ < async_depth()) && inbox_.size() < 4 * std::size_t(async_depth()));
4578 };
4579 if (!room()) {
4580 const auto start = std::chrono::steady_clock::now();
4581 room_cv_.wait(lock, room);
4582 ++async_stats_.room_waits;
4583 async_stats_.room_wait_ns += std::uint64_t(
4584 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count());
4585 }
4586 if (batch) {
4587 ++inbox_batches_;
4588 ++async_stats_.batches;
4589 }
4590 ++async_stats_.calls;
4591 call.seq = context_.holds().next_seq();
4592 call.queued_at = std::chrono::steady_clock::now();
4593 context_.holds().held_changed(1);
4594 inbox_.push_back(std::move(call));
4595 async_stats_.depth_max = std::max(async_stats_.depth_max, inbox_.size());
4596 lock.unlock();
4597 inbox_cv_.notify_one();
4598 }
4599
4600 void async_worker() {
4601 t_worker_of_ = this;
4602 for (;;) {
4603 Call call;
4604 bool have = false, release = false;
4605 {
4606 std::unique_lock lock(inbox_mutex_);
4607 inbox_cv_.wait(lock, [this] { return !inbox_.empty() || release_requested_ || async_stop_; });
4608 release = std::exchange(release_requested_, false);
4609 if (!inbox_.empty()) {
4610 call = std::move(inbox_.front());
4611 inbox_.pop_front();
4612 running_seq_ = call.seq;
4613 have = true;
4614 } else if (!release) {
4615 return; // stopping, nothing queued
4616 }
4617 worker_busy_ = true;
4618 }
4619 if (release) release_held();
4620 std::uint64_t ran_ns = 0;
4621 if (have) {
4622 const auto start = std::chrono::steady_clock::now();
4623 run_call(call);
4624 const auto end = std::chrono::steady_clock::now();
4625 ran_ns = std::uint64_t(std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count());
4626 const auto lag = std::uint64_t(
4627 std::chrono::duration_cast<std::chrono::nanoseconds>(start - call.queued_at).count());
4628 std::lock_guard lock(inbox_mutex_);
4629 async_stats_.run_ns += ran_ns;
4630 async_stats_.lag_ns += lag;
4631 async_stats_.lag_max_ns = std::max(async_stats_.lag_max_ns, lag);
4632 }
4633 {
4634 std::lock_guard lock(inbox_mutex_);
4635 running_seq_ = 0;
4636 worker_busy_ = false;
4637 if (have && call.kind == Call::Kind::execute) --inbox_batches_;
4638 if (have) room_cv_.notify_all();
4639 idle_cv_.notify_all();
4640 report_async_locked();
4641 }
4642 if (have) context_.holds().held_changed(-1);
4643 call = Call{}; // the copies and pins go before the pump, outside the lock
4644 context_.holds().pump_ready();
4645 }
4646 }
4647
4648 // An exception on the worker would end the process (std::terminate) and leave the queue's callers waiting: it is
4649 // turned into a held failure and a lost device instead, as a failed submission would be, and the worker goes on
4650 // (each later call fails at once on the lost device).
4651 void run_call(Call& call) {
4652 try {
4653 run_call_unguarded(call);
4654 } catch (const std::exception& e) {
4655 worker_threw(call, e.what());
4656 } catch (...) {
4657 worker_threw(call, "not a std::exception");
4658 }
4659 async_seq_ = 0;
4660 }
4661
4662 void worker_threw(const Call& call, const char* what) {
4663 int none = static_cast<int>(ReplayResult::success);
4664 held_failure_.compare_exchange_strong(none, static_cast<int>(ReplayResult::unsupported));
4665 std::fprintf(stderr, "[rt] d3d12: the queue's worker caught an exception running a queued %s (%s); the device is "
4666 "marked lost\n",
4667 call.kind == Call::Kind::execute ? "ExecuteCommandLists"
4668 : call.kind == Call::Kind::signal ? "Signal"
4669 : call.kind == Call::Kind::wait ? "Wait"
4670 : "marker",
4671 what);
4672 context_.mark_device_lost();
4673 }
4674
4675 void run_call_unguarded(Call& call) {
4676 async_seq_ = call.seq;
4677 const PinFn pin = call.pin ? PinFn([&call] { return call.pin; }) : PinFn{};
4678 switch (call.kind) {
4679 case Call::Kind::execute: {
4680 std::vector<const CommandList*> lists;
4681 lists.reserve(call.lists.size());
4682 for (const CommandList& list : call.lists) lists.push_back(&list);
4683 const ReplayResult result = execute_sync(lists, pin, call.execute_call);
4684 if (result != ReplayResult::success) {
4685 int none = static_cast<int>(ReplayResult::success);
4686 held_failure_.compare_exchange_strong(none, static_cast<int>(result));
4687 std::fprintf(stderr, "[rt] d3d12: a queued ExecuteCommandLists failed on the queue's worker (result "
4688 "%d); nothing was submitted for it\n",
4689 static_cast<int>(result));
4690 }
4691 break;
4692 }
4693 case Call::Kind::signal:
4694 if (!signal_sync(call.fence, call.value, pin)) {
4695 int none = static_cast<int>(ReplayResult::success);
4696 held_failure_.compare_exchange_strong(none, static_cast<int>(ReplayResult::unsupported));
4697 std::fprintf(stderr, "[rt] d3d12: a queued Signal failed on the queue's worker\n");
4698 }
4699 break;
4700 case Call::Kind::wait: wait_sync(call.fence, call.value, pin); break;
4701 case Call::Kind::marker: marker_sync(call.marker_kind, call.label.c_str()); break;
4702 }
4703 if (call.pin && call.kind == Call::Kind::execute) {
4704 // The pipeline states stay alive until what was just submitted has completed (a held batch keeps its own).
4705 std::lock_guard state(state_mutex_);
4706 std::vector<std::shared_ptr<void>> pins{std::move(call.pin)};
4707 retire_pins(pins, submitted_);
4708 }
4709 }
4710
4711 // Every 10 s, per queue: what the worker did. Called with inbox_mutex_ held.
4712 void report_async_locked() {
4713 const auto now = std::chrono::steady_clock::now();
4714 const double s = std::chrono::duration<double>(now - async_stats_.since).count();
4715 if (s < 10.0) return;
4716 static constexpr const char* kinds[] = {"direct", "compute", "copy"};
4717 const AsyncStats& a = async_stats_;
4718 std::fprintf(stderr,
4719 "[rt] submit-async: %s queue %p: %.1f calls/s (%.1f batches/s), queued now %zu (max %zu), "
4720 "worker busy %.0f%%, call waited for the worker avg %.2f ms max %.2f ms, caller waited for "
4721 "room %llu times %.1f ms\n",
4722 kinds[int(kind_) < 3 ? int(kind_) : 0], static_cast<const void*>(this), double(a.calls) / s,
4723 double(a.batches) / s, inbox_.size(), a.depth_max, 100.0 * double(a.run_ns) / (s * 1e9),
4724 a.calls ? double(a.lag_ns) / double(a.calls) / 1e6 : 0.0, double(a.lag_max_ns) / 1e6,
4725 static_cast<unsigned long long>(a.room_waits), double(a.room_wait_ns) / 1e6);
4726 async_stats_ = AsyncStats{};
4727 }
4728
4729 // What was queued before this call has run (held work may stay held, as without the worker). A worker that does
4730 // not come back (a GPU hang inside wait_for_room, say) is reported every 10 s, and after 60 s the caller goes on
4731 // without it: false.
4732 bool flush_async() {
4733 if (!async_started_.load(std::memory_order_acquire) || t_worker_of_ == this) return true;
4734 std::unique_lock lock(inbox_mutex_);
4735 const auto idle = [this] { return inbox_.empty() && !worker_busy_; };
4736 for (int slice = 1; slice <= 6; ++slice) {
4737 if (idle_cv_.wait_for(lock, std::chrono::seconds(10), idle)) return true;
4738 std::fprintf(stderr, "[rt] d3d12: waited %d s for a queue's worker to finish what is queued (%zu calls, "
4739 "running call %llu)%s\n",
4740 slice * 10, inbox_.size(), static_cast<unsigned long long>(running_seq_),
4741 slice == 6 ? "; going on without it" : "");
4742 }
4743 return false;
4744 }
4745
4746 void stop_async() {
4747 if (!async_started_.load(std::memory_order_acquire)) return;
4748 const bool drained = flush_async();
4749 {
4750 std::lock_guard lock(inbox_mutex_);
4751 async_stop_ = true;
4752 }
4753 inbox_cv_.notify_all();
4754 room_cv_.notify_all();
4755 if (!worker_.joinable()) return;
4756 if (drained) {
4757 worker_.join();
4758 return;
4759 }
4760 // A worker stuck for a minute holds this queue's objects: it is left running rather than joined forever
4761 // (only at teardown; the process is ending or the device is gone).
4762 std::fprintf(stderr, "[rt] d3d12: a queue's worker did not finish; it is detached at the queue's destruction\n");
4763 worker_.detach();
4764 }
4765
4766 std::mutex inbox_mutex_;
4767 std::condition_variable inbox_cv_, room_cv_, idle_cv_;
4768 std::deque<Call> inbox_;
4769 std::size_t inbox_batches_ = 0;
4770 std::uint64_t running_seq_ = 0; // the call the worker runs now
4771 bool worker_busy_ = false, release_requested_ = false, async_stop_ = false;
4772 AsyncStats async_stats_;
4773 std::atomic<bool> async_started_{false};
4774 bool synchronous_ = false; // make_synchronous()
4775 std::thread worker_;
4776 static inline thread_local VulkanQueue* t_worker_of_ = nullptr; // the queue whose worker this thread is
4777 static inline thread_local std::uint64_t async_seq_ = 0; // the sequence number of the call being run
4778 std::atomic<std::uint64_t> held_front_seq_{0}; // held_.front().seq, 0 when empty; see release_held()
4779
4780 // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ ->
4781 // submit_mutex_) and guards the members above that execute, signal, wait and marker touch.
4076 std::mutex state_mutex_; 4782 std::mutex state_mutex_;
4077 std::deque<Deferred> held_; 4783 std::deque<Deferred> held_;
4078 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive 4784 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive