upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_device_fault.h
diff options
context:
space:
mode:
authorTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
committerTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
commitbeffaa9a476ca1b3dfd9cfa55e39eafbb1f5eec6 (patch)
tree32877805bf4eb46d9a89d5753db6b5a2b06dc845 /runtime/src/vulkan_device_fault.h
parentf29ca7bacae9507f83e8c56abdb604bd4efb4cf1 (diff)
parenta73a57e1339be072baf5522351c8ec7f1482b56b (diff)
Merge main into fix/null-descriptor-generated-dir
Diffstat (limited to 'runtime/src/vulkan_device_fault.h')
-rw-r--r--runtime/src/vulkan_device_fault.h657
1 files changed, 644 insertions, 13 deletions
diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h
index d60367491..b3af188d1 100644
--- a/runtime/src/vulkan_device_fault.h
+++ b/runtime/src/vulkan_device_fault.h
@@ -2,19 +2,25 @@
2 2
3#include <vulkan/vulkan.h> 3#include <vulkan/vulkan.h>
4 4
5#include "vulkan_device_markers.h"
6
5#include <algorithm> 7#include <algorithm>
6#include <array> 8#include <array>
7#include <atomic> 9#include <atomic>
8#include <chrono> 10#include <chrono>
11#include <condition_variable>
9#include <cinttypes> 12#include <cinttypes>
10#include <cstddef> 13#include <cstddef>
11#include <cstdint> 14#include <cstdint>
12#include <cstdio> 15#include <cstdio>
13#include <cstdlib> 16#include <cstdlib>
14#include <functional> 17#include <functional>
18#include <memory>
15#include <cstring> 19#include <cstring>
16#include <mutex> 20#include <mutex>
17#include <span> 21#include <span>
22#include <string>
23#include <thread>
18#include <unordered_map> 24#include <unordered_map>
19#include <utility> 25#include <utility>
20#include <vector> 26#include <vector>
@@ -25,6 +31,7 @@ struct DeviceFaultExtensions {
25 bool fault = false; 31 bool fault = false;
26 bool checkpoints = false; 32 bool checkpoints = false;
27 bool diagnostics_config = false; 33 bool diagnostics_config = false;
34 bool markers = false; // VK_AMD_buffer_marker (LEONIDA_DEVICE_MARKERS=1, vulkan_device_markers.h)
28}; 35};
29 36
30// What a device asks for. LEONIDA_DEVICE_FAULT=1 wants all of it; LEONIDA_AFTERMATH=1 alone (vulkan_aftermath.h) only 37// What a device asks for. LEONIDA_DEVICE_FAULT=1 wants all of it; LEONIDA_AFTERMATH=1 alone (vulkan_aftermath.h) only
@@ -33,6 +40,7 @@ struct DeviceFaultRequest {
33 bool fault = true; // VK_EXT_device_fault and VK_NV_device_diagnostic_checkpoints 40 bool fault = true; // VK_EXT_device_fault and VK_NV_device_diagnostic_checkpoints
34 bool diagnostics_config = true; // VK_NV_device_diagnostics_config 41 bool diagnostics_config = true; // VK_NV_device_diagnostics_config
35 VkDeviceDiagnosticsConfigFlagsNV extra_flags = 0; // added to the default config flags below 42 VkDeviceDiagnosticsConfigFlagsNV extra_flags = 0; // added to the default config flags below
43 bool markers = false; // VK_AMD_buffer_marker, when the device has it
36}; 44};
37 45
38// Owns the feature structures until vkCreateDevice returns. 46// Owns the feature structures until vkCreateDevice returns.
@@ -62,13 +70,15 @@ struct DeviceFaultFeatures {
62 } 70 }
63 const DeviceFaultExtensions enabled{has_fault && fault.deviceFault == VK_TRUE, 71 const DeviceFaultExtensions enabled{has_fault && fault.deviceFault == VK_TRUE,
64 request.fault && has(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME), 72 request.fault && has(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME),
65 has_config && diagnostics.diagnosticsConfig == VK_TRUE}; 73 has_config && diagnostics.diagnosticsConfig == VK_TRUE,
74 request.markers && has(VK_AMD_BUFFER_MARKER_EXTENSION_NAME)};
66 if (enabled.fault) { 75 if (enabled.fault) {
67 extensions.push_back(VK_EXT_DEVICE_FAULT_EXTENSION_NAME); 76 extensions.push_back(VK_EXT_DEVICE_FAULT_EXTENSION_NAME);
68 fault.pNext = const_cast<void*>(device.pNext); 77 fault.pNext = const_cast<void*>(device.pNext);
69 device.pNext = &fault; 78 device.pNext = &fault;
70 } 79 }
71 if (enabled.checkpoints) extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME); 80 if (enabled.checkpoints) extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME);
81 if (enabled.markers) extensions.push_back(VK_AMD_BUFFER_MARKER_EXTENSION_NAME);
72 if (enabled.diagnostics_config) { 82 if (enabled.diagnostics_config) {
73 extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); 83 extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
74 diagnostics.pNext = const_cast<void*>(device.pNext); 84 diagnostics.pNext = const_cast<void*>(device.pNext);
@@ -153,6 +163,7 @@ struct CheckpointDispatch {
153 std::uint32_t max_count, stride; 163 std::uint32_t max_count, stride;
154 std::array<std::uint32_t, 32> roots; 164 std::array<std::uint32_t, 32> roots;
155 bool indirect; 165 bool indirect;
166 std::uint64_t seq = 0; // the report's dispatch number, counted over every recorded dispatch (CheckpointRecorder)
156}; 167};
157 168
158struct CheckpointSubmission { 169struct CheckpointSubmission {
@@ -165,6 +176,13 @@ struct CheckpointSubmission {
165 std::vector<CheckpointDispatch> dispatches; 176 std::vector<CheckpointDispatch> dispatches;
166 std::size_t dispatch_count = 0; 177 std::size_t dispatch_count = 0;
167 static constexpr std::size_t dispatch_limit = 64; 178 static constexpr std::size_t dispatch_limit = 64;
179 // Numbers every recorded dispatch, across queues and submissions (the report's seq). Null: no numbers.
180 std::atomic<std::uint64_t>* dispatch_seq = nullptr;
181 // LEONIDA_DEVICE_MARKERS=1: this queue's marker slot, every dispatch recorded for the marker history and the seq
182 // whose finished marker is still to be written after its dispatch (CheckpointRecorder::dispatched).
183 MarkerTarget markers;
184 std::vector<MarkedDispatch> marked;
185 std::uint64_t open_marker = 0;
168 186
169 void append_dispatch(CheckpointDispatch d) { 187 void append_dispatch(CheckpointDispatch d) {
170 if (dispatches.size() < dispatch_limit) dispatches.push_back(d); 188 if (dispatches.size() < dispatch_limit) dispatches.push_back(d);
@@ -201,11 +219,26 @@ struct CheckpointRecorder {
201 std::uintptr_t count = 0, std::uint64_t count_offset = 0, 219 std::uintptr_t count = 0, std::uint64_t count_offset = 0,
202 std::uint32_t max_count = 0, std::uint32_t stride = 0) const { 220 std::uint32_t max_count = 0, std::uint32_t stride = 0) const {
203 const auto names = pipeline_names.find(id); 221 const auto names = pipeline_names.find(id);
222 const char* shader = names != pipeline_names.end() ? names->second[0] : nullptr;
223 const std::uint64_t seq =
224 submission.dispatch_seq ? submission.dispatch_seq->fetch_add(1, std::memory_order_relaxed) + 1 : 0;
204 submission.append_dispatch({submission.execute_call, submission.queue, submission.queue_kind, list, command, 225 submission.append_dispatch({submission.execute_call, submission.queue, submission.queue_kind, list, command,
205 names != pipeline_names.end() ? names->second[0] : nullptr, groups, args, count, 226 shader, groups, args, count, offset, count_offset, max_count, stride, roots, indirect, seq});
206 offset, count_offset, max_count, stride, roots, indirect}); 227 if (submission.markers) {
228 submission.marked.push_back({seq, submission.execute_call, submission.queue, submission.queue_kind,
229 static_cast<std::uint32_t>(list), static_cast<std::uint32_t>(command), shader});
230 submission.markers.started(buffer, seq);
231 submission.open_marker = seq;
232 }
207 record(buffer, command, CheckpointKind::dispatch, pipeline, id); 233 record(buffer, command, CheckpointKind::dispatch, pipeline, id);
208 } 234 }
235
236 // After the dispatch call(s) that dispatch() announced: its finished marker.
237 void dispatched(VkCommandBuffer buffer) const {
238 if (!submission.open_marker) return;
239 submission.markers.finished(buffer, submission.open_marker);
240 submission.open_marker = 0;
241 }
209}; 242};
210 243
211// A D3D fence may stay unsignalled by design. Only queue retirement tickets represent 244// A D3D fence may stay unsignalled by design. Only queue retirement tickets represent
@@ -244,9 +277,308 @@ inline void run_device_lost_hook() noexcept {
244 if (const auto hook = device_lost_hook.load(std::memory_order_acquire)) hook(); 277 if (const auto hook = device_lost_hook.load(std::memory_order_acquire)) hook();
245} 278}
246 279
280// LOCAL DIAGNOSTIC (early device loss): what the submit lock, the recent submissions and the other threads were
281// doing when a submission stalled or the device was lost.
282inline std::int64_t diagnostic_ms() {
283 static const auto start = std::chrono::steady_clock::now();
284 return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
285}
286
287#ifdef _WIN32
288extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(void);
289inline std::uint32_t diagnostic_thread_id() { return static_cast<std::uint32_t>(GetCurrentThreadId()); }
290#else
291inline std::uint32_t diagnostic_thread_id() { return 0; }
292#endif
293
294// Set by gta6rt's main (src/thread_stacks.cpp): prints the call chain of thread `tid`, or of every other thread
295// when `tid` is 0. Unset in the tests.
296inline std::atomic<void (*)(std::uint32_t tid, const char* why) noexcept> thread_stack_hook{nullptr};
297
298inline void print_thread_stacks(std::uint32_t tid, const char* why) noexcept {
299 if (const auto hook = thread_stack_hook.load(std::memory_order_acquire)) hook(tid, why);
300}
301
302// The compute pipeline vkCreateComputePipelines is building now (one at a time is enough: the reports name the one
303// set last), for the submit-lock hold report. Names are ShaderLibrary strings, valid until device teardown.
304struct DriverCompile {
305 std::atomic<const char*> name{nullptr};
306 std::atomic<const char*> trigger{nullptr};
307 std::atomic<std::int64_t> since_ms{0};
308 std::atomic<std::size_t> bytes{0};
309};
310inline DriverCompile driver_compile;
311
312// 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
314// report name that thread, and a hold of a second or more is logged when it ends.
315class SubmitMutex {
316public:
317 static constexpr std::int64_t kLongHoldMs = 1000;
318 // How long let_submit_finish(true) keeps letting queued submitters go first before the caller goes ahead anyway,
319 // so a steady stream of submits cannot hold the compile worker back for ever. Waiting out the holder itself is
320 // not capped: entering the driver while a submit is inside it is what lost the device.
321 static constexpr std::int64_t kHandoffCapMs = 250;
322
323 void lock() {
324 if (mutex_.try_lock()) {
325 taken();
326 return;
327 }
328 // Counted until this thread owns the lock (owner_ set), so let_submit_finish never sees neither.
329 waiting_.fetch_add(1, std::memory_order_relaxed);
330 mutex_.lock();
331 taken();
332 waiting_.fetch_sub(1, std::memory_order_relaxed);
333 }
334 bool try_lock() {
335 if (!mutex_.try_lock()) return false;
336 taken();
337 return true;
338 }
339 void unlock() {
340 const std::int64_t since = since_.load(std::memory_order_relaxed);
341 const std::uint32_t owner = owner_.load(std::memory_order_relaxed);
342 owner_.store(0, std::memory_order_relaxed);
343 releases_.fetch_add(1); // seq_cst with the handoff_waiters_ load: no let_submit_finish misses this release
344 mutex_.unlock();
345 if (handoff_waiters_.load()) {
346 std::lock_guard lock(handoff_mutex_);
347 released_.notify_all();
348 }
349 const std::int64_t now = diagnostic_ms();
350 if (now - since >= kLongHoldMs)
351 std::fprintf(stderr, "[rt] submit-lock: held %lld ms by thread %u, t=%.3f..%.3f s\n",
352 static_cast<long long>(now - since), owner, double(since) / 1000.0, double(now) / 1000.0);
353 }
354
355 std::uint32_t owner() const { return owner_.load(std::memory_order_relaxed); }
356 std::int64_t since_ms() const { return since_.load(std::memory_order_relaxed); }
357 // Threads blocked in lock() (try_lock never counts).
358 std::uint32_t waiting() const { return waiting_.load(std::memory_order_relaxed); }
359
360 // Called before the driver calls that build pipelines: waits for a submit in progress to finish (unless this
361 // thread is the one submitting). Measured on NVIDIA 630.20 (three early losses): back-to-back pipeline creates on
362 // the compile worker keep re-taking a driver lock that vkQueueSubmit waits for; after 10 s of that wait the driver
363 // returns VK_ERROR_DEVICE_LOST, with no GPU fault and no TDR. Not entering the driver while a submit is in it lets
364 // the submit take that lock between two creates.
365 // `queued` (the compile worker): also lets the submitters queued behind the holder go first - std::mutex is not
366 // fair, so without that the worker's next create could get in ahead of them - for at most `cap_ms`; past it the
367 // hold in progress is the last one waited for. The wait never takes the lock itself (taking it could queue behind
368 // every submitter that re-takes it), it waits for the hold it saw to end. Returns how many milliseconds it waited.
369 std::int64_t let_submit_finish(bool queued = true, std::int64_t cap_ms = kHandoffCapMs) {
370 const std::uint32_t self = diagnostic_thread_id();
371 if (owner_.load(std::memory_order_relaxed) == self) return 0; // this thread submits: nothing to let through
372 const auto queue = [&] { return queued && waiting_.load(std::memory_order_relaxed) != 0; };
373 std::uint64_t seen = releases_.load();
374 const auto held = [&] {
375 seen = releases_.load(); // read before the owner: a hold that ends after this changes it
376 return owner_.load() != 0;
377 };
378 if (!held() && !queue()) return 0;
379 const std::int64_t start = diagnostic_ms();
380 for (;;) {
381 const bool over = diagnostic_ms() - start >= cap_ms;
382 if (held()) {
383 wait_release(seen);
384 if (!queued || over) break;
385 } else if (!queue() || over) {
386 break;
387 } else {
388 std::this_thread::yield(); // a queued submitter is between its wake-up and taking the lock
389 }
390 }
391 return diagnostic_ms() - start;
392 }
393
394 // The compile gate. A queue submission never enters the driver while a pipeline create is in it: measured on
395 // NVIDIA 630.20 (wf6), a vkQueueSubmit that entered while the warm-up thread was inside one long
396 // vkCreateComputePipelines waited 10 s in the driver and returned VK_ERROR_DEVICE_LOST; let_submit_finish cannot
397 // help once the create is already running. Creates pass the gate shared, a submission exclusively, and a create
398 // 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.
400 // 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.
402 class CompileTurn { // around vkCreate*Pipelines
403 public:
404 explicit CompileTurn(SubmitMutex& gate) : gate_(gate), waited_(gate.enter_compile()) {}
405 ~CompileTurn() { gate_.leave_compile(); }
406 CompileTurn(const CompileTurn&) = delete;
407 CompileTurn& operator=(const CompileTurn&) = delete;
408 std::int64_t waited_ms() const { return waited_; }
409
410 private:
411 SubmitMutex& gate_;
412 std::int64_t waited_;
413 };
414 class SubmitTurn { // around vkQueueSubmit, with the submit lock held
415 public:
416 explicit SubmitTurn(SubmitMutex& gate) : gate_(gate) { gate.enter_submit(); }
417 ~SubmitTurn() { gate_.leave_submit(); }
418 SubmitTurn(const SubmitTurn&) = delete;
419 SubmitTurn& operator=(const SubmitTurn&) = delete;
420
421 private:
422 SubmitMutex& gate_;
423 };
424
425 static bool compile_gate_enabled() {
426 static const bool on = [] {
427 const char* value = std::getenv("LEONIDA_COMPILE_GATE");
428 return !(value && !std::strcmp(value, "0"));
429 }();
430 return on;
431 }
432
433 // The thread waiting in enter_submit for creates to leave the driver, or 0.
434 std::uint32_t gate_waiter() const { return gate_waiter_.load(std::memory_order_relaxed); }
435
436 struct GateStats {
437 std::uint64_t submits = 0; // submissions that had to wait for a create
438 std::int64_t submit_ms = 0, submit_max_ms = 0;
439 std::uint64_t creates = 0; // creates that waited behind a submission
440 std::int64_t create_ms = 0, create_max_ms = 0;
441 };
442 GateStats gate_stats() {
443 std::lock_guard lock(gate_mutex_);
444 return stats_;
445 }
446
447 std::int64_t enter_compile() {
448 if (!compile_gate_enabled()) return 0;
449 std::unique_lock lock(gate_mutex_);
450 std::int64_t waited = 0;
451 if (submits_) {
452 const std::int64_t start = diagnostic_ms();
453 gate_changed_.wait(lock, [&] { return submits_ == 0; });
454 waited = diagnostic_ms() - start;
455 ++stats_.creates;
456 stats_.create_ms += waited;
457 stats_.create_max_ms = (std::max)(stats_.create_max_ms, waited);
458 }
459 ++compiles_;
460 return waited;
461 }
462 void leave_compile() {
463 if (!compile_gate_enabled()) return;
464 std::lock_guard lock(gate_mutex_);
465 if (--compiles_ == 0 && submits_) gate_changed_.notify_all();
466 }
467
468 std::int64_t enter_submit() {
469 if (!compile_gate_enabled()) return 0;
470 std::unique_lock lock(gate_mutex_);
471 ++submits_;
472 if (!compiles_) return 0;
473 const std::uint32_t self = diagnostic_thread_id();
474 gate_waiter_.store(self, std::memory_order_relaxed);
475 const std::int64_t start = diagnostic_ms();
476 const GateWait what{self, compiles_, driver_compile.name.load(std::memory_order_acquire),
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;
480 while (!gate_changed_.wait_for(lock, std::chrono::milliseconds(250), [&] { return compiles_ == 0; })) {
481 const std::int64_t waited = diagnostic_ms() - start;
482 if (waited < next_note) continue;
483 next_note = waited + 5000;
484 note_gate_wait("has waited", what, waited);
485 }
486 gate_waiter_.store(0, std::memory_order_relaxed);
487 const std::int64_t waited = diagnostic_ms() - start;
488 ++stats_.submits;
489 stats_.submit_ms += waited;
490 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.
492 if (waited >= 500 || (waited >= 50 && logged_waits_ < 32)) {
493 ++logged_waits_;
494 note_gate_wait("waited", what, waited);
495 }
496 return waited;
497 }
498 void leave_submit() {
499 if (!compile_gate_enabled()) return;
500 std::lock_guard lock(gate_mutex_);
501 if (--submits_ == 0) gate_changed_.notify_all();
502 }
503
504private:
505 void taken() {
506 since_.store(diagnostic_ms(), std::memory_order_relaxed);
507 owner_.store(diagnostic_thread_id(), std::memory_order_relaxed);
508 }
509
510 // Until a hold ends after `seen` releases.
511 void wait_release(std::uint64_t seen) {
512 handoff_waiters_.fetch_add(1);
513 {
514 std::unique_lock lock(handoff_mutex_);
515 released_.wait(lock, [&] { return releases_.load() != seen; });
516 }
517 handoff_waiters_.fetch_sub(1);
518 }
519
520 // With gate_mutex_ held.
521 // The creates a submission found in the driver: how many, and the compute one named last (graphics creates are
522 // not named). Names are ShaderLibrary strings, valid until device teardown.
523 struct GateWait {
524 std::uint32_t thread;
525 std::uint32_t creates;
526 const char* name;
527 const char* trigger;
528 std::size_t bytes;
529 };
530 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 "
532 "leave the driver (compute %s, %zu B SPIR-V, %s) at t=%.3f s; %llu such waits so far, "
533 "%lld ms in all, longest %lld ms\n",
534 what.thread, how, static_cast<long long>(waited), what.creates, what.name ? what.name : "-",
535 what.name ? what.bytes : std::size_t{0}, what.name && what.trigger ? what.trigger : "-",
536 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(stats_.submits),
537 static_cast<long long>(stats_.submit_ms), static_cast<long long>(stats_.submit_max_ms));
538 }
539
540 std::mutex mutex_;
541 std::atomic<std::uint32_t> owner_{0};
542 std::atomic<std::int64_t> since_{0};
543 std::atomic<std::uint32_t> waiting_{0};
544 std::atomic<std::uint64_t> releases_{0}; // unlocks so far
545 std::atomic<std::uint32_t> handoff_waiters_{0};
546 std::mutex handoff_mutex_; // leaf
547 std::condition_variable released_;
548
549 std::mutex gate_mutex_; // leaf: guards the gate counts and stats
550 std::condition_variable gate_changed_;
551 std::uint32_t compiles_ = 0; // creates in the driver
552 std::uint32_t submits_ = 0; // submissions waiting for them or in the driver
553 std::atomic<std::uint32_t> gate_waiter_{0};
554 GateStats stats_;
555 unsigned logged_waits_ = 0;
556};
557
558// One vkQueueSubmit of a VulkanQueue: its waits, its signals and how long the call took (-1: not returned yet).
559struct SubmitRecord {
560 static constexpr std::size_t max_waits = 6;
561 std::int64_t at_ms = 0;
562 std::int64_t took_ms = -1;
563 int result = 1;
564 VkQueue queue = VK_NULL_HANDLE;
565 const char* kind = "";
566 VkSemaphore progress = VK_NULL_HANDLE;
567 std::uint64_t ticket = 0;
568 VkSemaphore fence = VK_NULL_HANDLE;
569 std::uint64_t fence_value = 0;
570 std::uint32_t buffers = 0;
571 std::uint32_t waits = 0;
572 std::array<VkSemaphore, max_waits> wait_semaphores{};
573 std::array<std::uint64_t, max_waits> wait_values{};
574};
575
247class DeviceFaultDiagnostics { 576class DeviceFaultDiagnostics {
248public: 577public:
249 DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled) 578 // `memory` and `synchronization2` are for the AMD markers (enabled.markers): where their buffer goes and whether
579 // vkCmdWriteBufferMarker2AMD may be used.
580 DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled,
581 const VkPhysicalDeviceMemoryProperties* memory = nullptr, bool synchronization2 = false)
250 : device_(device) { 582 : device_(device) {
251#define LEONIDA_FAULT_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name)) 583#define LEONIDA_FAULT_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name))
252 if (enabled.fault) LEONIDA_FAULT_LOAD(vkGetDeviceFaultInfoEXT); 584 if (enabled.fault) LEONIDA_FAULT_LOAD(vkGetDeviceFaultInfoEXT);
@@ -254,10 +586,22 @@ public:
254 LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV); 586 LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV);
255 LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV); 587 LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV);
256 } 588 }
589 LEONIDA_FAULT_LOAD(vkGetSemaphoreCounterValue);
257#undef LEONIDA_FAULT_LOAD 590#undef LEONIDA_FAULT_LOAD
258 std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n", 591 std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n",
259 vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable", 592 vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable",
260 enabled.diagnostics_config ? "on" : "unavailable"); 593 enabled.diagnostics_config ? "on" : "unavailable");
594 if (enabled.markers) enable_markers(get, memory, synchronization2);
595 else if (device_markers_requested())
596 std::fprintf(stderr, "[rt] device-markers: unavailable: the device has no VK_AMD_buffer_marker\n");
597 }
598
599 bool markers_on() const { return markers_ != nullptr; }
600
601 // The queue's marker slot as the GPU last wrote it ({0, 0} without markers).
602 MarkerSlot marker_slot(VkQueue queue) {
603 std::lock_guard lock(mutex_);
604 return markers_ ? markers_->read(queue) : MarkerSlot{};
261 } 605 }
262 606
263 PFN_vkCmdSetCheckpointNV checkpoint_command() const { 607 PFN_vkCmdSetCheckpointNV checkpoint_command() const {
@@ -265,21 +609,166 @@ public:
265 } 609 }
266 610
267 void add_queue(VkQueue queue) { 611 void add_queue(VkQueue queue) {
268 if (!queue || !vkGetQueueCheckpointDataNV) return; 612 if (!queue) return;
269 std::lock_guard lock(mutex_); 613 std::lock_guard lock(mutex_);
614 if (markers_ && !markers_->add_queue(queue))
615 std::fprintf(stderr, "[rt] device-markers: no slot for queue %p (%u queues have one)\n",
616 static_cast<void*>(queue), DeviceMarkers::max_queues);
617 if (!vkGetQueueCheckpointDataNV) return;
270 if (std::find(queues_.begin(), queues_.end(), queue) == queues_.end()) queues_.push_back(queue); 618 if (std::find(queues_.begin(), queues_.end(), queue) == queues_.end()) queues_.push_back(queue);
271 } 619 }
272 620
273 std::uint64_t next_execute_call() { return ++execute_calls_; } 621 std::uint64_t next_execute_call() { return ++execute_calls_; }
274 622
623 void set_submit_lock(const SubmitMutex* lock) { submit_lock_ = lock; }
624
625 // Called under the submit lock, before and after the vkQueueSubmit it describes.
626 std::size_t begin_submit(const SubmitRecord& record) {
627 std::lock_guard lock(mutex_);
628 const std::size_t at = submit_count_++;
629 submits_[at % submits_.size()] = record;
630 return at;
631 }
632 void end_submit(std::size_t at, std::int64_t took_ms, VkResult result) {
633 std::lock_guard lock(mutex_);
634 if (submit_count_ - at > submits_.size()) return;
635 auto& record = submits_[at % submits_.size()];
636 record.took_ms = took_ms;
637 record.result = int(result);
638 }
639
640 // The holder of the submit lock has kept it for `held_ms`: its call chain and what was submitted last.
641 void report_submit_lock_holder(std::uint32_t owner, std::int64_t held_ms) {
642 std::fprintf(stderr, "[rt] submit-lock: thread %u has held it for %lld ms (t=%.3f s)\n", owner,
643 static_cast<long long>(held_ms), double(diagnostic_ms()) / 1000.0);
644 if (const char* name = driver_compile.name.load(std::memory_order_acquire)) {
645 const char* trigger = driver_compile.trigger.load(std::memory_order_relaxed);
646 std::fprintf(stderr, "[rt] submit-lock: vkCreateComputePipelines has been building %s (%zu B SPIR-V, %s) "
647 "for %lld ms\n",
648 name, driver_compile.bytes.load(std::memory_order_relaxed), trigger ? trigger : "?",
649 static_cast<long long>(diagnostic_ms() - driver_compile.since_ms.load(std::memory_order_relaxed)));
650 }
651 if (submit_lock_ && submit_lock_->gate_waiter() == owner) {
652 // Not in the driver: waiting at the compile gate for the create named above (SubmitMutex::CompileTurn).
653 std::fprintf(stderr, "[rt] submit-lock: thread %u is waiting at the compile gate, not in the driver\n", owner);
654 return;
655 }
656 // Every thread, the holder included: what the driver waits for may be another thread's work. No counters
657 // here (dump_submits would block in the driver behind the holder); the loss report has them. A long hold can
658 // also be a legitimate vkDeviceWaitIdle: the stacks of the first three holds, then at most one a minute.
659 const std::int64_t now = diagnostic_ms();
660 if (stack_reports_ >= 3 && now - last_stack_report_ms_ < 60000) return;
661 ++stack_reports_;
662 last_stack_report_ms_ = now;
663 print_thread_stacks(0, "submit-lock hold");
664 }
665
666 // Before `semaphore` is destroyed (~VulkanFence, ~VulkanQueue): the ring stops naming it, so no report reads the
667 // counter of a destroyed semaphore. Waits for a report that is reading counters now.
668 void forget(VkSemaphore semaphore) {
669 if (!semaphore) return;
670 std::lock_guard reading(read_mutex_);
671 if (stalled_progress_ == semaphore) stalled_progress_ = VK_NULL_HANDLE;
672 std::lock_guard lock(mutex_);
673 for (auto& r : submits_) {
674 if (r.progress == semaphore) r.progress = VK_NULL_HANDLE;
675 if (r.fence == semaphore) r.fence = VK_NULL_HANDLE;
676 for (auto& wait : r.wait_semaphores)
677 if (wait == semaphore) wait = VK_NULL_HANDLE;
678 }
679 }
680
681 // Once a second from the progress watch, without the submit lock: when the oldest submission in the ring that
682 // has not finished is 4 s old, the ring with every counter as it is now, once per such submission.
683 void check_submit_progress() {
684 std::lock_guard reading(read_mutex_); // the semaphores read below outlive this call (forget)
685 const std::vector<SubmitRecord> records = submit_records();
686 if (!vkGetSemaphoreCounterValue) return;
687 const std::int64_t now = diagnostic_ms();
688 for (const auto& r : records) {
689 if (r.took_ms < 0 || r.result != VK_SUCCESS || !r.progress) continue;
690 std::uint64_t done = 0;
691 if (vkGetSemaphoreCounterValue(device_, r.progress, &done) != VK_SUCCESS) return;
692 if (done >= r.ticket) continue;
693 // Age from when vkQueueSubmit returned: the call itself may have waited at the compile gate.
694 if (now - (r.at_ms + r.took_ms) < 4000) return; // the oldest unfinished one is young
695 if (r.progress == stalled_progress_ && r.ticket == stalled_ticket_) return;
696 stalled_progress_ = r.progress;
697 stalled_ticket_ = r.ticket;
698 std::fprintf(stderr, "[rt] gpu-stall: %s queue %p ticket %llu submitted at t=%.3f s not done after %lld ms "
699 "(progress %llu)\n",
700 r.kind, static_cast<void*>(r.queue), static_cast<unsigned long long>(r.ticket),
701 double(r.at_ms) / 1000.0, static_cast<long long>(now - r.at_ms),
702 static_cast<unsigned long long>(done));
703 dump_submits_reading();
704 return;
705 }
706 }
707
708 // The last submissions, oldest first, with every semaphore's counter now (? once the device is lost, or for a
709 // semaphore destroyed since).
710 void dump_submits() {
711 std::lock_guard reading(read_mutex_);
712 dump_submits_reading();
713 }
714
715private:
716 std::vector<SubmitRecord> submit_records() {
717 std::vector<SubmitRecord> records;
718 std::lock_guard lock(mutex_);
719 const std::size_t n = std::min(submit_count_, submits_.size());
720 records.reserve(n);
721 for (std::size_t i = submit_count_ - n; i < submit_count_; ++i) records.push_back(submits_[i % submits_.size()]);
722 return records;
723 }
724
725 // dump_submits with read_mutex_ held.
726 void dump_submits_reading() {
727 const std::vector<SubmitRecord> records = submit_records();
728 // Every semaphore the ring names is non-null when recorded: null is one destroyed since (forget).
729 const auto counter = [&](VkSemaphore semaphore) -> std::string {
730 std::uint64_t value = 0;
731 if (!semaphore) return "destroyed";
732 if (!vkGetSemaphoreCounterValue || vkGetSemaphoreCounterValue(device_, semaphore, &value) != VK_SUCCESS)
733 return "?";
734 return std::to_string(value);
735 };
736 const std::int64_t now = diagnostic_ms();
737 for (const auto& r : records) {
738 std::string line = "[rt] submit-ring: t=" + std::to_string(double(r.at_ms) / 1000.0) + " s " + r.kind +
739 " queue=" + std::to_string(reinterpret_cast<std::uintptr_t>(r.queue)) +
740 " buffers=" + std::to_string(r.buffers) + " ticket=" + std::to_string(r.ticket) +
741 " progress=" + counter(r.progress) + " took=" +
742 (r.took_ms < 0 ? "pending(" + std::to_string(now - r.at_ms) + " ms)"
743 : std::to_string(r.took_ms) + " ms") +
744 " result=" + std::to_string(r.result);
745 if (r.fence || r.fence_value)
746 line += " signal=" + std::to_string(pipeline_handle(r.fence)) + ":" + std::to_string(r.fence_value) +
747 " now " + counter(r.fence);
748 for (std::uint32_t i = 0; i < r.waits && i < SubmitRecord::max_waits; ++i)
749 line += " wait=" + std::to_string(pipeline_handle(r.wait_semaphores[i])) + ":" +
750 std::to_string(r.wait_values[i]) + " now " + counter(r.wait_semaphores[i]);
751 if (r.waits > SubmitRecord::max_waits) line += " (+" + std::to_string(r.waits - SubmitRecord::max_waits) + " waits)";
752 line += '\n';
753 std::fputs(line.c_str(), stderr);
754 }
755 }
756
757public:
275 // Accessed under the context's resource lock. Reports read the names copied into the ring instead. 758 // Accessed under the context's resource lock. Reports read the names copied into the ring instead.
276 std::unordered_map<std::uintptr_t, CheckpointShaders> pipeline_names; 759 std::unordered_map<std::uintptr_t, CheckpointShaders> pipeline_names;
277 760
278 // Called under the context's tracker lock, in replay order. 761 // Called under the context's tracker lock, in replay order.
279 CheckpointSubmission begin_submission(std::uint64_t call, VkQueue queue, const char* kind, std::size_t lists) { 762 CheckpointSubmission begin_submission(std::uint64_t call, VkQueue queue, const char* kind, std::size_t lists) {
280 if (!++sequence_) ++sequence_; // 0 is reserved for invalid markers 763 if (!++sequence_) ++sequence_; // 0 is reserved for invalid markers
281 return {sequence_, call, queue, kind, lists, 764 CheckpointSubmission submission{sequence_, call, queue, kind, lists,
282 std::vector<CheckpointList>(std::min(lists, std::size_t{CheckpointMarker::max_list} + 1))}; 765 std::vector<CheckpointList>(std::min(lists, std::size_t{CheckpointMarker::max_list} + 1))};
766 submission.dispatch_seq = &dispatch_seq_;
767 if (markers_) {
768 std::lock_guard lock(mutex_);
769 submission.markers = markers_->target(queue);
770 }
771 return submission;
283 } 772 }
284 773
285 void publish(CheckpointSubmission&& submission) { 774 void publish(CheckpointSubmission&& submission) {
@@ -287,12 +776,24 @@ public:
287 for (std::size_t i = submission.dispatch_count - submission.dispatches.size(); i < submission.dispatch_count; ++i) 776 for (std::size_t i = submission.dispatch_count - submission.dispatches.size(); i < submission.dispatch_count; ++i)
288 dispatches_[dispatch_count_++ % dispatches_.size()] = submission.dispatches[i % submission.dispatch_limit]; 777 dispatches_[dispatch_count_++ % dispatches_.size()] = submission.dispatches[i % submission.dispatch_limit];
289 submission.dispatches.clear(); 778 submission.dispatches.clear();
779 if (history_)
780 for (const auto& d : submission.marked) history_->push(d);
781 submission.marked.clear();
290 recent_[submission.sequence % recent_.size()] = std::move(submission); 782 recent_[submission.sequence % recent_.size()] = std::move(submission);
291 } 783 }
292 784
293 static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept { 785 static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept {
294 if (result == VK_ERROR_DEVICE_LOST) { 786 if (result == VK_ERROR_DEVICE_LOST) {
295 if (diagnostics) diagnostics->report(operation); 787 if (diagnostics) {
788 diagnostics->report(operation);
789 } else {
790 // Without LEONIDA_DEVICE_FAULT a loss was silent: the title only saw ~0 in its fence words.
791 static std::atomic<bool> logged{false};
792 if (!logged.exchange(true, std::memory_order_relaxed))
793 std::fprintf(stderr, "[rt] vulkan: VK_ERROR_DEVICE_LOST from %s at t=%.3f s on thread %u "
794 "(LEONIDA_DEVICE_FAULT=1 for the fault report)\n",
795 operation, double(diagnostic_ms()) / 1000.0, diagnostic_thread_id());
796 }
296 run_device_lost_hook(); 797 run_device_lost_hook();
297 } 798 }
298 return result; 799 return result;
@@ -301,8 +802,9 @@ public:
301 void report_stall(const char* reason, std::uint64_t submitted, std::uint64_t retired) { 802 void report_stall(const char* reason, std::uint64_t submitted, std::uint64_t retired) {
302 std::fprintf(stderr, "[rt] device-stall: %s for 15 s; submitted ticket %" PRIu64 803 std::fprintf(stderr, "[rt] device-stall: %s for 15 s; submitted ticket %" PRIu64
303 ", last observed retired ticket %" PRIu64 "\n", reason, submitted, retired); 804 ", last observed retired ticket %" PRIu64 "\n", reason, submitted, retired);
304 // NV checkpoints and EXT fault data require a lost device. The CPU ring is valid at any time. 805 // NV checkpoints and EXT fault data require a lost device. The CPU ring and the AMD markers are valid at any
305 dump_dispatches(); 806 // time.
807 dump_dispatches(report_markers(false));
306 // LEONIDA_STALL_CHECKPOINTS=1 (diagnostic): ask for the checkpoints anyway. A hang (Xid 109) the driver 808 // LEONIDA_STALL_CHECKPOINTS=1 (diagnostic): ask for the checkpoints anyway. A hang (Xid 109) the driver
307 // recovers from without losing the device otherwise names no program; outside the lost state the call is 809 // recovers from without losing the device otherwise names no program; outside the lost state the call is
308 // out of the extension's contract, which the NVIDIA driver has answered so far. 810 // out of the extension's contract, which the NVIDIA driver has answered so far.
@@ -319,14 +821,87 @@ public:
319 } 821 }
320 } 822 }
321 823
824 // LEONIDA_DEVICE_MARKERS=1: each queue's marker slot judged against the marker history, printed; returns the
825 // likely hangs (the oldest started, unfinished dispatch of each queue) for dump_dispatches to mark.
826 std::vector<std::uint64_t> report_markers(bool lost) noexcept {
827 std::vector<std::uint64_t> hangs;
828 if (!markers_) return hangs;
829 try {
830 std::lock_guard lock(mutex_);
831 std::fprintf(stderr, "[rt] device-markers: AMD buffer markers, read %s; best-effort: %s\n",
832 lost ? "after the device loss" : "while the device is still up",
833 lost ? "only what the GPU wrote before it stopped, and a reset may have lost the last writes"
834 : "the GPU may still be writing them");
835 for (VkQueue queue : markers_->queues()) {
836 const MarkerQueueReport r = judge_markers(queue, markers_->read(queue), *history_);
837 if (!r.slot.started && !r.slot.finished && !r.next_queued) continue; // never marked a dispatch
838 const char* kind = r.queue_kind ? r.queue_kind : "?";
839 if (r.idle()) {
840 std::fprintf(stderr, "[rt] device-markers: queue %p (%s) idle: finished seq=%u, nothing started "
841 "after it", static_cast<void*>(queue), kind, unsigned(r.slot.finished));
842 if (r.next_queued)
843 std::fprintf(stderr, "; next submitted seq=%" PRIu64 " not started (waiting, or behind other "
844 "work of the queue)", r.next_queued);
845 std::fputc('\n', stderr);
846 continue;
847 }
848 std::string line = "[rt] device-markers: queue " + hex(queue) + " (" + kind + ") finished seq=" +
849 std::to_string(r.slot.finished) + " started seq=" + std::to_string(r.slot.started) +
850 "; started, not finished:";
851 for (std::size_t i = 0; i < r.unfinished.size() && i < 16; ++i)
852 line += " " + std::to_string(r.unfinished[i]);
853 if (r.unfinished.size() > 16) line += " (+" + std::to_string(r.unfinished.size() - 16) + ")";
854 if (r.missing) line += " (no longer in the marker history)";
855 line += '\n';
856 std::fputs(line.c_str(), stderr);
857 if (!r.likely_hang) continue;
858 hangs.push_back(r.likely_hang);
859 history_->for_each([&](const MarkedDispatch& d) {
860 if (d.seq != r.likely_hang) return;
861 std::fprintf(stderr, "[rt] device-markers: likely hang: seq=%" PRIu64 " execute=%" PRIu64
862 " queue=%p (%s) list=%u command=%u shader=%s\n",
863 d.seq, d.execute_call, static_cast<void*>(d.queue), kind, d.list, d.command,
864 d.shader ? d.shader : "-");
865 });
866 }
867 } catch (...) {
868 std::fprintf(stderr, "[rt] device-markers: marker collection failed\n");
869 }
870 return hangs;
871 }
872
322private: 873private:
323 void dump_dispatches() { 874 void enable_markers(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties* memory,
875 bool synchronization2) {
876 auto markers = std::make_unique<DeviceMarkers>();
877 const VkResult result =
878 memory ? markers->create(get, device_, *memory, synchronization2) : VK_ERROR_INITIALIZATION_FAILED;
879 if (result != VK_SUCCESS) {
880 std::fprintf(stderr, "[rt] device-markers: unavailable: the marker buffer could not be made (%d)\n",
881 int(result));
882 return;
883 }
884 std::fprintf(stderr, "[rt] device-markers: on (VK_AMD_buffer_marker, %s): each dispatch writes its seq at top "
885 "and bottom of pipe\n",
886 markers->synchronization2() ? "vkCmdWriteBufferMarker2AMD" : "vkCmdWriteBufferMarkerAMD");
887 history_ = std::make_unique<MarkerHistory>();
888 markers_ = std::move(markers);
889 }
890
891 template<typename Handle>
892 static std::string hex(Handle handle) {
893 char text[24];
894 std::snprintf(text, sizeof(text), "%p", static_cast<void*>(handle));
895 return text;
896 }
897
898 void dump_dispatches(const std::vector<std::uint64_t>& hangs = {}) {
324 std::lock_guard lock(mutex_); 899 std::lock_guard lock(mutex_);
325 const auto n = std::min(dispatch_count_, dispatches_.size()); 900 const auto n = std::min(dispatch_count_, dispatches_.size());
326 for (std::size_t i = dispatch_count_ - n; i < dispatch_count_; ++i) { 901 for (std::size_t i = dispatch_count_ - n; i < dispatch_count_; ++i) {
327 const auto& d = dispatches_[i % dispatches_.size()]; 902 const auto& d = dispatches_[i % dispatches_.size()];
328 std::fprintf(stderr, "[rt] device-fault: submitted dispatch seq=%zu execute=%" PRIu64 903 std::fprintf(stderr, "[rt] device-fault: submitted dispatch seq=%" PRIu64 " execute=%" PRIu64
329 " queue=%p (%s) list=%zu command=%zu shader=%s ", i + 1, d.execute_call, 904 " queue=%p (%s) list=%zu command=%zu shader=%s ", d.seq, d.execute_call,
330 static_cast<void*>(d.queue), d.queue_kind, d.list, d.command, d.shader ? d.shader : "-"); 905 static_cast<void*>(d.queue), d.queue_kind, d.list, d.command, d.shader ? d.shader : "-");
331 if (d.indirect) 906 if (d.indirect)
332 std::fprintf(stderr, "indirect args=0x%" PRIxPTR "+0x%" PRIx64 " count=0x%" PRIxPTR 907 std::fprintf(stderr, "indirect args=0x%" PRIxPTR "+0x%" PRIx64 " count=0x%" PRIxPTR
@@ -337,6 +912,8 @@ private:
337 std::fputs(" roots=", stderr); 912 std::fputs(" roots=", stderr);
338 for (auto word : d.roots) std::fprintf(stderr, "%08x ", word); 913 for (auto word : d.roots) std::fprintf(stderr, "%08x ", word);
339 } 914 }
915 if (d.seq && std::find(hangs.begin(), hangs.end(), d.seq) != hangs.end())
916 std::fputs(" <- likely hang (device-markers)", stderr);
340 std::fputc('\n', stderr); 917 std::fputc('\n', stderr);
341 } 918 }
342 } 919 }
@@ -354,7 +931,17 @@ private:
354 void report(const char* operation) noexcept { 931 void report(const char* operation) noexcept {
355 if (reported_.exchange(true, std::memory_order_relaxed)) return; 932 if (reported_.exchange(true, std::memory_order_relaxed)) return;
356 std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation); 933 std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation);
357 dump_dispatches(); 934 try {
935 const std::int64_t now = diagnostic_ms();
936 const std::uint32_t owner = submit_lock_ ? submit_lock_->owner() : 0;
937 std::fprintf(stderr, "[rt] device-fault: t=%.3f s on thread %u; submit lock held by thread %u for %lld ms\n",
938 double(now) / 1000.0, diagnostic_thread_id(), owner,
939 owner ? static_cast<long long>(now - submit_lock_->since_ms()) : 0LL);
940 dump_submits();
941 print_thread_stacks(0, "device lost");
942 } catch (...) {
943 }
944 dump_dispatches(report_markers(true));
358 try { 945 try {
359 std::function<void()> hook; 946 std::function<void()> hook;
360 { 947 {
@@ -455,6 +1042,36 @@ private:
455 pipeline.shaders[2] ? pipeline.shaders[2] : "-"); 1042 pipeline.shaders[2] ? pipeline.shaders[2] : "-");
456 } 1043 }
457 } 1044 }
1045 // LOCAL DIAGNOSTIC (post-load GPU faults): the work in flight is between the bottom-of-pipe checkpoint (last
1046 // command finished) and the top-of-pipe one (last command started) of the same list. Every pipeline bound in
1047 // that window, so the faulting program is among them; the dispatch ring above only keeps the last 64
1048 // dispatches of all queues, and those were from another queue in the fault this was added for.
1049 for (std::uint32_t i = 0; i < count; ++i) {
1050 const auto top = CheckpointMarker::decode(reinterpret_cast<std::uintptr_t>(data[i].pCheckpointMarker));
1051 if (!top.submission || !(static_cast<std::uint64_t>(data[i].stage) & VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT))
1052 continue;
1053 std::uint32_t from = 0; // no bottom-of-pipe checkpoint in this list: from its start
1054 for (std::uint32_t j = 0; j < count; ++j) {
1055 const auto bottom = CheckpointMarker::decode(reinterpret_cast<std::uintptr_t>(data[j].pCheckpointMarker));
1056 if (bottom.submission == top.submission && bottom.list == top.list &&
1057 (static_cast<std::uint64_t>(data[j].stage) & VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT))
1058 from = bottom.command;
1059 }
1060 const auto& entry = recent_[top.submission % recent_.size()];
1061 if (entry.sequence != top.submission || entry.queue != queue || top.list >= entry.lists.size()) continue;
1062 const auto& shaders = entry.lists[top.list].shaders;
1063 // The pipeline bound when `from` ran, then every change up to the top-of-pipe command.
1064 auto it = std::upper_bound(shaders.begin(), shaders.end(), from,
1065 [](auto command, const auto& change) { return command < change.command; });
1066 if (it != shaders.begin()) --it;
1067 for (; it != shaders.end() && it->command <= top.command; ++it)
1068 std::fprintf(stderr, "[rt] device-fault: in flight (submission %u list %u, commands %u..%u): command %u "
1069 "pipeline=0x%" PRIx64 " shaders=%s %s %s\n",
1070 top.submission, top.list, from, top.command, unsigned(it->command),
1071 pipeline_handle(it->pipeline.handle), it->pipeline.shaders[0] ? it->pipeline.shaders[0] : "-",
1072 it->pipeline.shaders[1] ? it->pipeline.shaders[1] : "-",
1073 it->pipeline.shaders[2] ? it->pipeline.shaders[2] : "-");
1074 }
458 } 1075 }
459 1076
460 template<typename Handle> 1077 template<typename Handle>
@@ -467,9 +1084,20 @@ private:
467 PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr; 1084 PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr;
468 PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr; 1085 PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr;
469 PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr; 1086 PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr;
1087 PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue = nullptr;
1088 const SubmitMutex* submit_lock_ = nullptr;
1089 std::array<SubmitRecord, 96> submits_{}; // under mutex_
1090 std::size_t submit_count_ = 0;
1091 unsigned stack_reports_ = 0; // report_submit_lock_holder: the progress watch's thread only
1092 std::int64_t last_stack_report_ms_ = 0;
1093 VkSemaphore stalled_progress_ = VK_NULL_HANDLE; // under read_mutex_
1094 std::uint64_t stalled_ticket_ = 0;
470 std::atomic<bool> reported_{false}; 1095 std::atomic<bool> reported_{false};
471 std::atomic<std::uint64_t> execute_calls_{0}; 1096 std::atomic<std::uint64_t> execute_calls_{0};
472 std::uint32_t sequence_ = 0; 1097 std::uint32_t sequence_ = 0;
1098 // Held while a report reads the counters of the semaphores in the ring, and by forget before one is destroyed.
1099 // Before mutex_; the submit path never takes it.
1100 std::mutex read_mutex_;
473 std::mutex mutex_; // leaf lock, guards queues_ and recent_ 1101 std::mutex mutex_; // leaf lock, guards queues_ and recent_
474 std::vector<VkQueue> queues_; 1102 std::vector<VkQueue> queues_;
475 const bool include_roots_ = [] { 1103 const bool include_roots_ = [] {
@@ -478,6 +1106,9 @@ private:
478 }(); 1106 }();
479 std::array<CheckpointDispatch, CheckpointSubmission::dispatch_limit> dispatches_{}; 1107 std::array<CheckpointDispatch, CheckpointSubmission::dispatch_limit> dispatches_{};
480 std::size_t dispatch_count_ = 0; 1108 std::size_t dispatch_count_ = 0;
1109 std::atomic<std::uint64_t> dispatch_seq_{0}; // the last seq handed out (CheckpointRecorder::dispatch)
1110 std::unique_ptr<DeviceMarkers> markers_; // LEONIDA_DEVICE_MARKERS=1 on a device with VK_AMD_buffer_marker
1111 std::unique_ptr<MarkerHistory> history_; // with markers_, under mutex_
481 std::array<CheckpointSubmission, 64> recent_; 1112 std::array<CheckpointSubmission, 64> recent_;
482}; 1113};
483 1114