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:
authorAslan2142 <jan.trencansky@protonmail.com>2026-11-27 13:02:22 +0100
committerGitHub <noreply@github.com>2026-11-27 13:02:22 +0100
commitf75b2b4258cf25e360bd6d59f554ca4ebdf30bf4 (patch)
treeaed044faed97a033c8dc4a3b37b1c09fcb1f9162 /runtime
parenta3bafd05d02b1628796a24d851693adb0d9bd136 (diff)
parentebdc9916278981721453db22a533659a4e971efa (diff)
Merge pull request #2412 from OreoFR/fix/compile-gate-bounded
compile gate: adaptive per kind of create, re-armed by a held submission (RT-COMPILE-GATE-ADAPTIVE)
Diffstat (limited to 'runtime')
-rw-r--r--runtime/README.md5
-rw-r--r--runtime/shims/d3d12_pipeline_compile.h8
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp32
-rw-r--r--runtime/shims/dxgi_swapchain.h2
-rw-r--r--runtime/src/vulkan_backend.h15
-rw-r--r--runtime/src/vulkan_device_fault.h614
-rw-r--r--runtime/src/vulkan_present.h13
-rw-r--r--runtime/test/submit_mutex_test.cpp754
8 files changed, 1376 insertions, 67 deletions
diff --git a/runtime/README.md b/runtime/README.md
index ab8451e6f..b885981fc 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -421,7 +421,10 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
421| `LEONIDA_TEXTURE_REFRESH_ASYNC` | unset | `1` moves the before-submission refresh of the title textures (`refresh_title_textures`) to a worker: a submission only wakes it, and fills by itself only the mapped textures that were never filled, so their first draw has their bytes. Persistent mappings are hashed whole on the worker every pass; the rest is swept 128 textures at a time. A texture changed since may be sampled a frame behind. | 421| `LEONIDA_TEXTURE_REFRESH_ASYNC` | unset | `1` moves the before-submission refresh of the title textures (`refresh_title_textures`) to a worker: a submission only wakes it, and fills by itself only the mapped textures that were never filled, so their first draw has their bytes. Persistent mappings are hashed whole on the worker every pass; the rest is swept 128 textures at a time. A texture changed since may be sampled a frame behind. |
422| `LEONIDA_SUBMIT_ASYNC` | `0` | `<n>`: each queue's `ExecuteCommandLists`, `Signal`, `Wait` and markers run in call order on a worker of the queue's own (`src/vulkan_backend.h`), at most n batches queued; the caller of the next one waits for room. The replay, the before-submission refreshes and `vkQueueSubmit` then leave the title's thread. A batch that fails is reported as a held one is. `0`: on the caller's thread. | 422| `LEONIDA_SUBMIT_ASYNC` | `0` | `<n>`: each queue's `ExecuteCommandLists`, `Signal`, `Wait` and markers run in call order on a worker of the queue's own (`src/vulkan_backend.h`), at most n batches queued; the caller of the next one waits for room. The replay, the before-submission refreshes and `vkQueueSubmit` then leave the title's thread. A batch that fails is reported as a held one is. `0`: on the caller's thread. |
423| `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | `<n>`: a compute warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the last second); the pipeline is built at its first use instead (docs/d3d12_vulkan.md, "Pipelines still being built"). Unset or `0`: every warm-up runs, ordered behind a submission's compiles by the large-compile gate. | 423| `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | `<n>`: a compute warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the last second); the pipeline is built at its first use instead (docs/d3d12_vulkan.md, "Pipelines still being built"). Unset or `0`: every warm-up runs, ordered behind a submission's compiles by the large-compile gate. |
424| `LEONIDA_COMPILE_GATE` | unset | `1`: a compute pipeline build holds the device's submit lock for its driver calls, so no compute compile runs while a queue submits. Unset: the asynchronous workers compile while other queues submit. | 424| `LEONIDA_COMPILE_GATE` | on (classic) | The compile gate (`SubmitMutex::CompileTurn`, `src/vulkan_device_fault.h`): a queue submission (or a present or device wait) does not enter the driver while a pipeline create is in it, and waits in the runtime instead, since on NVIDIA 630.20 a `vkQueueSubmit` that entered during a long `vkCreateComputePipelines` waited 10 s in the driver and lost the device. Creates pass together; one that arrives while a submission waits queues behind it. Unset: the classic gate, as before the adaptive one: compute creates only, waited for however long they take (`LEONIDA_COMPILE_GATE_WAIT_MS` can bound it), no probes. `adaptive`: the adaptive gate, opt-in until it has run on a driver that holds submissions (630.20), where its first probe of a kind enters the driver after the probe budget and loses the device if that create stays 10 s more. The adaptive gate's wait is bounded by `LEONIDA_COMPILE_GATE_WAIT_MS`. Each submission that enters the driver next to a create the gate went past (at that limit, or earlier at the probe budget, `LEONIDA_COMPILE_GATE_PROBE_MS`) is a probe; two that come back in under 250 ms, at least 1 s apart, with the create still in the driver turn the gate off for the rest of the run (NVIDIA 621.40: 0-11 ms), and one that stays 2 s or more keeps it on; both are logged once. The verdict is kept per kind of create, compute and graphics (mesh included; graphics creates pass the gate since then, only compute ones did before): on NVIDIA 621.40 submissions came back in 0-12 ms beside compute creates, but one sat 54 s in the driver beside a 56 s mesh create and the device was lost. A kind that is off is still timed, and a submission that stays 2 s beside one of its creates turns it back on. A submission never goes ahead, at the limit or the budget, beside a create of a kind whose verdict is that it holds submissions: it waits for that create up to `LEONIDA_COMPILE_GATE_HELD_WAIT_MS`. On a device loss the log names the creates in the driver (kind, program, size, how long) and each kind's gate. `1`: always gate, graphics creates too, with no limit unless `LEONIDA_COMPILE_GATE_WAIT_MS` sets one, never probe or turn it off, and a compute pipeline build also holds the submit lock for its driver calls (`compute_driver_turn`, `shims/d3d12_vulkan_device.cpp`). `0`: no gate. |
425| `LEONIDA_COMPILE_GATE_WAIT_MS` | 0 (15000 with `LEONIDA_COMPILE_GATE=adaptive`) | `<ms>`: how long a submission waits at the compile gate before it goes ahead anyway; the creates in the driver then hold no later submission back (creates that enter after it are waited for again), and the log says how long the submission then took in the driver. The waiter holds the submit lock, so every queue stops behind it, and the title's hang watchdog ends the process after 30 s (one create stayed in the driver for over 54 s on NVIDIA 621.40). 15 s keeps the 630.20 protection for creates of up to 25 s. The same with the watchdog kept kicked: nothing ends the run then, but the stops still cost the frames (an RTX 4060 run that way had 459 waits, 155 s in all, by t=202 s). `0`: no limit, and with `LEONIDA_COMPILE_GATE_PROBE_MS` unset no probes either: the gate waits however long the creates take and never adapts. |
426| `LEONIDA_COMPILE_GATE_HELD_WAIT_MS` | 60000 | `<ms>`: with the adaptive gate, how long a submission waits for creates of a kind the gate found to hold submissions (`docs/d3d12_vulkan.md`) before it goes ahead anyway; those creates are then not waited for again. `0`: until they leave. |
427| `LEONIDA_COMPILE_GATE_PROBE_MS` | 2500 with `LEONIDA_COMPILE_GATE=adaptive` (0 with `LEONIDA_COMPILE_GATE_WAIT_MS=0`) | `<ms>`: the adaptive gate's probe budget. Until it knows whether the driver holds a submission behind a create, a submission also goes ahead once the submissions' waits at the gate in the last 10 s, its own included, add up to this; a single wait reaches it at 2.5 s. On NVIDIA 621.40 waits of 3-7 s, none near the 15 s limit, came back to back and kept the title's main loop from reporting for 30 s; on an RTX 4060 with the watchdog kept kicked, 459 waits of up to 2.9 s took 155 s by t=202 s. The cost on a driver that does hold submissions (630.20): the first probe enters the driver after 2.5 s of waiting and loses the device if the create stays 10 s more; the held verdict then stops the early probes. `0`: probes only at `LEONIDA_COMPILE_GATE_WAIT_MS`. Used only with `LEONIDA_COMPILE_GATE=adaptive`. |
425| `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. | 428| `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. |
426| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | A second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. | 429| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | A second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. |
427| `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. | 430| `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. |
diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h
index a0ff0e86d..bb4ab0327 100644
--- a/runtime/shims/d3d12_pipeline_compile.h
+++ b/runtime/shims/d3d12_pipeline_compile.h
@@ -165,13 +165,15 @@ inline bool compile_worker_trigger(const char* trigger) {
165// behind it go first, and does so before its vkCreateShaderModule and vkDestroyShaderModule too; a title thread 165// behind it go first, and does so before its vkCreateShaderModule and vkDestroyShaderModule too; a title thread
166// waits only for the holder, and only before a pipeline create (it may wait out a vkDeviceWaitIdle or a present: 166// waits only for the holder, and only before a pipeline create (it may wait out a vkDeviceWaitIdle or a present:
167// waits of 50 ms or more are logged). 167// waits of 50 ms or more are logged).
168// - a pipeline create passes the compile gate (SubmitMutex::CompileTurn) for the length of the call. 168// - a pipeline create passes the compile gate (SubmitMutex::CompileTurn) for the length of the call, as its kind
169// (compute, or graphics with mesh): the adaptive gate keeps a verdict per kind.
169// - the compile worker, which runs below normal priority, runs the call at normal priority, so a preempted worker 170// - the compile worker, which runs below normal priority, runs the call at normal priority, so a preempted worker
170// does not sit on a driver lock a submit waits for. 171// does not sit on a driver lock a submit waits for.
171class DriverTurn { 172class DriverTurn {
172public: 173public:
173 DriverTurn(leonida::SubmitMutex& submits, const char* trigger, const char* call, bool pipeline, 174 DriverTurn(leonida::SubmitMutex& submits, const char* trigger, const char* call, bool pipeline,
174 const char* name = nullptr) 175 const char* name = nullptr,
176 leonida::SubmitMutex::CreateKind kind = leonida::SubmitMutex::CreateKind::compute, std::size_t bytes = 0)
175 : worker_(compile_worker_trigger(trigger)) { 177 : worker_(compile_worker_trigger(trigger)) {
176 // Normal priority first: a below-normal worker that waits its turn at normal priority cannot keep losing the 178 // Normal priority first: a below-normal worker that waits its turn at normal priority cannot keep losing the
177 // race to the next submit, and holds the gate (below) only at normal priority. 179 // race to the next submit, and holds the gate (below) only at normal priority.
@@ -187,7 +189,7 @@ public:
187 if (waited >= 50) note("waited for the submit lock", trigger, call, name, waited); 189 if (waited >= 50) note("waited for the submit lock", trigger, call, name, waited);
188 } 190 }
189 if (pipeline) { 191 if (pipeline) {
190 gate_.emplace(submits); 192 gate_.emplace(submits, leonida::SubmitMutex::CreateInfo{kind, name, trigger, bytes});
191 if (gate_->waited_ms() >= 50) note("waited at the compile gate", trigger, call, name, gate_->waited_ms()); 193 if (gate_->waited_ms() >= 50) note("waited at the compile gate", trigger, call, name, gate_->waited_ms());
192 } 194 }
193 } 195 }
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 37d1d007e..6c8d9345c 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -11266,7 +11266,8 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn
11266 // gate: from the journal a build takes milliseconds and the warm-up worker makes them back to back, and 11266 // gate: from the journal a build takes milliseconds and the warm-up worker makes them back to back, and
11267 // three warm boots lost the device in a vkQueueSubmit (no GPU fault, no TDR) while only the create was 11267 // three warm boots lost the device in a vkQueueSubmit (no GPU fault, no TDR) while only the create was
11268 // gated. No file I/O in here. 11268 // gated. No file I/O in here.
11269 const DriverTurn turn(submits, trigger, "vkCreateComputePipelines", true, entry->name.c_str()); 11269 const DriverTurn turn(submits, trigger, "vkCreateComputePipelines", true, entry->name.c_str(),
11270 leonida::SubmitMutex::CreateKind::compute, bytes);
11270 { 11271 {
11271 const leonida::aftermath::ShaderName named(entry->name); 11272 const leonida::aftermath::ShaderName named(entry->name);
11272 if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return out; 11273 if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return out;
@@ -12902,11 +12903,26 @@ private:
12902 const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); 12903 const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline");
12903 const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", 12904 const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager",
12904 program, fragment, unbound); 12905 program, fragment, unbound);
12905 const auto result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { 12906 // Through the compile gate as a graphics create (a mesh pipeline is one): on NVIDIA 621.40 a vkQueueSubmit
12906 info.flags = f; 12907 // sat in the driver for as long as a mesh create was in it (54 s) and lost the device. Not with the classic
12907 pipeline = VK_NULL_HANDLE; 12908 // gate (the default), which keeps graphics creates out of it as before.
12908 return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline); 12909 const char* gate_name = nullptr;
12909 }); 12910 for (const auto& source : sources_)
12911 if (source.entry && source.slot == 0) gate_name = source.entry->name.c_str();
12912 VkResult result = VK_ERROR_UNKNOWN;
12913 {
12914 std::optional<DriverTurn> turn;
12915 if (leonida::SubmitMutex::compile_gate_graphics())
12916 turn.emplace(device_.context->submit_mutex(), trigger,
12917 r.mesh ? "vkCreateGraphicsPipelines (mesh)" : "vkCreateGraphicsPipelines", true, gate_name,
12918 leonida::SubmitMutex::CreateKind::graphics, bytes);
12919 result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) {
12920 info.flags = f;
12921 pipeline = VK_NULL_HANDLE;
12922 return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr,
12923 &pipeline);
12924 });
12925 }
12910 if (status) *status = result; 12926 if (status) *status = result;
12911 profile.finish(int(result)); 12927 profile.finish(int(result));
12912 trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); 12928 trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result);
@@ -14956,7 +14972,7 @@ public:
14956 // after it, so the generations flush() retires are free at once. 14972 // after it, so the generations flush() retires are free at once.
14957 { 14973 {
14958 std::lock_guard submit(context.submit_mutex()); 14974 std::lock_guard submit(context.submit_mutex());
14959 const leonida::SubmitMutex::SubmitTurn turn(context.submit_mutex()); // the compile gate 14975 const leonida::SubmitMutex::SubmitTurn turn(context.submit_mutex(), false); // the compile gate
14960 context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); 14976 context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle");
14961 } 14977 }
14962 state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); 14978 state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed);
@@ -15275,7 +15291,7 @@ public:
15275 if (state_.context) { 15291 if (state_.context) {
15276 { 15292 {
15277 std::lock_guard lock(state_.context->submit_mutex()); 15293 std::lock_guard lock(state_.context->submit_mutex());
15278 const leonida::SubmitMutex::SubmitTurn turn(state_.context->submit_mutex()); // the compile gate 15294 const leonida::SubmitMutex::SubmitTurn turn(state_.context->submit_mutex(), false); // the compile gate
15279 state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), 15295 state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device),
15280 "vkDeviceWaitIdle"); 15296 "vkDeviceWaitIdle");
15281 } 15297 }
diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h
index 477bc29b2..87351a344 100644
--- a/runtime/shims/dxgi_swapchain.h
+++ b/runtime/shims/dxgi_swapchain.h
@@ -220,7 +220,7 @@ public:
220 pi.pSwapchains = &swapchain_; 220 pi.pSwapchains = &swapchain_;
221 pi.pImageIndices = &image_index; 221 pi.pImageIndices = &image_index;
222 std::lock_guard lock(submit_mutex_); 222 std::lock_guard lock(submit_mutex_);
223 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate 223 const SubmitMutex::SubmitTurn turn(submit_mutex_, false); // a queue operation: the compile gate
224 const VkResult r = observe(fn_.queue_present(queue_, &pi), "vkQueuePresentKHR (DXGI)"); 224 const VkResult r = observe(fn_.queue_present(queue_, &pi), "vkQueuePresentKHR (DXGI)");
225 return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; 225 return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR;
226 } 226 }
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index bf970aa28..18bcc07ba 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1700,7 +1700,7 @@ public:
1700 ++host_texture_stats_.waits; 1700 ++host_texture_stats_.waits;
1701 // A device wait is a queue operation: it passes the compile gate, so it never waits in the driver behind a 1701 // A device wait is a queue operation: it passes the compile gate, so it never waits in the driver behind a
1702 // long pipeline create (the starved wait that loses the device after 10 s). 1702 // long pipeline create (the starved wait that loses the device after 10 s).
1703 const SubmitMutex::SubmitTurn turn(submit_mutex_); 1703 const SubmitMutex::SubmitTurn turn(submit_mutex_, false);
1704 const auto result = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title texture upload)"); 1704 const auto result = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title texture upload)");
1705 // Not done in time: VK_NOT_READY, so the caller takes its staged path (ordered on the queue) or tries 1705 // Not done in time: VK_NOT_READY, so the caller takes its staged path (ordered on the queue) or tries
1706 // again later, and the skip is not counted as a failed fill. 1706 // again later, and the skip is not counted as a failed fill.
@@ -1722,7 +1722,7 @@ public:
1722 LayoutPieces pieces; 1722 LayoutPieces pieces;
1723 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; 1723 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN;
1724 if (image_work_pending_) { 1724 if (image_work_pending_) {
1725 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate (as above) 1725 const SubmitMutex::SubmitTurn turn(submit_mutex_, false); // a queue operation: the compile gate (as above)
1726 const auto r = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title staging)"); 1726 const auto r = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title staging)");
1727 if (r != VK_SUCCESS) return r; 1727 if (r != VK_SUCCESS) return r;
1728 image_work_pending_ = false; 1728 image_work_pending_ = false;
@@ -2073,7 +2073,7 @@ public:
2073 } 2073 }
2074 2074
2075 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept { 2075 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept {
2076 set_device_lost(device_lost_, where); 2076 if (set_device_lost(device_lost_, where)) submit_mutex_.report_creates_on_loss(); // which creates were in it
2077 run_device_lost_hook(); // LEONIDA_AFTERMATH: the GPU crash dump is written before waiters wake 2077 run_device_lost_hook(); // LEONIDA_AFTERMATH: the GPU crash dump is written before waiters wake
2078 if (fence_dispatcher_) { 2078 if (fence_dispatcher_) {
2079 try { 2079 try {
@@ -2308,10 +2308,11 @@ private:
2308 if (gate.submits != gate_logged.submits || gate.creates != gate_logged.creates) { 2308 if (gate.submits != gate_logged.submits || gate.creates != gate_logged.creates) {
2309 gate_logged = gate; 2309 gate_logged = gate;
2310 std::fprintf(stderr, "[rt] compile-gate: t=%.0f s: %llu submissions waited for pipeline creates " 2310 std::fprintf(stderr, "[rt] compile-gate: t=%.0f s: %llu submissions waited for pipeline creates "
2311 "(%lld ms in all, longest %lld ms); %llu creates waited behind a submission " 2311 "(%lld ms in all, longest %lld ms, %llu went ahead at the limit); %llu creates "
2312 "(%lld ms in all, longest %lld ms)\n", 2312 "waited behind a submission (%lld ms in all, longest %lld ms)\n",
2313 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(gate.submits), 2313 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(gate.submits),
2314 static_cast<long long>(gate.submit_ms), static_cast<long long>(gate.submit_max_ms), 2314 static_cast<long long>(gate.submit_ms), static_cast<long long>(gate.submit_max_ms),
2315 static_cast<unsigned long long>(gate.ahead),
2315 static_cast<unsigned long long>(gate.creates), static_cast<long long>(gate.create_ms), 2316 static_cast<unsigned long long>(gate.creates), static_cast<long long>(gate.create_ms),
2316 static_cast<long long>(gate.create_max_ms)); 2317 static_cast<long long>(gate.create_max_ms));
2317 } 2318 }
@@ -2614,7 +2615,7 @@ public:
2614 context_.holds().pump_ready(); // presents queued behind what was just dropped can run 2615 context_.holds().pump_ready(); // presents queued behind what was just dropped can run
2615 if (queue_) { 2616 if (queue_) {
2616 std::lock_guard lock(context_.submit_mutex()); 2617 std::lock_guard lock(context_.submit_mutex());
2617 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 2618 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
2618 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 2619 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
2619 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); 2620 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle");
2620 if (idle_result == VK_SUCCESS) { 2621 if (idle_result == VK_SUCCESS) {
@@ -2903,7 +2904,7 @@ public:
2903 bool idle() { 2904 bool idle() {
2904 flush_async(); 2905 flush_async();
2905 std::lock_guard lock(context_.submit_mutex()); 2906 std::lock_guard lock(context_.submit_mutex());
2906 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 2907 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
2907 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; 2908 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS;
2908 } 2909 }
2909 2910
diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h
index b3af188d1..17f420934 100644
--- a/runtime/src/vulkan_device_fault.h
+++ b/runtime/src/vulkan_device_fault.h
@@ -309,6 +309,27 @@ struct DriverCompile {
309}; 309};
310inline DriverCompile driver_compile; 310inline DriverCompile driver_compile;
311 311
312// The compile gate's types, for SubmitMutex (which names them CreateKind, CreateInfo and GateAhead). At namespace
313// scope, not nested: a default argument `= {}` of a nested class with default member initializers is rejected by
314// clang and GCC inside the enclosing class (the member initializers are not parsed until that class is complete).
315enum class CompileGateKind : std::uint8_t { compute, graphics }; // graphics: mesh pipelines too
316// What a create is, for the verdicts and the reports. Names are ShaderLibrary strings, valid until device teardown
317// (or literals).
318struct CompileGateCreate {
319 CompileGateKind kind = CompileGateKind::compute;
320 const char* name = nullptr;
321 const char* trigger = nullptr;
322 std::size_t bytes = 0; // SPIR-V
323};
324struct CompileGateAhead { // a submission that entered the driver alongside creates not waited for
325 std::int64_t since_ms = -1; // when it entered, or -1: no such create was in the driver
326 std::uint64_t last_create = 0; // the number of the last create that had entered then
327 std::uint32_t creates = 0; // such creates in the driver then
328 std::uint8_t kinds = 0; // their kinds, bit per CompileGateKind
329 bool went_ahead = false; // it waited at the gate up to the limit or the probe budget
330 bool probe = true; // its time in the driver is a probe (a submission, not a present or a wait)
331};
332
312// VulkanContext's submit lock, which also remembers who holds it, since when and how many threads wait for it. A 333// VulkanContext's submit lock, which also remembers who holds it, since when and how many threads wait for it. A
313// submit or an idle wait blocked inside the driver holds it for as long as it blocks; the stall watchdog and the loss 334// submit or an idle wait blocked inside the driver holds it for as long as it blocks; the stall watchdog and the loss
314// report name that thread, and a hold of a second or more is logged when it ends. 335// report name that thread, and a hold of a second or more is logged when it ends.
@@ -398,36 +419,243 @@ public:
398 // that arrives while a submission waits queues behind it, so a submission waits only for the creates already in 419 // that arrives while a submission waits queues behind it, so a submission waits only for the creates already in
399 // the driver. A long compile then stalls the submitting thread here, in our code, instead of in the driver. 420 // the driver. A long compile then stalls the submitting thread here, in our code, instead of in the driver.
400 // No deadlock: a create holds the gate only across its vkCreate*Pipelines and a submission only across its 421 // No deadlock: a create holds the gate only across its vkCreate*Pipelines and a submission only across its
401 // vkQueueSubmit, and neither driver call waits for anything of ours. LEONIDA_COMPILE_GATE=0 turns it off. 422 // vkQueueSubmit, and neither driver call waits for anything of ours.
423 //
424 // By default (classic) only compute creates pass the gate and a submission waits for them however long they take,
425 // as before the adaptive gate; LEONIDA_COMPILE_GATE_WAIT_MS bounds that too. With the adaptive gate
426 // (LEONIDA_COMPILE_GATE=adaptive) the wait is bounded (gate_wait_limit_ms, LEONIDA_COMPILE_GATE_WAIT_MS): a
427 // submission waiting at the gate holds the submit lock, so every queue stops behind it, and the title's hang
428 // watchdog ends the process once its main loop has not reported for 30 s. One create stayed in the driver for more
429 // than 54 s (RTX 4070 Laptop, NVIDIA 621.40), and the gate turned it into that exit. Past the limit the submission
430 // goes ahead, and the creates that were in the driver then no longer hold any submission back; creates that enter
431 // later are waited for again. The default limit, 15 s, keeps the protection measured above for every create of up
432 // to 25 s: 630.20 gave the submission 10 s in the driver before the loss, and a stop much longer than 25 s ends at
433 // the watchdog anyway. The same with the watchdog kept kicked (LEONIDA_TITLE_WATCHDOG=0 with
434 // LEONIDA_TITLE_WATCHDOG_KICK): nothing ends the run then, but the stops still cost the frames (an RTX 4060 run
435 // that way had 459 waits, 155 s in all, by t=202 s). Only LEONIDA_COMPILE_GATE_WAIT_MS=0 waits for the creates
436 // however long they take.
437 //
438 // Adaptive (LEONIDA_COMPILE_GATE=adaptive, opt-in): each submission that enters the driver alongside a create the
439 // gate no longer waits for is a probe of whether this driver holds a submission behind a create. Back while that
440 // create is still in the driver: under kProbeQuickMs is quick, kProbeHeldMs or more is held, between says nothing.
441 // On 621.40 the three that went ahead came back in 0-11 ms, the create still there; the one 630.20 held stayed 10
442 // s, until the loss. Two quick probes at least kProbeSpanMs apart turn the gate off for the rest of the run (the
443 // device's, which is the process's), logged once. Two because on 630.20 back-to-back creates take and release the
444 // driver's lock (see let_submit_finish), so one submission could slip in between and come back quickly from a
445 // driver that does hold submissions; a second one a second later must be as lucky. It costs no extra wait: once one
446 // has gone ahead, the next ones enter at once while that create is still in the driver. One held probe keeps the
447 // gate on for the rest of the run. Only submissions (vkQueueSubmit, vkQueueBindSparse) probe: presents and idle or
448 // semaphore waits pass the gate as submissions do, but take seconds on their own while the GPU is busy, so their
449 // time in the driver judges nothing. LEONIDA_COMPILE_GATE=1 gates without probing, LEONIDA_COMPILE_GATE=0 turns the
450 // gate off. let_submit_finish is unaffected by all of this.
451 //
452 // The first probes come early: while no verdict is in, a submission also goes ahead once the submissions' waits at
453 // the gate in the last kProbeWindowMs, its own included, add up to the probe budget (gate_probe_budget_ms,
454 // LEONIDA_COMPILE_GATE_PROBE_MS, 2500 ms). On 621.40 no single wait reached 15 s, but 80 waits of up to 6.7 s,
455 // back to back, kept the main loop from reporting for 30 s. A budget over a window rather than a shorter limit
456 // per wait, because it also counts many short waits, and a single wait reaches it as soon as a 2.5 s limit
457 // would. Before the verdict the gate then stops the queues for at most a quarter of any 10 s; after a quick
458 // verdict not at all. The price is on a driver that does hold submissions (630.20): the first probe enters the
459 // driver after 2.5 s of waiting instead of 15, and loses the device if the create stays in the driver 10 s more.
460 // That is one probe per kind and run: the probe holds the submit lock while it is in the driver, so no other
461 // submission enters until it comes back, and then (within 500 ms of the create leaving, 2 s or more) it gives the
462 // held verdict, after which no submission enters next to a create of that kind early again. This is why the
463 // adaptive gate is opt-in until it has run on such a driver. The alternative there is the same run starved
464 // by waits like the ones above. LEONIDA_COMPILE_GATE_WAIT_MS=0 without LEONIDA_COMPILE_GATE_PROBE_MS also makes the
465 // budget 0: the gate then waits however long the creates take and never probes, as LEONIDA_COMPILE_GATE=1 does.
466 //
467 // A verdict per kind of create (CreateKind: compute, or graphics with mesh): a submission that came back quickly
468 // beside a compute create says nothing about a graphics one, and a run on 621.40 lost the device beside a mesh
469 // pipeline create 9 s after compute probes had turned the gate off. A probe counts for each kind that had a
470 // create in the driver from before the submission entered until it came back: a quick one for all of them, a
471 // held one against all of them, since which create held it cannot be told. A submission waits for the creates of
472 // every kind whose gate is not off; the probe budget applies only while all of those are of kinds still pending.
473 // A kind that is off is still timed: a submission that stays kProbeHeldMs or more beside one of its creates turns
474 // that kind's gate back on for the rest of the run (logged once), so the submissions after it wait. The one that
475 // stayed cannot be helped. A held probe counts only if the submission came back within kHeldReturnMs after a
476 // create of that kind, there when it entered, left the driver: a submission held behind a create comes back when
477 // the create does. One that comes back slow with its creates still there was slow for another reason (on 621.40,
478 // a 36 s submission came back 18 s before the compute create beside it, and the 4070 Laptop's 8 GB were full);
479 // counting it re-armed the gate and starved the title for 78 s behind creates that were not holding anything. A submission never goes ahead (at the limit or the budget) while a create of a kind
480 // that holds submissions is in the driver, and such creates are waited for even if one was gone past before the
481 // verdict: on 621.40, with the gate off, a vkQueueSubmit sat 54 s in the driver beside a 56 s mesh create and the
482 // device was lost; waiting here starves the title as long, but keeps the device. Graphics creates pass the gate
483 // since this split (adaptive and LEONIDA_COMPILE_GATE=1; the classic gate, as before, only compute ones). On a
484 // device loss, report_creates_on_loss names the creates in the driver and the verdicts.
485 // classic (the default): the gate as on main before the adaptive one, compute creates only, no limit, no probes.
486 enum class GateMode { off, classic, adaptive, always };
487 enum class GateVerdict { pending, driver_does_not_hold, driver_holds };
488 static constexpr std::int64_t kProbeQuickMs = 250;
489 static constexpr std::int64_t kProbeHeldMs = 2000;
490 static constexpr std::int64_t kHeldReturnMs = 500;
491 static constexpr std::int64_t kProbeSpanMs = 1000;
492 static constexpr unsigned kQuickProbes = 2;
493 static constexpr std::int64_t kProbeWindowMs = 10000;
494 static constexpr std::int64_t kDefaultProbeBudgetMs = 2500;
495 using CreateKind = CompileGateKind; // graphics: mesh pipelines too
496 static constexpr std::size_t kKinds = 2;
497 static const char* kind_name(CreateKind kind) { return kind == CreateKind::compute ? "compute" : "graphics"; }
498 using CreateInfo = CompileGateCreate;
499 using GateAhead = CompileGateAhead;
402 class CompileTurn { // around vkCreate*Pipelines 500 class CompileTurn { // around vkCreate*Pipelines
403 public: 501 public:
404 explicit CompileTurn(SubmitMutex& gate) : gate_(gate), waited_(gate.enter_compile()) {} 502 explicit CompileTurn(SubmitMutex& gate, const CreateInfo& info = {})
405 ~CompileTurn() { gate_.leave_compile(); } 503 : gate_(gate), waited_(gate.enter_compile(seq_, info)) {}
504 ~CompileTurn() { gate_.leave_compile(seq_); }
406 CompileTurn(const CompileTurn&) = delete; 505 CompileTurn(const CompileTurn&) = delete;
407 CompileTurn& operator=(const CompileTurn&) = delete; 506 CompileTurn& operator=(const CompileTurn&) = delete;
408 std::int64_t waited_ms() const { return waited_; } 507 std::int64_t waited_ms() const { return waited_; }
409 508
410 private: 509 private:
411 SubmitMutex& gate_; 510 SubmitMutex& gate_;
511 std::uint64_t seq_ = 0; // declared before waited_: enter_compile sets it
412 std::int64_t waited_; 512 std::int64_t waited_;
413 }; 513 };
414 class SubmitTurn { // around vkQueueSubmit, with the submit lock held 514 class SubmitTurn { // around vkQueueSubmit, with the submit lock held
415 public: 515 public:
416 explicit SubmitTurn(SubmitMutex& gate) : gate_(gate) { gate.enter_submit(); } 516 // `probe` false for a present or an idle or semaphore wait: it waits at the gate like a submission, but its
417 ~SubmitTurn() { gate_.leave_submit(); } 517 // time in the driver judges nothing (it can take seconds on its own while the GPU is busy).
518 explicit SubmitTurn(SubmitMutex& gate, bool probe = true) : gate_(gate) {
519 gate.enter_submit(&ahead_, probe);
520 ahead_.probe = probe;
521 }
522 ~SubmitTurn() { gate_.leave_submit(ahead_); }
418 SubmitTurn(const SubmitTurn&) = delete; 523 SubmitTurn(const SubmitTurn&) = delete;
419 SubmitTurn& operator=(const SubmitTurn&) = delete; 524 SubmitTurn& operator=(const SubmitTurn&) = delete;
525 // It went ahead at the wait limit with creates still in the driver.
526 bool went_ahead() const { return ahead_.went_ahead; }
420 527
421 private: 528 private:
422 SubmitMutex& gate_; 529 SubmitMutex& gate_;
530 GateAhead ahead_;
423 }; 531 };
424 532
425 static bool compile_gate_enabled() { 533 // LEONIDA_COMPILE_GATE: 0 off, 1 always (both kinds, and compute builds hold the submit lock, compute_driver_turn
426 static const bool on = [] { 534 // in shims/d3d12_vulkan_device.cpp), `adaptive` the adaptive gate, anything else (unset) classic. Classic stays
535 // the default until the adaptive gate has run on a driver that holds submissions (630.20): there its first probe
536 // of a kind enters the driver after the probe budget and loses the device if the create stays 10 s more.
537 static GateMode compile_gate_mode() {
538 static const GateMode mode = [] {
427 const char* value = std::getenv("LEONIDA_COMPILE_GATE"); 539 const char* value = std::getenv("LEONIDA_COMPILE_GATE");
428 return !(value && !std::strcmp(value, "0")); 540 if (value && !std::strcmp(value, "0")) return GateMode::off;
541 if (value && !std::strcmp(value, "1")) return GateMode::always;
542 if (value && !std::strcmp(value, "adaptive")) return GateMode::adaptive;
543 return GateMode::classic;
544 }();
545 return mode;
546 }
547 static bool compile_gate_enabled() { return compile_gate_mode() != GateMode::off; }
548 // Whether graphics (and mesh) creates pass the gate: not in the classic gate, where only compute ones did.
549 static bool compile_gate_graphics() {
550 return compile_gate_mode() == GateMode::adaptive || compile_gate_mode() == GateMode::always;
551 }
552
553 // Read once. How long one submission waits at the gate before it goes ahead (0: until the creates leave):
554 // LEONIDA_COMPILE_GATE_WAIT_MS=<ms>. The adaptive gate's probe budget over kProbeWindowMs (0: no early probes):
555 // LEONIDA_COMPILE_GATE_PROBE_MS=<ms>. Unset, kDefaultGateWaitMs and kDefaultProbeBudgetMs, whatever the title's
556 // hang watchdog does; the budget is 0 when the limit is, and the limit 0 with LEONIDA_COMPILE_GATE=1.
557 static constexpr std::int64_t kDefaultGateWaitMs = 15000;
558 struct GateDefaults {
559 std::int64_t wait_ms;
560 std::int64_t probe_ms;
561 };
562 static GateDefaults gate_defaults() {
563 static const GateDefaults defaults = [] {
564 const auto read = [](const char* name, std::int64_t fallback) -> std::int64_t {
565 const char* value = std::getenv(name);
566 if (!value || !*value) return fallback;
567 char* end = nullptr;
568 const long long n = std::strtoll(value, &end, 10);
569 if (end && !*end && n >= 0) return n;
570 std::fprintf(stderr, "[rt] compile-gate: %s=%s is not a number of milliseconds; ignored\n", name, value);
571 return fallback;
572 };
573 const GateMode mode = compile_gate_mode();
574 const bool always = mode == GateMode::always;
575 const bool adaptive = mode == GateMode::adaptive; // classic and always: no limit by default
576 const std::int64_t wait_ms = read("LEONIDA_COMPILE_GATE_WAIT_MS", adaptive ? kDefaultGateWaitMs : 0);
577 const GateDefaults d{wait_ms, read("LEONIDA_COMPILE_GATE_PROBE_MS", wait_ms ? kDefaultProbeBudgetMs : 0)};
578 if (mode == GateMode::classic && d.wait_ms)
579 std::fprintf(stderr, "[rt] compile-gate: classic (compute creates); a submission waits at most %lld ms "
580 "for them to leave the driver (LEONIDA_COMPILE_GATE_WAIT_MS; "
581 "LEONIDA_COMPILE_GATE=adaptive for the adaptive gate)\n",
582 static_cast<long long>(d.wait_ms));
583 else if (always && d.wait_ms)
584 std::fprintf(stderr, "[rt] compile-gate: always (LEONIDA_COMPILE_GATE=1); a submission waits at most "
585 "%lld ms for pipeline creates to leave the driver (LEONIDA_COMPILE_GATE_WAIT_MS)\n",
586 static_cast<long long>(d.wait_ms));
587 else if (always)
588 std::fprintf(stderr, "[rt] compile-gate: always (LEONIDA_COMPILE_GATE=1); a submission waits for "
589 "pipeline creates to leave the driver, however long they take\n");
590 else if (adaptive)
591 std::fprintf(stderr, "[rt] compile-gate: adaptive (LEONIDA_COMPILE_GATE=adaptive), off once "
592 "submissions come back quickly with a create in the driver; a submission goes "
593 "ahead after %lld ms of waiting (0: no limit, LEONIDA_COMPILE_GATE_WAIT_MS) or, "
594 "until that is known, once the waits of the last "
595 "%lld s add up to %lld ms (0: never, LEONIDA_COMPILE_GATE_PROBE_MS)\n",
596 static_cast<long long>(d.wait_ms), static_cast<long long>(kProbeWindowMs / 1000),
597 static_cast<long long>(d.probe_ms));
598 return d;
599 }();
600 return defaults;
601 }
602 static std::int64_t default_gate_wait_limit_ms() { return gate_defaults().wait_ms; }
603 static std::int64_t default_gate_probe_budget_ms() { return gate_defaults().probe_ms; }
604 // How long a submission waits for creates of a kind that holds submissions before it goes ahead anyway
605 // (LEONIDA_COMPILE_GATE_HELD_WAIT_MS, 0: until they leave). Longer than the plain limit: going ahead there means
606 // waiting in the driver, where the device was lost once (a 54 s submission beside a 56 s mesh create on 621.40,
607 // the gate off); a false "holds" verdict costs at most this per create instead of the rest of the run.
608 static constexpr std::int64_t kDefaultHeldWaitMs = 60000;
609 static std::int64_t default_gate_held_limit_ms() {
610 static const std::int64_t ms = [] {
611 const char* value = std::getenv("LEONIDA_COMPILE_GATE_HELD_WAIT_MS");
612 if (!value || !*value) return kDefaultHeldWaitMs;
613 char* end = nullptr;
614 const long long n = std::strtoll(value, &end, 10);
615 if (end && !*end && n >= 0) return std::int64_t{n};
616 std::fprintf(stderr, "[rt] compile-gate: LEONIDA_COMPILE_GATE_HELD_WAIT_MS=%s is not a number of "
617 "milliseconds; ignored\n", value);
618 return kDefaultHeldWaitMs;
429 }(); 619 }();
430 return on; 620 return ms;
621 }
622 void set_gate_held_limit_ms(std::int64_t ms) { // for tests
623 std::lock_guard lock(gate_mutex_);
624 held_limit_ms_ = (std::max)(ms, std::int64_t{0});
625 }
626 std::int64_t gate_wait_limit_ms() {
627 std::lock_guard lock(gate_mutex_);
628 return wait_limit_ms_;
629 }
630 void set_gate_wait_limit_ms(std::int64_t ms) { // for tests
631 std::lock_guard lock(gate_mutex_);
632 wait_limit_ms_ = (std::max)(ms, std::int64_t{0});
633 }
634 std::int64_t gate_probe_budget_ms() {
635 std::lock_guard lock(gate_mutex_);
636 return probe_budget_ms_;
637 }
638 void set_gate_probe_budget_ms(std::int64_t ms) { // for tests
639 std::lock_guard lock(gate_mutex_);
640 probe_budget_ms_ = (std::max)(ms, std::int64_t{0});
641 }
642 void set_gate_adaptive(bool on) { // for tests
643 std::lock_guard lock(gate_mutex_);
644 adaptive_ = on;
645 }
646 void set_gate_graphics(bool on) { // for tests: whether graphics creates pass the gate
647 std::lock_guard lock(gate_mutex_);
648 graphics_ = on;
649 }
650 GateVerdict gate_verdict(CreateKind kind = CreateKind::compute) {
651 std::lock_guard lock(gate_mutex_);
652 return verdict_[std::size_t(kind)];
653 }
654
655 // How many "reached the limit, but a create of a kind that holds ..." notices were due (for tests: one per wait).
656 unsigned gate_held_notices() {
657 std::lock_guard lock(gate_mutex_);
658 return logged_held_waits_;
431 } 659 }
432 660
433 // The thread waiting in enter_submit for creates to leave the driver, or 0. 661 // The thread waiting in enter_submit for creates to leave the driver, or 0.
@@ -436,6 +664,7 @@ public:
436 struct GateStats { 664 struct GateStats {
437 std::uint64_t submits = 0; // submissions that had to wait for a create 665 std::uint64_t submits = 0; // submissions that had to wait for a create
438 std::int64_t submit_ms = 0, submit_max_ms = 0; 666 std::int64_t submit_ms = 0, submit_max_ms = 0;
667 std::uint64_t ahead = 0; // of those, the ones that went ahead at the wait limit
439 std::uint64_t creates = 0; // creates that waited behind a submission 668 std::uint64_t creates = 0; // creates that waited behind a submission
440 std::int64_t create_ms = 0, create_max_ms = 0; 669 std::int64_t create_ms = 0, create_max_ms = 0;
441 }; 670 };
@@ -444,64 +673,342 @@ public:
444 return stats_; 673 return stats_;
445 } 674 }
446 675
447 std::int64_t enter_compile() { 676 // `seq` receives the create's number, which leave_compile takes back.
677 std::int64_t enter_compile(std::uint64_t& seq, const CreateInfo& info = {}) {
448 if (!compile_gate_enabled()) return 0; 678 if (!compile_gate_enabled()) return 0;
449 std::unique_lock lock(gate_mutex_); 679 std::unique_lock lock(gate_mutex_);
450 std::int64_t waited = 0; 680 std::int64_t waited = 0;
451 if (submits_) { 681 if (info.kind == CreateKind::graphics && !graphics_) { // the classic gate: compute creates only
682 seq = 0;
683 return 0;
684 }
685 // Not behind this thread's own submission (it holds the submit lock: none of its submissions is in the
686 // driver now, and waiting for them would never end).
687 const bool own = owner_.load(std::memory_order_relaxed) == diagnostic_thread_id();
688 if (submits_ && !own && !kind_off(info.kind)) {
452 const std::int64_t start = diagnostic_ms(); 689 const std::int64_t start = diagnostic_ms();
453 gate_changed_.wait(lock, [&] { return submits_ == 0; }); 690 gate_changed_.wait(lock, [&] { return submits_ == 0 || kind_off(info.kind); });
454 waited = diagnostic_ms() - start; 691 waited = diagnostic_ms() - start;
455 ++stats_.creates; 692 ++stats_.creates;
456 stats_.create_ms += waited; 693 stats_.create_ms += waited;
457 stats_.create_max_ms = (std::max)(stats_.create_max_ms, waited); 694 stats_.create_max_ms = (std::max)(stats_.create_max_ms, waited);
458 } 695 }
459 ++compiles_; 696 seq = ++last_create_;
697 in_driver_.push_back(InDriver{seq, info, diagnostic_ms(), diagnostic_thread_id()});
460 return waited; 698 return waited;
461 } 699 }
462 void leave_compile() { 700 void leave_compile(std::uint64_t seq) {
463 if (!compile_gate_enabled()) return; 701 if (!compile_gate_enabled()) return;
464 std::lock_guard lock(gate_mutex_); 702 std::lock_guard lock(gate_mutex_);
465 if (--compiles_ == 0 && submits_) gate_changed_.notify_all(); 703 for (auto it = in_driver_.begin(); it != in_driver_.end(); ++it)
704 if (it->seq == seq) {
705 recent_leaves_[leave_count_++ % kRecentLeaves] = Leave{seq, diagnostic_ms(), it->info.kind};
706 in_driver_.erase(it);
707 break;
708 }
709 if (submits_) gate_changed_.notify_all();
466 } 710 }
467 711
468 std::int64_t enter_submit() { 712 // `ahead` (optional) is told whether the submission entered the driver alongside creates the gate does not wait
713 // for, and whether it went ahead at the wait limit or the probe budget, for leave_submit.
714 // `probe` false (a present or an idle or semaphore wait): it never goes ahead at the probe budget, only at the
715 // wait limit, since its time in the driver judges nothing.
716 std::int64_t enter_submit(GateAhead* ahead = nullptr, bool probe = true) {
469 if (!compile_gate_enabled()) return 0; 717 if (!compile_gate_enabled()) return 0;
470 std::unique_lock lock(gate_mutex_); 718 std::unique_lock lock(gate_mutex_);
471 ++submits_; 719 ++submits_;
472 if (!compiles_) return 0; 720 const InDriver* first = first_blocking();
721 if (!first) {
722 if (ahead) *ahead = beside(diagnostic_ms(), false);
723 return 0;
724 }
473 const std::uint32_t self = diagnostic_thread_id(); 725 const std::uint32_t self = diagnostic_thread_id();
474 gate_waiter_.store(self, std::memory_order_relaxed); 726 gate_waiter_.store(self, std::memory_order_relaxed);
475 const std::int64_t start = diagnostic_ms(); 727 const std::int64_t start = diagnostic_ms();
476 const GateWait what{self, compiles_, driver_compile.name.load(std::memory_order_acquire), 728 const GateWait what{self, blocking(), first->info};
477 driver_compile.trigger.load(std::memory_order_relaxed),
478 driver_compile.bytes.load(std::memory_order_relaxed)};
479 std::int64_t next_note = 2000; 729 std::int64_t next_note = 2000;
480 while (!gate_changed_.wait_for(lock, std::chrono::milliseconds(250), [&] { return compiles_ == 0; })) { 730 const char* why = nullptr; // set: it goes ahead
481 const std::int64_t waited = diagnostic_ms() - start; 731 std::int64_t limit = 0, budget = 0; // in force at the last check
482 if (waited < next_note) continue; 732 std::int64_t window_ms = 0; // with the probe budget: the waits of the window, this one's included
483 next_note = waited + 5000; 733 bool held_noted = false; // the "reached the limit, but ..." notice, once per wait
484 note_gate_wait("has waited", what, waited); 734 for (;;) {
735 const std::int64_t now = diagnostic_ms();
736 const std::int64_t waited = now - start;
737 // Checked each time: a create of a kind that holds submissions, not gone past, may have left (or entered)
738 // since, while creates of other kinds stay.
739 const bool held = held_blocking();
740 // The plain limit, and the probe budget only for a probe while every kind it waits for has no verdict.
741 const std::int64_t plain_budget = probe && adaptive_ && blocking_kinds_pending() ? probe_budget_ms_ : 0;
742 const char* plain = nullptr;
743 if (plain_budget > 0) window_ms = recent_waits_ms(now) + waited;
744 if (wait_limit_ms_ > 0 && waited >= wait_limit_ms_) {
745 plain = "limit";
746 } else if (plain_budget > 0 && window_ms >= plain_budget) {
747 plain = "probe budget";
748 }
749 if (!held) {
750 limit = wait_limit_ms_;
751 budget = plain_budget;
752 why = plain;
753 } else {
754 // Not into the driver beside a create of a kind that holds submissions: there it would wait for the
755 // create anyway, and the driver lost the device under such waits (621.40, a mesh create). It waits
756 // here for those, up to the held limit (LEONIDA_COMPILE_GATE_HELD_WAIT_MS; 0: however long), which
757 // applies on its own, also when it is shorter than the plain limit.
758 limit = held_limit_ms_;
759 budget = 0;
760 if (limit > 0 && waited >= limit) why = "held limit";
761 if (plain && !why && !held_noted) {
762 held_noted = true;
763 if (logged_held_waits_++ < 8)
764 std::fprintf(stderr, "[rt] compile-gate: vkQueueSubmit on thread %u reached the %s after %lld "
765 "ms, but a create of a kind that holds submissions is in the driver: it "
766 "waits until that create leaves or %lld ms have passed\n",
767 self, plain, static_cast<long long>(waited),
768 static_cast<long long>(held_limit_ms_));
769 }
770 }
771 if (why) {
772 // Every create in the driver now stops holding submissions back; later ones are waited for.
773 overdue_through_ = last_create_;
774 if (why[0] == 'h') held_overdue_through_ = last_create_;
775 gate_changed_.notify_all();
776 break;
777 }
778 if (waited >= next_note) {
779 next_note = waited + 5000;
780 note_gate_wait("has waited", what, waited);
781 }
782 std::int64_t step = 250;
783 if (limit > 0) step = (std::min)(step, limit - waited);
784 if (budget > 0) step = (std::min)(step, budget - window_ms);
785 step = (std::max)(step, std::int64_t{1});
786 // Woken when no create holds it back any more, or when whether a holding create does has changed.
787 if (gate_changed_.wait_for(lock, std::chrono::milliseconds(step),
788 [&] { return !first_blocking() || held_blocking() != held; }) &&
789 !first_blocking())
790 break;
485 } 791 }
486 gate_waiter_.store(0, std::memory_order_relaxed); 792 gate_waiter_.store(0, std::memory_order_relaxed);
487 const std::int64_t waited = diagnostic_ms() - start; 793 const std::int64_t end = diagnostic_ms();
794 const std::int64_t waited = end - start;
795 remember_wait(start, end);
488 ++stats_.submits; 796 ++stats_.submits;
489 stats_.submit_ms += waited; 797 stats_.submit_ms += waited;
490 stats_.submit_max_ms = (std::max)(stats_.submit_max_ms, waited); 798 stats_.submit_max_ms = (std::max)(stats_.submit_max_ms, waited);
491 // Every wait of 500 ms or more, and the first 32 of 50 ms or more. 799 const auto creates = static_cast<unsigned>(in_driver_.size());
492 if (waited >= 500 || (waited >= 50 && logged_waits_ < 32)) { 800 if (why && logged_go_ahead_ >= 16) {
801 ++stats_.ahead; // the stats line counts the rest
802 } else if (why) {
803 ++stats_.ahead;
804 ++logged_go_ahead_;
805 note_gate_wait("goes ahead after", what, waited);
806 if (why[0] == 'l')
807 std::fprintf(stderr, "[rt] compile-gate: at the %lld ms limit (LEONIDA_COMPILE_GATE_WAIT_MS): the %u "
808 "create(s) still in the driver hold no submission back from now on (%llu "
809 "submissions went ahead so far)\n",
810 static_cast<long long>(limit), creates, static_cast<unsigned long long>(stats_.ahead));
811 else if (why[0] == 'h')
812 std::fprintf(stderr, "[rt] compile-gate: at the %lld ms held limit (LEONIDA_COMPILE_GATE_HELD_WAIT_MS): "
813 "the %u create(s) still in the driver hold no submission back from now on, those "
814 "of a kind that holds submissions included (%llu submissions went ahead so far)\n",
815 static_cast<long long>(limit), creates, static_cast<unsigned long long>(stats_.ahead));
816 else
817 std::fprintf(stderr, "[rt] compile-gate: the waits of the last %lld s add up to %lld ms, the probe "
818 "budget is %lld ms (LEONIDA_COMPILE_GATE_PROBE_MS): the %u create(s) still in the "
819 "driver hold no submission back from now on (%llu submissions went ahead so far)\n",
820 static_cast<long long>(kProbeWindowMs / 1000), static_cast<long long>(window_ms),
821 static_cast<long long>(budget), creates, static_cast<unsigned long long>(stats_.ahead));
822 } else if (waited >= 500 || (waited >= 50 && logged_waits_ < 32)) {
823 // Every wait of 500 ms or more, and the first 32 of 50 ms or more.
493 ++logged_waits_; 824 ++logged_waits_;
494 note_gate_wait("waited", what, waited); 825 note_gate_wait("waited", what, waited);
495 } 826 }
827 if (ahead) *ahead = beside(end, why != nullptr);
496 return waited; 828 return waited;
497 } 829 }
498 void leave_submit() { 830 void leave_submit(const GateAhead& ahead = {}) {
499 if (!compile_gate_enabled()) return; 831 if (!compile_gate_enabled()) return;
500 std::lock_guard lock(gate_mutex_); 832 std::lock_guard lock(gate_mutex_);
833 if (ahead.since_ms >= 0 && ahead.probe) probe(ahead);
501 if (--submits_ == 0) gate_changed_.notify_all(); 834 if (--submits_ == 0) gate_changed_.notify_all();
502 } 835 }
503 836
837 // On a device loss (VulkanContext::mark_device_lost, once): the creates in the driver, how long each has been
838 // there and whether submissions wait for it, and the verdict of each kind.
839 void report_creates_on_loss() noexcept {
840 if (!compile_gate_enabled()) return;
841 try {
842 std::lock_guard lock(gate_mutex_);
843 const std::int64_t now = diagnostic_ms();
844 std::fprintf(stderr, "[rt] compile-gate: at the device loss (t=%.3f s): compute gate %s, graphics gate %s; "
845 "%zu pipeline create(s) in the driver\n",
846 double(now) / 1000.0, verdict_name(CreateKind::compute), verdict_name(CreateKind::graphics),
847 in_driver_.size());
848 for (const auto& c : in_driver_)
849 std::fprintf(stderr, "[rt] compile-gate: %s create %s (%zu B SPIR-V, %s) on thread %u, in the driver "
850 "for %lld ms, %s\n",
851 kind_name(c.info.kind), c.info.name ? c.info.name : "-", c.info.bytes,
852 c.info.trigger ? c.info.trigger : "-", c.thread, static_cast<long long>(now - c.since_ms),
853 is_blocking(c) ? "submissions wait for it" : "submissions do not wait for it");
854 } catch (...) {
855 }
856 }
857
504private: 858private:
859 struct InDriver {
860 std::uint64_t seq;
861 CreateInfo info;
862 std::int64_t since_ms;
863 std::uint32_t thread;
864 };
865
866 // With gate_mutex_ held.
867 bool kind_off(CreateKind kind) const {
868 return verdict_[std::size_t(kind)] == GateVerdict::driver_does_not_hold;
869 }
870 // A create a submission waits for: of a kind whose gate is on, and either of a kind that holds submissions or not
871 // gone past at the limit or the budget.
872 bool is_blocking(const InDriver& c) const {
873 if (kind_off(c.info.kind)) return false;
874 if (verdict_[std::size_t(c.info.kind)] == GateVerdict::driver_holds) return c.seq > held_overdue_through_;
875 return c.seq > overdue_through_;
876 }
877 bool held_blocking() const {
878 for (const auto& c : in_driver_)
879 if (verdict_[std::size_t(c.info.kind)] == GateVerdict::driver_holds && c.seq > held_overdue_through_)
880 return true;
881 return false;
882 }
883 const InDriver* first_blocking() const {
884 for (const auto& c : in_driver_)
885 if (is_blocking(c)) return &c;
886 return nullptr;
887 }
888 std::uint32_t blocking() const {
889 std::uint32_t n = 0;
890 for (const auto& c : in_driver_) n += is_blocking(c);
891 return n;
892 }
893 bool blocking_kinds_pending() const {
894 for (const auto& c : in_driver_)
895 if (is_blocking(c) && verdict_[std::size_t(c.info.kind)] != GateVerdict::pending) return false;
896 return true;
897 }
898 // The creates a submission entering the driver at `now` does not wait for (all of those in it: it got past the
899 // gate).
900 GateAhead beside(std::int64_t now, bool went_ahead) const {
901 GateAhead a;
902 if (in_driver_.empty()) return a;
903 a.since_ms = now;
904 a.last_create = last_create_;
905 a.creates = static_cast<std::uint32_t>(in_driver_.size());
906 for (const auto& c : in_driver_) a.kinds |= std::uint8_t(1u << unsigned(c.info.kind));
907 a.went_ahead = went_ahead;
908 return a;
909 }
910 const char* verdict_name(CreateKind kind) const {
911 switch (verdict_[std::size_t(kind)]) {
912 case GateVerdict::driver_does_not_hold: return "off (the driver does not hold submissions)";
913 case GateVerdict::driver_holds: return rearmed_[std::size_t(kind)] ? "on again (re-armed)" : "on (held probe)";
914 default: return adaptive_ ? "on (no verdict yet)" : "on";
915 }
916 }
917
918 // With gate_mutex_ held: the submissions' past waits at the gate, for the probe budget. The last kRecentWaits
919 // are kept; more in one window are short ones, so dropping the oldest of them costs little.
920 static constexpr std::size_t kRecentWaits = 64;
921 void remember_wait(std::int64_t start, std::int64_t end) {
922 if (end <= start) return;
923 recent_waits_[recent_count_++ % kRecentWaits] = {start, end};
924 }
925 // How much of the last kProbeWindowMs before `now` they took.
926 std::int64_t recent_waits_ms(std::int64_t now) const {
927 const std::int64_t from = now - kProbeWindowMs;
928 std::int64_t sum = 0;
929 for (std::size_t i = 0; i < (std::min)(recent_count_, kRecentWaits); ++i) {
930 const auto& [start, end] = recent_waits_[i];
931 sum += (std::max)(std::int64_t{0}, (std::min)(end, now) - (std::max)(start, from));
932 }
933 return sum;
934 }
935
936 // With gate_mutex_ held, as a submission leaves the driver: what its time there says about the driver, for each
937 // kind with a create in the driver from before it entered until now (see the gate's comment). The ones that went
938 // ahead are logged (the first 8), each verdict once.
939 void probe(const GateAhead& ahead) {
940 const std::int64_t now = diagnostic_ms();
941 const std::int64_t took = now - ahead.since_ms;
942 std::uint32_t still = 0;
943 std::uint8_t kinds = 0; // of the creates it entered beside, the kinds still in the driver
944 for (const auto& c : in_driver_)
945 if (c.seq <= ahead.last_create) {
946 ++still;
947 kinds |= std::uint8_t(1u << unsigned(c.info.kind));
948 }
949 kinds &= ahead.kinds;
950 if (ahead.went_ahead && logged_ahead_ < 8) {
951 ++logged_ahead_;
952 std::fprintf(stderr, "[rt] compile-gate: the submission that went ahead on thread %u was in the driver "
953 "for %lld ms; %u of the %u create(s) it went past are still there\n",
954 diagnostic_thread_id(), static_cast<long long>(took), still, ahead.creates);
955 }
956 if (!adaptive_) return;
957 for (std::size_t k = 0; k < kKinds; ++k) {
958 if (!(ahead.kinds & (1u << k))) continue;
959 if (took >= kProbeHeldMs) {
960 // Held behind a create of this kind only if one it entered beside has just left.
961 bool left_just_before = false;
962 for (std::size_t i = 0; i < (std::min)(leave_count_, kRecentLeaves) && !left_just_before; ++i) {
963 const Leave& l = recent_leaves_[i];
964 left_just_before = std::size_t(l.kind) == k && l.seq <= ahead.last_create &&
965 l.ms >= ahead.since_ms && now - l.ms <= kHeldReturnMs;
966 }
967 if (left_just_before) {
968 judge(CreateKind(k), took, now);
969 } else if (logged_not_held_++ < 8) {
970 std::fprintf(stderr, "[rt] compile-gate: a submission stayed %lld ms in the driver beside a %s "
971 "create but came back %s: not counted as held by it\n",
972 static_cast<long long>(took), kind_name(CreateKind(k)),
973 (kinds & (1u << k)) ? "with the create still there" : "long after the create left");
974 }
975 } else if (kinds & (1u << k)) {
976 judge(CreateKind(k), took, now);
977 }
978 }
979 }
980 void judge(CreateKind kind, std::int64_t took, std::int64_t now) {
981 const std::size_t k = std::size_t(kind);
982 GateVerdict& verdict = verdict_[k];
983 if (verdict == GateVerdict::driver_holds) return;
984 if (took >= kProbeHeldMs) {
985 const bool was_off = verdict == GateVerdict::driver_does_not_hold;
986 verdict = GateVerdict::driver_holds;
987 rearmed_[k] = was_off;
988 std::fprintf(stderr, "[rt] compile-gate: a submission stayed %lld ms in the driver beside a %s create at "
989 "t=%.3f s: this driver may hold submissions behind %s creates, so the %s gate is %s "
990 "for the rest of the run\n",
991 static_cast<long long>(took), kind_name(kind), double(now) / 1000.0, kind_name(kind),
992 kind_name(kind), was_off ? "back on" : "on");
993 return;
994 }
995 if (verdict != GateVerdict::pending || took >= kProbeQuickMs) return; // off already, or says nothing
996 if (quick_probes_[k]++ == 0) first_quick_ms_[k] = now;
997 longest_quick_ms_[k] = (std::max)(longest_quick_ms_[k], took);
998 if (quick_probes_[k] < kQuickProbes || now - first_quick_ms_[k] < kProbeSpanMs) return;
999 verdict = GateVerdict::driver_does_not_hold;
1000 gate_changed_.notify_all(); // the submissions and creates waiting now go
1001 std::fprintf(stderr, "[rt] compile-gate: %s gate off at t=%.3f s: %u submissions entered the driver beside a "
1002 "%s create and came back in at most %lld ms (under %lld ms), the first and last %lld ms "
1003 "apart, the create still there: this driver does not hold a submission behind a %s "
1004 "create. Still timed: one that stays %lld ms turns it back on (LEONIDA_COMPILE_GATE=1 "
1005 "keeps the gate)\n",
1006 kind_name(kind), double(now) / 1000.0, quick_probes_[k], kind_name(kind),
1007 static_cast<long long>(longest_quick_ms_[k]), static_cast<long long>(kProbeQuickMs),
1008 static_cast<long long>(now - first_quick_ms_[k]), kind_name(kind),
1009 static_cast<long long>(kProbeHeldMs));
1010 }
1011
505 void taken() { 1012 void taken() {
506 since_.store(diagnostic_ms(), std::memory_order_relaxed); 1013 since_.store(diagnostic_ms(), std::memory_order_relaxed);
507 owner_.store(diagnostic_thread_id(), std::memory_order_relaxed); 1014 owner_.store(diagnostic_thread_id(), std::memory_order_relaxed);
@@ -518,23 +1025,21 @@ private:
518 } 1025 }
519 1026
520 // With gate_mutex_ held. 1027 // With gate_mutex_ held.
521 // The creates a submission found in the driver: how many, and the compute one named last (graphics creates are 1028 // The creates a submission found in the driver: how many it waits for, and the first of them.
522 // not named). Names are ShaderLibrary strings, valid until device teardown.
523 struct GateWait { 1029 struct GateWait {
524 std::uint32_t thread; 1030 std::uint32_t thread;
525 std::uint32_t creates; 1031 std::uint32_t creates;
526 const char* name; 1032 CreateInfo first;
527 const char* trigger;
528 std::size_t bytes;
529 }; 1033 };
530 void note_gate_wait(const char* how, const GateWait& what, std::int64_t waited) const { 1034 void note_gate_wait(const char* how, const GateWait& what, std::int64_t waited) const {
531 std::fprintf(stderr, "[rt] compile-gate: vkQueueSubmit on thread %u %s %lld ms for %u pipeline create(s) to " 1035 std::fprintf(stderr, "[rt] compile-gate: vkQueueSubmit on thread %u %s %lld ms for %u pipeline create(s) to "
532 "leave the driver (compute %s, %zu B SPIR-V, %s) at t=%.3f s; %llu such waits so far, " 1036 "leave the driver (%s %s, %zu B SPIR-V, %s) at t=%.3f s; %llu such waits so far, "
533 "%lld ms in all, longest %lld ms\n", 1037 "%lld ms in all, longest %lld ms\n",
534 what.thread, how, static_cast<long long>(waited), what.creates, what.name ? what.name : "-", 1038 what.thread, how, static_cast<long long>(waited), what.creates, kind_name(what.first.kind),
535 what.name ? what.bytes : std::size_t{0}, what.name && what.trigger ? what.trigger : "-", 1039 what.first.name ? what.first.name : "-", what.first.bytes,
536 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(stats_.submits), 1040 what.first.trigger ? what.first.trigger : "-", double(diagnostic_ms()) / 1000.0,
537 static_cast<long long>(stats_.submit_ms), static_cast<long long>(stats_.submit_max_ms)); 1041 static_cast<unsigned long long>(stats_.submits), static_cast<long long>(stats_.submit_ms),
1042 static_cast<long long>(stats_.submit_max_ms));
538 } 1043 }
539 1044
540 std::mutex mutex_; 1045 std::mutex mutex_;
@@ -548,11 +1053,40 @@ private:
548 1053
549 std::mutex gate_mutex_; // leaf: guards the gate counts and stats 1054 std::mutex gate_mutex_; // leaf: guards the gate counts and stats
550 std::condition_variable gate_changed_; 1055 std::condition_variable gate_changed_;
551 std::uint32_t compiles_ = 0; // creates in the driver 1056 std::vector<InDriver> in_driver_; // the creates in the driver now, oldest first
1057 std::uint64_t last_create_ = 0; // the number of the last create that entered
1058 std::uint64_t overdue_through_ = 0; // creates up to this number were in the driver when a submission went ahead
1059 std::uint64_t held_overdue_through_ = 0; // the same, for creates of a kind that holds (at the held limit)
1060 std::int64_t held_limit_ms_ = default_gate_held_limit_ms(); // 0: no limit
552 std::uint32_t submits_ = 0; // submissions waiting for them or in the driver 1061 std::uint32_t submits_ = 0; // submissions waiting for them or in the driver
1062 std::int64_t wait_limit_ms_ = default_gate_wait_limit_ms(); // 0: no limit
1063 std::int64_t probe_budget_ms_ = default_gate_probe_budget_ms(); // 0: no early probes
1064 bool adaptive_ = compile_gate_mode() == GateMode::adaptive;
1065 bool graphics_ = compile_gate_graphics(); // graphics creates pass the gate
1066 std::array<std::pair<std::int64_t, std::int64_t>, kRecentWaits> recent_waits_{}; // [start, end) ms
1067 std::size_t recent_count_ = 0;
1068 // Per CreateKind.
1069 std::array<GateVerdict, kKinds> verdict_{GateVerdict::pending, GateVerdict::pending};
1070 std::array<bool, kKinds> rearmed_{};
1071 // The last creates to leave the driver: a held probe needs one it entered beside to have just left. A ring, so a
1072 // later create leaving does not hide an earlier one that did.
1073 struct Leave {
1074 std::uint64_t seq = 0;
1075 std::int64_t ms = 0;
1076 CreateKind kind{};
1077 };
1078 static constexpr std::size_t kRecentLeaves = 64;
1079 std::array<Leave, kRecentLeaves> recent_leaves_{};
1080 std::size_t leave_count_ = 0;
1081 unsigned logged_not_held_ = 0;
1082 std::array<unsigned, kKinds> quick_probes_{};
1083 std::array<std::int64_t, kKinds> first_quick_ms_{}, longest_quick_ms_{};
1084 unsigned logged_held_waits_ = 0;
553 std::atomic<std::uint32_t> gate_waiter_{0}; 1085 std::atomic<std::uint32_t> gate_waiter_{0};
554 GateStats stats_; 1086 GateStats stats_;
555 unsigned logged_waits_ = 0; 1087 unsigned logged_waits_ = 0;
1088 unsigned logged_ahead_ = 0;
1089 unsigned logged_go_ahead_ = 0;
556}; 1090};
557 1091
558// One vkQueueSubmit of a VulkanQueue: its waits, its signals and how long the call took (-1: not returned yet). 1092// One vkQueueSubmit of a VulkanQueue: its waits, its signals and how long the call took (-1: not returned yet).
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 81f3b57e1..da9376e54 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -212,7 +212,7 @@ public:
212 const VkDevice device = context_.device(); 212 const VkDevice device = context_.device();
213 { 213 {
214 std::lock_guard lock(context_.submit_mutex()); 214 std::lock_guard lock(context_.submit_mutex());
215 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 215 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
216 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 216 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
217 // A WSI layer may perform a device-wide idle while destroying the swapchain. 217 // A WSI layer may perform a device-wide idle while destroying the swapchain.
218 // Keep that implicit idle serialized with submits from every context queue. 218 // Keep that implicit idle serialized with submits from every context queue.
@@ -650,8 +650,9 @@ private:
650 { 650 {
651 std::lock_guard lock(context_.submit_mutex()); 651 std::lock_guard lock(context_.submit_mutex());
652 // One turn of the compile gate for the submit and the present after it: no pipeline create enters the 652 // One turn of the compile gate for the submit and the present after it: no pipeline create enters the
653 // driver between the two (queue_submit's own turn nests inside this one). 653 // driver between the two (queue_submit's own turn nests inside this one). Not a probe: it also covers
654 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 654 // finish_startup_frame's fence wait and the present; the nested turn probes the vkQueueSubmit alone.
655 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
655 submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, frame.done), 656 submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, frame.done),
656 "vkQueueSubmit (present)"); 657 "vkQueueSubmit (present)");
657 if (submitted == VK_SUCCESS) context_.note_image_work_locked(); 658 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
@@ -1083,7 +1084,7 @@ private:
1083 const VkDevice device = context_.device(); 1084 const VkDevice device = context_.device();
1084 { 1085 {
1085 std::lock_guard lock(context_.submit_mutex()); 1086 std::lock_guard lock(context_.submit_mutex());
1086 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 1087 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
1087 // The old swapchain's images and semaphores may still be in use. 1088 // The old swapchain's images and semaphores may still be in use.
1088 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 1089 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1089 release(swapchain_); 1090 release(swapchain_);
@@ -1174,7 +1175,7 @@ private:
1174 return true; 1175 return true;
1175 { 1176 {
1176 std::lock_guard lock(context_.submit_mutex()); 1177 std::lock_guard lock(context_.submit_mutex());
1177 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 1178 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
1178 // The old target may still be in use. 1179 // The old target may still be in use.
1179 context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 1180 context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1180 } 1181 }
@@ -1531,7 +1532,7 @@ private:
1531 const VkDevice device = context_.device(); 1532 const VkDevice device = context_.device();
1532 { 1533 {
1533 std::lock_guard lock(context_.submit_mutex()); 1534 std::lock_guard lock(context_.submit_mutex());
1534 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate 1535 const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate
1535 // The old swapchain's images and semaphores may still be in use. 1536 // The old swapchain's images and semaphores may still be in use.
1536 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 1537 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1537 } 1538 }
diff --git a/runtime/test/submit_mutex_test.cpp b/runtime/test/submit_mutex_test.cpp
index 345f30887..a98c6effa 100644
--- a/runtime/test/submit_mutex_test.cpp
+++ b/runtime/test/submit_mutex_test.cpp
@@ -9,6 +9,8 @@
9#include <atomic> 9#include <atomic>
10#include <chrono> 10#include <chrono>
11#include <cstdio> 11#include <cstdio>
12#include <cstdlib>
13#include <memory>
12#include <mutex> 14#include <mutex>
13#include <thread> 15#include <thread>
14 16
@@ -136,6 +138,8 @@ int compile_gate() {
136 return 0; 138 return 0;
137 } 139 }
138 SubmitMutex m; 140 SubmitMutex m;
141 m.set_gate_wait_limit_ms(0); // no limit: gate_wait_limit checks the limit
142 m.set_gate_adaptive(false); // gate_adapts checks the switch
139 // Nothing in the driver: a submission passes at once. 143 // Nothing in the driver: a submission passes at once.
140 { 144 {
141 const std::int64_t start = now_ms(); 145 const std::int64_t start = now_ms();
@@ -197,12 +201,760 @@ int compile_gate() {
197 return 0; 201 return 0;
198} 202}
199 203
204int gate_wait_limit() {
205 if (!SubmitMutex::compile_gate_enabled()) {
206 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): wait limit not checked\n");
207 return 0;
208 }
209 // The default with LEONIDA_COMPILE_GATE_WAIT_MS unset, whatever the title watchdog variables say: none with
210 // LEONIDA_COMPILE_GATE=1 or unset (classic), kDefaultGateWaitMs with LEONIDA_COMPILE_GATE=adaptive.
211 const bool adaptive = SubmitMutex::compile_gate_mode() == SubmitMutex::GateMode::adaptive;
212 if (!std::getenv("LEONIDA_COMPILE_GATE_WAIT_MS"))
213 EXPECT(SubmitMutex::default_gate_wait_limit_ms() == (adaptive ? SubmitMutex::kDefaultGateWaitMs : 0));
214 SubmitMutex m;
215 m.set_gate_adaptive(false); // as LEONIDA_COMPILE_GATE=1: it never turns off
216 m.set_gate_wait_limit_ms(150);
217 EXPECT(m.gate_wait_limit_ms() == 150);
218 // A create that stays in the driver until it is let go (one that takes longer than the limit).
219 std::atomic<bool> long_in{false}, release_long{false};
220 std::atomic<std::int64_t> long_left_at{0};
221 std::thread long_create([&] {
222 const SubmitMutex::CompileTurn turn(m);
223 long_in = true;
224 while (!release_long) std::this_thread::sleep_for(1ms);
225 long_left_at = now_ms();
226 });
227 EXPECT(eventually([&] { return long_in.load(); }));
228 // The submission goes ahead at the limit, the create still in the driver.
229 std::int64_t first_waited = 0;
230 bool first_ahead = false;
231 {
232 const std::int64_t start = now_ms();
233 const SubmitMutex::SubmitTurn turn(m);
234 first_waited = now_ms() - start;
235 first_ahead = turn.went_ahead();
236 }
237 // The next one passes at once: the create the first went past holds no submission back.
238 std::int64_t second_waited = 0;
239 bool second_ahead = true;
240 {
241 const std::int64_t start = now_ms();
242 const SubmitMutex::SubmitTurn turn(m);
243 second_waited = now_ms() - start;
244 second_ahead = turn.went_ahead();
245 }
246 // A create that enters after that is waited for again, until it leaves (well within the limit now), while the
247 // long one is still in the driver.
248 m.set_gate_wait_limit_ms(5000);
249 std::atomic<bool> short_in{false};
250 std::atomic<std::int64_t> short_left_at{0};
251 std::thread short_create([&] {
252 const SubmitMutex::CompileTurn turn(m);
253 short_in = true;
254 std::this_thread::sleep_for(200ms);
255 short_left_at = now_ms();
256 });
257 const bool short_entered = eventually([&] { return short_in.load(); });
258 std::int64_t third_entered_at = 0;
259 bool third_ahead = true;
260 {
261 const SubmitMutex::SubmitTurn turn(m);
262 third_entered_at = now_ms();
263 third_ahead = turn.went_ahead();
264 }
265 const bool long_still_in = long_left_at.load() == 0;
266 release_long = true;
267 long_create.join();
268 short_create.join();
269 EXPECT(short_entered);
270 EXPECT(first_ahead && first_waited >= 140 && first_waited < 1000);
271 EXPECT(!second_ahead && second_waited < 50);
272 EXPECT(!third_ahead && third_entered_at >= short_left_at.load() && long_still_in);
273 const SubmitMutex::GateStats stats = m.gate_stats();
274 EXPECT(stats.submits == 2 && stats.ahead == 1);
275 EXPECT(m.gate_verdict() == SubmitMutex::GateVerdict::pending); // quick probes, but not adaptive
276 // Both gone: a submission passes at once.
277 {
278 const std::int64_t start = now_ms();
279 const SubmitMutex::SubmitTurn turn(m);
280 EXPECT(now_ms() - start < 50 && !turn.went_ahead());
281 }
282 std::printf("compile gate: a submission went ahead after %lld ms (limit 150 ms) with the create still in the "
283 "driver, the next passed in %lld ms, and a create that entered later was waited for again\n",
284 static_cast<long long>(first_waited), static_cast<long long>(second_waited));
285 return 0;
286}
287
288int gate_adapts() {
289 if (!SubmitMutex::compile_gate_enabled()) {
290 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): adaptive switch not checked\n");
291 return 0;
292 }
293 using Verdict = SubmitMutex::GateVerdict;
294 // Quick probes: the gate goes off once two, a second apart, came back with the create still in the driver.
295 {
296 SubmitMutex m;
297 m.set_gate_adaptive(true);
298 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
299 m.set_gate_wait_limit_ms(100);
300 m.set_gate_probe_budget_ms(0); // probes at the limit only: gate_probe_budget checks the budget
301 std::atomic<bool> in{false}, release{false};
302 std::thread create([&] {
303 const SubmitMutex::CompileTurn turn(m);
304 in = true;
305 while (!release) std::this_thread::sleep_for(1ms);
306 });
307 const bool entered = eventually([&] { return in.load(); });
308 bool first_ahead = false;
309 {
310 const SubmitMutex::SubmitTurn turn(m); // goes ahead at the limit: the first quick probe
311 first_ahead = turn.went_ahead();
312 }
313 { const SubmitMutex::SubmitTurn turn(m); } // the second, too soon after the first
314 const Verdict soon = m.gate_verdict();
315 std::this_thread::sleep_for(1100ms);
316 { const SubmitMutex::SubmitTurn turn(m); } // the third, a second later
317 const Verdict later = m.gate_verdict();
318 // Off: a create that enters now holds no submission back.
319 std::atomic<bool> fresh_in{false}, release_fresh{false};
320 std::thread fresh([&] {
321 const SubmitMutex::CompileTurn turn(m);
322 fresh_in = true;
323 while (!release_fresh) std::this_thread::sleep_for(1ms);
324 });
325 const bool fresh_entered = eventually([&] { return fresh_in.load(); });
326 const std::int64_t start = now_ms();
327 bool fresh_ahead = true;
328 {
329 const SubmitMutex::SubmitTurn turn(m);
330 fresh_ahead = turn.went_ahead();
331 }
332 const std::int64_t passed = now_ms() - start;
333 release = true;
334 release_fresh = true;
335 create.join();
336 fresh.join();
337 EXPECT(entered && fresh_entered && first_ahead);
338 EXPECT(soon == Verdict::pending);
339 EXPECT(later == Verdict::driver_does_not_hold);
340 EXPECT(passed < 50 && !fresh_ahead);
341 }
342 std::printf("compile gate: off after two quick probes a second apart, not after two within the second\n");
343 // A held probe: a submission that comes back just after the create beside it leaves. The gate stays on, and a
344 // later create is waited for however long it takes.
345 {
346 SubmitMutex m;
347 m.set_gate_adaptive(true);
348 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
349 m.set_gate_wait_limit_ms(100);
350 m.set_gate_probe_budget_ms(0); // probes at the limit only: gate_probe_budget checks the budget
351 std::atomic<bool> first_in{false}, first_release{false};
352 std::thread first([&] {
353 const SubmitMutex::CompileTurn turn(m);
354 first_in = true;
355 while (!first_release) std::this_thread::sleep_for(1ms);
356 });
357 const bool first_entered = eventually([&] { return first_in.load(); });
358 {
359 const SubmitMutex::SubmitTurn turn(m); // goes ahead, then stays "in the driver" for 2.1 s
360 std::this_thread::sleep_for(2000ms);
361 first_release = true; // the create leaves 100 ms before the submission comes back
362 first.join();
363 std::this_thread::sleep_for(100ms);
364 }
365 const Verdict held = m.gate_verdict();
366 // A create of the same kind is waited for, past the limit (its kind holds submissions), until it leaves.
367 std::atomic<bool> in{false}, release{false};
368 std::thread create([&] {
369 const SubmitMutex::CompileTurn turn(m);
370 in = true;
371 while (!release) std::this_thread::sleep_for(1ms);
372 });
373 const bool entered = first_entered && eventually([&] { return in.load(); });
374 std::atomic<std::int64_t> released_at{0};
375 std::thread releaser([&] {
376 std::this_thread::sleep_for(300ms);
377 released_at = now_ms();
378 release = true;
379 });
380 std::int64_t entered_at = 0;
381 bool ahead = true;
382 {
383 const SubmitMutex::SubmitTurn turn(m);
384 entered_at = now_ms();
385 ahead = turn.went_ahead();
386 }
387 releaser.join();
388 create.join();
389 const Verdict still = m.gate_verdict();
390 EXPECT(entered);
391 EXPECT(held == Verdict::driver_holds && still == Verdict::driver_holds);
392 EXPECT(!ahead && entered_at >= released_at.load());
393 }
394 std::printf("compile gate: a probe held 2.1 s keeps it on, and the create is then waited out past the limit\n");
395 // A slow submission that comes back with the create beside it still there was not held by it: no verdict.
396 {
397 SubmitMutex m;
398 m.set_gate_adaptive(true);
399 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
400 m.set_gate_wait_limit_ms(100);
401 m.set_gate_probe_budget_ms(0);
402 std::atomic<bool> in{false}, release{false};
403 std::thread create([&] {
404 const SubmitMutex::CompileTurn turn(m);
405 in = true;
406 while (!release) std::this_thread::sleep_for(1ms);
407 });
408 const bool entered = eventually([&] { return in.load(); });
409 {
410 const SubmitMutex::SubmitTurn turn(m); // goes ahead at the limit, then stays 2.1 s
411 std::this_thread::sleep_for(2100ms);
412 }
413 const Verdict after = m.gate_verdict();
414 release = true;
415 create.join();
416 EXPECT(entered);
417 EXPECT(after != Verdict::driver_holds);
418 }
419 std::printf("compile gate: a 2.1 s submission that came back with the create still there is not a held probe\n");
420 return 0;
421}
422
423int gate_probe_budget() {
424 if (!SubmitMutex::compile_gate_enabled()) {
425 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): probe budget not checked\n");
426 return 0;
427 }
428 using Verdict = SubmitMutex::GateVerdict;
429 // The default budget, 0 when the limit is.
430 if (!std::getenv("LEONIDA_COMPILE_GATE_PROBE_MS"))
431 EXPECT(SubmitMutex::default_gate_probe_budget_ms() ==
432 (SubmitMutex::default_gate_wait_limit_ms() ? SubmitMutex::kDefaultProbeBudgetMs : 0));
433 // Short waits add up: with no per-wait limit, a submission goes ahead once the waits of the window reach the budget.
434 {
435 SubmitMutex m;
436 m.set_gate_adaptive(true);
437 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
438 m.set_gate_wait_limit_ms(0);
439 m.set_gate_probe_budget_ms(300);
440 EXPECT(m.gate_probe_budget_ms() == 300);
441 std::atomic<bool> a_in{false};
442 std::thread a([&] {
443 const SubmitMutex::CompileTurn turn(m);
444 a_in = true;
445 std::this_thread::sleep_for(200ms);
446 });
447 const bool a_entered = eventually([&] { return a_in.load(); });
448 std::int64_t first_waited = 0;
449 bool first_ahead = true;
450 {
451 const std::int64_t start = now_ms();
452 const SubmitMutex::SubmitTurn turn(m); // waits the create out: under the budget
453 first_waited = now_ms() - start;
454 first_ahead = turn.went_ahead();
455 }
456 a.join();
457 std::atomic<bool> b_in{false}, release{false};
458 std::thread b([&] {
459 const SubmitMutex::CompileTurn turn(m);
460 b_in = true;
461 while (!release) std::this_thread::sleep_for(1ms);
462 });
463 const bool b_entered = eventually([&] { return b_in.load(); });
464 std::int64_t second_waited = 0;
465 bool second_ahead = false;
466 {
467 const std::int64_t start = now_ms();
468 const SubmitMutex::SubmitTurn turn(m); // goes ahead once both waits add up to 300 ms
469 second_waited = now_ms() - start;
470 second_ahead = turn.went_ahead();
471 }
472 const Verdict after_one = m.gate_verdict();
473 release = true;
474 b.join();
475 EXPECT(a_entered && b_entered);
476 EXPECT(!first_ahead && first_waited >= 100);
477 EXPECT(second_ahead && first_waited + second_waited >= 250 && second_waited < 300);
478 EXPECT(after_one == Verdict::pending); // one quick probe is not enough
479 std::printf("compile gate: waits of %lld and %lld ms reached the 300 ms probe budget, the second went ahead\n",
480 static_cast<long long>(first_waited), static_cast<long long>(second_waited));
481 }
482 // After a held verdict the budget no longer applies: a submission waits a create out again.
483 {
484 SubmitMutex m;
485 m.set_gate_adaptive(true);
486 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
487 m.set_gate_wait_limit_ms(0);
488 m.set_gate_probe_budget_ms(100);
489 std::atomic<bool> in{false}, release{false};
490 std::thread create([&] {
491 const SubmitMutex::CompileTurn turn(m);
492 in = true;
493 while (!release) std::this_thread::sleep_for(1ms);
494 });
495 const bool entered = eventually([&] { return in.load(); });
496 bool ahead = false;
497 {
498 const SubmitMutex::SubmitTurn turn(m); // goes ahead at the budget, then is held 2.1 s
499 ahead = turn.went_ahead();
500 std::this_thread::sleep_for(2000ms);
501 release = true; // the create it stayed beside leaves 100 ms before it comes back: a held probe
502 create.join();
503 std::this_thread::sleep_for(100ms);
504 }
505 const Verdict held = m.gate_verdict();
506 std::atomic<bool> short_in{false};
507 std::atomic<std::int64_t> short_left_at{0};
508 std::thread short_create([&] {
509 const SubmitMutex::CompileTurn turn(m);
510 short_in = true;
511 std::this_thread::sleep_for(400ms);
512 short_left_at = now_ms();
513 });
514 const bool short_entered = eventually([&] { return short_in.load(); });
515 std::int64_t entered_at = 0;
516 bool later_ahead = true;
517 {
518 const SubmitMutex::SubmitTurn turn(m);
519 entered_at = now_ms();
520 later_ahead = turn.went_ahead();
521 }
522 short_create.join();
523 EXPECT(entered && short_entered && ahead);
524 EXPECT(held == Verdict::driver_holds);
525 EXPECT(!later_ahead && entered_at >= short_left_at.load());
526 }
527 std::printf("compile gate: after a held probe a 400 ms create is waited out past the 100 ms budget\n");
528 return 0;
529}
530
531int gate_per_kind() {
532 if (!SubmitMutex::compile_gate_enabled()) {
533 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): per-kind verdicts not checked\n");
534 return 0;
535 }
536 using Verdict = SubmitMutex::GateVerdict;
537 using Kind = SubmitMutex::CreateKind;
538 SubmitMutex m;
539 m.set_gate_adaptive(true);
540 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
541 m.set_gate_wait_limit_ms(100);
542 m.set_gate_probe_budget_ms(0);
543 const SubmitMutex::CreateInfo compute{Kind::compute, "test compute", "test", 1000};
544 const SubmitMutex::CreateInfo graphics{Kind::graphics, "test mesh", "test", 2000};
545 // A compute create that stays until let go; the compute gate goes off after two quick probes a second apart.
546 std::atomic<bool> c_in{false}, c_release{false};
547 std::atomic<std::int64_t> c_left_at{0};
548 std::thread c([&] {
549 const SubmitMutex::CompileTurn turn(m, compute);
550 c_in = true;
551 while (!c_release) std::this_thread::sleep_for(1ms);
552 c_left_at = now_ms();
553 });
554 const bool c_entered = eventually([&] { return c_in.load(); });
555 { const SubmitMutex::SubmitTurn turn(m); } // goes ahead at the limit: the first quick probe
556 std::this_thread::sleep_for(1100ms);
557 { const SubmitMutex::SubmitTurn turn(m); } // the second
558 const Verdict compute_off = m.gate_verdict(Kind::compute), graphics_before = m.gate_verdict(Kind::graphics);
559 // A graphics create is still waited for: its kind has no verdict, so the submission goes ahead only at the limit.
560 std::atomic<bool> g_in{false}, g_release{false};
561 std::thread g([&] {
562 const SubmitMutex::CompileTurn turn(m, graphics);
563 g_in = true;
564 while (!g_release) std::this_thread::sleep_for(1ms);
565 });
566 const bool g_entered = eventually([&] { return g_in.load(); });
567 std::int64_t g_waited = 0;
568 bool g_ahead = false;
569 {
570 const std::int64_t start = now_ms();
571 const SubmitMutex::SubmitTurn turn(m);
572 g_waited = now_ms() - start;
573 g_ahead = turn.went_ahead();
574 }
575 g_release = true;
576 g.join();
577 const Verdict graphics_after = m.gate_verdict(Kind::graphics); // one quick probe: still pending
578 // A second compute create, there through the rest.
579 std::atomic<bool> c2_in{false}, c2_release{false};
580 std::atomic<std::int64_t> c2_left_at{0};
581 std::thread c2([&] {
582 const SubmitMutex::CompileTurn turn(m, compute);
583 c2_in = true;
584 while (!c2_release) std::this_thread::sleep_for(1ms);
585 c2_left_at = now_ms();
586 });
587 const bool c2_entered = eventually([&] { return c2_in.load(); });
588 // Re-arm: beside the compute creates (gate off), a submission stays 2.1 s in the "driver" and comes back 100 ms
589 // after the first one leaves.
590 {
591 const SubmitMutex::SubmitTurn turn(m);
592 std::this_thread::sleep_for(2000ms);
593 c_release = true;
594 c.join();
595 std::this_thread::sleep_for(100ms);
596 }
597 const Verdict compute_rearmed = m.gate_verdict(Kind::compute);
598 // The second compute create is waited for, and not gone past at the limit: its kind holds submissions.
599 std::atomic<std::int64_t> released_at{0};
600 std::thread releaser([&] {
601 std::this_thread::sleep_for(400ms);
602 released_at = now_ms();
603 c2_release = true;
604 });
605 std::int64_t entered_at = 0;
606 bool after_ahead = true;
607 {
608 const SubmitMutex::SubmitTurn turn(m);
609 entered_at = now_ms();
610 after_ahead = turn.went_ahead();
611 }
612 releaser.join();
613 c2.join();
614 EXPECT(c_entered && c2_entered && g_entered);
615 EXPECT(compute_off == Verdict::driver_does_not_hold && graphics_before == Verdict::pending);
616 EXPECT(g_ahead && g_waited >= 90 && g_waited < 1000);
617 EXPECT(graphics_after == Verdict::pending);
618 EXPECT(compute_rearmed == Verdict::driver_holds);
619 EXPECT(!after_ahead && entered_at >= c2_left_at.load() && entered_at >= released_at.load());
620 m.report_creates_on_loss(); // nothing in the driver now: the verdicts only
621 std::printf("compile gate: compute off with graphics still gated; a 2.1 s submission re-armed compute, and the next "
622 "one waited %lld ms past the 100 ms limit for the compute create\n",
623 static_cast<long long>(entered_at - (released_at.load() - 400)));
624 return 0;
625}
626
627// A create that stays in the "driver" until `release` is set; `in` is set once it is there, `left_at` when it leaves.
628struct HeldCreate {
629 std::atomic<bool> in{false}, release{false};
630 std::atomic<std::int64_t> left_at{0};
631 std::thread thread;
632 HeldCreate(SubmitMutex& m, const SubmitMutex::CreateInfo& info) {
633 thread = std::thread([&m, info, this] {
634 const SubmitMutex::CompileTurn turn(m, info);
635 in = true;
636 while (!release) std::this_thread::sleep_for(1ms);
637 left_at = now_ms();
638 });
639 }
640 void let_go() {
641 release = true;
642 if (thread.joinable()) thread.join();
643 }
644 ~HeldCreate() { let_go(); }
645};
646
647// The cases raised in review of #2412: a later create leaving does not hide an earlier one, presents and waits do
648// not probe, and a kind that holds submissions is waited for up to the held limit only.
649int gate_review_cases() {
650 if (!SubmitMutex::compile_gate_enabled()) {
651 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): review cases not checked\n");
652 return 0;
653 }
654 using Verdict = SubmitMutex::GateVerdict;
655 using Kind = SubmitMutex::CreateKind;
656 const SubmitMutex::CreateInfo compute{Kind::compute, "test compute", "test", 1000};
657 const auto turn_compute_off = [&](SubmitMutex& m, HeldCreate& c) {
658 { const SubmitMutex::SubmitTurn turn(m); }
659 std::this_thread::sleep_for(1100ms);
660 { const SubmitMutex::SubmitTurn turn(m); }
661 return m.gate_verdict(Kind::compute) == Verdict::driver_does_not_hold && c.in.load();
662 };
663 // A, there when the submission entered, leaves; then B, which entered after it, leaves; then the submission comes
664 // back. A's leave still counts: re-armed.
665 for (const bool a_first : {true, false}) {
666 SubmitMutex m;
667 m.set_gate_adaptive(true);
668 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
669 m.set_gate_wait_limit_ms(100);
670 m.set_gate_probe_budget_ms(0);
671 HeldCreate a(m, compute);
672 const bool off = eventually([&] { return a.in.load(); }) && turn_compute_off(m, a);
673 std::unique_ptr<HeldCreate> b;
674 {
675 const SubmitMutex::SubmitTurn turn(m);
676 b = std::make_unique<HeldCreate>(m, compute); // enters after the submission did
677 EXPECT(eventually([&] { return b->in.load(); }));
678 std::this_thread::sleep_for(2000ms);
679 if (a_first) {
680 a.let_go();
681 std::this_thread::sleep_for(30ms);
682 b->let_go();
683 } else {
684 b->let_go();
685 std::this_thread::sleep_for(30ms);
686 a.let_go();
687 }
688 std::this_thread::sleep_for(50ms);
689 }
690 EXPECT(off);
691 EXPECT(m.gate_verdict(Kind::compute) == Verdict::driver_holds);
692 }
693 std::printf("compile gate: A then B and B then A leaving just before a 2.1 s submission both re-arm compute\n");
694 // B alone leaves (it entered after the submission), A is still there: not held.
695 {
696 SubmitMutex m;
697 m.set_gate_adaptive(true);
698 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
699 m.set_gate_wait_limit_ms(100);
700 m.set_gate_probe_budget_ms(0);
701 HeldCreate a(m, compute);
702 const bool off = eventually([&] { return a.in.load(); }) && turn_compute_off(m, a);
703 {
704 const SubmitMutex::SubmitTurn turn(m);
705 HeldCreate b(m, compute);
706 EXPECT(eventually([&] { return b.in.load(); }));
707 std::this_thread::sleep_for(2000ms);
708 b.let_go();
709 std::this_thread::sleep_for(50ms);
710 }
711 EXPECT(off);
712 EXPECT(m.gate_verdict(Kind::compute) == Verdict::driver_does_not_hold);
713 }
714 std::printf("compile gate: a create that entered after the submission leaving does not re-arm compute\n");
715 // A present or wait (probe false) that comes back 2.1 s later, just after the create left, judges nothing.
716 {
717 SubmitMutex m;
718 m.set_gate_adaptive(true);
719 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
720 m.set_gate_wait_limit_ms(100);
721 m.set_gate_probe_budget_ms(0);
722 HeldCreate a(m, compute);
723 EXPECT(eventually([&] { return a.in.load(); }));
724 {
725 const SubmitMutex::SubmitTurn turn(m, false);
726 std::this_thread::sleep_for(2000ms);
727 a.let_go();
728 std::this_thread::sleep_for(50ms);
729 }
730 EXPECT(m.gate_verdict(Kind::compute) == Verdict::pending);
731 }
732 std::printf("compile gate: a 2.1 s present or wait judges nothing\n");
733 // A kind that holds is waited for up to the held limit, then gone past; the next submission does not wait for it.
734 {
735 SubmitMutex m;
736 m.set_gate_adaptive(true);
737 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
738 m.set_gate_wait_limit_ms(100);
739 m.set_gate_probe_budget_ms(0);
740 m.set_gate_held_limit_ms(400);
741 {
742 HeldCreate first(m, compute);
743 EXPECT(eventually([&] { return first.in.load(); }));
744 const SubmitMutex::SubmitTurn turn(m);
745 std::this_thread::sleep_for(2000ms);
746 first.let_go();
747 std::this_thread::sleep_for(50ms);
748 }
749 const Verdict held = m.gate_verdict(Kind::compute);
750 HeldCreate stays(m, compute);
751 EXPECT(eventually([&] { return stays.in.load(); }));
752 std::int64_t waited = 0, next_waited = 0;
753 bool ahead = false;
754 {
755 const std::int64_t start = now_ms();
756 const SubmitMutex::SubmitTurn turn(m);
757 waited = now_ms() - start;
758 ahead = turn.went_ahead();
759 }
760 {
761 const std::int64_t start = now_ms();
762 const SubmitMutex::SubmitTurn turn(m);
763 next_waited = now_ms() - start;
764 }
765 EXPECT(held == Verdict::driver_holds);
766 EXPECT(ahead && waited >= 390 && waited < 2000);
767 EXPECT(next_waited < 50);
768 std::printf("compile gate: with a holding kind a submission waited %lld ms (held limit 400 ms), the next %lld ms\n",
769 static_cast<long long>(waited), static_cast<long long>(next_waited));
770 }
771 return 0;
772}
773
774// The second review of #2412: whether a create that holds is in the driver is checked on every pass of the wait, the
775// held limit applies on its own, the notice comes once per wait, and a present or wait never uses the probe budget.
776int gate_second_review() {
777 if (!SubmitMutex::compile_gate_enabled()) {
778 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): second review cases not checked\n");
779 return 0;
780 }
781 using Verdict = SubmitMutex::GateVerdict;
782 using Kind = SubmitMutex::CreateKind;
783 const SubmitMutex::CreateInfo compute{Kind::compute, "test compute", "test", 1000};
784 const SubmitMutex::CreateInfo graphics{Kind::graphics, "test mesh", "test", 2000};
785 const auto adaptive = [](SubmitMutex& m) {
786 m.set_gate_adaptive(true);
787 m.set_gate_graphics(true); // as LEONIDA_COMPILE_GATE=adaptive
788 m.set_gate_probe_budget_ms(0);
789 };
790 // Compute gets the held verdict: a submission goes ahead at a 100 ms limit, stays 2 s, and comes back just after
791 // the create leaves.
792 const auto compute_holds = [&](SubmitMutex& m) {
793 m.set_gate_wait_limit_ms(100);
794 HeldCreate first(m, compute);
795 if (!eventually([&] { return first.in.load(); })) return false;
796 {
797 const SubmitMutex::SubmitTurn turn(m);
798 std::this_thread::sleep_for(2000ms);
799 first.let_go();
800 std::this_thread::sleep_for(50ms);
801 }
802 return m.gate_verdict(Kind::compute) == Verdict::driver_holds;
803 };
804 // (a) The holding compute create leaves while a graphics create (no verdict) stays: the submission goes ahead at
805 // the plain limit, even with no held limit.
806 {
807 SubmitMutex m;
808 adaptive(m);
809 const bool holds = compute_holds(m);
810 m.set_gate_wait_limit_ms(300);
811 m.set_gate_held_limit_ms(0);
812 HeldCreate c(m, compute);
813 HeldCreate g(m, graphics);
814 EXPECT(eventually([&] { return c.in.load() && g.in.load(); }));
815 std::atomic<std::int64_t> waited{-1};
816 std::atomic<bool> ahead{false};
817 std::thread submit([&] {
818 const std::int64_t start = now_ms();
819 const SubmitMutex::SubmitTurn turn(m);
820 waited = now_ms() - start;
821 ahead = turn.went_ahead();
822 });
823 std::this_thread::sleep_for(150ms);
824 c.let_go();
825 const bool went = eventually([&] { return waited.load() >= 0; }); // within 2 s, the graphics one still there
826 g.let_go();
827 submit.join();
828 EXPECT(holds);
829 EXPECT(went && ahead.load() && waited.load() >= 290 && waited.load() < 1000);
830 std::printf("compile gate: the holding create left, the other kind's stayed: went ahead after %lld ms "
831 "(limit 300 ms, no held limit)\n", static_cast<long long>(waited.load()));
832 }
833 // (b) and (c): a held limit under the plain limit applies on its own, and one over it gives one notice per wait.
834 for (const bool shorter : {true, false}) {
835 SubmitMutex m;
836 adaptive(m);
837 const bool holds = compute_holds(m);
838 m.set_gate_wait_limit_ms(shorter ? 2000 : 100);
839 m.set_gate_held_limit_ms(shorter ? 300 : 400);
840 HeldCreate c(m, compute);
841 EXPECT(eventually([&] { return c.in.load(); }));
842 const unsigned notices = m.gate_held_notices();
843 std::int64_t waited = 0;
844 bool ahead = false;
845 {
846 const std::int64_t start = now_ms();
847 const SubmitMutex::SubmitTurn turn(m);
848 waited = now_ms() - start;
849 ahead = turn.went_ahead();
850 }
851 const unsigned noted = m.gate_held_notices() - notices;
852 c.let_go();
853 EXPECT(holds && ahead);
854 if (shorter) {
855 EXPECT(waited >= 290 && waited < 1000 && noted == 0);
856 } else {
857 EXPECT(waited >= 390 && waited < 1000 && noted == 1);
858 }
859 std::printf("compile gate: held limit %s the plain limit: went ahead after %lld ms, %u notice(s)\n",
860 shorter ? "300 ms, under" : "400 ms, over", static_cast<long long>(waited), noted);
861 }
862 // (d) A present or wait beside a create with no verdict never goes ahead at the probe budget, only at the limit.
863 {
864 SubmitMutex m;
865 adaptive(m);
866 m.set_gate_wait_limit_ms(1000);
867 m.set_gate_probe_budget_ms(200);
868 HeldCreate c(m, compute);
869 EXPECT(eventually([&] { return c.in.load(); }));
870 std::int64_t waited = 0;
871 bool ahead = false;
872 {
873 const std::int64_t start = now_ms();
874 const SubmitMutex::SubmitTurn turn(m, false);
875 waited = now_ms() - start;
876 ahead = turn.went_ahead();
877 }
878 c.let_go();
879 EXPECT(ahead && waited >= 990 && waited < 2000);
880 EXPECT(m.gate_verdict(Kind::compute) == Verdict::pending);
881 std::printf("compile gate: a present beside an unverified create waited %lld ms (budget 200 ms, limit 1000 "
882 "ms)\n", static_cast<long long>(waited));
883 }
884 return 0;
885}
886
887// The classic gate (LEONIDA_COMPILE_GATE unset, the default): compute creates are waited for however long they take,
888// graphics creates do not pass the gate, nothing probes.
889int gate_classic() {
890 if (!SubmitMutex::compile_gate_enabled()) {
891 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): classic gate not checked\n");
892 return 0;
893 }
894 using Kind = SubmitMutex::CreateKind;
895 using Verdict = SubmitMutex::GateVerdict;
896 const SubmitMutex::GateMode mode = SubmitMutex::compile_gate_mode();
897 if (mode == SubmitMutex::GateMode::classic) {
898 EXPECT(!SubmitMutex::compile_gate_graphics());
899 if (!std::getenv("LEONIDA_COMPILE_GATE_PROBE_MS") && !std::getenv("LEONIDA_COMPILE_GATE_WAIT_MS"))
900 EXPECT(SubmitMutex::default_gate_wait_limit_ms() == 0 && SubmitMutex::default_gate_probe_budget_ms() == 0);
901 }
902 SubmitMutex m;
903 m.set_gate_adaptive(false);
904 m.set_gate_graphics(false);
905 m.set_gate_wait_limit_ms(0);
906 m.set_gate_probe_budget_ms(0);
907 // A graphics create in the driver holds no submission back.
908 std::atomic<bool> g_in{false}, g_release{false};
909 std::thread g([&] {
910 const SubmitMutex::CompileTurn turn(m, SubmitMutex::CreateInfo{Kind::graphics, "test mesh", "test", 2000});
911 g_in = true;
912 while (!g_release) std::this_thread::sleep_for(1ms);
913 });
914 const bool g_entered = eventually([&] { return g_in.load(); });
915 std::int64_t beside_graphics = 0;
916 {
917 const std::int64_t start = now_ms();
918 const SubmitMutex::SubmitTurn turn(m);
919 beside_graphics = now_ms() - start;
920 }
921 g_release = true;
922 g.join();
923 // A compute create is waited for until it leaves, well past the adaptive gate's 2.5 s budget, and decides nothing.
924 std::atomic<bool> c_in{false};
925 std::atomic<std::int64_t> c_left_at{0};
926 std::thread c([&] {
927 const SubmitMutex::CompileTurn turn(m, SubmitMutex::CreateInfo{Kind::compute, "test compute", "test", 1000});
928 c_in = true;
929 std::this_thread::sleep_for(3000ms);
930 c_left_at = now_ms();
931 });
932 const bool c_entered = eventually([&] { return c_in.load(); });
933 std::int64_t entered_at = 0;
934 bool ahead = true;
935 {
936 const SubmitMutex::SubmitTurn turn(m);
937 entered_at = now_ms();
938 ahead = turn.went_ahead();
939 }
940 c.join();
941 EXPECT(g_entered && c_entered);
942 EXPECT(beside_graphics < 50);
943 EXPECT(entered_at >= c_left_at.load() && !ahead);
944 EXPECT(m.gate_verdict(Kind::compute) == Verdict::pending && m.gate_verdict(Kind::graphics) == Verdict::pending);
945 std::printf("classic gate: %lld ms beside a graphics create; a submission waited out a 3 s compute create\n",
946 static_cast<long long>(beside_graphics));
947 return 0;
948}
949
200} // namespace 950} // namespace
201 951
202int main() { 952int main() {
203 std::setvbuf(stdout, nullptr, _IONBF, 0); 953 std::setvbuf(stdout, nullptr, _IONBF, 0);
204 if (owner_tracking() || waits_for_holder() || waits_for_queued_submitter() || handoff_is_capped() || 954 if (owner_tracking() || waits_for_holder() || waits_for_queued_submitter() || handoff_is_capped() ||
205 compile_gate()) 955 compile_gate() || gate_wait_limit() || gate_adapts() ||
956 gate_probe_budget() || gate_per_kind() || gate_review_cases() || gate_second_review() ||
957 gate_classic())
206 return 1; 958 return 1;
207 std::printf("submit_mutex_test: all passed\n"); 959 std::printf("submit_mutex_test: all passed\n");
208 return 0; 960 return 0;