upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorIlyassRS <ilyassroussi2000@gmail.com>2026-11-25 11:47:40 +0100
committerIlyassRS <ilyassroussi2000@gmail.com>2026-11-25 13:15:02 +0100
commit3ab657b058f1c130b4d554d5ecfcd5dc4d86a0cc (patch)
tree51c9f541cf524e3aece6c9c63cf7b9210e843988 /runtime
parent0d80bc5df7c873f40965f34f185cb96913786765 (diff)
runtime: unlock resource_mutex while compiling unbuilt pipelines
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt10
-rw-r--r--runtime/src/vulkan_backend.h434
-rw-r--r--runtime/src/vulkan_replay.h63
-rw-r--r--runtime/test/replay_pipeline_compile_unlock_test.cpp291
-rw-r--r--runtime/test/replay_pipeline_compiles_test.cpp46
5 files changed, 640 insertions, 204 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e9cb8d434..97d90741a 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -4232,6 +4232,16 @@ if(TARGET Vulkan::Headers)
4232 add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test) 4232 add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test)
4233 add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test) 4233 add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test)
4234 set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1") 4234 set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1")
4235 # Compiling unbuilt pipelines releases resource_mutex_ and tracker_mutex_ while keeping pipeline_mutex_ (no GPU).
4236 add_executable(replay_pipeline_compile_unlock_test test/replay_pipeline_compile_unlock_test.cpp)
4237 target_link_libraries(replay_pipeline_compile_unlock_test PRIVATE Vulkan::Headers Threads::Threads)
4238 if(WIN32)
4239 target_compile_definitions(replay_pipeline_compile_unlock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
4240 endif()
4241 if(MSVC)
4242 target_compile_options(replay_pipeline_compile_unlock_test PRIVATE /W4 /permissive- /utf-8)
4243 endif()
4244 add_test(NAME replay_pipeline_compile_unlock COMMAND replay_pipeline_compile_unlock_test)
4235 add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) 4245 add_executable(replay_quad_list_test test/replay_quad_list_test.cpp)
4236 target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) 4246 target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers)
4237 if(WIN32) 4247 if(WIN32)
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 145fa11ee..9a6027787 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1545,32 +1545,34 @@ public:
1545 } 1545 }
1546 1546
1547 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1547 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1548 // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block
1549 // resource registration or destruction on the render thread.
1548 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { 1550 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1549 std::unique_lock lock(resource_mutex_); 1551 std::unique_lock lock(pipeline_mutex_);
1550 pipelines_[id] = pipeline; 1552 pipelines_[id] = pipeline;
1551 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; 1553 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1552 } 1554 }
1553 void remove_pipeline(std::uintptr_t id) { 1555 void remove_pipeline(std::uintptr_t id) {
1554 std::unique_lock lock(resource_mutex_); 1556 std::unique_lock lock(pipeline_mutex_);
1555 pipelines_.erase(id); 1557 pipelines_.erase(id);
1556 graphics_pipelines_.erase(id); 1558 graphics_pipelines_.erase(id);
1557 if (device_fault_) device_fault_->pipeline_names.erase(id); 1559 if (device_fault_) device_fault_->pipeline_names.erase(id);
1558 } 1560 }
1559 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, 1561 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1560 const CheckpointShaders* shaders = nullptr) { 1562 const CheckpointShaders* shaders = nullptr) {
1561 std::unique_lock lock(resource_mutex_); 1563 std::unique_lock lock(pipeline_mutex_);
1562 graphics_pipelines_[id] = pipeline; 1564 graphics_pipelines_[id] = pipeline;
1563 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; 1565 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1564 } 1566 }
1565 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where 1567 // 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 1568 // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and
1567 // workers it had. 1569 // ends the workers it had.
1568 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { 1570 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) {
1569 std::unique_lock lock(resource_mutex_); 1571 std::unique_lock lock(pipeline_mutex_);
1570 pipeline_workers_.swap(workers); 1572 pipeline_workers_.swap(workers);
1571 } 1573 }
1572 PipelineWorkers::Stats pipeline_worker_stats() { 1574 PipelineWorkers::Stats pipeline_worker_stats() {
1573 std::shared_lock lock(resource_mutex_); 1575 std::shared_lock lock(pipeline_mutex_);
1574 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1576 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
1575 } 1577 }
1576 // Configure before queue creation, when the selected queue family supports compute. 1578 // Configure before queue creation, when the selected queue family supports compute.
@@ -1774,7 +1776,7 @@ public:
1774 return true; 1776 return true;
1775 } 1777 }
1776 const char* diagnostic_compute_name(std::uintptr_t id) { 1778 const char* diagnostic_compute_name(std::uintptr_t id) {
1777 std::shared_lock lock(resource_mutex_); 1779 std::shared_lock lock(pipeline_mutex_);
1778 if (!device_fault_) return nullptr; 1780 if (!device_fault_) return nullptr;
1779 const auto it = device_fault_->pipeline_names.find(id); 1781 const auto it = device_fault_->pipeline_names.find(id);
1780 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; 1782 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
@@ -2166,6 +2168,7 @@ private:
2166 bool ray_tracing_ = false; 2168 bool ray_tracing_ = false;
2167 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records 2169 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records
2168 std::atomic<bool> device_lost_{false}; 2170 std::atomic<bool> device_lost_{false};
2171 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 2172 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove
2170 alignas(64) std::mutex tracker_mutex_; 2173 alignas(64) std::mutex tracker_mutex_;
2171 alignas(64) std::mutex views_mutex_; 2174 alignas(64) std::mutex views_mutex_;
@@ -2899,11 +2902,15 @@ private:
2899 } 2902 }
2900 } khr_guard{this}; 2903 } khr_guard{this};
2901 std::function<void(bool)> bindless_commit; 2904 std::function<void(bool)> bindless_commit;
2902 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 2905 // 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 2906 // 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 2907 // 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. 2908 // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader
2906 std::shared_lock resource_lock(context_.resource_mutex_); 2909 // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and
2910 // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and
2911 // submissions stay in order.
2912 std::shared_lock pipeline_lock(context_.pipeline_mutex_);
2913 std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock);
2907 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 2914 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 2915 // 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. 2916 // with ticket 0 while tracker_lock is still held.
@@ -2914,7 +2921,7 @@ private:
2914 ~Depth24Guard() { 2921 ~Depth24Guard() {
2915 if (active && d24) d24->retire(progress, 0); 2922 if (active && d24) d24->retire(progress, 0);
2916 } 2923 }
2917 } depth24_guard{context_.depth24_.get(), progress_, false}; 2924 } depth24_guard{nullptr, progress_, false};
2918 struct ScratchGuard { // the same for the copy scratch 2925 struct ScratchGuard { // the same for the copy scratch
2919 ScratchBuffers* scratch = nullptr; 2926 ScratchBuffers* scratch = nullptr;
2920 VkSemaphore progress = VK_NULL_HANDLE; 2927 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2922,7 +2929,7 @@ private:
2922 ~ScratchGuard() { 2929 ~ScratchGuard() {
2923 if (active && scratch) scratch->retire(progress, 0); 2930 if (active && scratch) scratch->retire(progress, 0);
2924 } 2931 }
2925 } scratch_guard{context_.scratch_.get(), progress_, false}; 2932 } scratch_guard{nullptr, progress_, false};
2926 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch 2933 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch
2927 IndirectArgumentClamp* clamp = nullptr; 2934 IndirectArgumentClamp* clamp = nullptr;
2928 VkSemaphore progress = VK_NULL_HANDLE; 2935 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2930,9 +2937,8 @@ private:
2930 ~ClampGuard() { 2937 ~ClampGuard() {
2931 if (active && clamp) clamp->retire(progress, 0); 2938 if (active && clamp) clamp->retire(progress, 0);
2932 } 2939 }
2933 } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; 2940 } clamp_guard{nullptr, progress_, false};
2934 const bool transfer_only = family_ == context_.transfer_only_family_; 2941 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 2942 // 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). 2943 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
2938 auto& prepared = prepared_; 2944 auto& prepared = prepared_;
@@ -2940,42 +2946,9 @@ private:
2940 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below 2946 // 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. 2947 // 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()); 2948 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2943 ReplayFunctions replay = context_.replay_; 2949 ReplayFunctions replay{};
2944 unsigned mesh_draws = 0; 2950 unsigned mesh_draws = 0;
2945 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2946 std::vector<VulkanContext::GeometryUpload> geometry; 2951 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; 2952 std::uint64_t captures = 0;
2980 for (const auto* list : lists) 2953 for (const auto* list : lists)
2981 for (const auto& command : list->commands()) 2954 for (const auto& command : list->commands())
@@ -2984,149 +2957,233 @@ private:
2984 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 2957 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
2985 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 2958 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2986 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; 2959 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch;
2987 if (captures) { 2960 const auto& occlusion_memory = context_.occlusion_resolve_memory_;
2988 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 2961 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0;
2989 return queue_unsupported(__LINE__); 2962 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, 2963 std::uint32_t segments = 0, statistics_segments = 0;
2991 // retaining main's resource -> tracker -> submit lock order through emit and submission. 2964 bool has_queries = false;
2992 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2965 const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) {
2993 batch = context_.predicate_reducer_->batch(captures); 2966 if (context_.pipeline_workers_) {
2994 if (!batch) return queue_unsupported(__LINE__); 2967 context_.pipeline_workers_->run(count, job);
2995 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 2968 } else {
2996 return batch->prepare(buffer, offset, out); 2969 for (std::size_t i = 0; i < count; ++i) job(i);
2970 }
2971 };
2972 PipelineCompiles prior_compiles;
2973 bool has_prior_compiles = false;
2974 for (int pass = 0;; ++pass) {
2975 resource_lock.lock();
2976 bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{};
2977 replay = context_.replay_;
2978 mesh_draws = 0;
2979 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2980 if (context_.geometry_provider_) {
2981 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2982 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2983 for (const auto& upload : geometry) {
2984 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2985 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2986 return true;
2987 }
2988 VulkanContext::GeometryUpload upload;
2989 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2990 buffer=upload.buffer;offset=upload.offset;
2991 geometry.push_back(std::move(upload));
2992 return true;
2993 };
2994 }
2995 replay.graphics_family = family_ == context_.graphics_family_;
2996 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2997 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2998 : 0;
2999 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
3000 VkDeviceAddress& address) {
3001 return stage_khr_instances(replay, build, khr_guard.stages, address);
2997 }; 3002 };
2998 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { 3003 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2999 context_.predicate_reducer_->capture(cb, p); 3004 return stage_xdxr_table(khr_guard.stages, address, count);
3000 }; 3005 };
3001 if (context_.predicated_copier_) { 3006 if (replay.write_acceleration_structures_properties) {
3002 copy_batch = context_.predicated_copier_->batch(); 3007 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
3003 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, 3008 std::uint32_t& first) {
3004 VkDeviceSize dst, VkDeviceSize size, 3009 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 }; 3010 };
3011 } 3011 }
3012 } 3012 if (captures) {
3013 if (context_.scratch_) { 3013 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
3014 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, 3014 return queue_unsupported(__LINE__);
3015 VkDeviceSize& offset) { 3015 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
3016 // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission.
3016 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3017 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3017 if (!scratch_guard.active) { 3018 batch = context_.predicate_reducer_->batch(captures);
3018 context_.scratch_->collect(); 3019 if (!batch) return queue_unsupported(__LINE__);
3019 scratch_guard.active = true; 3020 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
3021 return batch->prepare(buffer, offset, out);
3022 };
3023 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) {
3024 context_.predicate_reducer_->capture(cb, p);
3025 };
3026 if (context_.predicated_copier_) {
3027 copy_batch = context_.predicated_copier_->batch();
3028 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src,
3029 VkDeviceSize dst, VkDeviceSize size,
3030 std::vector<PredicatedCopyDispatch>& out) {
3031 return copy_batch->prepare(source, destination, src, dst, size, out);
3032 };
3033 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3034 context_.predicated_copier_->emit(cb, jobs);
3035 };
3020 } 3036 }
3021 return context_.scratch_->get(bytes, buffer, offset); 3037 }
3022 }; 3038 if (context_.scratch_) {
3023 } 3039 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
3024 if (kind_ != QueueKind::copy && context_.indirect_clamp_) { 3040 VkDeviceSize& offset) {
3025 // The record scratch belongs to this submission: collected here, retired below with its ticket. The 3041 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3026 // counter slots are read back once that ticket completes (the batch's destructor). 3042 if (!scratch_guard.active) {
3027 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( 3043 scratch_guard.scratch = context_.scratch_.get();
3028 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, 3044 context_.scratch_->collect();
3029 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, 3045 scratch_guard.active = true;
3030 std::uint32_t max_count, ClampedIndirect& out) { 3046 }
3031 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3047 return context_.scratch_->get(bytes, buffer, offset);
3032 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3048 };
3033 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); 3049 }
3034 if (!clamp_guard.active) { 3050 if (kind_ != QueueKind::copy && context_.indirect_clamp_) {
3035 context_.indirect_clamp_->collect(); 3051 // The record scratch belongs to this submission: collected here, retired below with its ticket. The
3036 clamp_guard.active = true; 3052 // counter slots are read back once that ticket completes (the batch's destructor).
3053 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard](
3054 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
3055 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride,
3056 std::uint32_t max_count, ClampedIndirect& out) {
3057 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3058 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3059 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch();
3060 if (!clamp_guard.active) {
3061 clamp_guard.clamp = context_.indirect_clamp_.get();
3062 context_.indirect_clamp_->collect();
3063 clamp_guard.active = true;
3064 }
3065 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride,
3066 max_count, out);
3067 };
3068 }
3069 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
3070 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
3071 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
3072 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
3073 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3074 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3075 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
3076 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3077 };
3078 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3079 context_.counted_dispatch_->emit(cb, job);
3080 };
3081 }
3082 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3083 replay.prepare_quad_indices = [this, &tracker_lock](
3084 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3085 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3086 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3087 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3088 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3089 scratch_offset, out);
3090 };
3091 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3092 context_.quad_indices_->emit(cb, job);
3093 };
3094 }
3095 if (context_.depth24_ && !transfer_only) {
3096 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3097 std::vector<Depth24Job>& parts) {
3098 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3099 if (!depth24_guard.active) {
3100 depth24_guard.d24 = context_.depth24_.get();
3101 context_.depth24_->collect();
3102 depth24_guard.active = true;
3103 }
3104 return context_.depth24_->prepare(job, parts);
3105 };
3106 }
3107 if (can_resolve_occlusion) {
3108 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3109 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3110 occlusion_resolve_->sum(cb, pool, first, count, dst, offset);
3111 };
3112 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3113 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3114 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
3115 };
3116 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
3117 VkQueryPool primitives_pool, const std::uint8_t* mesh,
3118 std::uint32_t first, std::uint32_t count, VkBuffer dst,
3119 VkDeviceSize offset) {
3120 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
3121 offset);
3122 };
3123 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3124 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3125 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
3126 };
3127 }
3128 segments = 0;
3129 statistics_segments = 0;
3130 has_queries = false;
3131 // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial).
3132 // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock
3133 // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and
3134 // workers stay alive), then re-prepare on pass 1 against current resources.
3135 PipelineCompiles compiles;
3136 replay.compiles = &compiles;
3137 ReplayResult prepare_result = ReplayResult::success;
3138 for (std::size_t i = 0; i < lists.size(); ++i) {
3139 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3140 if (result != ReplayResult::success) {
3141 prepare_result = result;
3142 break;
3037 } 3143 }
3038 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, 3144 if (prepared[i].segment_count > UINT32_MAX - segments ||
3039 out); 3145 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
3040 }; 3146 return queue_unsupported(__LINE__);
3041 } 3147 segments += prepared[i].segment_count;
3042 if (kind_ != QueueKind::copy && context_.counted_dispatch_) { 3148 statistics_segments += prepared[i].statistics_segment_count;
3043 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( 3149 has_queries = has_queries || !prepared[i].queries.empty();
3044 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, 3150 }
3045 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { 3151 if (pass == 0 && !compiles.empty()) {
3046 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3152 if (depth24_guard.active) {
3047 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3153 context_.depth24_->retire(progress_, 0);
3048 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); 3154 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 } 3155 }
3076 return context_.depth24_->prepare(job, parts); 3156 if (scratch_guard.active) {
3077 }; 3157 context_.scratch_->retire(progress_, 0);
3078 } 3158 scratch_guard.active = false;
3079 const auto& occlusion_memory = context_.occlusion_resolve_memory_; 3159 }
3080 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; 3160 if (clamp_guard.active) {
3081 if (can_resolve_occlusion) { 3161 context_.indirect_clamp_->retire(progress_, 0);
3082 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3162 clamp_guard.active = false;
3083 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3163 }
3084 occlusion_resolve_->sum(cb, pool, first, count, dst, offset); 3164 batch.reset();
3085 }; 3165 copy_batch.reset();
3086 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3166 counted_batch.reset();
3087 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3167 clamp_batch.reset();
3088 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 3168 if (tracker_lock.owns_lock()) tracker_lock.unlock();
3089 }; 3169 resource_lock.unlock();
3090 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 3170 recycle_khr_stages(khr_guard.stages);
3091 VkQueryPool primitives_pool, const std::uint8_t* mesh, 3171 recycle_khr_as_queries(khr_guard.as_queries);
3092 std::uint32_t first, std::uint32_t count, VkBuffer dst, 3172 geometry.clear();
3093 VkDeviceSize offset) { 3173
3094 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, 3174 compiles.build(run_compiles);
3095 offset); 3175 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3096 }; 3176 if (compile_result != ReplayResult::success) return compile_result;
3097 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3177 prior_compiles = std::move(compiles);
3098 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3178 has_prior_compiles = true;
3099 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); 3179 continue;
3100 };
3101 }
3102 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
3103 std::uint32_t segments = 0, statistics_segments = 0;
3104 bool has_queries = false;
3105 // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of
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 } 3180 }
3117 if (prepared[i].segment_count > UINT32_MAX - segments || 3181 prepare_result = build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3118 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 3182 run_compiles, has_prior_compiles ? &prior_compiles : nullptr);
3119 return queue_unsupported(__LINE__); 3183 replay.compiles = nullptr;
3120 segments += prepared[i].segment_count; 3184 if (prepare_result != ReplayResult::success) return prepare_result;
3121 statistics_segments += prepared[i].statistics_segment_count; 3185 break;
3122 has_queries = has_queries || !prepared[i].queries.empty();
3123 } 3186 }
3124 prepare_result = build_pipelines(
3125 compiles, std::span(prepared).first(lists.size()), prepare_result,
3126 [this](std::size_t count, const std::function<void(std::size_t)>& job) {
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, 3187 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
3131 std::shared_ptr<OcclusionSegmentPool>& out) { 3188 std::shared_ptr<OcclusionSegmentPool>& out) {
3132 const auto& vk = context_.vk; 3189 const auto& vk = context_.vk;
@@ -3253,6 +3310,7 @@ private:
3253 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3310 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3254 "vkEndCommandBuffer") == VK_SUCCESS; 3311 "vkEndCommandBuffer") == VK_SUCCESS;
3255 resource_lock.unlock(); 3312 resource_lock.unlock();
3313 pipeline_lock.unlock();
3256 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3314 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
3257 if (!submitted) discard(); 3315 if (!submitted) discard();
3258 if (depth24_guard.active) { 3316 if (depth24_guard.active) {
@@ -3386,7 +3444,8 @@ private:
3386 } 3444 }
3387 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3445 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3388 "vkEndCommandBuffer") == VK_SUCCESS; 3446 "vkEndCommandBuffer") == VK_SUCCESS;
3389 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3447 resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held
3448 pipeline_lock.unlock();
3390 const bool wait_previous = ordered_timestamps && submitted_; 3449 const bool wait_previous = ordered_timestamps && submitted_;
3391 if (wait_previous) { 3450 if (wait_previous) {
3392 waits_.push_back(progress_); 3451 waits_.push_back(progress_);
@@ -4071,7 +4130,8 @@ private:
4071 std::vector<PreparedList> prepared_; 4130 std::vector<PreparedList> prepared_;
4072 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 4131 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
4073 bool ok_ = false; 4132 bool ok_ = false;
4074 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and 4133 // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ ->
4134 // submit_mutex_) and
4075 // guards the members above that execute, signal, wait and marker touch. 4135 // guards the members above that execute, signal, wait and marker touch.
4076 std::mutex state_mutex_; 4136 std::mutex state_mutex_;
4077 std::deque<Deferred> held_; 4137 std::deque<Deferred> held_;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index e20a29105..62ea5af93 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -967,7 +967,7 @@ inline ReplayResult unsupported_at(int line) {
967 967
968// The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines() 968// The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines()
969// then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid 969// then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid
970// while the context's resource lock is held. 970// while the context's pipeline lock is held.
971class PipelineCompiles { 971class PipelineCompiles {
972public: 972public:
973 // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none. 973 // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none.
@@ -992,12 +992,33 @@ public:
992 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } 992 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; }
993 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands 993 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands
994 994
995 // Whether this batch already attempted (pipeline, flags); writes its outcome (built handle or VK_NULL_HANDLE) to `out`.
996 bool lookup(const GraphicsPipeline* graphics, const ComputePipeline* compute, std::uint32_t flags,
997 VkPipeline& out) const {
998 const void* const pipeline = graphics ? static_cast<const void*>(graphics) : compute;
999 const auto it = tickets_.find({pipeline, flags});
1000 if (it == tickets_.end()) return false;
1001 out = jobs_[it->second - 1].built;
1002 return true;
1003 }
1004
1005 // Whether this batch already attempted the job named by `other`'s `ticket`.
1006 bool contains_ticket(const PipelineCompiles& other, Ticket ticket) const {
1007 VkPipeline unused = VK_NULL_HANDLE;
1008 const Job& job = other.jobs_[ticket - 1];
1009 return lookup(job.graphics, job.compute, job.flags, unused);
1010 }
1011
995 // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without 1012 // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without
996 // workers, beside the others. 1013 // workers, beside the others. Jobs already attempted in `prior` reuse that outcome without re-invoking build().
997 template<typename Run> 1014 template<typename Run>
998 void build(Run&& run) { 1015 void build(Run&& run, const PipelineCompiles* prior = nullptr) {
999 std::vector<std::size_t> single, large; 1016 std::vector<std::size_t> single, large;
1000 for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); 1017 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1018 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue;
1019 (is_large(jobs_[i]) ? large : single).push_back(i);
1020 }
1021 if (single.empty() && large.empty()) return;
1001 const auto compile = [this](std::size_t i) { 1022 const auto compile = [this](std::size_t i) {
1002 Job& job = jobs_[i]; 1023 Job& job = jobs_[i];
1003 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); 1024 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context);
@@ -2902,30 +2923,38 @@ public:
2902 std::vector<detail::PreparedKhrPostbuild> khr_postbuilds; 2923 std::vector<detail::PreparedKhrPostbuild> khr_postbuilds;
2903}; 2924};
2904 2925
2905// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that 2926// Checks the outcomes of a compiled PipelineCompiles batch against `result` (the first prepare() failure, if any).
2906// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would 2927// Every use in `compiles` comes from a command before the one that failed, so a pipeline that cannot be built counts
2907// have returned had they built each pipeline themselves. Every use in `compiles` comes from a command before the one that 2928// first, at the earliest command that uses it: it fails the list of a draw or an indirect dispatch, and a dispatch is
2908// failed, so a pipeline that cannot be built counts first, at the earliest command that uses it: it fails the list of a 2929// dropped as prepare() drops one. Non-strict failed dispatches already logged in `prior` are not logged twice.
2909// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. 2930inline ReplayResult check_compiled_pipelines(const PipelineCompiles& compiles, ReplayResult result,
2910template<typename Run> 2931 const PipelineCompiles* prior = nullptr) {
2911ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
2912 Run&& run) {
2913 if (compiles.empty()) return result;
2914 compiles.build(run);
2915 for (const PipelineCompiles::Use& use : compiles.uses()) { 2932 for (const PipelineCompiles::Use& use : compiles.uses()) {
2916 if (compiles.built(use.ticket)) continue; 2933 if (compiles.built(use.ticket)) continue;
2917 if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); 2934 if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__);
2918 if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__); 2935 if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__);
2919 unresolved_at(__LINE__); 2936 if (!prior || !prior->contains_ticket(compiles, use.ticket)) unresolved_at(__LINE__);
2920 } 2937 }
2921 if (result != ReplayResult::success) return result; 2938 return result;
2939}
2940
2941// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that
2942// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would
2943// have returned had they built each pipeline themselves.
2944template<typename Run>
2945ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
2946 Run&& run, const PipelineCompiles* prior = nullptr) {
2947 if (compiles.empty()) return result;
2948 compiles.build(run, prior);
2949 const ReplayResult checked = check_compiled_pipelines(compiles, result, prior);
2950 if (checked != ReplayResult::success) return checked;
2922 for (PreparedList& list : lists) { 2951 for (PreparedList& list : lists) {
2923 for (detail::Prepared& command : list.commands) 2952 for (detail::Prepared& command : list.commands)
2924 if (command.compile) command.pipeline.pipeline = compiles.built(command.compile); 2953 if (command.compile) command.pipeline.pipeline = compiles.built(command.compile);
2925 for (std::size_t i = 0; i < list.draw_count; ++i) 2954 for (std::size_t i = 0; i < list.draw_count; ++i)
2926 if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile); 2955 if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile);
2927 } 2956 }
2928 return result; 2957 return checked;
2929} 2958}
2930 2959
2931inline ReplayResult plan_occlusion_segments(PreparedList& out) { 2960inline ReplayResult plan_occlusion_segments(PreparedList& out) {
diff --git a/runtime/test/replay_pipeline_compile_unlock_test.cpp b/runtime/test/replay_pipeline_compile_unlock_test.cpp
new file mode 100644
index 000000000..801f79b19
--- /dev/null
+++ b/runtime/test/replay_pipeline_compile_unlock_test.cpp
@@ -0,0 +1,291 @@
1// VulkanQueue::execute_now() releases resource_mutex_ and tracker_mutex_ while compiling unbuilt pipelines under
2// pipeline_mutex_ alone, so add_resource()/remove_resource() and other queues do not stall behind shader compiles,
3// remove_pipeline() still waits until compilation finishes, failed non-strict dispatches build only once, and
4// pass-1 re-preparation observes resource updates made while resource_mutex_ was unlocked. No GPU or game data.
5#include "../src/vulkan_backend.h"
6
7#include <atomic>
8#include <chrono>
9#include <condition_variable>
10#include <cstdint>
11#include <cstdio>
12#include <memory>
13#include <mutex>
14#include <string_view>
15#include <thread>
16#include <vector>
17
18#define EXPECT(condition) do { \
19 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
20} while (0)
21
22namespace {
23
24using namespace leonida;
25
26template<class T>
27T handle(std::uintptr_t n) {
28 return reinterpret_cast<T>(n);
29}
30
31VulkanDeviceFunctions driver{};
32std::atomic<std::uintptr_t> next_handle{10};
33std::mutex record_mutex;
34std::vector<std::pair<VkBuffer, VkBuffer>> recorded_copies;
35
36PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc(VkDevice, const char* name) {
37#define MOCK_DEVICE_FUNCTION(n) \
38 if (std::string_view(name) == #n) return reinterpret_cast<PFN_vkVoidFunction>(driver.n);
39 LEONIDA_VK_DEVICE_FUNCTIONS(MOCK_DEVICE_FUNCTION)
40#undef MOCK_DEVICE_FUNCTION
41 return nullptr;
42}
43
44void init_mock_driver() {
45 driver = {};
46 driver.vkCreateCommandPool = +[](VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*,
47 VkCommandPool* out) {
48 *out = handle<VkCommandPool>(next_handle.fetch_add(1));
49 return VK_SUCCESS;
50 };
51 driver.vkDestroyCommandPool = +[](VkDevice, VkCommandPool, const VkAllocationCallbacks*) {};
52 driver.vkCreateSemaphore = +[](VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*,
53 VkSemaphore* out) {
54 *out = handle<VkSemaphore>(next_handle.fetch_add(1));
55 return VK_SUCCESS;
56 };
57 driver.vkDestroySemaphore = +[](VkDevice, VkSemaphore, const VkAllocationCallbacks*) {};
58 driver.vkGetSemaphoreCounterValue = +[](VkDevice, VkSemaphore, std::uint64_t* value) {
59 *value = UINT64_MAX;
60 return VK_SUCCESS;
61 };
62 driver.vkQueueWaitIdle = +[](VkQueue) { return VK_SUCCESS; };
63 driver.vkAllocateCommandBuffers = +[](VkDevice, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* out) {
64 for (std::uint32_t i = 0; i < info->commandBufferCount; ++i)
65 out[i] = handle<VkCommandBuffer>(next_handle.fetch_add(1));
66 return VK_SUCCESS;
67 };
68 driver.vkResetCommandBuffer = +[](VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; };
69 driver.vkBeginCommandBuffer = +[](VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; };
70 driver.vkEndCommandBuffer = +[](VkCommandBuffer) { return VK_SUCCESS; };
71 driver.vkQueueSubmit = +[](VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { return VK_SUCCESS; };
72 driver.vkCmdPipelineBarrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
73 std::uint32_t, const VkMemoryBarrier*, std::uint32_t,
74 const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {};
75 driver.vkCmdBindPipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {};
76 driver.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t,
77 std::uint32_t, const void*) {};
78 driver.vkCmdDispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {};
79 driver.vkCmdCopyBuffer = +[](VkCommandBuffer, VkBuffer src, VkBuffer dst, std::uint32_t, const VkBufferCopy*) {
80 std::lock_guard lock(record_mutex);
81 recorded_copies.emplace_back(src, dst);
82 };
83 driver.vkCmdCopyBufferToImage = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, std::uint32_t,
84 const VkBufferImageCopy*) {};
85 driver.vkCmdCopyImageToBuffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer, std::uint32_t,
86 const VkBufferImageCopy*) {};
87 driver.vkCmdCopyImage = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, std::uint32_t,
88 const VkImageCopy*) {};
89}
90
91struct SlowPipeline {
92 std::mutex mutex;
93 std::condition_variable cv;
94 bool entered = false;
95 bool allow_finish = false;
96 bool fail = false;
97 std::atomic<int> builds{0};
98 VkPipeline handle_out = VK_NULL_HANDLE;
99
100 VkPipeline build() {
101 builds.fetch_add(1, std::memory_order_relaxed);
102 {
103 std::unique_lock lock(mutex);
104 entered = true;
105 cv.notify_all();
106 cv.wait(lock, [this] { return allow_finish; });
107 if (!fail) handle_out = handle<VkPipeline>(0x7001);
108 return handle_out;
109 }
110 }
111
112 VkPipeline find() {
113 std::unique_lock lock(mutex, std::try_to_lock);
114 return lock.owns_lock() ? handle_out : VK_NULL_HANDLE;
115 }
116
117 void release() {
118 std::lock_guard lock(mutex);
119 allow_finish = true;
120 cv.notify_all();
121 }
122};
123
124// Exercises concurrent add_resource/remove_resource, a second queue submission, resource replacement observed on
125// pass-1 re-prepare, and remove_pipeline() waiting on pipeline_mutex_ while a slow compile runs.
126int test_unlocks_resources_during_compile(bool with_workers) {
127 {
128 std::lock_guard lock(record_mutex);
129 recorded_copies.clear();
130 }
131 VulkanContext context(mock_get_device_proc, handle<VkDevice>(1), false);
132 if (with_workers) context.set_pipeline_workers(std::make_unique<PipelineWorkers>(2));
133
134 ResourceBinding src{};
135 src.buffer = handle<VkBuffer>(101);
136 src.size = 64;
137 ResourceBinding dst_old{};
138 dst_old.buffer = handle<VkBuffer>(102);
139 dst_old.size = 64;
140 ResourceBinding dst_new{};
141 dst_new.buffer = handle<VkBuffer>(202);
142 dst_new.size = 64;
143 context.add_resource(1, src);
144 context.add_resource(2, dst_old);
145
146 SlowPipeline slow;
147 constexpr std::uintptr_t slow_id = 0x100;
148 constexpr std::uintptr_t fast_id = 0x200;
149
150 ComputePipeline slow_pso{};
151 slow_pso.layout = handle<VkPipelineLayout>(5);
152 slow_pso.build_context = &slow;
153 slow_pso.build = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->build(); };
154 slow_pso.built = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->find(); };
155 context.add_pipeline(slow_id, slow_pso);
156
157 ComputePipeline fast_pso{};
158 fast_pso.layout = handle<VkPipelineLayout>(5);
159 fast_pso.pipeline = handle<VkPipeline>(0x8001);
160 context.add_pipeline(fast_id, fast_pso);
161
162 VulkanQueue queue_a(context, handle<VkQueue>(1), 0, QueueKind::compute);
163 VulkanQueue queue_b(context, handle<VkQueue>(2), 0, QueueKind::compute);
164 EXPECT(queue_a.ok() && queue_b.ok());
165
166 CommandList list_a;
167 EXPECT(list_a.dispatch({slow_id, {}, 1, 1, 1}));
168 EXPECT(list_a.copy_buffer({2, 0, 1, 0, 64}));
169 EXPECT(list_a.close());
170
171 CommandList list_b;
172 EXPECT(list_b.dispatch({fast_id, {}, 1, 1, 1}));
173 EXPECT(list_b.close());
174
175 ReplayResult result_a = ReplayResult::unsupported;
176 std::thread thread_a([&] {
177 const CommandList* ptr = &list_a;
178 result_a = queue_a.execute({&ptr, 1});
179 });
180
181 // Wait for thread_a (or a PipelineWorkers thread) to enter slow.build().
182 {
183 std::unique_lock lock(slow.mutex);
184 const bool entered = slow.cv.wait_for(lock, std::chrono::seconds(5), [&] { return slow.entered; });
185 if (!entered) {
186 slow.allow_finish = true;
187 slow.cv.notify_all();
188 lock.unlock();
189 thread_a.join();
190 EXPECT(false);
191 }
192 }
193
194 // While compilation is paused:
195 // 1. add_resource() / remove_resource() and a second queue submission must complete without blocking.
196 std::atomic<bool> resources_unblocked{false};
197 ReplayResult result_b = ReplayResult::unsupported;
198 std::thread resource_thread([&] {
199 ResourceBinding temp{};
200 temp.buffer = handle<VkBuffer>(303);
201 temp.size = 64;
202 context.add_resource(3, temp);
203 context.remove_resource(3);
204 // Replace resource 2 while resource_mutex_ is unlocked so pass-1 re-prepare must bind dst_new.
205 context.remove_resource(2);
206 context.add_resource(2, dst_new);
207 const CommandList* ptr = &list_b;
208 result_b = queue_b.execute({&ptr, 1});
209 resources_unblocked.store(true, std::memory_order_release);
210 });
211
212 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
213 while (!resources_unblocked.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline)
214 std::this_thread::sleep_for(std::chrono::milliseconds(5));
215
216 if (!resources_unblocked.load(std::memory_order_acquire)) {
217 slow.release();
218 resource_thread.join();
219 thread_a.join();
220 EXPECT(false);
221 }
222 resource_thread.join();
223 EXPECT(result_b == ReplayResult::success);
224
225 // 2. remove_pipeline() must wait on pipeline_mutex_ until compilation finishes (protecting ComputePipeline*).
226 std::atomic<bool> remove_started{false};
227 std::atomic<bool> remove_finished{false};
228 std::thread remove_thread([&] {
229 remove_started.store(true, std::memory_order_release);
230 context.remove_pipeline(slow_id);
231 remove_finished.store(true, std::memory_order_release);
232 });
233 while (!remove_started.load(std::memory_order_acquire))
234 std::this_thread::sleep_for(std::chrono::milliseconds(1));
235 std::this_thread::sleep_for(std::chrono::milliseconds(30));
236 const bool removed_early = remove_finished.load(std::memory_order_acquire);
237
238 slow.release();
239 thread_a.join();
240 remove_thread.join();
241
242 EXPECT(!removed_early);
243 EXPECT(remove_finished.load(std::memory_order_acquire));
244 EXPECT(result_a == ReplayResult::success);
245 EXPECT(slow.builds.load() == 1);
246 {
247 std::lock_guard lock(record_mutex);
248 EXPECT(recorded_copies.size() == 1);
249 EXPECT(recorded_copies[0].first == src.buffer && recorded_copies[0].second == dst_new.buffer);
250 }
251 return 0;
252}
253
254// A non-strict failed compute dispatch must not invoke build() a second time on pass-1 re-prepare.
255int test_failed_compute_dispatch_built_once() {
256 VulkanContext context(mock_get_device_proc, handle<VkDevice>(1), false);
257 SlowPipeline failing;
258 failing.fail = true;
259 failing.allow_finish = true;
260
261 constexpr std::uintptr_t fail_id = 0x300;
262 ComputePipeline pso{};
263 pso.layout = handle<VkPipelineLayout>(5);
264 pso.build_context = &failing;
265 pso.build = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->build(); };
266 pso.built = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->find(); };
267 context.add_pipeline(fail_id, pso);
268
269 VulkanQueue queue(context, handle<VkQueue>(3), 0, QueueKind::compute);
270 EXPECT(queue.ok());
271
272 CommandList list;
273 EXPECT(list.dispatch({fail_id, {}, 1, 1, 1}));
274 EXPECT(list.close());
275 const CommandList* ptr = &list;
276 const ReplayResult r = queue.execute({&ptr, 1});
277 EXPECT(r == (strict_replay() ? ReplayResult::unresolved : ReplayResult::success));
278 EXPECT(failing.builds.load() == 1);
279 return 0;
280}
281
282} // namespace
283
284int main() {
285 init_mock_driver();
286 if (test_unlocks_resources_during_compile(true) != 0) return 1;
287 if (test_unlocks_resources_during_compile(false) != 0) return 1;
288 if (test_failed_compute_dispatch_built_once() != 0) return 1;
289 std::printf("replay_pipeline_compile_unlock_test: passed\n");
290 return 0;
291}
diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp
index 35b6057ed..d8f5ba895 100644
--- a/runtime/test/replay_pipeline_compiles_test.cpp
+++ b/runtime/test/replay_pipeline_compiles_test.cpp
@@ -547,6 +547,51 @@ void random_submissions(PipelineWorkers& workers) {
547 std::to_string(succeeded)); 547 std::to_string(succeeded));
548} 548}
549 549
550// Re-preparing after a prior compile pass reuses prior outcomes (both built handles and non-strict failed compute
551// dispatches) without re-invoking build() or failing the submission.
552void prior_compiles_reuse(PipelineWorkers& workers) {
553 Registry registry({
554 {.compute = true, .pending = true, .fails = false, .with_built = true},
555 {.compute = true, .pending = true, .fails = true, .with_built = true},
556 });
557 const std::vector<CommandList> lists = record({{
558 CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 1},
559 CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 2},
560 }});
561 std::vector<PreparedList> prepared(1);
562 ReplayFunctions vk = functions(registry);
563 PipelineCompiles first;
564 vk.compiles = &first;
565 const ReplayResult r0 = prepare(lists[0], resolve, vk, prepared[0]);
566 check(r0 == ReplayResult::success && first.size() == 2, "prior_compiles_reuse: pass 0 collected both");
567 first.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); });
568 const ReplayResult c0 = check_compiled_pipelines(first, r0);
569 if (strict_replay()) {
570 check(c0 == ReplayResult::unresolved, "prior_compiles_reuse: strict fails on failed dispatch");
571 return;
572 }
573 check(c0 == ReplayResult::success, "prior_compiles_reuse: non-strict tolerates failed dispatch");
574 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1,
575 "prior_compiles_reuse: each pipeline built once on pass 0");
576 // Reset the failed flag on owner 2 so any redundant build() call on pass 1 would be caught in attempts.
577 registry.owners[1]->failed = false;
578
579 PipelineCompiles second;
580 vk.compiles = &second;
581 const ReplayResult r1 = prepare(lists[0], resolve, vk, prepared[0]);
582 const ReplayResult b1 = build_pipelines(
583 second, std::span(prepared), r1,
584 [&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); },
585 &first);
586 check(b1 == ReplayResult::success, "prior_compiles_reuse: pass 1 succeeded");
587 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1,
588 "prior_compiles_reuse: pass 1 did not re-invoke build() on prior failure");
589 check(prepared[0].commands[0].pipeline.pipeline == handle<VkPipeline>(0x1001),
590 "prior_compiles_reuse: built compute handle attached");
591 check(prepared[0].commands[1].pipeline.pipeline == VK_NULL_HANDLE,
592 "prior_compiles_reuse: failed compute dispatch stays dropped");
593}
594
550} // namespace 595} // namespace
551 596
552int main() { 597int main() {
@@ -555,6 +600,7 @@ int main() {
555 cases(workers); 600 cases(workers);
556 if (threads) many(workers); 601 if (threads) many(workers);
557 reused_lists(workers); 602 reused_lists(workers);
603 prior_compiles_reuse(workers);
558 random_submissions(workers); 604 random_submissions(workers);
559 } 605 }
560 check(large_together == 0, "two large pipelines were built at once"); 606 check(large_together == 0, "two large pipelines were built at once");