diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md index 986acf680..7211c44db 100644 --- a/docs/d3d12_xs_console_abi.md +++ b/docs/d3d12_xs_console_abi.md @@ -271,6 +271,15 @@ The runtime's model: behind a gate takes longer: the remap is then deferred to the releaser, which runs it once the queue's write fence passes the call's point and only then opens a gate the queue's later work waits on, so the GPU sees the order of the call and the title's thread does not wait (the console's CPU does not either). +- Every 10 s the pump logs its counters (`list values so far`): writes recorded (once per recording), submitted + (each time a list that holds them is executed) and landed, waits, gates and the releaser's work. Recorded but never + submitted is a list the title did not execute, not a write in flight. When three of those lines in a row are the + same while recorded writes have not all landed, the pump logs a stall snapshot once (again only after the counters + moved): each submitted write group still waiting, with the `written` fence value it needs and the value the fence + has reached; each closed gate, with its address, comparison, reference and what memory holds; and from the Vulkan + layer (`src/held_work_report.h`), the CPU waits on fences that are not satisfied and, for each queue that holds + work, what its oldest held operation waits for, both with the highest Signal submitted for that fence. A fence + whose wait has no Signal of that value submitted names what the stall is waiting for. Logging only. ## 6. Root arguments diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f8edc3508..d1aaceb0f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4602,6 +4602,14 @@ if(TARGET Vulkan::Headers) target_compile_definitions(clear_color_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME clear_color COMMAND clear_color_test) + # The stall report of QueueHolds (src/queue_holds.h, src/held_work_report.h); no GPU, no Vulkan. + add_executable(queue_holds_report_test test/queue_holds_report_test.cpp) + find_package(Threads REQUIRED) + target_link_libraries(queue_holds_report_test PRIVATE Threads::Threads) + if(MSVC) + target_compile_options(queue_holds_report_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME queue_holds_report COMMAND queue_holds_report_test) # FramePacer of the Xbox presentation path on a fake clock (src/frame_pacer.h); no GPU, no Vulkan. add_executable(frame_pacer_test test/frame_pacer_test.cpp) find_package(Threads REQUIRED) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index c5f12dc05..165d2971c 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -3943,6 +3943,7 @@ class ValueSubmission { group_.clear(); } if (writes_.empty()) return; + list_values::bump(list_values::counters().writes_submitted, writes_.size()); list_values::QueueValues* values = queue_->values.get(); if (values) { const std::uint64_t value = ++values->written_value; @@ -7000,7 +7001,8 @@ const char* list_tail_slot_name(unsigned slot, unsigned char console_layout) { // Every counter of list_values::Counters, by name: the stats and their reset stay in step. #define LEONIDA_LIST_VALUE_COUNTERS(X) \ - X(writes_recorded) X(writes_landed) X(writes_failed) X(waits_recorded) X(waits_met_at_submit) \ + X(writes_recorded) X(writes_submitted) X(writes_landed) X(writes_failed) X(waits_recorded) \ + X(waits_met_at_submit) \ X(waits_relayed) X(gates_held) X(gates_met) X(gates_timed_out) X(cuts) X(cuts_deferred) X(cut_failures) \ X(gates_short) X(demotions) X(late_met) X(bundle_ops) X(releases) X(release_us) X(release_us_max) \ X(pass_us_max) X(release_stalls) X(remaps_now) X(remaps_deferred) X(remaps_failed) X(remap_wait_us_max) \ @@ -7031,6 +7033,8 @@ void stop_list_values(unsigned ms) { list_values::Pump::get().stop(ms); } bool list_values_idle(unsigned ms) { return list_values::Pump::get().idle(ms); } +void list_values_snapshot(std::FILE* out) { list_values::Pump::get().snapshot(out); } + unsigned list_proxy_part_count(const void* list) { if (!is_list_proxy_impl(list)) return 0; return static_cast(static_cast(list)->parts.size()) + 1; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 67097a7d4..ef27fd6dc 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -130,6 +130,7 @@ #include #include +#include #include #include #include @@ -473,7 +474,7 @@ inline constexpr bool console_value_met(std::uint32_t comparison, std::uint64_t } } struct ListValueStats { - std::uint64_t writes_recorded, writes_landed, writes_failed; + std::uint64_t writes_recorded, writes_submitted, writes_landed, writes_failed; // submitted: per execution std::uint64_t waits_recorded, waits_met_at_submit, waits_relayed; // relayed: a GPU wait on a write in flight std::uint64_t gates_held, gates_met, gates_timed_out; // gate: opened from the CPU std::uint64_t cuts, cuts_deferred, cut_failures; // a list split at a wait after work @@ -496,6 +497,9 @@ void set_list_values_enabled(bool on); void stop_list_values(unsigned ms); // Test helper: true once every write landed and every gate opened, waiting up to `ms`. bool list_values_idle(unsigned ms); +// The stall snapshot the pump logs once its counters stood still with writes not landed (unlanded write groups, +// open gates, the D3D12 layer's held work), written to `out` now. Test helper and debugger aid. +void list_values_snapshot(std::FILE* out); // Test helper: the real lists a list proxy's recording is in (1 + its cuts), 0 for anything else. unsigned list_proxy_part_count(const void* list); diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index b4f24bbbb..e755a80e1 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -40,6 +40,10 @@ // a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full // timeout: met in that time, its address keeps the full timeout from then on. A gate cut short that is met within // its short timeout gives every wait the full timeout again. +// Stall snapshot: when the 10 s summary has not changed three times in a row while writes are still waiting to land, +// the pump says once which write groups wait for which queue's `written` fence (and how far that fence got), which +// gates are closed on what memory, and what the D3D12 layer holds and why (QueueHolds, src/held_work_report.h). +// Logging only. // LEONIDA_LIST_VALUES=0 drops both methods (the behaviour before this file). #include @@ -55,6 +59,7 @@ #include #include #include +#include #include #include #include @@ -63,6 +68,7 @@ #include #include "d3d12_xs_device.h" // console_value_met, ListValueStats +#include "../src/held_work_report.h" // leonida::report_held_work: the stall snapshot #include "../src/list_value_wait_budget.h" // leonida::list_value_wait: work-aware timeout clock & producer graph #include "../src/title_page_watch.h" // leonida::kernel_writes::store #include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages @@ -161,7 +167,8 @@ struct Write { }; struct Counters { - std::atomic writes_recorded{0}, writes_landed{0}, writes_failed{0}; + // Recorded into a list (once per recording), submitted (each time a list that holds them is executed), landed. + std::atomic writes_recorded{0}, writes_submitted{0}, writes_landed{0}, writes_failed{0}; std::atomic waits_recorded{0}, waits_met_at_submit{0}, waits_relayed{0}; std::atomic gates_held{0}, gates_met{0}, gates_timed_out{0}; std::atomic cuts{0}, cuts_deferred{0}, cut_failures{0}; @@ -502,6 +509,8 @@ class Pump { static constexpr std::size_t kMaxStreaks = 256; // addresses whose timeouts are counted (least recently used go) static constexpr std::size_t kMaxLate = 64; // waits cut short watched for the rest of the full timeout static constexpr std::uint64_t kStallMs = 1000; // a gate Signal this long is reported (watch_releaser) + static constexpr unsigned kStillSummaries = 3; // 10 s summaries alike before the stall snapshot + static constexpr std::size_t kSnapshotItems = 8; // write groups and gates the snapshot lists struct WriteGroup { std::shared_ptr queue; @@ -592,7 +601,9 @@ class Pump { // Writes wake us through SetEventOnCompletion; the timeout is only a safety net (and, while the // releaser is inside a Signal, how often watch_releaser looks at it). const bool releasing = signal_since_ms_.load(std::memory_order_relaxed) != 0; - WaitForSingleObject(wake_, polling ? kPollMs : writes ? 50 : releasing ? 500 : INFINITE); + // With nothing in flight it still looks every 10 s, so the summary and the stall snapshot are said + // when the title stopped submitting altogether. + WaitForSingleObject(wake_, polling ? kPollMs : writes ? 50 : releasing ? 500 : 10000); } if (stop_.load(std::memory_order_relaxed)) break; pass(false); @@ -886,7 +897,9 @@ class Pump { busy_ = false; } - // One line every 10 s while there is traffic, for boot logs. + // One line every 10 s once list values are in use, for boot logs. When three in a row are the same while recorded + // writes have not all landed, the stall snapshot follows once (snapshot()), and again only after the counters + // moved. void summarize() { const auto now = Clock::now(); if (now < next_summary_) return; @@ -895,14 +908,31 @@ class Pump { const auto get = [](const std::atomic& v) { return static_cast(v.load(std::memory_order_relaxed)); }; + const std::uint64_t moved[] = {get(c.writes_recorded), get(c.writes_submitted), get(c.writes_landed), + get(c.writes_failed), get(c.waits_recorded), get(c.gates_held), + get(c.gates_met), get(c.gates_timed_out), get(c.releases)}; + const bool unlanded = moved[0] > moved[2] + moved[3]; // recorded, not landed (or never submitted) + if (std::equal(std::begin(moved), std::end(moved), std::begin(last_moved_)) && unlanded) { + if (++still_summaries_ >= kStillSummaries && !snapshot_logged_) { + snapshot_logged_ = true; + snapshot(stderr, still_summaries_ * 10); + } + } else { + still_summaries_ = 0; + snapshot_logged_ = false; + std::copy(std::begin(moved), std::end(moved), std::begin(last_moved_)); + } std::fprintf(stderr, - "[rt] d3d12_xs: list values so far: %llu writes recorded, %llu landed, %llu failed; %llu waits " - "recorded, %llu met at submission, %llu relayed; %llu gates held, %llu met, %llu timed out " + "[rt] d3d12_xs: list values so far: %llu writes recorded (once per recording), %llu submitted " + "(once per execution: recorded but never submitted is a list the title did not execute), %llu " + "landed, %llu failed; %llu waits recorded, %llu met at submission, %llu relayed; %llu gates held, %llu met, " + "%llu timed out " "(%llu short, %llu demotions, %llu met late); %llu cuts (%llu deferred to a query's end, %llu " "failed), %llu on bundles; releaser %llu signals, %.1f ms, longest %.2f ms, %llu stalls; longest pump pass " "%.2f ms; %llu page remaps at the call (longest wait %.2f ms), %llu deferred (%llu failed); " "timestamps %llu from the GPU, %llu from the CPU clock\n", - get(c.writes_recorded), get(c.writes_landed), get(c.writes_failed), get(c.waits_recorded), + get(c.writes_recorded), get(c.writes_submitted), get(c.writes_landed), get(c.writes_failed), + get(c.waits_recorded), get(c.waits_met_at_submit), get(c.waits_relayed), get(c.gates_held), get(c.gates_met), get(c.gates_timed_out), get(c.gates_short), get(c.demotions), get(c.late_met), get(c.cuts), get(c.cuts_deferred), get(c.cut_failures), get(c.bundle_ops), get(c.releases), @@ -912,6 +942,104 @@ class Pump { get(c.remaps_failed), get(c.stamps_gpu), get(c.stamps_cpu)); } +public: + // The stall snapshot: what the writes still waiting to land and the gates still closed wait for, and what the + // D3D12 layer holds (leonida::report_held_work). Said when the counters stood still for `still_s` seconds (0: on + // request, the test). A write group lands once its queue's `written` fence reaches its value: a completed value + // below it means the queue has not run that far, so the queue's held work (the lines after) or its GPU work is + // what to look at. The fences are read with no lock held. + void snapshot(std::FILE* out, unsigned still_s = 0) { + struct GroupView { + std::shared_ptr queue; + std::uint64_t value; + std::size_t writes; + std::uint64_t first_address; + }; + struct GateView { + std::shared_ptr queue; + std::uint64_t value; + bool started, action; + std::uint64_t after; + double open_s; + std::vector waits; + }; + std::vector groups; + std::vector gates; + std::size_t group_count = 0, gate_count = 0; + const auto now = Clock::now(); + { + std::lock_guard lock(mutex_); + group_count = writes_.size(); + gate_count = gates_.size(); + for (const WriteGroup& group : writes_) { + if (groups.size() == kSnapshotItems) break; + groups.push_back({group.queue, group.value, group.writes.size(), + group.writes.empty() ? 0 : group.writes.front().address}); + } + for (const Gate& gate : gates_) { + if (gates.size() == kSnapshotItems) break; + gates.push_back({gate.queue, gate.value, gate.started, static_cast(gate.action), gate.after, + gate.started ? std::chrono::duration(now - gate.since).count() : 0.0, + gate.waits}); + } + } + const Counters& c = counters(); + const unsigned long long recorded = c.writes_recorded.load(std::memory_order_relaxed), + submitted = c.writes_submitted.load(std::memory_order_relaxed), + landed = c.writes_landed.load(std::memory_order_relaxed), + failed = c.writes_failed.load(std::memory_order_relaxed); + if (still_s) + std::fprintf(out, "[rt] d3d12_xs: stall snapshot: the list-value counters have not moved for %u s (writes " + "%llu recorded, %llu submitted, %llu landed, %llu failed: recorded but never submitted " + "is a list the title did not execute); %zu write group(s) and %zu gate(s) are " + "waiting:\n", + still_s, recorded, submitted, landed, failed, group_count, gate_count); + else + std::fprintf(out, "[rt] d3d12_xs: stall snapshot: %zu write group(s) and %zu gate(s) are waiting:\n", + group_count, gate_count); + for (const GroupView& group : groups) { + const unsigned long long completed = + group.queue && group.queue->written ? group.queue->written->GetCompletedValue() : 0; + std::fprintf(out, "[rt] d3d12_xs: %zu write(s) (first at 0x%llx) on queue values %p land at its written " + "fence %llu, completed %llu%s\n", + group.writes, static_cast(group.first_address), + static_cast(group.queue.get()), static_cast(group.value), + completed, + completed >= group.value ? " (reached: the pump has not landed them yet)" + : " (the queue has not run that far)"); + } + for (const GateView& gate : gates) { + const unsigned long long gate_done = + gate.queue && gate.queue->gate ? gate.queue->gate->GetCompletedValue() : 0; + if (gate.action) { + std::fprintf(out, "[rt] d3d12_xs: an action gate %llu on queue values %p runs behind its written " + "fence %llu (gate fence completed %llu)\n", + static_cast(gate.value), static_cast(gate.queue.get()), + static_cast(gate.after), gate_done); + continue; + } + char state[64] = "behind an earlier gate of its queue"; + if (gate.started) std::snprintf(state, sizeof(state), "its time has run for %.1f s", gate.open_s); + std::fprintf(out, "[rt] d3d12_xs: gate %llu on queue values %p (gate fence completed %llu), %s:\n", + static_cast(gate.value), static_cast(gate.queue.get()), + gate_done, state); + for (const Wait& wait : gate.waits) { + std::uint64_t memory = 0; + const bool readable = read_value(wait.address, wait.wide, memory); + std::fprintf(out, + "[rt] d3d12_xs: wait%u for 0x%llx, comparison %u against 0x%llx; memory %s0x%llx\n", + wait.wide ? 64u : 32u, static_cast(wait.address), wait.comparison, + static_cast(wait.reference), readable ? "" : "unreadable, ", + static_cast(memory)); + } + } + if (group_count > groups.size() || gate_count > gates.size()) + std::fprintf(out, "[rt] d3d12_xs: (the first %zu of each are shown)\n", kSnapshotItems); + leonida::report_held_work(out); + std::fflush(out); + } + +private: // A timestamp write's value: the GPU's timestamp for the write's place in its list when the GPU wrote one, else // the CPU's clock now. Flag 1 is in the queue's GetTimestampFrequency ticks; flag 2 (the system timestamp) is a // QueryPerformanceCounter value, the GPU's timestamp turned into one through the queue's clock calibration (never @@ -1137,6 +1265,10 @@ class Pump { bool busy_ = false; // a pass is landing or handing over what it took off the lists unsigned logged_met_ = 0; Clock::time_point next_summary_ = Clock::now() + std::chrono::seconds(10); // the pump thread's only + // summarize()'s: the counters at the last change, 10 s summaries alike since, the snapshot said for this stall. + std::uint64_t last_moved_[9] = {}; + unsigned still_summaries_ = 0; + bool snapshot_logged_ = false; std::mutex release_mutex_; // releases_ and releasing_ std::condition_variable release_ready_; std::deque releases_; diff --git a/runtime/src/held_work_report.h b/runtime/src/held_work_report.h new file mode 100644 index 000000000..20562e35e --- /dev/null +++ b/runtime/src/held_work_report.h @@ -0,0 +1,53 @@ +#pragma once +// Stall reports across layers: who holds work, asked by whoever sees nothing move. +// +// QueueHolds (queue_holds.h) registers each instance here; the console list-value pump (shims/d3d12_xs_list_values.h) +// calls report_held_work() when its counters have stood still while writes are still waiting to land. The two live +// in different layers of one process and know nothing else of each other. Diagnostics only: nothing here changes +// what runs. + +#include +#include +#include +#include + +namespace leonida { + +using HeldWorkReport = void (*)(const void* owner, std::FILE* out); + +struct HeldWorkRegistry { + std::mutex mutex; + std::vector> entries; +}; + +inline HeldWorkRegistry& held_work_registry() { + static HeldWorkRegistry* registry = new HeldWorkRegistry; // immortal: owners may unregister during teardown + return *registry; +} + +inline void register_held_work(const void* owner, HeldWorkReport report) { + HeldWorkRegistry& registry = held_work_registry(); + std::lock_guard lock(registry.mutex); + registry.entries.emplace_back(owner, report); +} + +// Returns once no report of `owner` is running: an owner unregisters before it is destroyed. +inline void unregister_held_work(const void* owner) { + HeldWorkRegistry& registry = held_work_registry(); + std::lock_guard lock(registry.mutex); + for (auto it = registry.entries.begin(); it != registry.entries.end(); ++it) + if (it->first == owner) { + registry.entries.erase(it); + return; + } +} + +// Asks every registered owner to describe what it holds. The registry stays locked meanwhile, so an owner cannot +// go away during its own report; a report must not register or unregister anything. +inline void report_held_work(std::FILE* out) { + HeldWorkRegistry& registry = held_work_registry(); + std::lock_guard lock(registry.mutex); + for (const auto& [owner, report] : registry.entries) report(owner, out); +} + +} // namespace leonida diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h index 40cc33117..0ea91a31e 100644 --- a/runtime/src/queue_holds.h +++ b/runtime/src/queue_holds.h @@ -1,13 +1,18 @@ #pragma once #include +#include #include +#include #include #include #include +#include #include #include +#include "held_work_report.h" + namespace leonida { // Cross-queue Wait-before-Signal (docs section 4.4, "Wait before Signal across queues"). @@ -44,11 +49,25 @@ class QueueHolds { virtual void discard_waiting_on(Semaphore semaphore) = 0; // Sequence number (next_seq()) of the oldest held operation, 0 when nothing is held. virtual std::uint64_t oldest_held_seq() = 0; + // For a stall report (describe()): one or more lines on what the queue holds and what its oldest held + // operation waits for. Nothing when it holds nothing. Diagnostics only; the default says nothing. + virtual void describe_held(std::FILE* out) { (void)out; } protected: ~Holder() = default; }; + // Every QueueHolds can be asked from anywhere what it holds (report_held_work, held_work_report.h): a stall + // watchdog that sees nothing move names the fence the held work waits for. + QueueHolds() { + register_held_work(this, [](const void* self, std::FILE* out) { + const_cast(static_cast(self))->describe(out); + }); + } + ~QueueHolds() { unregister_held_work(this); } + QueueHolds(const QueueHolds&) = delete; + QueueHolds& operator=(const QueueHolds&) = delete; + void add_fence(Semaphore semaphore, std::uint64_t initial) { std::lock_guard lock(mutex_); fences_[semaphore] = initial; @@ -107,6 +126,43 @@ class QueueHolds { return it != fences_.end() && it->second < value; } + // The highest value a Signal was submitted for (or the CPU set), for reports. False for a semaphore it was never + // told about. + bool submitted(Semaphore semaphore, std::uint64_t& value) const { + std::lock_guard lock(mutex_); + const auto it = fences_.find(semaphore); + if (it == fences_.end()) return false; + value = it->second; + return true; + } + + // More for the stall report, said before the queues (the owner's CPU fence waits, say); null removes it. Taken + // under the report registry's lock, so removing it waits for a report that is running. + void set_describe_extra(std::function extra) { + std::lock_guard lock(held_work_registry().mutex); + describe_extra_ = std::move(extra); + } + + // A stall report: what every queue holds (Holder::describe_held). Waits up to a second for a running release, + // since a holder may be detached and destroyed meanwhile; a release that does not end in that time is itself + // the answer, and is said instead. + void describe(std::FILE* out) { + if (describe_extra_) describe_extra_(out); + if (!any_held()) return; + std::unique_lock pump(pump_mutex_, std::defer_lock); + const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(1); + while (!pump.try_lock()) { + if (std::chrono::steady_clock::now() >= until) { + std::fprintf(out, "[rt] d3d12: stall report: %lld operation(s) held, and a release of held work has " + "been running for over a second (the thread that runs it is busy or blocked)\n", + static_cast(held_.load(std::memory_order_acquire))); + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + for (Holder* holder : snapshot()) holder->describe_held(out); + } + void attach(Holder* holder) { std::lock_guard lock(mutex_); holders_.push_back(holder); @@ -237,6 +293,7 @@ class QueueHolds { std::atomic barrier_count_{0}; std::atomic seq_{0}; std::atomic dirty_{false}; + std::function describe_extra_; // set_describe_extra; read under the registry's lock }; } // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index bf970aa28..16a4c4591 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -764,6 +764,21 @@ class FenceWaitDispatcher { void set_device_fault(DeviceFaultDiagnostics* diagnostics) { diagnostics_ = diagnostics; } + // For a stall report: the waits not yet satisfied, as (fence, value, a callback rather than an event). + struct PendingWait { + VkSemaphore semaphore; + std::uint64_t value; + bool callback; + }; + std::vector pending_waits() { + std::lock_guard lock(mutex_); + std::vector out; + out.reserve(pending_.size()); + for (const Entry& entry : pending_) + out.push_back({entry.semaphore, entry.value, static_cast(entry.callback)}); + return out; + } + void set_signal_event_fn(SignalEventFn fn) { std::lock_guard lock(mutex_); signal_event_ = fn; @@ -1306,10 +1321,12 @@ class VulkanContext { replay_.separate_depth_stencil_layouts = separate_depth_stencil_layouts; if (loaded_) { fence_dispatcher_ = std::make_unique(device_, vk, device_lost_); + holds_.set_describe_extra([this](std::FILE* out) { describe_cpu_waits(out); }); } } ~VulkanContext() { + holds_.set_describe_extra(nullptr); // waits for a stall report that is running progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away gpu_labels_.stop(device_); fence_dispatcher_.reset(); @@ -2093,6 +2110,48 @@ class VulkanContext { void enqueue_fence_callback(VkSemaphore sem, std::uint64_t value, std::function cb) { if (fence_dispatcher_) fence_dispatcher_->enqueue_callback(sem, value, std::move(cb)); } + // For a stall report (QueueHolds::describe): the CPU waits on fences not yet satisfied (SetEventOnCompletion and + // the layer's own callbacks), one line per fence: the lowest value waited for, the fence's counter now and the + // highest Signal submitted for it. A counter below the value with a Signal submitted is the GPU's to finish; with + // none submitted, nothing will finish it until someone submits that Signal. + void describe_cpu_waits(std::FILE* out) { + if (!fence_dispatcher_) return; + auto waits = fence_dispatcher_->pending_waits(); + if (waits.empty()) return; + std::sort(waits.begin(), waits.end(), [](const auto& a, const auto& b) { + return a.semaphore != b.semaphore ? reinterpret_cast(a.semaphore) < + reinterpret_cast(b.semaphore) + : a.value < b.value; + }); + std::fprintf(out, "[rt] d3d12: stall report: %zu CPU wait(s) on fences are not satisfied:\n", waits.size()); + unsigned lines = 0; + for (std::size_t i = 0; i < waits.size();) { + std::size_t j = i; + unsigned events = 0, callbacks = 0; + for (; j < waits.size() && waits[j].semaphore == waits[i].semaphore; ++j) + (waits[j].callback ? callbacks : events) += 1; + if (lines++ < 16) { + std::uint64_t counter = 0, submitted = 0; + const bool counted = vk.vkGetSemaphoreCounterValue(device_, waits[i].semaphore, &counter) == VK_SUCCESS; + const bool known = holds_.submitted(waits[i].semaphore, submitted); + char counter_text[32] = "unreadable", submitted_text[32] = "not tracked"; + if (counted) + std::snprintf(counter_text, sizeof(counter_text), "%llu", static_cast(counter)); + if (known) + std::snprintf(submitted_text, sizeof(submitted_text), "%llu", + static_cast(submitted)); + std::fprintf(out, + "[rt] d3d12: fence %p: %u event(s) and %u callback(s) wait for >= %llu; counter %s, " + "highest Signal submitted %s%s\n", + reinterpret_cast(waits[i].semaphore), events, callbacks, + static_cast(waits[i].value), counter_text, submitted_text, + known && submitted < waits[i].value ? " (no Signal of that value submitted yet)" : ""); + } + i = j; + } + if (lines > 16) std::fprintf(out, "[rt] d3d12: (%u fences in all; the first 16 are shown)\n", lines); + } + void cancel_fence_waits(VkSemaphore sem) { if (fence_dispatcher_) fence_dispatcher_->cancel(sem); } @@ -3882,7 +3941,7 @@ class VulkanQueue : private QueueHolds::Holder { // signatures of the lists (the application may release them right after the call). std::vector> pins; std::vector> wait_pins; // the fences of `waits` - std::chrono::steady_clock::time_point held_at{}; // LEONIDA_GPU_LATENCY: when it was held + std::chrono::steady_clock::time_point held_at{}; // when it was held (LEONIDA_GPU_LATENCY, stall report) }; bool waits_pending(const std::vector& semaphores, const std::vector& values) const { @@ -3938,7 +3997,7 @@ class VulkanQueue : private QueueHolds::Holder { wait_values_.clear(); wait_pins_.clear(); } - if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now(); + op.held_at = std::chrono::steady_clock::now(); // LEONIDA_GPU_LATENCY and the stall report held_.push_back(std::move(op)); held_front_seq_.store(held_.front().seq, std::memory_order_release); context_.holds().held_changed(1); @@ -4051,6 +4110,53 @@ class VulkanQueue : private QueueHolds::Holder { } } + // Holder: for a stall report (QueueHolds::describe), what this queue holds and what its oldest held operation + // waits for: each fence, the value it waits for and the highest Signal submitted for it so far. The state lock + // is tried for a while only: a thread stuck inside this queue is itself what the report should show. + void describe_held(std::FILE* out) override { + std::unique_lock state(state_mutex_, std::defer_lock); + const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (!state.try_lock()) { + if (std::chrono::steady_clock::now() >= until) { + std::fprintf(out, "[rt] d3d12: stall report: %s queue %p: its state lock has been held for over half " + "a second (a submission on it is busy or blocked)\n", + queue_kind_name(), static_cast(this)); + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + if (held_.empty()) return; + const Deferred& op = held_.front(); + const double held_s = + std::chrono::duration(std::chrono::steady_clock::now() - op.held_at).count(); + const char* what = op.kind == Deferred::Kind::batch ? "ExecuteCommandLists" + : op.kind == Deferred::Kind::signal ? "Signal" : "debug marker"; + std::fprintf(out, "[rt] d3d12: stall report: %s queue %p holds %zu operation(s); the oldest, a %s held %.1f s " + "ago, %s\n", + queue_kind_name(), static_cast(this), held_.size(), what, held_s, + op.waits.empty() ? "waits for nothing itself (it is behind work held before it)" + : "waits for:"); + for (std::size_t i = 0; i < op.waits.size(); ++i) { + std::uint64_t submitted = 0; + const bool known = context_.holds().submitted(op.waits[i], submitted); + if (!known) + std::fprintf(out, "[rt] d3d12: fence %p >= %llu (not a tracked fence: counted as satisfied)\n", + reinterpret_cast(op.waits[i]), + static_cast(op.wait_values[i])); + else + std::fprintf(out, "[rt] d3d12: fence %p >= %llu, highest Signal submitted %llu%s\n", + reinterpret_cast(op.waits[i]), + static_cast(op.wait_values[i]), + static_cast(submitted), + submitted >= op.wait_values[i] ? " (satisfied: the release has not run yet)" + : " (no Signal of that value yet)"); + } + } + + const char* queue_kind_name() const { + return kind_ == QueueKind::direct ? "direct" : kind_ == QueueKind::compute ? "compute" : "copy"; + } + // Holder: the sequence number of the oldest held operation. std::uint64_t oldest_held_seq() override { if (!async_on()) { diff --git a/runtime/test/queue_holds_report_test.cpp b/runtime/test/queue_holds_report_test.cpp new file mode 100644 index 000000000..47f4ed2c2 --- /dev/null +++ b/runtime/test/queue_holds_report_test.cpp @@ -0,0 +1,122 @@ +// The stall report of QueueHolds (src/queue_holds.h, src/held_work_report.h): every instance answers +// report_held_work() with what its queues hold and the owner's extra lines, and stops answering once it is gone. +// Portable: no Vulkan, no Windows headers, no GPU, no game data. +#define _CRT_SECURE_NO_WARNINGS // std::tmpfile for the report text (MSVC) +#include "../src/queue_holds.h" + +#include +#include +#include +#include + +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ + } while (0) + +namespace { + +using Holds = leonida::QueueHolds; + +// One held operation that waits for (fence, value); it describes itself the way a real queue does. +struct TestHolder final : Holds::Holder { + explicit TestHolder(Holds& holds) : holds(holds) {} + Holds& holds; + std::uint64_t fence = 0, value = 0; + bool held = false; + + void hold(std::uint64_t f, std::uint64_t v) { + fence = f; + value = v; + held = true; + holds.held_changed(1); + } + bool release_ready() override { + if (!held || holds.pending(fence, value)) return false; + held = false; + holds.held_changed(-1); + return true; + } + void discard_waiting_on(std::uint64_t) override {} + std::uint64_t oldest_held_seq() override { return held ? 1 : 0; } + void describe_held(std::FILE* out) override { + if (!held) return; + std::uint64_t submitted = 0; + const bool known = holds.submitted(fence, submitted); + std::fprintf(out, "held: fence %llu >= %llu, submitted %s%llu\n", static_cast(fence), + static_cast(value), known ? "" : "untracked ", + static_cast(submitted)); + } +}; + +// What report_held_work() says now. +std::string report() { + std::FILE* out = std::tmpfile(); + if (!out) return ""; + leonida::report_held_work(out); + std::rewind(out); + std::string text; + char chunk[256]; + for (std::size_t got; (got = std::fread(chunk, 1, sizeof(chunk), out)) > 0;) text.append(chunk, got); + std::fclose(out); + return text; +} + +bool has(const std::string& text, const char* part) { return text.find(part) != std::string::npos; } + +} // namespace + +int main() { + EXPECT(report().empty()); // nothing registered, nothing said + { + auto holds = std::make_unique(); + TestHolder holder(*holds); + holds->attach(&holder); + holds->add_fence(7, 0); + EXPECT(report().empty()); // registered, but nothing held and no extra lines + + // A held operation names its fence, the value it waits for and the highest Signal submitted so far. + holds->signaled(7, 2); + holder.hold(7, 5); + std::string text = report(); + EXPECT(has(text, "held: fence 7 >= 5, submitted 2")); + + // The owner's extra lines come first, and removing them is seen at once. + holds->set_describe_extra([](std::FILE* out) { std::fprintf(out, "extra: cpu waits\n"); }); + text = report(); + EXPECT(has(text, "extra: cpu waits") && text.find("extra") < text.find("held:")); + holds->set_describe_extra(nullptr); + EXPECT(!has(report(), "extra")); + + // An unknown fence reads as untracked; once the Signal is submitted and released, nothing is held. + std::uint64_t value = 0; + EXPECT(!holds->submitted(99, value)); + holds->signaled(7, 5); + holds->pump_ready(); + EXPECT(!holder.held && report().empty()); + + // Two instances report independently. + Holds other; + TestHolder other_holder(other); + other.attach(&other_holder); + other.add_fence(3, 0); + other_holder.hold(3, 1); + holder.hold(7, 9); + text = report(); + EXPECT(has(text, "held: fence 3 >= 1, submitted 0") && has(text, "held: fence 7 >= 9, submitted 5")); + other.signaled(3, 1); + other.pump_ready(); + other.detach(&other_holder); + holds->signaled(7, 9); + holds->pump_ready(); + holds->detach(&holder); + } + // Destroyed instances unregister: the report is empty again. + EXPECT(report().empty()); + std::printf("queue_holds_report_test: a stall report names each held operation's fence, value and highest " + "Signal submitted, with the owner's extra lines, per instance, until the instance is gone\n"); + return 0; +} diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index e80825623..3b816b28f 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -4072,7 +4072,8 @@ int check_list_values() { EXPECT(xs::list_values_idle(2000)); EXPECT(cell(0) == 0x1374 && cell(1) == 0xabcd && cell(2) != 0); xs::ListValueStats stats = xs::list_value_stats(); - EXPECT(stats.writes_recorded == 3 && stats.writes_landed == 3 && stats.writes_failed == 0); + EXPECT(stats.writes_recorded == 3 && stats.writes_submitted == 3 && stats.writes_landed == 3 && + stats.writes_failed == 0); // 2. A wait holds its part until another queue's write lands: the waiter's queue waits on its gate before the // part, and the pump signals the gate only after the writer's fence is reached and the value is in memory. @@ -4239,6 +4240,40 @@ int check_list_values() { InterlockedExchange64(reinterpret_cast(&g_cells[7]), 3); EXPECT(xs::list_values_idle(2000) && fence_completed(a_gate) == 3); + // 9. The stall snapshot names what is still waiting: a write group whose queue has not reached its `written` + // value (with how far the fence got), and a closed gate with its address, comparison, reference and memory. + EXPECT(hr_of(raw(lw, 139, word(allocator), 0)) == S_OK); + raw(lw, 14, 1, 1, 1); + raw(lw, 72, word(&g_cells[0]), 0x99, 0, 0); + EXPECT(hr_of(raw(lw, 9)) == S_OK); + EXPECT(submit(qa, lw) == 0); // a_written 6, not reached (5 is) + EXPECT(hr_of(raw(lv, 139, word(allocator), 0)) == S_OK); + raw(lv, 74, word(&g_cells[1]), 7, 0x100000, 1); // wait64(>=): memory holds 0xabcd, nothing in flight writes it + raw(lv, 14, 1, 1, 1); + EXPECT(hr_of(raw(lv, 9)) == S_OK); + EXPECT(submit(qb, lv) == 0); + EXPECT(!xs::list_values_idle(30)); + { + std::FILE* out = std::tmpfile(); + EXPECT(out); + xs::list_values_snapshot(out); + std::rewind(out); + std::string text; + char chunk[512]; + for (std::size_t got; (got = std::fread(chunk, 1, sizeof(chunk), out)) > 0;) text.append(chunk, got); + std::fclose(out); + char address[64]; + std::snprintf(address, sizeof(address), "0x%llx", static_cast(word(&g_cells[1]))); + EXPECT(text.find("1 write group(s) and 1 gate(s) are waiting") != std::string::npos); + EXPECT(text.find("land at its written fence 6, completed 5 (the queue has not run that far)") != + std::string::npos); + EXPECT(text.find(std::string("wait64 for ") + address + ", comparison 7 against 0x100000; memory 0xabcd") != + std::string::npos); + } + fence_signal(a_written, 6); + InterlockedExchange64(reinterpret_cast(&g_cells[1]), 0x100000); + EXPECT(xs::list_values_idle(2000) && cell(0) == 0x99); + // Every real list, spare and fence goes with its proxy. EXPECT(xs::list_values_idle(2000)); EXPECT(release(lw) == 0 && lw_real->refs == 0 && spare->refs == 0);