diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e9cb8d4345..97d90741ad 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4232,6 +4232,16 @@ if(TARGET Vulkan::Headers) add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test) add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test) set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1") + # Compiling unbuilt pipelines releases resource_mutex_ and tracker_mutex_ while keeping pipeline_mutex_ (no GPU). + add_executable(replay_pipeline_compile_unlock_test test/replay_pipeline_compile_unlock_test.cpp) + target_link_libraries(replay_pipeline_compile_unlock_test PRIVATE Vulkan::Headers Threads::Threads) + if(WIN32) + target_compile_definitions(replay_pipeline_compile_unlock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(replay_pipeline_compile_unlock_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME replay_pipeline_compile_unlock COMMAND replay_pipeline_compile_unlock_test) add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) if(WIN32) diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 145fa11ee5..7e717d27fa 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1545,32 +1545,34 @@ class VulkanContext { } // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. + // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block + // resource registration or destruction on the render thread. void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { - std::unique_lock lock(resource_mutex_); + std::unique_lock lock(pipeline_mutex_); pipelines_[id] = pipeline; if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; } void remove_pipeline(std::uintptr_t id) { - std::unique_lock lock(resource_mutex_); + std::unique_lock lock(pipeline_mutex_); pipelines_.erase(id); graphics_pipelines_.erase(id); if (device_fault_) device_fault_->pipeline_names.erase(id); } void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, const CheckpointShaders* shaders = nullptr) { - std::unique_lock lock(resource_mutex_); + std::unique_lock lock(pipeline_mutex_); graphics_pipelines_[id] = pipeline; if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; } - // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where - // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the - // workers it had. + // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on + // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and + // ends the workers it had. void set_pipeline_workers(std::unique_ptr workers) { - std::unique_lock lock(resource_mutex_); + std::unique_lock lock(pipeline_mutex_); pipeline_workers_.swap(workers); } PipelineWorkers::Stats pipeline_worker_stats() { - std::shared_lock lock(resource_mutex_); + std::shared_lock lock(pipeline_mutex_); return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; } // Configure before queue creation, when the selected queue family supports compute. @@ -1774,7 +1776,7 @@ class VulkanContext { return true; } const char* diagnostic_compute_name(std::uintptr_t id) { - std::shared_lock lock(resource_mutex_); + std::shared_lock lock(pipeline_mutex_); if (!device_fault_) return nullptr; const auto it = device_fault_->pipeline_names.find(id); return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; @@ -2166,6 +2168,7 @@ class VulkanContext { bool ray_tracing_ = false; std::unique_ptr xdxr_; // set: acceleration structures are XDXR BVH4 records std::atomic device_lost_{false}; + alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove alignas(64) std::mutex tracker_mutex_; alignas(64) std::mutex views_mutex_; @@ -2899,11 +2902,15 @@ class VulkanQueue : private QueueHolds::Holder { } } khr_guard{this}; std::function bindless_commit; - // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. - // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during - // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before - // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. - std::shared_lock resource_lock(context_.resource_mutex_); + // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_. + // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across + // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is + // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader + // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and + // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and + // submissions stay in order. + std::shared_lock pipeline_lock(context_.pipeline_mutex_); + std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock); std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools // with ticket 0 while tracker_lock is still held. @@ -2914,7 +2921,7 @@ class VulkanQueue : private QueueHolds::Holder { ~Depth24Guard() { if (active && d24) d24->retire(progress, 0); } - } depth24_guard{context_.depth24_.get(), progress_, false}; + } depth24_guard{nullptr, progress_, false}; struct ScratchGuard { // the same for the copy scratch ScratchBuffers* scratch = nullptr; VkSemaphore progress = VK_NULL_HANDLE; @@ -2922,7 +2929,7 @@ class VulkanQueue : private QueueHolds::Holder { ~ScratchGuard() { if (active && scratch) scratch->retire(progress, 0); } - } scratch_guard{context_.scratch_.get(), progress_, false}; + } scratch_guard{nullptr, progress_, false}; struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch IndirectArgumentClamp* clamp = nullptr; VkSemaphore progress = VK_NULL_HANDLE; @@ -2930,9 +2937,8 @@ class VulkanQueue : private QueueHolds::Holder { ~ClampGuard() { if (active && clamp) clamp->retire(progress, 0); } - } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; + } clamp_guard{nullptr, progress_, false}; const bool transfer_only = family_ == context_.transfer_only_family_; - if (!transfer_only) bindless_commit = context_.bindless_commit_; // Kept between executions: prepare refills each list's entries in the storage the last execution left, where // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). auto& prepared = prepared_; @@ -2940,42 +2946,9 @@ class VulkanQueue : private QueueHolds::Holder { // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. if (prepared.size() < lists.size()) prepared.resize(lists.size()); - ReplayFunctions replay = context_.replay_; + ReplayFunctions replay{}; unsigned mesh_draws = 0; - if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; std::vector geometry; - if (context_.geometry_provider_) { - replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { - if (!va || !bytes || bytes>UINT64_MAX-va) return false; - for (const auto& upload : geometry) { - if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; - buffer=upload.buffer; offset=upload.offset+(va-upload.source); - return true; - } - VulkanContext::GeometryUpload upload; - if (!context_.geometry_provider_(va,bytes,upload)) return false; - buffer=upload.buffer;offset=upload.offset; - geometry.push_back(std::move(upload)); - return true; - }; - } - replay.graphics_family = family_ == context_.graphics_family_; - replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy - : kind_ == QueueKind::compute ? detail::queue_stages_compute - : 0; - replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, - VkDeviceAddress& address) { - return stage_khr_instances(replay, build, khr_guard.stages, address); - }; - replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) { - return stage_xdxr_table(khr_guard.stages, address, count); - }; - if (replay.write_acceleration_structures_properties) { - replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool, - std::uint32_t& first) { - return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first); - }; - } std::uint64_t captures = 0; for (const auto* list : lists) for (const auto& command : list->commands()) @@ -2984,149 +2957,236 @@ class VulkanQueue : private QueueHolds::Holder { std::unique_ptr copy_batch; std::unique_ptr counted_batch; std::unique_ptr clamp_batch; - if (captures) { - if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) - return queue_unsupported(__LINE__); - // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, - // retaining main's resource -> tracker -> submit lock order through emit and submission. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - batch = context_.predicate_reducer_->batch(captures); - if (!batch) return queue_unsupported(__LINE__); - replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { - return batch->prepare(buffer, offset, out); + const auto& occlusion_memory = context_.occlusion_resolve_memory_; + const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; + const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; + std::uint32_t segments = 0, statistics_segments = 0; + bool has_queries = false; + const auto run_compiles = [this](std::size_t count, const std::function& job) { + context_.pipeline_workers_->run(count, job); + }; + PipelineCompiles prior_compiles; + bool has_prior_compiles = false; + for (int pass = 0;; ++pass) { + resource_lock.lock(); + bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function{}; + replay = context_.replay_; + mesh_draws = 0; + if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; + if (context_.geometry_provider_) { + replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { + if (!va || !bytes || bytes>UINT64_MAX-va) return false; + for (const auto& upload : geometry) { + if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; + buffer=upload.buffer; offset=upload.offset+(va-upload.source); + return true; + } + VulkanContext::GeometryUpload upload; + if (!context_.geometry_provider_(va,bytes,upload)) return false; + buffer=upload.buffer;offset=upload.offset; + geometry.push_back(std::move(upload)); + return true; + }; + } + replay.graphics_family = family_ == context_.graphics_family_; + replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy + : kind_ == QueueKind::compute ? detail::queue_stages_compute + : 0; + replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, + VkDeviceAddress& address) { + return stage_khr_instances(replay, build, khr_guard.stages, address); }; - replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { - context_.predicate_reducer_->capture(cb, p); + replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) { + return stage_xdxr_table(khr_guard.stages, address, count); }; - if (context_.predicated_copier_) { - copy_batch = context_.predicated_copier_->batch(); - replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, - VkDeviceSize dst, VkDeviceSize size, - std::vector& out) { - return copy_batch->prepare(source, destination, src, dst, size, out); - }; - replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector& jobs) { - context_.predicated_copier_->emit(cb, jobs); + if (replay.write_acceleration_structures_properties) { + replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool, + std::uint32_t& first) { + return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first); }; } - } - if (context_.scratch_) { - replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, - VkDeviceSize& offset) { + if (captures) { + if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) + return queue_unsupported(__LINE__); + // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, + // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission. if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!scratch_guard.active) { - context_.scratch_->collect(); - scratch_guard.active = true; + batch = context_.predicate_reducer_->batch(captures); + if (!batch) return queue_unsupported(__LINE__); + replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { + return batch->prepare(buffer, offset, out); + }; + replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { + context_.predicate_reducer_->capture(cb, p); + }; + if (context_.predicated_copier_) { + copy_batch = context_.predicated_copier_->batch(); + replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, + VkDeviceSize dst, VkDeviceSize size, + std::vector& out) { + return copy_batch->prepare(source, destination, src, dst, size, out); + }; + replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector& jobs) { + context_.predicated_copier_->emit(cb, jobs); + }; } - return context_.scratch_->get(bytes, buffer, offset); - }; - } - if (kind_ != QueueKind::copy && context_.indirect_clamp_) { - // The record scratch belongs to this submission: collected here, retired below with its ticket. The - // counter slots are read back once that ticket completes (the batch's destructor). - replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( - VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, - VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, - std::uint32_t max_count, ClampedIndirect& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); - if (!clamp_guard.active) { - context_.indirect_clamp_->collect(); - clamp_guard.active = true; + } + if (context_.scratch_) { + replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, + VkDeviceSize& offset) { + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!scratch_guard.active) { + scratch_guard.scratch = context_.scratch_.get(); + context_.scratch_->collect(); + scratch_guard.active = true; + } + return context_.scratch_->get(bytes, buffer, offset); + }; + } + if (kind_ != QueueKind::copy && context_.indirect_clamp_) { + // The record scratch belongs to this submission: collected here, retired below with its ticket. The + // counter slots are read back once that ticket completes (the batch's destructor). + replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( + VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, + VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, + std::uint32_t max_count, ClampedIndirect& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); + if (!clamp_guard.active) { + clamp_guard.clamp = context_.indirect_clamp_.get(); + context_.indirect_clamp_->collect(); + clamp_guard.active = true; + } + return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, + max_count, out); + }; + } + if (kind_ != QueueKind::copy && context_.counted_dispatch_) { + replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( + VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, + std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); + return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); + }; + replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { + context_.counted_dispatch_->emit(cb, job); + }; + } + if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { + replay.prepare_quad_indices = [this, &tracker_lock]( + VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, + VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, + scratch_offset, out); + }; + replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { + context_.quad_indices_->emit(cb, job); + }; + } + if (context_.depth24_ && !transfer_only) { + replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, + std::vector& parts) { + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!depth24_guard.active) { + depth24_guard.d24 = context_.depth24_.get(); + context_.depth24_->collect(); + depth24_guard.active = true; + } + return context_.depth24_->prepare(job, parts); + }; + } + if (can_resolve_occlusion) { + replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, + std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { + occlusion_resolve_->sum(cb, pool, first, count, dst, offset); + }; + replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, + std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { + occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); + }; + replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, + VkQueryPool primitives_pool, const std::uint8_t* mesh, + std::uint32_t first, std::uint32_t count, VkBuffer dst, + VkDeviceSize offset) { + occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, + offset); + }; + replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, + std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { + occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); + }; + } + segments = 0; + statistics_segments = 0; + has_queries = false; + // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial). + // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock + // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and + // workers stay alive), then re-prepare on pass 1 against current resources. + PipelineCompiles compiles; + replay.compiles = &compiles; + ReplayResult prepare_result = ReplayResult::success; + for (std::size_t i = 0; i < lists.size(); ++i) { + const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion); + if (result != ReplayResult::success) { + prepare_result = result; + break; } - return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, - out); - }; - } - if (kind_ != QueueKind::copy && context_.counted_dispatch_) { - replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( - VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, - std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); - return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); - }; - replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { - context_.counted_dispatch_->emit(cb, job); - }; - } - if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { - replay.prepare_quad_indices = [this, &tracker_lock]( - VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, - VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, - scratch_offset, out); - }; - replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { - context_.quad_indices_->emit(cb, job); - }; - } - if (context_.depth24_ && !transfer_only) { - replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, - std::vector& parts) { - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!depth24_guard.active) { - context_.depth24_->collect(); - depth24_guard.active = true; + if (prepared[i].segment_count > UINT32_MAX - segments || + prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) + return queue_unsupported(__LINE__); + segments += prepared[i].segment_count; + statistics_segments += prepared[i].statistics_segment_count; + has_queries = has_queries || !prepared[i].queries.empty(); + } + if (pass == 0 && !compiles.empty()) { + if (depth24_guard.active) { + context_.depth24_->retire(progress_, 0); + depth24_guard.active = false; } - return context_.depth24_->prepare(job, parts); - }; - } - const auto& occlusion_memory = context_.occlusion_resolve_memory_; - const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; - if (can_resolve_occlusion) { - replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum(cb, pool, first, count, dst, offset); - }; - replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); - }; - replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, - VkQueryPool primitives_pool, const std::uint8_t* mesh, - std::uint32_t first, std::uint32_t count, VkBuffer dst, - VkDeviceSize offset) { - occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, - offset); - }; - replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); - }; - } - const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; - std::uint32_t segments = 0, statistics_segments = 0; - bool has_queries = false; - // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of - // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline - // states that own them alive (remove_pipeline takes it uniquely). - PipelineCompiles compiles; - if (context_.pipeline_workers_) replay.compiles = &compiles; - ReplayResult prepare_result = ReplayResult::success; - for (std::size_t i = 0; i < lists.size(); ++i) { - const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion); - if (result != ReplayResult::success) { - prepare_result = result; - break; + if (scratch_guard.active) { + context_.scratch_->retire(progress_, 0); + scratch_guard.active = false; + } + if (clamp_guard.active) { + context_.indirect_clamp_->retire(progress_, 0); + clamp_guard.active = false; + } + batch.reset(); + copy_batch.reset(); + counted_batch.reset(); + clamp_batch.reset(); + if (tracker_lock.owns_lock()) tracker_lock.unlock(); + resource_lock.unlock(); + recycle_khr_stages(khr_guard.stages); + recycle_khr_as_queries(khr_guard.as_queries); + geometry.clear(); + + if (context_.pipeline_workers_) + compiles.build(run_compiles); + else + compiles.build_serial(); + const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result); + if (compile_result != ReplayResult::success) return compile_result; + prior_compiles = std::move(compiles); + has_prior_compiles = true; + continue; } - if (prepared[i].segment_count > UINT32_MAX - segments || - prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) - return queue_unsupported(__LINE__); - segments += prepared[i].segment_count; - statistics_segments += prepared[i].statistics_segment_count; - has_queries = has_queries || !prepared[i].queries.empty(); - } - prepare_result = build_pipelines( - compiles, std::span(prepared).first(lists.size()), prepare_result, - [this](std::size_t count, const std::function& job) { - context_.pipeline_workers_->run(count, job); - }); - if (prepare_result != ReplayResult::success) return prepare_result; + const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr; + prepare_result = context_.pipeline_workers_ + ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result, + run_compiles, prior) + : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()), + prepare_result, prior); + replay.compiles = nullptr; + if (prepare_result != ReplayResult::success) return prepare_result; + break; + } const auto segment_pool = [this](VkQueryType type, std::uint32_t count, std::shared_ptr& out) { const auto& vk = context_.vk; @@ -3253,6 +3313,7 @@ class VulkanQueue : private QueueHolds::Holder { const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), "vkEndCommandBuffer") == VK_SUCCESS; resource_lock.unlock(); + pipeline_lock.unlock(); const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); if (!submitted) discard(); if (depth24_guard.active) { @@ -3386,7 +3447,8 @@ class VulkanQueue : private QueueHolds::Holder { } const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), "vkEndCommandBuffer") == VK_SUCCESS; - resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held + resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held + pipeline_lock.unlock(); const bool wait_previous = ordered_timestamps && submitted_; if (wait_previous) { waits_.push_back(progress_); @@ -4071,7 +4133,8 @@ class VulkanQueue : private QueueHolds::Holder { std::vector prepared_; std::uint32_t open_labels_ = 0; // queue labels begun and not ended bool ok_ = false; - // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and + // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> + // submit_mutex_) and // guards the members above that execute, signal, wait and marker touch. std::mutex state_mutex_; std::deque held_; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index e20a291057..cb9e717c71 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -967,7 +967,7 @@ inline ReplayResult unsupported_at(int line) { // The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines() // then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid -// while the context's resource lock is held. +// while the context's pipeline lock is held. class PipelineCompiles { public: // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none. @@ -992,12 +992,33 @@ class PipelineCompiles { VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } const std::vector& uses() const { return uses_; } // in the order of the commands + // Whether this batch already attempted (pipeline, flags); writes its outcome (built handle or VK_NULL_HANDLE) to `out`. + bool lookup(const GraphicsPipeline* graphics, const ComputePipeline* compute, std::uint32_t flags, + VkPipeline& out) const { + const void* const pipeline = graphics ? static_cast(graphics) : compute; + const auto it = tickets_.find({pipeline, flags}); + if (it == tickets_.end()) return false; + out = jobs_[it->second - 1].built; + return true; + } + + // Whether this batch already attempted the job named by `other`'s `ticket`. + bool contains_ticket(const PipelineCompiles& other, Ticket ticket) const { + VkPipeline unused = VK_NULL_HANDLE; + const Job& job = other.jobs_[ticket - 1]; + return lookup(job.graphics, job.compute, job.flags, unused); + } + // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without - // workers, beside the others. + // workers, beside the others. Jobs already attempted in `prior` reuse that outcome without re-invoking build(). template - void build(Run&& run) { + void build(Run&& run, const PipelineCompiles* prior = nullptr) { std::vector single, large; - for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); + for (std::size_t i = 0; i < jobs_.size(); ++i) { + if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue; + (is_large(jobs_[i]) ? large : single).push_back(i); + } + if (single.empty() && large.empty()) return; const auto compile = [this](std::size_t i) { Job& job = jobs_[i]; job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); @@ -1011,6 +1032,26 @@ class PipelineCompiles { }); } + // Compiles jobs serially in command order without workers, stopping at the first fatal refusal (a failed draw, a + // failed indirect dispatch, or any failed dispatch under strict_replay()). Matches serial prepare() short-circuit + // semantics while allowing the caller to compile outside resource_mutex_. + void build_serial(const PipelineCompiles* prior = nullptr) { + std::vector done(jobs_.size(), false); + for (const Use& use : uses_) { + const std::size_t i = use.ticket - 1; + if (!done[i]) { + done[i] = true; + Job& job = jobs_[i]; + if (!prior || !prior->lookup(job.graphics, job.compute, job.flags, job.built)) { + job.built = + job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); + } + } + if (!jobs_[i].built && (use.user == User::draw || use.user == User::indirect_dispatch || strict_replay())) + return; + } + } + private: struct Job { const GraphicsPipeline* graphics; // one of the two @@ -2902,30 +2943,50 @@ class PreparedList { std::vector khr_postbuilds; }; -// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that -// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would -// have returned had they built each pipeline themselves. Every use in `compiles` comes from a command before the one that -// failed, so a pipeline that cannot be built counts first, at the earliest command that uses it: it fails the list of a -// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. -template -ReplayResult build_pipelines(PipelineCompiles& compiles, std::span lists, ReplayResult result, - Run&& run) { - if (compiles.empty()) return result; - compiles.build(run); +// Checks the outcomes of a compiled PipelineCompiles batch against `result` (the first prepare() failure, if any). +// Every use in `compiles` comes from a command before the one that failed, so a pipeline that cannot be built counts +// first, at the earliest command that uses it: it fails the list of a draw or an indirect dispatch, and a dispatch is +// dropped as prepare() drops one. Non-strict failed dispatches already logged in `prior` are not logged twice. +inline ReplayResult check_compiled_pipelines(const PipelineCompiles& compiles, ReplayResult result, + const PipelineCompiles* prior = nullptr) { for (const PipelineCompiles::Use& use : compiles.uses()) { if (compiles.built(use.ticket)) continue; if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__); - unresolved_at(__LINE__); + if (!prior || !prior->contains_ticket(compiles, use.ticket)) unresolved_at(__LINE__); } - if (result != ReplayResult::success) return result; + return result; +} + +inline ReplayResult finish_compiled_pipelines(const PipelineCompiles& compiles, std::span lists, + ReplayResult result, const PipelineCompiles* prior = nullptr) { + const ReplayResult checked = check_compiled_pipelines(compiles, result, prior); + if (checked != ReplayResult::success) return checked; for (PreparedList& list : lists) { for (detail::Prepared& command : list.commands) if (command.compile) command.pipeline.pipeline = compiles.built(command.compile); for (std::size_t i = 0; i < list.draw_count; ++i) if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile); } - return result; + return checked; +} + +// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that +// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would +// have returned had they built each pipeline themselves. +template +ReplayResult build_pipelines(PipelineCompiles& compiles, std::span lists, ReplayResult result, + Run&& run, const PipelineCompiles* prior = nullptr) { + if (compiles.empty()) return result; + compiles.build(run, prior); + return finish_compiled_pipelines(compiles, lists, result, prior); +} + +inline ReplayResult build_pipelines_serial(PipelineCompiles& compiles, std::span lists, + ReplayResult result, const PipelineCompiles* prior = nullptr) { + if (compiles.empty()) return result; + compiles.build_serial(prior); + return finish_compiled_pipelines(compiles, lists, result, prior); } inline 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 0000000000..045f81864d --- /dev/null +++ b/runtime/test/replay_pipeline_compile_unlock_test.cpp @@ -0,0 +1,291 @@ +// VulkanQueue::execute_now() releases resource_mutex_ and tracker_mutex_ while compiling unbuilt pipelines under +// pipeline_mutex_ alone, so add_resource()/remove_resource() and other queues do not stall behind shader compiles, +// remove_pipeline() still waits until compilation finishes, failed non-strict dispatches build only once, and +// pass-1 re-preparation observes resource updates made while resource_mutex_ was unlocked. No GPU or game data. +#include "../src/vulkan_backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using namespace leonida; + +template +T handle(std::uintptr_t n) { + return reinterpret_cast(n); +} + +VulkanDeviceFunctions driver{}; +std::atomic next_handle{10}; +std::mutex record_mutex; +std::vector> recorded_copies; + +PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc(VkDevice, const char* name) { +#define MOCK_DEVICE_FUNCTION(n) \ + if (std::string_view(name) == #n) return reinterpret_cast(driver.n); + LEONIDA_VK_DEVICE_FUNCTIONS(MOCK_DEVICE_FUNCTION) +#undef MOCK_DEVICE_FUNCTION + return nullptr; +} + +void init_mock_driver() { + driver = {}; + driver.vkCreateCommandPool = +[](VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*, + VkCommandPool* out) { + *out = handle(next_handle.fetch_add(1)); + return VK_SUCCESS; + }; + driver.vkDestroyCommandPool = +[](VkDevice, VkCommandPool, const VkAllocationCallbacks*) {}; + driver.vkCreateSemaphore = +[](VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*, + VkSemaphore* out) { + *out = handle(next_handle.fetch_add(1)); + return VK_SUCCESS; + }; + driver.vkDestroySemaphore = +[](VkDevice, VkSemaphore, const VkAllocationCallbacks*) {}; + driver.vkGetSemaphoreCounterValue = +[](VkDevice, VkSemaphore, std::uint64_t* value) { + *value = UINT64_MAX; + return VK_SUCCESS; + }; + driver.vkQueueWaitIdle = +[](VkQueue) { return VK_SUCCESS; }; + driver.vkAllocateCommandBuffers = +[](VkDevice, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* out) { + for (std::uint32_t i = 0; i < info->commandBufferCount; ++i) + out[i] = handle(next_handle.fetch_add(1)); + return VK_SUCCESS; + }; + driver.vkResetCommandBuffer = +[](VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; }; + driver.vkBeginCommandBuffer = +[](VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; }; + driver.vkEndCommandBuffer = +[](VkCommandBuffer) { return VK_SUCCESS; }; + driver.vkQueueSubmit = +[](VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { return VK_SUCCESS; }; + driver.vkCmdPipelineBarrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, + const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {}; + driver.vkCmdBindPipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + driver.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + driver.vkCmdDispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}; + driver.vkCmdCopyBuffer = +[](VkCommandBuffer, VkBuffer src, VkBuffer dst, std::uint32_t, const VkBufferCopy*) { + std::lock_guard lock(record_mutex); + recorded_copies.emplace_back(src, dst); + }; + driver.vkCmdCopyBufferToImage = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, std::uint32_t, + const VkBufferImageCopy*) {}; + driver.vkCmdCopyImageToBuffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer, std::uint32_t, + const VkBufferImageCopy*) {}; + driver.vkCmdCopyImage = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, std::uint32_t, + const VkImageCopy*) {}; +} + +struct SlowPipeline { + std::mutex mutex; + std::condition_variable cv; + bool entered = false; + bool allow_finish = false; + bool fail = false; + std::atomic builds{0}; + VkPipeline handle_out = VK_NULL_HANDLE; + + VkPipeline build() { + builds.fetch_add(1, std::memory_order_relaxed); + { + std::unique_lock lock(mutex); + entered = true; + cv.notify_all(); + cv.wait(lock, [this] { return allow_finish; }); + if (!fail) handle_out = handle(0x7001); + return handle_out; + } + } + + VkPipeline find() { + std::unique_lock lock(mutex, std::try_to_lock); + return lock.owns_lock() ? handle_out : VK_NULL_HANDLE; + } + + void release() { + std::lock_guard lock(mutex); + allow_finish = true; + cv.notify_all(); + } +}; + +// Exercises concurrent add_resource/remove_resource, a second queue submission, resource replacement observed on +// pass-1 re-prepare, and remove_pipeline() waiting on pipeline_mutex_ while a slow compile runs. +int test_unlocks_resources_during_compile(bool with_workers) { + { + std::lock_guard lock(record_mutex); + recorded_copies.clear(); + } + VulkanContext context(mock_get_device_proc, handle(1), false); + if (with_workers) context.set_pipeline_workers(std::make_unique(2)); + + ResourceBinding src{}; + src.buffer = handle(101); + src.size = 64; + ResourceBinding dst_old{}; + dst_old.buffer = handle(102); + dst_old.size = 64; + ResourceBinding dst_new{}; + dst_new.buffer = handle(202); + dst_new.size = 64; + context.add_resource(1, src); + context.add_resource(2, dst_old); + + SlowPipeline slow; + constexpr std::uintptr_t slow_id = 0x100; + constexpr std::uintptr_t fast_id = 0x200; + + ComputePipeline slow_pso{}; + slow_pso.layout = handle(5); + slow_pso.build_context = &slow; + slow_pso.build = [](void* ctx) { return static_cast(ctx)->build(); }; + slow_pso.built = [](void* ctx) { return static_cast(ctx)->find(); }; + context.add_pipeline(slow_id, slow_pso); + + ComputePipeline fast_pso{}; + fast_pso.layout = handle(5); + fast_pso.pipeline = handle(0x8001); + context.add_pipeline(fast_id, fast_pso); + + VulkanQueue queue_a(context, handle(1), 0, VulkanQueue::QueueKind::compute); + VulkanQueue queue_b(context, handle(2), 0, VulkanQueue::QueueKind::compute); + EXPECT(queue_a.ok() && queue_b.ok()); + + CommandList list_a; + EXPECT(list_a.dispatch({slow_id, {}, 1, 1, 1})); + EXPECT(list_a.copy_buffer({2, 0, 1, 0, 64})); + EXPECT(list_a.close()); + + CommandList list_b; + EXPECT(list_b.dispatch({fast_id, {}, 1, 1, 1})); + EXPECT(list_b.close()); + + ReplayResult result_a = ReplayResult::unsupported; + std::thread thread_a([&] { + const CommandList* ptr = &list_a; + result_a = queue_a.execute({&ptr, 1}); + }); + + // Wait for thread_a (or a PipelineWorkers thread) to enter slow.build(). + { + std::unique_lock lock(slow.mutex); + const bool entered = slow.cv.wait_for(lock, std::chrono::seconds(5), [&] { return slow.entered; }); + if (!entered) { + slow.allow_finish = true; + slow.cv.notify_all(); + lock.unlock(); + thread_a.join(); + EXPECT(false); + } + } + + // While compilation is paused: + // 1. add_resource() / remove_resource() and a second queue submission must complete without blocking. + std::atomic resources_unblocked{false}; + ReplayResult result_b = ReplayResult::unsupported; + std::thread resource_thread([&] { + ResourceBinding temp{}; + temp.buffer = handle(303); + temp.size = 64; + context.add_resource(3, temp); + context.remove_resource(3); + // Replace resource 2 while resource_mutex_ is unlocked so pass-1 re-prepare must bind dst_new. + context.remove_resource(2); + context.add_resource(2, dst_new); + const CommandList* ptr = &list_b; + result_b = queue_b.execute({&ptr, 1}); + resources_unblocked.store(true, std::memory_order_release); + }); + + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (!resources_unblocked.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + + if (!resources_unblocked.load(std::memory_order_acquire)) { + slow.release(); + resource_thread.join(); + thread_a.join(); + EXPECT(false); + } + resource_thread.join(); + EXPECT(result_b == ReplayResult::success); + + // 2. remove_pipeline() must wait on pipeline_mutex_ until compilation finishes (protecting ComputePipeline*). + std::atomic remove_started{false}; + std::atomic remove_finished{false}; + std::thread remove_thread([&] { + remove_started.store(true, std::memory_order_release); + context.remove_pipeline(slow_id); + remove_finished.store(true, std::memory_order_release); + }); + while (!remove_started.load(std::memory_order_acquire)) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + const bool removed_early = remove_finished.load(std::memory_order_acquire); + + slow.release(); + thread_a.join(); + remove_thread.join(); + + EXPECT(!removed_early); + EXPECT(remove_finished.load(std::memory_order_acquire)); + EXPECT(result_a == ReplayResult::success); + EXPECT(slow.builds.load() == 1); + { + std::lock_guard lock(record_mutex); + EXPECT(recorded_copies.size() == 1); + EXPECT(recorded_copies[0].first == src.buffer && recorded_copies[0].second == dst_new.buffer); + } + return 0; +} + +// A non-strict failed compute dispatch must not invoke build() a second time on pass-1 re-prepare. +int test_failed_compute_dispatch_built_once() { + VulkanContext context(mock_get_device_proc, handle(1), false); + SlowPipeline failing; + failing.fail = true; + failing.allow_finish = true; + + constexpr std::uintptr_t fail_id = 0x300; + ComputePipeline pso{}; + pso.layout = handle(5); + pso.build_context = &failing; + pso.build = [](void* ctx) { return static_cast(ctx)->build(); }; + pso.built = [](void* ctx) { return static_cast(ctx)->find(); }; + context.add_pipeline(fail_id, pso); + + VulkanQueue queue(context, handle(3), 0, VulkanQueue::QueueKind::compute); + EXPECT(queue.ok()); + + CommandList list; + EXPECT(list.dispatch({fail_id, {}, 1, 1, 1})); + EXPECT(list.close()); + const CommandList* ptr = &list; + const ReplayResult r = queue.execute({&ptr, 1}); + EXPECT(r == (strict_replay() ? ReplayResult::unresolved_resource : ReplayResult::success)); + EXPECT(failing.builds.load() == 1); + return 0; +} + +} // namespace + +int main() { + init_mock_driver(); + if (test_unlocks_resources_during_compile(true) != 0) return 1; + if (test_unlocks_resources_during_compile(false) != 0) return 1; + if (test_failed_compute_dispatch_built_once() != 0) return 1; + std::printf("replay_pipeline_compile_unlock_test: passed\n"); + return 0; +} diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp index 35b6057edb..45a28f7c20 100644 --- a/runtime/test/replay_pipeline_compiles_test.cpp +++ b/runtime/test/replay_pipeline_compiles_test.cpp @@ -547,6 +547,80 @@ void random_submissions(PipelineWorkers& workers) { std::to_string(succeeded)); } +// Re-preparing after a prior compile pass reuses prior outcomes (both built handles and non-strict failed compute +// dispatches) without re-invoking build() or failing the submission. +void prior_compiles_reuse(PipelineWorkers& workers) { + Registry registry({ + {.compute = true, .pending = true, .fails = false, .with_built = true}, + {.compute = true, .pending = true, .fails = true, .with_built = true}, + }); + const std::vector lists = record({{ + CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 1}, + CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 2}, + }}); + std::vector prepared(1); + ReplayFunctions vk = functions(registry); + PipelineCompiles first; + vk.compiles = &first; + const ReplayResult r0 = prepare(lists[0], resolve, vk, prepared[0]); + check(r0 == ReplayResult::success && first.size() == 2, "prior_compiles_reuse: pass 0 collected both"); + first.build([&](std::size_t count, const std::function& job) { workers.run(count, job); }); + const ReplayResult c0 = check_compiled_pipelines(first, r0); + if (strict_replay()) { + check(c0 == ReplayResult::unresolved_resource, "prior_compiles_reuse: strict fails on failed dispatch"); + return; + } + check(c0 == ReplayResult::success, "prior_compiles_reuse: non-strict tolerates failed dispatch"); + check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, + "prior_compiles_reuse: each pipeline built once on pass 0"); + // Reset the failed flag on owner 2 so any redundant build() call on pass 1 would be caught in attempts. + registry.owners[1]->failed = false; + + PipelineCompiles second; + vk.compiles = &second; + const ReplayResult r1 = prepare(lists[0], resolve, vk, prepared[0]); + const ReplayResult b1 = build_pipelines( + second, std::span(prepared), r1, + [&](std::size_t count, const std::function& job) { workers.run(count, job); }, + &first); + check(b1 == ReplayResult::success, "prior_compiles_reuse: pass 1 succeeded"); + check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, + "prior_compiles_reuse: pass 1 did not re-invoke build() on prior failure"); + check(prepared[0].commands[0].pipeline.pipeline == handle(0x1001), + "prior_compiles_reuse: built compute handle attached"); + check(prepared[0].commands[1].pipeline.pipeline == VK_NULL_HANDLE, + "prior_compiles_reuse: failed compute dispatch stays dropped"); +} + +// Serial compilation stops at the first refused graphics draw (matching pre-unlock serial semantics and +// d3d12_pipeline_workers::refused_graphics) instead of compiling later pipelines in the same submission. +void serial_stops_at_refused_draw() { + Registry registry({ + {.compute = false, .pending = true, .fails = false}, + {.compute = false, .pending = true, .fails = true}, + {.compute = false, .pending = true, .fails = false}, + {.compute = false, .pending = true, .fails = false}, + }); + const std::vector lists = record({{ + CommandSpec{.kind = CommandSpec::draw, .pipeline = 1}, + CommandSpec{.kind = CommandSpec::draw, .pipeline = 2}, + CommandSpec{.kind = CommandSpec::draw, .pipeline = 3}, + CommandSpec{.kind = CommandSpec::draw, .pipeline = 4}, + }}); + std::vector prepared(1); + ReplayFunctions vk = functions(registry); + PipelineCompiles compiles; + vk.compiles = &compiles; + const ReplayResult r = prepare(lists[0], resolve, vk, prepared[0]); + check(r == ReplayResult::success && compiles.size() == 4, "serial_stops: collected all 4 draws"); + const ReplayResult out = build_pipelines_serial(compiles, std::span(prepared), r); + check(out == ReplayResult::unsupported, "serial_stops: refused draw returns unsupported"); + check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, + "serial_stops: built first draw and attempted refused second draw"); + check(registry.owners[2]->attempts.empty() && registry.owners[3]->attempts.empty(), + "serial_stops: did not compile draws past the first refused draw"); +} + } // namespace int main() { @@ -555,8 +629,10 @@ int main() { cases(workers); if (threads) many(workers); reused_lists(workers); + prior_compiles_reuse(workers); random_submissions(workers); } + serial_stops_at_refused_draw(); check(large_together == 0, "two large pipelines were built at once"); if (failures) return 1; std::printf("replay_pipeline_compiles_test: passed\n");