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:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
commit154e4ec034902deffa4b89b2cbca9a949f38baec (patch)
tree1b2ef5656de42c172291bc6009efa4c510650815 /runtime/src/vulkan_backend.h
parenteb6a08cd359d98b5777e70d54d0ae8a75879495a (diff)
parent8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (diff)
Merge the #984 result (main + RT-PROTON-STORY-LOAD) into #939
The base is 8a242efeb, the merge of main and #984. 68 files conflicted; they were resolved in seven groups by one rule: the same change in two forms keeps the base's form, everything only #939 has is kept, and where the two solve one problem in two ways the base's is the frame and #939's plugs into it. A, the Xbox proxy (d3d12_xs_device.cpp/.h, d3d12_xs.cpp, d3d12_xs_pso_stream.cpp/.h, d3d12_xs_alloc_size.h, d3d12_xs_desc_clean.h, device_proxy_test.cpp, queue_proxy_test.cpp): the base's files with #939's additions ported in. Device slot 57 asks #939's NativeGraphicsFactory first and falls back to the base's proxy_create_graphics_pipeline_from_native_code on E_NOTIMPL. Kept from #939: the providers (texture lease, raw texture view, resource by address, constant view, descriptor mapping, depth-stencil UAV, texture pages), the title-backed descriptor mirror, slot 13's feature answers, GPU labels on list slots 71/72. Dropped: #939's duplicates of the boot ladder routes, its fallback window, its slot 133 stand-in. A2 (xs_proxy_mock_test.cpp): the base's test with #939's slot 70 raw-buffer case; presentation cases follow #939's rule that a device which ever had a handler has no queue fallback. B1, the Vulkan device (d3d12_vulkan_device.cpp, d3d12_com.cpp/.h, shader_library.h, queue_families.h, pipeline_cache_file.h, startup_trace.h): one lazy-pipeline mechanism, the base's; #939's pending_base_compile and first_use_backend_pipelines dropped, prepare_on_bind and cold_graphics_compile kept. create_texture keeps the base's signature; #939's deferred backing is folded into the base's placed-memory binder. #939's quad lists as triangle indices. B2, the D3D12 tests (d3d12_existing_heap, a8_dimensions, pipeline_cache_seed, title_va, rect_list, shader_library, loader_tls_index0, draw, compute, xmem_placed, shader_library_corpus): the base's tests where both carry the same case, #939's cases added (rebound tables, linear texture map, large vertex batch, executable shaders, default A8 views). C, the backend (vulkan_replay.h, vulkan_backend.h, vulkan_bindless.h, vulkan_scratch.h, vulkan_present.h, rect_list_geometry.h, vk_test_device.h, vk_pipeline_check.cpp, vk_store_test.cpp, bindless_sizing_test.cpp, replay_texture_barrier_test.cpp): the base's prepare_draw and lazy compute, its #1055 release rule and its rectangle generator; #939's rectangle variants, GPU quad index expansion, 1D/3D and depth-stencil UAVs, the label fence on the base's submit. D, memory, services, presentation (xmem.cpp/.h, xg_xs.cpp, xg_xs_test.cpp, title_va_alias.h and its test, main.cpp, frame_pacer.h, xbox_present.cpp/.h; xgameruntime_offline.cpp for one comment): the base's xmem with #939's label hooks, file-backed sections and pin_mapped_data; both texture computers in xg_xs.cpp, the base's answering first; --first-run-ui kept without host speech in its profile. E, build, tools, docs (runtime/CMakeLists.txt, make_game.py, tools/rdna2spirv.py, tools/shader_disasm.py, scripts, tests, docs; docs/README.md and tests/test_exe_shaders_stage.py beyond the conflicts): the base's v_dot4 decode, #281's disassembler form and tests/semantic/test_fspx_dot4_op_sel_disasm.py dropped; the base's executable-shader step with #939's cache fix; 366 registered tests. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h375
1 files changed, 316 insertions, 59 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 87ae6f436..b89c005c0 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -12,17 +12,20 @@
12#endif 12#endif
13#include "binary_occlusion_spirv.h" 13#include "binary_occlusion_spirv.h"
14#include "buffer_va_index.h" 14#include "buffer_va_index.h"
15#include "image_memory.h"
15#include "occlusion_sum_spirv.h" 16#include "occlusion_sum_spirv.h"
16#include "queue_holds.h" 17#include "queue_holds.h"
17#include "retire_tickets.h" 18#include "retire_tickets.h"
18#include "statistics_sum_spirv.h" 19#include "statistics_sum_spirv.h"
19#include "vulkan13_features.h" 20#include "vulkan13_features.h"
20#include "vulkan_depth24.h" 21#include "vulkan_depth24.h"
22#include "vulkan_title_image_pool.h"
21#include "vulkan_indirect_dispatch_count.h" 23#include "vulkan_indirect_dispatch_count.h"
22#include "vulkan_scratch.h" 24#include "vulkan_scratch.h"
23#include "vulkan_replay.h" 25#include "vulkan_replay.h"
24#include "queue_families.h" 26#include "queue_families.h"
25#include "resource_tiling.h" 27#include "resource_tiling.h"
28#include "pipeline_profile.h"
26#include "xdxr_build.h" 29#include "xdxr_build.h"
27 30
28#include <algorithm> 31#include <algorithm>
@@ -47,6 +50,15 @@
47 50
48namespace leonida { 51namespace leonida {
49 52
53// Which check of the queue's replay refused a batch ("ExecuteCommandLists failed: unsupported"), by source line,
54// the first time each one does. The batch is then not submitted at all.
55inline ReplayResult queue_unsupported(int line) {
56 static std::atomic<bool> seen[4096];
57 if (line < 0 || line >= 4096 || !seen[line].exchange(true, std::memory_order_relaxed))
58 std::fprintf(stderr, "[rt] d3d12: queue replay refused a batch at vulkan_backend.h:%d\n", line);
59 return ReplayResult::unsupported;
60}
61
50// A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes. 62// A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes.
51// Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame. 63// Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame.
52struct KhrInstanceStage { 64struct KhrInstanceStage {
@@ -102,6 +114,7 @@ struct VulkanDeviceFunctions {
102 X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ 114 X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \
103 X(vkCmdPushConstants) X(vkCmdDispatch) \ 115 X(vkCmdPushConstants) X(vkCmdDispatch) \
104 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 116 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
117 X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \
105 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 118 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
106 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 119 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
107 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 120 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
@@ -426,6 +439,7 @@ private:
426}; 439};
427 440
428struct SparseResource; 441struct SparseResource;
442using ImageMemory = ImageMemoryPool<VkDeviceMemory>;
429 443
430// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. 444// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore.
431class DeferredDeletionQueue { 445class DeferredDeletionQueue {
@@ -435,8 +449,10 @@ public:
435 image_view, 449 image_view,
436 image, 450 image,
437 sparse_resource, 451 sparse_resource,
452 pooled_title_image,
438 buffer, 453 buffer,
439 device_memory, 454 device_memory,
455 image_memory, // an ImageMemory::Range*, deleted: its bytes go back to their block
440 acceleration_structure, 456 acceleration_structure,
441 framebuffer, 457 framebuffer,
442 }; 458 };
@@ -512,6 +528,9 @@ public:
512 case Kind::image: 528 case Kind::image:
513 vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); 529 vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr);
514 break; 530 break;
531 case Kind::pooled_title_image:
532 delete reinterpret_cast<PooledTitleImage*>(item.handle);
533 break;
515 case Kind::sparse_resource: 534 case Kind::sparse_resource:
516 // Releases the resource and its page backing together after outstanding submissions. 535 // Releases the resource and its page backing together after outstanding submissions.
517 delete reinterpret_cast<std::shared_ptr<SparseResource>*>(item.handle); 536 delete reinterpret_cast<std::shared_ptr<SparseResource>*>(item.handle);
@@ -522,6 +541,9 @@ public:
522 case Kind::device_memory: 541 case Kind::device_memory:
523 vk.vkFreeMemory(device, reinterpret_cast<VkDeviceMemory>(item.handle), nullptr); 542 vk.vkFreeMemory(device, reinterpret_cast<VkDeviceMemory>(item.handle), nullptr);
524 break; 543 break;
544 case Kind::image_memory:
545 delete reinterpret_cast<ImageMemory::Range*>(item.handle);
546 break;
525 case Kind::acceleration_structure: 547 case Kind::acceleration_structure:
526 if (vk.vkDestroyAccelerationStructureKHR) 548 if (vk.vkDestroyAccelerationStructureKHR)
527 vk.vkDestroyAccelerationStructureKHR( 549 vk.vkDestroyAccelerationStructureKHR(
@@ -550,6 +572,22 @@ private:
550 void* bindless_release_user_ = nullptr; 572 void* bindless_release_user_ = nullptr;
551}; 573};
552 574
575// Sets a device's lost flag and says so once, on stderr, at the moment it is first seen. From then on every fence of
576// the device reads UINT64_MAX and device calls return DXGI_ERROR_DEVICE_REMOVED, so a title takes its own
577// device-removed path (on the retail boot an int3 at game_scarlett_master.exe+0x2474606, reached from its frame wait
578// reading a fence's completed value as ~0); without this line that later stop is the first sign of the loss.
579// True when this call set the flag. device_lost_reports counts the lines said in this process (for tests).
580inline std::atomic<unsigned> device_lost_reports{0};
581inline bool set_device_lost(std::atomic<bool>& flag, const char* where) noexcept {
582 if (flag.exchange(true, std::memory_order_acq_rel)) return false;
583 device_lost_reports.fetch_add(1, std::memory_order_relaxed);
584 std::fprintf(stderr,
585 "[rt] vulkan: the device was lost (%s); its fences now read UINT64_MAX and device calls return "
586 "DXGI_ERROR_DEVICE_REMOVED\n",
587 where);
588 return true;
589}
590
553// Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT). 591// Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT).
554// Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0 592// Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0
555// wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true. 593// wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true.
@@ -601,6 +639,8 @@ public:
601 FenceWaitDispatcher(const FenceWaitDispatcher&) = delete; 639 FenceWaitDispatcher(const FenceWaitDispatcher&) = delete;
602 FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete; 640 FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete;
603 641
642 void set_device_fault(DeviceFaultDiagnostics* diagnostics) { diagnostics_ = diagnostics; }
643
604 void set_signal_event_fn(SignalEventFn fn) { 644 void set_signal_event_fn(SignalEventFn fn) {
605 std::lock_guard lock(mutex_); 645 std::lock_guard lock(mutex_);
606 signal_event_ = fn; 646 signal_event_ = fn;
@@ -777,7 +817,8 @@ private:
777 VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 817 VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
778 si.semaphore = wakeup_sem_; 818 si.semaphore = wakeup_sem_;
779 si.value = next; 819 si.value = next;
780 vk_.vkSignalSemaphore(device_, &si); 820 DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkSignalSemaphore(device_, &si),
821 "vkSignalSemaphore (fence wakeup)");
781 } 822 }
782 823
783 void run() { 824 void run() {
@@ -814,7 +855,8 @@ private:
814 // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes 855 // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes
815 // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the 856 // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the
816 // same wait; completions still wake it at once through the ANY wait. 857 // same wait; completions still wake it at once through the ANY wait.
817 const VkResult res = vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs); 858 const VkResult res = DeviceFaultDiagnostics::observe(
859 diagnostics_, vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs), "vkWaitSemaphores (fence dispatcher)");
818 860
819 lock.lock(); 861 lock.lock();
820 waiting_ = false; 862 waiting_ = false;
@@ -822,7 +864,7 @@ private:
822 epoch_cv_.notify_all(); 864 epoch_cv_.notify_all();
823 865
824 if (res == VK_ERROR_DEVICE_LOST || device_lost_.load(std::memory_order_acquire)) { 866 if (res == VK_ERROR_DEVICE_LOST || device_lost_.load(std::memory_order_acquire)) {
825 device_lost_.store(true, std::memory_order_release); 867 set_device_lost(device_lost_, "vkWaitSemaphores in the fence dispatcher returned VK_ERROR_DEVICE_LOST");
826 std::vector<Entry> drained = std::move(pending_); 868 std::vector<Entry> drained = std::move(pending_);
827 pending_.clear(); 869 pending_.clear();
828 dispatch_outside_lock(lock, drained, signal_event_); 870 dispatch_outside_lock(lock, drained, signal_event_);
@@ -835,7 +877,9 @@ private:
835 std::size_t write = 0; 877 std::size_t write = 0;
836 for (std::size_t i = 0; i < pending_.size(); ++i) { 878 for (std::size_t i = 0; i < pending_.size(); ++i) {
837 std::uint64_t done = 0; 879 std::uint64_t done = 0;
838 const VkResult cr = vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done); 880 const VkResult cr = DeviceFaultDiagnostics::observe(
881 diagnostics_, vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done),
882 "vkGetSemaphoreCounterValue (fence dispatcher)");
839 if (cr == VK_ERROR_DEVICE_LOST) { 883 if (cr == VK_ERROR_DEVICE_LOST) {
840 lost = true; 884 lost = true;
841 for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j])); 885 for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j]));
@@ -852,7 +896,8 @@ private:
852 pending_.resize(write); 896 pending_.resize(write);
853 for (Entry& e : pending_) ready.push_back(std::move(e)); 897 for (Entry& e : pending_) ready.push_back(std::move(e));
854 pending_.clear(); 898 pending_.clear();
855 device_lost_.store(true, std::memory_order_release); 899 set_device_lost(device_lost_,
900 "vkGetSemaphoreCounterValue in the fence dispatcher returned VK_ERROR_DEVICE_LOST");
856 dispatch_outside_lock(lock, ready, signal_event_); 901 dispatch_outside_lock(lock, ready, signal_event_);
857 return; 902 return;
858 } 903 }
@@ -867,6 +912,7 @@ private:
867 VkDevice device_; 912 VkDevice device_;
868 const VulkanDeviceFunctions& vk_; 913 const VulkanDeviceFunctions& vk_;
869 std::atomic<bool>& device_lost_; 914 std::atomic<bool>& device_lost_;
915 DeviceFaultDiagnostics* diagnostics_ = nullptr; // configured before the dispatcher starts
870 SignalEventFn signal_event_ = nullptr; 916 SignalEventFn signal_event_ = nullptr;
871 VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; 917 VkSemaphore wakeup_sem_ = VK_NULL_HANDLE;
872 std::uint64_t wakeup_val_ = 0; 918 std::uint64_t wakeup_val_ = 0;
@@ -992,6 +1038,8 @@ public:
992 replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; 1038 replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer;
993 replay_.set_viewport = vk.vkCmdSetViewport; 1039 replay_.set_viewport = vk.vkCmdSetViewport;
994 replay_.set_scissor = vk.vkCmdSetScissor; 1040 replay_.set_scissor = vk.vkCmdSetScissor;
1041 replay_.set_viewport_with_count = vk.vkCmdSetViewportWithCount;
1042 replay_.set_scissor_with_count = vk.vkCmdSetScissorWithCount;
995 replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; 1043 replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology;
996 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; 1044 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable;
997 replay_.set_stencil_reference = vk.vkCmdSetStencilReference; 1045 replay_.set_stencil_reference = vk.vkCmdSetStencilReference;
@@ -1022,7 +1070,7 @@ public:
1022 // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. 1070 // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write.
1023 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { 1071 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) {
1024 BufferVaIndex<ResourceId>::Hit hit{}; 1072 BufferVaIndex<ResourceId>::Hit hit{};
1025 if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; 1073 if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent;
1026 const ResourceBinding* b = resolve(hit.id); 1074 const ResourceBinding* b = resolve(hit.id);
1027 if (!b) return HostReadStatus::absent; 1075 if (!b) return HostReadStatus::absent;
1028 if (!b->host) return HostReadStatus::not_cpu_written; 1076 if (!b->host) return HostReadStatus::not_cpu_written;
@@ -1108,6 +1156,7 @@ public:
1108 } 1156 }
1109 1157
1110 ~VulkanContext() { 1158 ~VulkanContext() {
1159 progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away
1111 gpu_labels_.stop(device_); 1160 gpu_labels_.stop(device_);
1112 fence_dispatcher_.reset(); 1161 fence_dispatcher_.reset();
1113 deletion_queue_.drain(UINT64_MAX, device_, vk); 1162 deletion_queue_.drain(UINT64_MAX, device_, vk);
@@ -1121,6 +1170,22 @@ public:
1121 VulkanContext& operator=(const VulkanContext&) = delete; 1170 VulkanContext& operator=(const VulkanContext&) = delete;
1122 1171
1123 bool loaded() const { return loaded_; } 1172 bool loaded() const { return loaded_; }
1173
1174 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) {
1175 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled);
1176 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get());
1177 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); });
1178 }
1179
1180 void add_diagnostic_queue(VkQueue queue) {
1181 if (device_fault_) device_fault_->add_queue(queue);
1182 }
1183
1184 DeviceFaultDiagnostics* device_fault() const { return device_fault_.get(); }
1185
1186 VkResult observe_result(VkResult result, const char* operation) const noexcept {
1187 return DeviceFaultDiagnostics::observe(device_fault_.get(), result, operation);
1188 }
1124 void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, 1189 void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
1125 VkDeviceSize max_range, std::uint32_t family) { 1190 VkDeviceSize max_range, std::uint32_t family) {
1126 std::unique_lock lock(resource_mutex_); 1191 std::unique_lock lock(resource_mutex_);
@@ -1166,10 +1231,9 @@ public:
1166 set_resource_locked(id, binding); 1231 set_resource_locked(id, binding);
1167 } 1232 }
1168 // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). 1233 // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches).
1169 bool knows_buffer_va(std::uint64_t va) { 1234 bool knows_buffer_va(std::uint64_t va, std::uint64_t bytes = 1) {
1170 std::shared_lock lock(resource_mutex_); 1235 std::shared_lock lock(resource_mutex_);
1171 BufferVaIndex<ResourceId>::Hit hit{}; 1236 return buffer_vas_.covers(va, bytes);
1172 return buffer_vas_.find(va, hit);
1173 } 1237 }
1174 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { 1238 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) {
1175 std::unique_lock rlock(resource_mutex_); 1239 std::unique_lock rlock(resource_mutex_);
@@ -1305,6 +1369,11 @@ public:
1305 replay_.zero_size = size; 1369 replay_.zero_size = size;
1306 } 1370 }
1307 1371
1372 void set_depth_range_unrestricted(bool enabled) {
1373 std::unique_lock lock(resource_mutex_);
1374 replay_.depth_range_unrestricted = enabled;
1375 }
1376
1308 struct GeometryUpload { 1377 struct GeometryUpload {
1309 std::uint64_t source{}, size{}; 1378 std::uint64_t source{}, size{};
1310 VkBuffer buffer{}; 1379 VkBuffer buffer{};
@@ -1342,24 +1411,77 @@ public:
1342 } 1411 }
1343 1412
1344 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1413 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1345 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline) { 1414 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1346 std::unique_lock lock(resource_mutex_); 1415 std::unique_lock lock(resource_mutex_);
1347 pipelines_[id] = pipeline; 1416 pipelines_[id] = pipeline;
1417 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1348 } 1418 }
1349 void remove_pipeline(std::uintptr_t id) { 1419 void remove_pipeline(std::uintptr_t id) {
1350 std::unique_lock lock(resource_mutex_); 1420 std::unique_lock lock(resource_mutex_);
1351 pipelines_.erase(id); 1421 pipelines_.erase(id);
1352 graphics_pipelines_.erase(id); 1422 graphics_pipelines_.erase(id);
1423 if (device_fault_) device_fault_->pipeline_names.erase(id);
1353 } 1424 }
1354 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline) { 1425 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1426 const CheckpointShaders* shaders = nullptr) {
1355 std::unique_lock lock(resource_mutex_); 1427 std::unique_lock lock(resource_mutex_);
1356 graphics_pipelines_[id] = pipeline; 1428 graphics_pipelines_[id] = pipeline;
1429 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1357 } 1430 }
1358 // Configure before queue creation, when the selected queue family supports compute. 1431 // Configure before queue creation, when the selected queue family supports compute.
1359 void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { 1432 void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) {
1360 occlusion_resolve_memory_ = memory; 1433 occlusion_resolve_memory_ = memory;
1361 } 1434 }
1362 1435
1436 struct HostTextureStats { std::uint64_t copies = 0, waits = 0; };
1437 HostTextureStats host_texture_stats() {
1438 std::lock_guard lock(submit_mutex_);
1439 return host_texture_stats_;
1440 }
1441
1442 // CPU writes to a title texture have no application fence. Prevent another queue from
1443 // claiming a new layout or submitting work between the completion check and the host copy.
1444 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues.
1445 template<class Copy>
1446 VkResult write_host_texture(ResourceId id, std::uint32_t subresource, Copy&& copy) {
1447 std::lock_guard layout_lock(tracker_mutex_);
1448 std::lock_guard queue_lock(submit_mutex_);
1449 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY;
1450 if (image_work_pending_) {
1451 ++host_texture_stats_.waits;
1452 const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)");
1453 if (result != VK_SUCCESS) return result;
1454 image_work_pending_ = false;
1455 }
1456 if (!copy()) return VK_ERROR_UNKNOWN;
1457 ++host_texture_stats_.copies;
1458 return VK_SUCCESS;
1459 }
1460
1461 // A complete CPU-side replacement of these color subresources. Serialize with replay and
1462 // present while recording the old layouts, finishing prior reads and publishing the copy.
1463 template<class Copy>
1464 VkResult write_staged_title_image(ResourceId id, const VkImageSubresourceRange& range, Copy&& copy) {
1465 std::lock_guard layout_lock(tracker_mutex_);
1466 std::lock_guard queue_lock(submit_mutex_);
1467 LayoutPieces pieces;
1468 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN;
1469 if (image_work_pending_) {
1470 const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)");
1471 if (r != VK_SUCCESS) return r;
1472 image_work_pending_ = false;
1473 }
1474 const auto r = observe_result(copy(replay_, pieces), "title staging upload");
1475 if (r == VK_SUCCESS) {
1476 for (const auto& p : pieces)
1477 if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) tracker_.set(id, p.range, VK_IMAGE_LAYOUT_GENERAL);
1478 }
1479 return r;
1480 }
1481
1482 // Present and probe submissions have their own fences, outside the queue retirement timelines.
1483 void note_image_work_locked() { image_work_pending_ = true; }
1484
1363 // For tests and traces. 1485 // For tests and traces.
1364 VkImageLayout layout(ResourceId id, std::uint32_t subresource) { 1486 VkImageLayout layout(ResourceId id, std::uint32_t subresource) {
1365 std::lock_guard lock(tracker_mutex_); 1487 std::lock_guard lock(tracker_mutex_);
@@ -1485,6 +1607,29 @@ public:
1485 if (table_scanner_) table_scanner_(va, descriptors); 1607 if (table_scanner_) table_scanner_(va, descriptors);
1486 } 1608 }
1487 1609
1610 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1611 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1612 // Set once, before the first queue exists.
1613 using InputProbe = std::function<void(std::span<const CommandList* const>, std::uint64_t, const char*)>;
1614 void set_input_probe(InputProbe probe) { input_probe_ = std::move(probe); }
1615 bool diagnostic_buffer(std::uint64_t va, std::uint64_t& host, std::uint64_t& room) {
1616 std::shared_lock lock(resource_mutex_);
1617 BufferVaIndex<ResourceId>::Hit hit{};
1618 if (!buffer_vas_.find(va, hit)) return false;
1619 const auto* b = resolve(hit.id);
1620 if (!b || va - b->va >= b->size) return false;
1621 const auto offset = va - b->va;
1622 host = b->host ? reinterpret_cast<std::uint64_t>(b->host + offset) : 0;
1623 room = b->size - offset;
1624 return true;
1625 }
1626 const char* diagnostic_compute_name(std::uintptr_t id) {
1627 std::shared_lock lock(resource_mutex_);
1628 if (!device_fault_) return nullptr;
1629 const auto it = device_fault_->pipeline_names.find(id);
1630 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
1631 }
1632
1488 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1633 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1489 std::unique_lock lock(resource_mutex_); 1634 std::unique_lock lock(resource_mutex_);
1490 bindless_prepare_ = std::move(prepare); 1635 bindless_prepare_ = std::move(prepare);
@@ -1495,7 +1640,8 @@ public:
1495 void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, 1640 void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate,
1496 std::uint64_t max_storage_range = 1u << 27) { 1641 std::uint64_t max_storage_range = 1u << 27) {
1497 std::unique_lock lock(resource_mutex_); 1642 std::unique_lock lock(resource_mutex_);
1498 depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); 1643 depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range,
1644 device_fault_.get());
1499 if (!depth24_->loaded()) { 1645 if (!depth24_->loaded()) {
1500 depth24_.reset(); 1646 depth24_.reset();
1501 return; 1647 return;
@@ -1512,7 +1658,8 @@ public:
1512 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, 1658 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate,
1513 VkBufferUsageFlags extra_usage = 0, std::vector<std::uint32_t> families = {}) { 1659 VkBufferUsageFlags extra_usage = 0, std::vector<std::uint32_t> families = {}) {
1514 std::unique_lock lock(resource_mutex_); 1660 std::unique_lock lock(resource_mutex_);
1515 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage, std::move(families)); 1661 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage, std::move(families),
1662 device_fault_.get());
1516 if (!scratch_->loaded()) scratch_.reset(); 1663 if (!scratch_->loaded()) scratch_.reset();
1517 } 1664 }
1518 1665
@@ -1576,7 +1723,8 @@ public:
1576 wait.semaphoreCount = std::uint32_t(semaphores.size()); 1723 wait.semaphoreCount = std::uint32_t(semaphores.size());
1577 wait.pSemaphores = semaphores.data(); 1724 wait.pSemaphores = semaphores.data();
1578 wait.pValues = values.data(); 1725 wait.pValues = values.data();
1579 vk.vkWaitSemaphores(device_, &wait, UINT64_MAX); // outside submit_mutex_: a signal may need it 1726 // Outside submit_mutex_: a signal may need it.
1727 observe_result(vk.vkWaitSemaphores(device_, &wait, UINT64_MAX), "vkWaitSemaphores (retirement)");
1580 } 1728 }
1581 return completed_retire_ticket(); 1729 return completed_retire_ticket();
1582 } 1730 }
@@ -1594,7 +1742,8 @@ public:
1594 if (is_device_lost()) return 0; 1742 if (is_device_lost()) return 0;
1595 ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { 1743 ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) {
1596 std::uint64_t done = 0; 1744 std::uint64_t done = 0;
1597 const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); 1745 const VkResult result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done),
1746 "vkGetSemaphoreCounterValue (retirement)");
1598 if (result == VK_ERROR_DEVICE_LOST) lost = true; 1747 if (result == VK_ERROR_DEVICE_LOST) lost = true;
1599 return result == VK_SUCCESS && done >= value; 1748 return result == VK_SUCCESS && done >= value;
1600 }); 1749 });
@@ -1615,6 +1764,7 @@ public:
1615 void record_submit_locked(VkSemaphore progress, std::uint64_t value) { 1764 void record_submit_locked(VkSemaphore progress, std::uint64_t value) {
1616 const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; 1765 const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1;
1617 retire_tickets_.record(ticket, progress, value); 1766 retire_tickets_.record(ticket, progress, value);
1767 note_image_work_locked();
1618 } 1768 }
1619 void retire_queue_idle_locked(VkSemaphore progress) { 1769 void retire_queue_idle_locked(VkSemaphore progress) {
1620 retire_tickets_.queue_idle(progress); 1770 retire_tickets_.queue_idle(progress);
@@ -1625,8 +1775,8 @@ public:
1625 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 1775 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
1626 std::mutex& submit_mutex() { return submit_mutex_; } 1776 std::mutex& submit_mutex() { return submit_mutex_; }
1627 1777
1628 void mark_device_lost() noexcept { 1778 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept {
1629 device_lost_.store(true, std::memory_order_release); 1779 set_device_lost(device_lost_, where);
1630 if (fence_dispatcher_) { 1780 if (fence_dispatcher_) {
1631 try { 1781 try {
1632 fence_dispatcher_->notify_device_lost(); 1782 fence_dispatcher_->notify_device_lost();
@@ -1686,8 +1836,11 @@ private:
1686 const auto it = resources_.find(id); 1836 const auto it = resources_.find(id);
1687 if (it == resources_.end()) return nullptr; 1837 if (it == resources_.end()) return nullptr;
1688 const auto& binding = it->second; 1838 const auto& binding = it->second;
1839 if (auto* memory = binding.deferred_memory; memory && !memory->ensure()) return nullptr;
1689 // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind. 1840 // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind.
1690 if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr; 1841 if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr;
1842 if (auto* seen = binding.replay_seen; seen && !seen->load(std::memory_order_relaxed))
1843 seen->store(true, std::memory_order_relaxed);
1691 return &binding; 1844 return &binding;
1692 } 1845 }
1693 1846
@@ -1776,6 +1929,52 @@ private:
1776 return framebuffer; 1929 return framebuffer;
1777 } 1930 }
1778 1931
1932 std::uint64_t poll_retirement_locked(VkResult& result) {
1933 return retire_tickets_.completed([&](VkSemaphore semaphore, std::uint64_t value) {
1934 std::uint64_t done = 0;
1935 result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done),
1936 "vkGetSemaphoreCounterValue (retirement)");
1937 return result == VK_SUCCESS && done >= value;
1938 });
1939 }
1940
1941 void watch_queue_progress(std::stop_token stop) {
1942 using Watch = SubmissionProgressWatch;
1943 Watch watch;
1944 std::uint64_t retired = 0;
1945 std::mutex timer_mutex;
1946 std::condition_variable_any timer;
1947 std::unique_lock timer_lock(timer_mutex);
1948 while (!stop.stop_requested()) {
1949 timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; });
1950 if (stop.stop_requested() || is_device_lost()) break;
1951 auto state = Watch::State::submit_lock_busy;
1952 VkResult result = VK_SUCCESS;
1953 std::uint64_t submitted;
1954 {
1955 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait
1956 // blocked inside the driver can hold this mutex indefinitely.
1957 std::unique_lock lock(submit_mutex_, std::try_to_lock);
1958 submitted = submitted_retire_ticket();
1959 if (lock.owns_lock()) {
1960 if (is_device_lost()) break;
1961 retired = poll_retirement_locked(result);
1962 state = retired < submitted ? Watch::State::pending : Watch::State::idle;
1963 }
1964 }
1965 if (result == VK_ERROR_DEVICE_LOST) {
1966 mark_device_lost();
1967 break;
1968 }
1969 // A failed counter query does not measure GPU progress.
1970 if (result != VK_SUCCESS) state = Watch::State::idle;
1971 if (watch.sample(state, retired, Watch::Clock::now()))
1972 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced"
1973 : "could not sample the submit lock",
1974 submitted, retired);
1975 }
1976 }
1977
1779 VkDevice device_; 1978 VkDevice device_;
1780 bool loaded_ = false; 1979 bool loaded_ = false;
1781 bool ray_tracing_ = false; 1980 bool ray_tracing_ = false;
@@ -1785,9 +1984,13 @@ private:
1785 alignas(64) std::mutex tracker_mutex_; 1984 alignas(64) std::mutex tracker_mutex_;
1786 alignas(64) std::mutex views_mutex_; 1985 alignas(64) std::mutex views_mutex_;
1787 alignas(64) std::mutex submit_mutex_; 1986 alignas(64) std::mutex submit_mutex_;
1987 bool image_work_pending_ = false; // under submit_mutex_
1988 HostTextureStats host_texture_stats_; // under submit_mutex_
1788 RetireTickets<VkSemaphore> retire_tickets_; 1989 RetireTickets<VkSemaphore> retire_tickets_;
1789 std::atomic<std::uint64_t> submitted_ticket_{0}; 1990 std::atomic<std::uint64_t> submitted_ticket_{0};
1790 DeferredDeletionQueue deletion_queue_; 1991 DeferredDeletionQueue deletion_queue_;
1992 std::unique_ptr<DeviceFaultDiagnostics> device_fault_;
1993 std::jthread progress_watch_;
1791 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; 1994 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_;
1792 QueueHolds<VkSemaphore> holds_; 1995 QueueHolds<VkSemaphore> holds_;
1793 std::unordered_map<ResourceId, ResourceBinding> resources_; 1996 std::unordered_map<ResourceId, ResourceBinding> resources_;
@@ -1816,6 +2019,7 @@ private:
1816 resolve_passes_; 2019 resolve_passes_;
1817 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; 2020 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_;
1818 std::function<void()> before_execute_; 2021 std::function<void()> before_execute_;
2022 InputProbe input_probe_;
1819 TableScanner table_scanner_; 2023 TableScanner table_scanner_;
1820 GeometryProvider geometry_provider_; 2024 GeometryProvider geometry_provider_;
1821 std::function<bool(std::uint64_t,std::uint32_t)> sample_table_resolver_; 2025 std::function<bool(std::uint64_t,std::uint32_t)> sample_table_resolver_;
@@ -1875,7 +2079,8 @@ public:
1875 std::uint64_t completed() const { 2079 std::uint64_t completed() const {
1876 if (context_.is_device_lost()) return UINT64_MAX; 2080 if (context_.is_device_lost()) return UINT64_MAX;
1877 std::uint64_t value = 0; 2081 std::uint64_t value = 0;
1878 const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); 2082 const VkResult result = context_.observe_result(
2083 context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value), "vkGetSemaphoreCounterValue");
1879 if (result == VK_ERROR_DEVICE_LOST) { 2084 if (result == VK_ERROR_DEVICE_LOST) {
1880 context_.mark_device_lost(); 2085 context_.mark_device_lost();
1881 return UINT64_MAX; 2086 return UINT64_MAX;
@@ -1891,13 +2096,15 @@ public:
1891 // it marks the context lost on a query error and prevents the dispatcher from waking. 2096 // it marks the context lost on a query error and prevents the dispatcher from waking.
1892 if (context_.is_device_lost()) return false; 2097 if (context_.is_device_lost()) return false;
1893 std::uint64_t current = 0; 2098 std::uint64_t current = 0;
1894 if (context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &current) == VK_SUCCESS && 2099 if (context_.observe_result(context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &current),
2100 "vkGetSemaphoreCounterValue") == VK_SUCCESS &&
1895 value <= current) 2101 value <= current)
1896 return false; 2102 return false;
1897 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 2103 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
1898 info.semaphore = semaphore_; 2104 info.semaphore = semaphore_;
1899 info.value = value; 2105 info.value = value;
1900 const VkResult result = context_.vk.vkSignalSemaphore(context_.device(), &info); 2106 const VkResult result = context_.observe_result(context_.vk.vkSignalSemaphore(context_.device(), &info),
2107 "vkSignalSemaphore");
1901 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 2108 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
1902 if (result != VK_SUCCESS) return false; 2109 if (result != VK_SUCCESS) return false;
1903 context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now 2110 context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now
@@ -1911,7 +2118,8 @@ public:
1911 info.semaphoreCount = 1; 2118 info.semaphoreCount = 1;
1912 info.pSemaphores = &semaphore_; 2119 info.pSemaphores = &semaphore_;
1913 info.pValues = &value; 2120 info.pValues = &value;
1914 const VkResult result = context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns); 2121 const VkResult result = context_.observe_result(
2122 context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns), "vkWaitSemaphores");
1915 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 2123 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
1916 return result == VK_SUCCESS; 2124 return result == VK_SUCCESS;
1917 } 2125 }
@@ -1984,7 +2192,7 @@ public:
1984 if (queue_) { 2192 if (queue_) {
1985 std::lock_guard lock(context_.submit_mutex()); 2193 std::lock_guard lock(context_.submit_mutex());
1986 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 2194 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
1987 const VkResult idle_result = vk.vkQueueWaitIdle(queue_); 2195 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle");
1988 if (idle_result == VK_SUCCESS) { 2196 if (idle_result == VK_SUCCESS) {
1989 if (progress_) context_.retire_queue_idle_locked(progress_); 2197 if (progress_) context_.retire_queue_idle_locked(progress_);
1990 } else { 2198 } else {
@@ -2105,18 +2313,21 @@ public:
2105 using PinFn = std::function<std::shared_ptr<void>()>; 2313 using PinFn = std::function<std::shared_ptr<void>()>;
2106 2314
2107 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { 2315 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) {
2316 auto* diagnostics = context_.device_fault();
2317 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0;
2108 ReplayResult result = ReplayResult::success; 2318 ReplayResult result = ReplayResult::success;
2109 bool held = false; 2319 bool held = false;
2110 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released 2320 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released
2111 { 2321 {
2112 std::lock_guard state(state_mutex_); 2322 std::lock_guard state(state_mutex_);
2113 if (!must_hold()) { 2323 if (!must_hold()) {
2114 result = execute_now(lists); 2324 result = execute_now(lists, execute_call);
2115 } else if (context_.is_device_lost()) { 2325 } else if (context_.is_device_lost()) {
2116 result = ReplayResult::unsupported; 2326 result = queue_unsupported(__LINE__);
2117 } else { 2327 } else {
2118 Deferred op; 2328 Deferred op;
2119 op.kind = Deferred::Kind::batch; 2329 op.kind = Deferred::Kind::batch;
2330 op.execute_call = execute_call;
2120 op.lists.reserve(lists.size()); 2331 op.lists.reserve(lists.size());
2121 for (const CommandList* list : lists) op.lists.push_back(*list); 2332 for (const CommandList* list : lists) op.lists.push_back(*list);
2122 if (pin) op.pins.push_back(pin()); 2333 if (pin) op.pins.push_back(pin());
@@ -2195,7 +2406,7 @@ public:
2195 2406
2196 bool idle() { 2407 bool idle() {
2197 std::lock_guard lock(context_.submit_mutex()); 2408 std::lock_guard lock(context_.submit_mutex());
2198 return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; 2409 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS;
2199 } 2410 }
2200 2411
2201private: 2412private:
@@ -2281,11 +2492,11 @@ private:
2281 !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || 2492 !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory ||
2282 !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || 2493 !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at ||
2283 !build.instance_count) 2494 !build.instance_count)
2284 return ReplayResult::unsupported; 2495 return queue_unsupported(__LINE__);
2285 const std::uint64_t bytes = 8ull * build.instance_count; 2496 const std::uint64_t bytes = 8ull * build.instance_count;
2286 const std::uint8_t* guest = nullptr; 2497 const std::uint8_t* guest = nullptr;
2287 const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); 2498 const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest);
2288 if (status == HostReadStatus::not_cpu_written) return ReplayResult::unsupported; 2499 if (status == HostReadStatus::not_cpu_written) return queue_unsupported(__LINE__);
2289 if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; 2500 if (status != HostReadStatus::ok) return ReplayResult::invalid_copy;
2290 2501
2291 KhrInstanceStage stage{}; 2502 KhrInstanceStage stage{};
@@ -2308,7 +2519,7 @@ private:
2308 info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | 2519 info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
2309 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; 2520 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
2310 if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) 2521 if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS)
2311 return ReplayResult::unsupported; 2522 return queue_unsupported(__LINE__);
2312 VkMemoryRequirements requirements{}; 2523 VkMemoryRequirements requirements{};
2313 funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); 2524 funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements);
2314 const auto& memory = context_.occlusion_resolve_memory_; 2525 const auto& memory = context_.occlusion_resolve_memory_;
@@ -2324,7 +2535,7 @@ private:
2324 } 2535 }
2325 if (type == memory.memoryTypeCount) { 2536 if (type == memory.memoryTypeCount) {
2326 discard(); 2537 discard();
2327 return ReplayResult::unsupported; 2538 return queue_unsupported(__LINE__);
2328 } 2539 }
2329 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; 2540 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
2330 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; 2541 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
@@ -2334,7 +2545,7 @@ private:
2334 if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || 2545 if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS ||
2335 funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { 2546 funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) {
2336 discard(); 2547 discard();
2337 return ReplayResult::unsupported; 2548 return queue_unsupported(__LINE__);
2338 } 2549 }
2339 stage.size = bytes; 2550 stage.size = bytes;
2340 } 2551 }
@@ -2342,7 +2553,7 @@ private:
2342 void* mapped = nullptr; 2553 void* mapped = nullptr;
2343 if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { 2554 if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) {
2344 discard(); 2555 discard();
2345 return ReplayResult::unsupported; 2556 return queue_unsupported(__LINE__);
2346 } 2557 }
2347 // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. 2558 // Validate and translate in one pass straight into the staging buffer; no second vector of addresses.
2348 for (std::uint32_t i = 0; i < build.instance_count; ++i) { 2559 for (std::uint32_t i = 0; i < build.instance_count; ++i) {
@@ -2368,22 +2579,25 @@ private:
2368 stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); 2579 stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address);
2369 if (!stage.address) { 2580 if (!stage.address) {
2370 discard(); 2581 discard();
2371 return ReplayResult::unsupported; 2582 return queue_unsupported(__LINE__);
2372 } 2583 }
2373 stages.push_back(std::move(stage)); 2584 stages.push_back(std::move(stage));
2374 address = stages.back().address; 2585 address = stages.back().address;
2375 return ReplayResult::success; 2586 return ReplayResult::success;
2376 } 2587 }
2377 2588
2378 ReplayResult execute_now(std::span<const CommandList* const> lists) { 2589 ReplayResult execute_now(std::span<const CommandList* const> lists, std::uint64_t execute_call) {
2379 if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; 2590 if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__);
2380 if (context_.before_execute_) context_.before_execute_(); 2591 if (context_.before_execute_) context_.before_execute_();
2592 if (context_.input_probe_)
2593 context_.input_probe_(lists, execute_call, kind_ == QueueKind::direct ? "direct" :
2594 kind_ == QueueKind::compute ? "compute" : "copy");
2381 if (kind_ != QueueKind::direct) 2595 if (kind_ != QueueKind::direct)
2382 for (const auto* list : lists) 2596 for (const auto* list : lists)
2383 for (const auto& command : list->commands()) 2597 for (const auto& command : list->commands())
2384 if (std::holds_alternative<ClearRenderTarget>(command) || 2598 if (std::holds_alternative<ClearRenderTarget>(command) ||
2385 std::holds_alternative<ClearDepthStencil>(command)) 2599 std::holds_alternative<ClearDepthStencil>(command))
2386 return ReplayResult::unsupported; 2600 return queue_unsupported(__LINE__);
2387 VkCommandBuffer command_buffer = VK_NULL_HANDLE; 2601 VkCommandBuffer command_buffer = VK_NULL_HANDLE;
2388 struct KhrGuard { 2602 struct KhrGuard {
2389 VulkanQueue* queue; 2603 VulkanQueue* queue;
@@ -2429,6 +2643,8 @@ private:
2429 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 2643 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2430 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 2644 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2431 ReplayFunctions replay = context_.replay_; 2645 ReplayFunctions replay = context_.replay_;
2646 unsigned mesh_draws = 0;
2647 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2432 std::vector<VulkanContext::GeometryUpload> geometry; 2648 std::vector<VulkanContext::GeometryUpload> geometry;
2433 if (context_.geometry_provider_) { 2649 if (context_.geometry_provider_) {
2434 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { 2650 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
@@ -2468,12 +2684,12 @@ private:
2468 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 2684 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2469 if (captures) { 2685 if (captures) {
2470 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 2686 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
2471 return ReplayResult::unsupported; 2687 return queue_unsupported(__LINE__);
2472 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 2688 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
2473 // retaining main's resource -> tracker -> submit lock order through emit and submission. 2689 // retaining main's resource -> tracker -> submit lock order through emit and submission.
2474 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2690 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2475 batch = context_.predicate_reducer_->batch(captures); 2691 batch = context_.predicate_reducer_->batch(captures);
2476 if (!batch) return ReplayResult::unsupported; 2692 if (!batch) return queue_unsupported(__LINE__);
2477 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 2693 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
2478 return batch->prepare(buffer, offset, out); 2694 return batch->prepare(buffer, offset, out);
2479 }; 2695 };
@@ -2571,7 +2787,7 @@ private:
2571 if (result != ReplayResult::success) return result; 2787 if (result != ReplayResult::success) return result;
2572 if (prepared[i].segment_count > UINT32_MAX - segments || 2788 if (prepared[i].segment_count > UINT32_MAX - segments ||
2573 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 2789 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
2574 return ReplayResult::unsupported; 2790 return queue_unsupported(__LINE__);
2575 segments += prepared[i].segment_count; 2791 segments += prepared[i].segment_count;
2576 statistics_segments += prepared[i].statistics_segment_count; 2792 statistics_segments += prepared[i].statistics_segment_count;
2577 has_queries = has_queries || !prepared[i].queries.empty(); 2793 has_queries = has_queries || !prepared[i].queries.empty();
@@ -2591,12 +2807,12 @@ private:
2591 return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS; 2807 return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS;
2592 }; 2808 };
2593 std::shared_ptr<OcclusionSegmentPool> physical, statistics; 2809 std::shared_ptr<OcclusionSegmentPool> physical, statistics;
2594 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; 2810 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return queue_unsupported(__LINE__);
2595 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before 2811 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before
2596 // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). 2812 // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then).
2597 if (statistics_segments && can_resolve_occlusion) { 2813 if (statistics_segments && can_resolve_occlusion) {
2598 if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) 2814 if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics))
2599 return ReplayResult::unsupported; 2815 return queue_unsupported(__LINE__);
2600 for (const auto& list : prepared) 2816 for (const auto& list : prepared)
2601 statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), 2817 statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(),
2602 list.statistics_mesh.end()); 2818 list.statistics_mesh.end());
@@ -2611,7 +2827,7 @@ private:
2611 info.pipelineStatistics = kMeshStatisticsFlags; 2827 info.pipelineStatistics = kMeshStatisticsFlags;
2612 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != 2828 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) !=
2613 VK_SUCCESS) 2829 VK_SUCCESS)
2614 return ReplayResult::unsupported; 2830 return queue_unsupported(__LINE__);
2615 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, 2831 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type,
2616 // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, 2832 // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature,
2617 // or the clipping field of a mesh segment stays 0. 2833 // or the clipping field of a mesh segment stays 0.
@@ -2621,7 +2837,7 @@ private:
2621 primitives.queryCount = statistics_segments; 2837 primitives.queryCount = statistics_segments;
2622 if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, 2838 if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr,
2623 &statistics->primitives_pool) != VK_SUCCESS) 2839 &statistics->primitives_pool) != VK_SUCCESS)
2624 return ReplayResult::unsupported; 2840 return queue_unsupported(__LINE__);
2625 } 2841 }
2626 } 2842 }
2627 } 2843 }
@@ -2641,16 +2857,16 @@ private:
2641 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) { 2857 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) {
2642 if (!occlusion_resolve_) { 2858 if (!occlusion_resolve_) {
2643 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); 2859 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device());
2644 if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; 2860 if (!helper->initialize(occlusion_memory)) return queue_unsupported(__LINE__);
2645 occlusion_resolve_ = std::move(helper); 2861 occlusion_resolve_ = std::move(helper);
2646 } 2862 }
2647 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum, 2863 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum,
2648 queries.needs_sum_binary)) 2864 queries.needs_sum_binary))
2649 return ReplayResult::unsupported; 2865 return queue_unsupported(__LINE__);
2650 } 2866 }
2651 2867
2652 CommandSlot* slot = acquire(); 2868 CommandSlot* slot = acquire();
2653 if (!slot) return ReplayResult::unsupported; 2869 if (!slot) return queue_unsupported(__LINE__);
2654 slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused 2870 slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused
2655 khr_guard.stages.clear(); 2871 khr_guard.stages.clear();
2656 slot->khr_as_queries = std::move(khr_guard.as_queries); 2872 slot->khr_as_queries = std::move(khr_guard.as_queries);
@@ -2680,13 +2896,27 @@ private:
2680 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 2896 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
2681 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; 2897 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
2682 context_.gpu_labels_.begin_record(command_buffer); 2898 context_.gpu_labels_.begin_record(command_buffer);
2683 if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { 2899 if (context_.observe_result(context_.vk.vkBeginCommandBuffer(command_buffer, &begin),
2900 "vkBeginCommandBuffer") != VK_SUCCESS) {
2684 discard(); 2901 discard();
2685 return ReplayResult::unsupported; 2902 return queue_unsupported(__LINE__);
2903 }
2904 // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the
2905 // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier:
2906 // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their
2907 // barriers say, so this one starts with a full memory barrier against everything submitted before it
2908 // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies).
2909 if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out
2910 VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
2911 full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
2912 full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2913 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
2914 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr);
2686 } 2915 }
2687 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2916 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2688 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 2917 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
2689 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 2918 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
2919 "vkEndCommandBuffer") == VK_SUCCESS;
2690 resource_lock.unlock(); 2920 resource_lock.unlock();
2691 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 2921 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
2692 if (!submitted) discard(); 2922 if (!submitted) discard();
@@ -2700,7 +2930,7 @@ private:
2700 } 2930 }
2701 if (bindless_commit) bindless_commit(submitted); 2931 if (bindless_commit) bindless_commit(submitted);
2702 tracker_lock.unlock(); 2932 tracker_lock.unlock();
2703 return ReplayResult::unsupported; 2933 return queue_unsupported(__LINE__);
2704 } 2934 }
2705 replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; 2935 replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE;
2706 const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); 2936 const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false);
@@ -2754,9 +2984,23 @@ private:
2754 bool wrote_readback = false; 2984 bool wrote_readback = false;
2755 VkPipelineStageFlags2 readback_stages = 0; 2985 VkPipelineStageFlags2 readback_stages = 0;
2756 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 2986 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
2987 CheckpointSubmission diagnostics;
2988 PFN_vkCmdSetCheckpointNV checkpoint = nullptr;
2989 if (execute_call) {
2990 auto& fault = *context_.device_fault();
2991 checkpoint = fault.checkpoint_command();
2992 const char* queue_kind = kind_ == QueueKind::direct ? "direct" :
2993 kind_ == QueueKind::compute ? "compute" : "copy";
2994 diagnostics = fault.begin_submission(execute_call, queue_, queue_kind, lists.size());
2995 }
2757 for (std::size_t i = 0; i < lists.size(); ++i) { 2996 for (std::size_t i = 0; i < lists.size(); ++i) {
2758 const auto& list = prepared[i]; 2997 const auto& list = prepared[i];
2759 emit(list, command_buffer, replay, &next_tracker, &open_labels); 2998 if (execute_call && i < diagnostics.lists.size()) {
2999 const CheckpointRecorder recorder{checkpoint, diagnostics, context_.device_fault()->pipeline_names, i};
3000 emit_commands<true>(list, command_buffer, replay, &next_tracker, &open_labels, &recorder);
3001 } else {
3002 emit(list, command_buffer, replay, &next_tracker, &open_labels);
3003 }
2760 wrote_readback |= list.wrote_readback; 3004 wrote_readback |= list.wrote_readback;
2761 readback_stages |= list.readback_src_stages; 3005 readback_stages |= list.readback_src_stages;
2762 } 3006 }
@@ -2791,14 +3035,19 @@ private:
2791 0, 1, &host, 0, nullptr, 0, nullptr); 3035 0, 1, &host, 0, nullptr, 0, nullptr);
2792 } 3036 }
2793 } 3037 }
2794 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 3038 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3039 "vkEndCommandBuffer") == VK_SUCCESS;
2795 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3040 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held
2796 const bool wait_previous = ordered_timestamps && submitted_; 3041 const bool wait_previous = ordered_timestamps && submitted_;
2797 if (wait_previous) { 3042 if (wait_previous) {
2798 waits_.push_back(progress_); 3043 waits_.push_back(progress_);
2799 wait_values_.push_back(submitted_); 3044 wait_values_.push_back(submitted_);
2800 } 3045 }
2801 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3046 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0,
3047 execute_call ? &diagnostics : nullptr);
3048 if (mesh_draws)
3049 std::fprintf(stderr, "[rt] pso-mesh unix_ms=%lld draws=%u submitted=%d\n",
3050 pipeline_profile::unix_ms(), mesh_draws, int(submitted));
2802 if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { 3051 if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) {
2803 // not initialized after all: try again with the next submission 3052 // not initialized after all: try again with the next submission
2804 std::lock_guard lock(context_.storage_mutex_); 3053 std::lock_guard lock(context_.storage_mutex_);
@@ -2846,7 +3095,7 @@ private:
2846 // the queue (it keeps a single upload obligation). 3095 // the queue (it keeps a single upload obligation).
2847 if (bindless_commit) bindless_commit(submitted); 3096 if (bindless_commit) bindless_commit(submitted);
2848 tracker_lock.unlock(); 3097 tracker_lock.unlock();
2849 return submitted ? ReplayResult::success : ReplayResult::unsupported; 3098 return submitted ? ReplayResult::success : queue_unsupported(__LINE__);
2850 } 3099 }
2851 3100
2852 void marker_now(DebugMarker::Kind kind, const char* label) { 3101 void marker_now(DebugMarker::Kind kind, const char* label) {
@@ -2874,6 +3123,7 @@ private:
2874 enum class Kind : std::uint8_t { batch, signal, marker }; 3123 enum class Kind : std::uint8_t { batch, signal, marker };
2875 Kind kind = Kind::batch; 3124 Kind kind = Kind::batch;
2876 std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues 3125 std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues
3126 std::uint64_t execute_call = 0; // original ExecuteCommandLists call for a held batch
2877 std::vector<VkSemaphore> waits; 3127 std::vector<VkSemaphore> waits;
2878 std::vector<std::uint64_t> wait_values; 3128 std::vector<std::uint64_t> wait_values;
2879 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call 3129 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call
@@ -2958,7 +3208,7 @@ private:
2958 for (const CommandList& list : op.lists) lists.push_back(&list); 3208 for (const CommandList& list : op.lists) lists.push_back(&list);
2959 // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until 3209 // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until
2960 // the batch has been recorded and then, with the fences, until its submission has completed (below). 3210 // the batch has been recorded and then, with the fences, until its submission has completed (below).
2961 const ReplayResult result = execute_now(lists); 3211 const ReplayResult result = execute_now(lists, op.execute_call);
2962 if (result != ReplayResult::success) { 3212 if (result != ReplayResult::success) {
2963 int none = static_cast<int>(ReplayResult::success); 3213 int none = static_cast<int>(ReplayResult::success);
2964 held_failure_.compare_exchange_strong(none, static_cast<int>(result)); 3214 held_failure_.compare_exchange_strong(none, static_cast<int>(result));
@@ -3184,7 +3434,8 @@ private:
3184 pending_bindings_.push_back(std::move(pending)); 3434 pending_bindings_.push_back(std::move(pending));
3185 { 3435 {
3186 std::lock_guard lock(context_.submit_mutex()); 3436 std::lock_guard lock(context_.submit_mutex());
3187 const auto result = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE); 3437 const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE),
3438 "vkQueueBindSparse");
3188 if (result != VK_SUCCESS) { 3439 if (result != VK_SUCCESS) {
3189 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 3440 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3190 pending_bindings_.pop_back(); 3441 pending_bindings_.pop_back();
@@ -3206,7 +3457,8 @@ private:
3206 std::uint64_t completed() const { 3457 std::uint64_t completed() const {
3207 if (context_.is_device_lost()) return 0; 3458 if (context_.is_device_lost()) return 0;
3208 std::uint64_t done = 0; 3459 std::uint64_t done = 0;
3209 const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); 3460 const VkResult result = context_.observe_result(
3461 context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done), "vkGetSemaphoreCounterValue");
3210 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 3462 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3211 // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. 3463 // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket.
3212 return result == VK_SUCCESS ? done : 0; 3464 return result == VK_SUCCESS ? done : 0;
@@ -3275,7 +3527,8 @@ private:
3275 info.semaphoreCount = 1; 3527 info.semaphoreCount = 1;
3276 info.pSemaphores = &progress_; 3528 info.pSemaphores = &progress_;
3277 info.pValues = &oldest; 3529 info.pValues = &oldest;
3278 return context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs); 3530 return context_.observe_result(context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs),
3531 "vkWaitSemaphores (queue progress)");
3279 } 3532 }
3280 3533
3281 CommandSlot* acquire() { 3534 CommandSlot* acquire() {
@@ -3315,7 +3568,8 @@ private:
3315 return event; 3568 return event;
3316 } 3569 }
3317 3570
3318 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { 3571 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value,
3572 CheckpointSubmission* diagnostics = nullptr) {
3319 if (context_.is_device_lost()) return false; 3573 if (context_.is_device_lost()) return false;
3320 const std::uint64_t ticket = submitted_ + 1; 3574 const std::uint64_t ticket = submitted_ + 1;
3321 if (last_sparse_) { 3575 if (last_sparse_) {
@@ -3364,8 +3618,11 @@ private:
3364 submit.pCommandBuffers = &command_buffer; 3618 submit.pCommandBuffers = &command_buffer;
3365 submit.signalSemaphoreCount = signal_count; 3619 submit.signalSemaphoreCount = signal_count;
3366 submit.pSignalSemaphores = signals; 3620 submit.pSignalSemaphores = signals;
3621 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss.
3622 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics));
3367 const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); 3623 const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer);
3368 res = context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence); 3624 res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence),
3625 "vkQueueSubmit");
3369 context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); 3626 context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS);
3370 if (res == VK_SUCCESS) { 3627 if (res == VK_SUCCESS) {
3371 context_.record_submit_locked(progress_, ticket); 3628 context_.record_submit_locked(progress_, ticket);