From efcb6851ce89f690b599dcbdf6ac3faa384b41d9 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 20:30:28 -0800 Subject: [PATCH] The encoder trail: name the encoder a stalled GPU stopped in, and the last one that completed A GPU hang (a CTX SWITCH TIMEOUT on an RTX 3090) left the runtime with no way to say which encoder never completed: encoders share batches and grouped submissions, and neither METAL2VULKAN_LOG_PASSES nor METAL2VULKAN_QUEUE_TIMES logs anything at a stall. METAL2VULKAN_ENCODER_TRAIL (env_vars.rs), or DeviceOptions::encoder_trail for one device, is a default-off diagnostic (encoder_trail.rs): - Each encoder, and each part of one a host step splits off, ends its batch (Batches::alone), and no batch waits in a group, so each goes in a vkQueueSubmit of its own that signals its queue's timeline. When work goes to the driver changes; what it computes does not. - Each encoder notes what it was: its kind, its command buffer's object ID, its place, a render pass's area, samples, attachments' formats and sizes, instances and rate map, its indirect command executions, and the label hash of each state it bound (the first 8 bytes of a SHA-256 of the state's label and its functions' names; no name, no shader text). A host step adds the states its indirect commands named, as the GPU and the CPU left the records. - Once no work of the device advanced for 2 s with some pending, completion.rs's stall path logs one Info line (id name metal2vulkan-encoder-trail) for each VkQueue whose oldest batch is pending: that batch's encoders and the last batch the queue completed, with how long before; once a stall. - A submission a host step makes and waits for itself (a rasterization-rate map's fan-out probe, a predicated loop's check run again) signals no timeline; once it ran 2 s, one line names it, the encoder whose step made it and the states its commands named. Off, a device reads the switch once and notes nothing. Verified on msi (lavapipe, --cfg m2v_cpu_icd), at the branch tip this commit's tree equals: - tests::stall::the_encoder_trail_names_the_stuck_encoder_and_the_last_one_completed: a cb stuck on an event wait before two blit fills; the line names the stuck cb's encoder 0 (not its encoder 1) and the earlier completed cb's encoder 0: "VkQueue 0's oldest pending batch: Blit encoder 0 of command buffer 3, states []; the last batch it completed: Blit encoder 0 of command buffer 2, states [] (2.106823047s before)". - tests::rate_mapped_fan_out::the_encoder_trail_fans_out_the_same_pixels: with the trail on, probes/flagged/fanned [1, 1, 6] as without, no texel differs from the encoder's own draws. - The host-step families (rate_mapped_fan_out, rate_mapped_pieces, indirect_command_buffer_device, host_step_neutrals, ycbcr_in_place_loop) with METAL2VULKAN_ENCODER_TRAIL=1: 11 passed. - encoder_trail's unit test (one state's hash pinned: a reader of the pipeline creation log computes it again); the runtime suite 1504 passed; api_ tests 16 passed; clippy all features and the runtime under m2v_gpu and m2v_cpu_icd; rustdoc of the runtime and metal2vulkan. The runtime-sources pin moves (not re-pinned here). --- .../src/command_buffer/batches.rs | 9 + .../src/command_buffer/completion.rs | 61 +++- .../src/command_buffer/group.rs | 7 +- .../src/command_buffer/mod.rs | 47 ++- .../src/command_buffer/rerun.rs | 35 +- .../src/command_buffer/stall.rs | 14 + .../src/command_buffer/storage_form.rs | 2 + .../src/command_buffer/submit.rs | 25 +- crates/metal2vulkan-runtime/src/compute.rs | 6 + .../metal2vulkan-runtime/src/device/adopt.rs | 2 + .../metal2vulkan-runtime/src/device/create.rs | 14 + crates/metal2vulkan-runtime/src/device/mod.rs | 9 + crates/metal2vulkan-runtime/src/encoder.rs | 27 ++ .../metal2vulkan-runtime/src/encoder_trail.rs | 342 ++++++++++++++++++ .../src/indirect_execute.rs | 27 ++ crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/render.rs | 11 + .../src/render/executions.rs | 19 +- .../src/sparse/encoder.rs | 6 + .../src/tests/rate_mapped_fan_out.rs | 23 ++ .../metal2vulkan-runtime/src/tests/stall.rs | 104 ++++++ .../src/candidate/engine/artifact/tests.rs | 2 +- crates/metal2vulkan/src/env_vars.rs | 26 ++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 15 + 25 files changed, 821 insertions(+), 14 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/encoder_trail.rs diff --git a/crates/metal2vulkan-runtime/src/command_buffer/batches.rs b/crates/metal2vulkan-runtime/src/command_buffer/batches.rs index 3c0cec41f..bf172e861 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/batches.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/batches.rs @@ -89,6 +89,15 @@ impl Batches { self.split(); } + /// The next encoder goes in a batch of its own, where the current one holds an encoder + /// already: the encoder trail's (`encoder_trail.rs`), whose batches hold one encoder each. + /// The current batch's waits stay with it, and so does the encoder where it holds none. + pub(crate) fn alone(&mut self) { + if self.encoders > 0 { + self.split(); + } + } + /// The next encoder is a resource state encoder: its updates bind before its batch's work, so /// it starts a batch unless the current one holds only such encoders and no signal. pub(crate) fn sparse(&mut self) { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index 6e4f6bec3..0f4cbca9b 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -192,7 +192,7 @@ use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex}; use std::thread::JoinHandle; -use std::time::Duration; +use std::time::{Duration, Instant}; /// How long one wait on the timelines lasts. const WAIT_SLICE: Duration = Duration::from_millis(100); @@ -286,6 +286,9 @@ struct Pending { /// The `VkQueue` whose front batch went past the watchdog's bound (`stall.rs`): the loss's /// hang is its command buffer, exactly ([`Answers::recovered`]). timed_out: Option, + /// Per `VkQueue`: what the last batch a turn took held, as the encoder trail names it, and + /// when it was taken, where the device's trail is on (`encoder_trail.rs`). + trails: Vec, Instant)>>, } /// A submitted batch its queue's waiter waits for. @@ -312,6 +315,9 @@ pub(crate) struct Submitted { pub(crate) after: Vec, /// A take left it for one of those ([`reached`]): counted once. pub(crate) held: bool, + /// What its encoders were, as the encoder trail names them, where the device's trail is on + /// (`encoder_trail.rs`). + pub(crate) trail: Option>, } /// A batch of another `VkQueue` that a batch waited for and finishes after @@ -351,6 +357,7 @@ impl Completion { draining: 0, stall: super::stall::Clock::new(queues), timed_out: None, + trails: vec![None; queues], }), wakes: (0..queues).map(|_| Condvar::new()).collect(), drained: Condvar::new(), @@ -386,6 +393,14 @@ impl Completion { } } + /// The last batch `VkQueue` `queue` completed of those the encoder trail named, and how long + /// before (`encoder_trail.rs`). + pub(crate) fn trail_last(&self, queue: usize) -> Option<(Arc, Duration)> { + let pending = lock(&self.watch.pending); + let (trail, at) = pending.trails.get(queue)?.as_ref()?; + Some((Arc::clone(trail), at.elapsed())) + } + /// Wait for `batch`, just submitted to `VkQueue` `queue` (or a failed command buffer's end, /// at the queue's last submitted value). pub(crate) fn watch(&self, queue: usize, batch: Submitted) { @@ -613,6 +628,12 @@ fn turns(watch: &Watch, lists: &mut FenceLists) -> bool { pending.turning = false; return true; } + // The last batch of each queue taken, as the encoder trail names it. + for (queue, batch) in &finished { + if let Some(trail) = &batch.trail { + pending.trails[*queue] = Some((Arc::clone(trail), Instant::now())); + } + } // The waiters of the queues whose batches it took, where they sleep and their // queue still holds a batch to arm for, or they stop: one whose queue it emptied // has nothing to do, and the next batch watched wakes it. @@ -1260,6 +1281,9 @@ fn stalled( let Ok(value) = polled else { return polled; }; + if device.shared().encoder_trail { + trail(watch, device, queue, front, value); + } let counts = &device.shared().counts; let stalled = { let mut pending = lock(&watch.pending); @@ -1303,6 +1327,41 @@ fn stalled( } } +/// The encoder trail's lines (`encoder_trail.rs`), where `queue`'s waiter's wait for `front` read +/// its timeline at `value`, short of it, and no queue's work advanced for +/// [`AFTER`](crate::encoder_trail::AFTER) since: one for each `VkQueue` whose oldest batch is +/// pending, once a stall. Formatted under the lock, said after it. +fn trail(watch: &Watch, device: &Device, queue: usize, front: Front, value: u64) { + let lines = { + let mut pending = lock(&watch.pending); + if value > pending.reached[queue] || value >= front.value { + return; + } + let Some(stalled) = pending.stall.trail_due(crate::encoder_trail::AFTER) else { + return; + }; + let Pending { + queues, + reached, + trails, + .. + } = &*pending; + let mut lines = Vec::new(); + for (queue, batches) in queues.iter().enumerate() { + let Some(oldest) = batches.front().filter(|batch| batch.value > reached[queue]) else { + continue; + }; + let last = (trails[queue].as_ref()).map(|(trail, at)| (&**trail, at.elapsed())); + let front = oldest.trail.as_deref(); + lines.push(crate::encoder_trail::line(queue, stalled, front, last)); + } + lines + }; + for line in lines { + device.inform(crate::encoder_trail::ID_NAME, line); + } +} + /// Whether a turn has work that `queue`'s waiter sees: a waiter's failure, or its queue's first /// pending batch due. fn due(pending: &Pending, queue: usize) -> bool { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs index c38bf4ae5..10438f088 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs @@ -126,12 +126,15 @@ const BATCH_INFOS: usize = 2; const MOST_INFOS: usize = GROUP_BATCHES * BATCH_INFOS + 1 + BATCH_INFOS; /// Whether `device`'s batches on `VkQueue` `queue` may wait in a group: its policy groups them, -/// its check found a submission that signals nothing merged into the next (the module docs), and -/// the queue's failures are not relayed (each relayed batch takes a fence, `device/relay.rs`). +/// its check found a submission that signals nothing merged into the next (the module docs), +/// the queue's failures are not relayed (each relayed batch takes a fence, `device/relay.rs`), +/// and its encoder trail is off (`encoder_trail.rs`: each batch goes alone). pub(crate) fn groups(device: &Device, queue: usize) -> bool { device.compile_device().policy().completion == CompletionPolicy::Grouped && device.submissions_merge_now() && device.shared().flights(queue).is_none() + // The encoder trail submits each batch alone (`encoder_trail.rs`). + && !device.shared().encoder_trail } impl CommandBufferShared { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 6a240b288..755adf74d 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -266,6 +266,10 @@ pub(super) struct CommandBufferShared { /// The `MTLCommandBufferError` code the driver relayed for one of its batches, with Metal's /// description, empty until one (`device/relay.rs`). relayed: Arc, + /// What its host step under way noted, where the device's encoder trail is on + /// (`encoder_trail.rs`, **Host steps**): set and taken by `record_host_step` around each + /// segment's step, and read by a submission the step waits for (`rerun.rs`). + step_trail: Mutex>, /// The numbers its host steps give the variant instances they make, drawn at its commit in /// the program's call (`pipeline/kept.rs`). step_numbers: OnceLock, @@ -1884,6 +1888,10 @@ impl State { /// that batch ended before this encoder ([`CommandBufferShared::close_tail`]). pub(super) fn end_encoder(&mut self, command_buffer: &CommandBuffer, recorded: Recorded) { self.recorded.push(recorded); + // Each encoder in a batch of its own, where the encoder trail is on (`encoder_trail.rs`). + if command_buffer.device().shared().encoder_trail { + self.batches.alone(); + } self.batches.encoder(); self.carry_batches = self.batches.all().len(); self.encoder_open = false; @@ -2446,6 +2454,7 @@ impl CommandBuffer { changed: Condvar::new(), gate: Arc::default(), relayed: Arc::default(), + step_trail: Mutex::new(None), step_numbers: OnceLock::new(), making_deadline: OnceLock::new(), unmade: Mutex::new(Vec::new()), @@ -2534,23 +2543,36 @@ impl CommandBuffer { /// Submit `raws`, ended, in order, on its `VkQueue`, and wait for them to complete: a host /// step's own submission, its probe of a rate-mapped pass's draws (`rate_mapped_pass.rs`, - /// **Fan-out**), as a predicated loop's run again's (`rerun.rs`). Whether they completed: - /// `false` where the driver relayed a failure for them, which fails the command buffer at its - /// completion, or the process is exiting. + /// **Fan-out**), as a predicated loop's run again's (`rerun.rs`), `what` naming it for the + /// encoder trail (`encoder_trail.rs`). Whether they completed: `false` where the driver + /// relayed a failure for them, which fails the command buffer at its completion, or the + /// process is exiting. /// /// # Safety /// /// Each of `raws` is a command buffer of its pool, ended, in no pending submission, and /// recorded for this submission alone; what it uses lives until it completes. - pub(crate) unsafe fn submit_waited(&self, raws: &[vk::CommandBuffer]) -> Result { + pub(crate) unsafe fn submit_waited( + &self, + raws: &[vk::CommandBuffer], + what: &str, + ) -> Result { // SAFETY: the caller's. - match unsafe { rerun::submit_waited(&self.0, raws) } { + match unsafe { rerun::submit_waited(&self.0, raws, what) } { rerun::Waited::Completed => Ok(true), rerun::Waited::Relayed | rerun::Waited::Exiting => Ok(false), rerun::Waited::Failed(error) => Err(self.device().failed(error)), } } + /// Note, for the encoder trail, the states of `notes` that its host step under way read its + /// commands to name (`encoder_trail.rs`, **Host steps**); nothing outside a step. + pub(crate) fn trail_step(&self, notes: crate::encoder_trail::Notes) { + if let Some(step) = lock(&self.0.step_trail).as_mut() { + step.noted(notes); + } + } + /// Its queue's place on the generation it was made on, which its commands' pools and kept /// images are of (`queue.rs`). pub(crate) fn queue_place(&self) -> &QueueGen { @@ -4929,8 +4951,17 @@ impl CommandBufferShared { let segment = &state.recorded[encoder].segments[at]; let replaced = segment.recorded.as_ref().map(|done| done.takes.clone()); state.step_takes = replaced.unwrap_or_default(); + // What the step records, as the encoder trail names it (`encoder_trail.rs`). + if device.shared().encoder_trail { + let ended = state.recorded[encoder].trail.clone(); + *lock(&self.step_trail) = Some(crate::encoder_trail::Step::new(ended)); + } } let recorded = work.step(&buffer, &inputs); + let stepped = match device.shared().encoder_trail { + true => lock(&self.step_trail).take(), + false => None, + }; // A device test's failure of the recording (`CommandBuffer::fail_host_step`), the // recording it made dropped without the lock. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -4945,6 +4976,11 @@ impl CommandBufferShared { state.step_takes.clear(); match recorded { Ok(done) => { + // The encoder as its batch's trail names it, the states its commands named + // after its own (`encoder_trail.rs`). + if let Some(trail) = stepped.as_ref().and_then(|step| step.stepped()) { + state.recorded[encoder].trail = Some(trail); + } let segment = &mut state.recorded[encoder].segments[at]; segment.stepped = true; // Its recording is the step's now, which a rebind does not record again. @@ -5585,6 +5621,7 @@ impl CommandBufferShared { holds: Vec::new(), after: Vec::new(), held: false, + trail: None, }, ); } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs index 1c280316f..bea5716a5 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs @@ -391,7 +391,7 @@ impl LoopCheck { // for this submission alone (a run again's), ended, and is in no pending submission: the // laying's batch completed before the check's step, and each submission of a run again // before the next. - match unsafe { submit_waited(buffer, raws) } { + match unsafe { submit_waited(buffer, raws, "a predicated loop's check, run again") } { Waited::Completed => Ok(()), Waited::Relayed => Err(Stop::Relayed), Waited::Failed(error) => Err(Stop::Failed(submission_error(&buffer.device, error))), @@ -413,7 +413,8 @@ pub(super) enum Waited { /// Submit `raws` (ended, in order) on `buffer`'s `VkQueue` and wait for them to complete, in /// slices: a predicated loop's run again ([`LoopCheck`]), a host step's probe of a rate-mapped -/// pass (`rate_mapped_pass.rs`, **Fan-out**). +/// pass (`rate_mapped_pass.rs`, **Fan-out**). `what` names it for the encoder trail's line, where +/// the device's trail is on and it ran for its bound (`encoder_trail.rs`, **Host steps**). /// /// # Safety /// @@ -423,6 +424,7 @@ pub(super) enum Waited { pub(super) unsafe fn submit_waited( buffer: &CommandBufferShared, raws: &[vk::CommandBuffer], + what: &str, ) -> Waited { let device = &buffer.device; let Some(busy) = exit_guard::enter() else { @@ -453,6 +455,9 @@ pub(super) unsafe fn submit_waited( return Waited::Failed(error); } drop(busy); + // The encoder trail's line is due once, past its bound. + let began = std::time::Instant::now(); + let mut trailed = !shared.encoder_trail; loop { let Some(_busy) = exit_guard::enter() else { return Waited::Exiting; @@ -462,7 +467,13 @@ pub(super) unsafe fn submit_waited( exit_guard::called(Call::WaitForFences); match waited { Ok(()) => break, - Err(vk::Result::TIMEOUT) => continue, + Err(vk::Result::TIMEOUT) => { + if !trailed && began.elapsed() >= crate::encoder_trail::AFTER { + trailed = true; + trail_waited(buffer, queue, what, began.elapsed()); + } + continue; + } // The fence stays in the relay's log, as a failed batch's does, never released. Err(error) => return Waited::Failed(error), } @@ -493,6 +504,24 @@ pub(super) unsafe fn submit_waited( } } +/// The encoder trail's line of `what`, a submission on `VkQueue` `queue` of `buffer`'s that the host +/// waits for and that ran for `ran` (`encoder_trail.rs`, **Host steps**): the encoder whose host +/// step made it, where one did, with the states its commands named so far. +fn trail_waited(buffer: &CommandBufferShared, queue: usize, what: &str, ran: Duration) { + let device = &buffer.device; + let step = lock(&buffer.step_trail) + .as_ref() + .map(|step| step.described()); + let what = match step { + Some(step) => format!("{what} of a host step of {step}"), + None => format!("{what} of command buffer {}", buffer.id.get()), + }; + let last = device.shared().completion.trail_last(queue); + let last = last.as_ref().map(|(trail, ago)| (&**trail, *ago)); + let line = crate::encoder_trail::waited_line(queue, &what, ran, last); + device.inform(crate::encoder_trail::ID_NAME, line); +} + /// A recording of nothing: a check records no command. fn nothing() -> RecordedSegment { RecordedSegment { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/stall.rs b/crates/metal2vulkan-runtime/src/command_buffer/stall.rs index a52922f69..241004639 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/stall.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/stall.rs @@ -98,6 +98,8 @@ pub(super) struct Clock { probing: bool, /// Per `VkQueue`: since when its front batch has gone without its timeline advancing. fronts: Vec>, + /// The encoder trail named this stall's stuck encoders (`encoder_trail.rs`). + trailed: bool, } impl Clock { @@ -107,6 +109,7 @@ impl Clock { since: None, probing: false, fronts: vec![None; queues], + trailed: false, } } @@ -125,9 +128,20 @@ impl Clock { /// A queue's timeline advanced: the clock stops. How long it ran, where it ran. pub(super) fn advanced(&mut self) -> Option { + self.trailed = false; self.since.take().map(|since| since.elapsed()) } + /// A waiter's wait ran out with its queue's front pending, the device's encoder trail on + /// (`encoder_trail.rs`): the clock runs. How long it has run where it passed `after` and the + /// trail named this stall's encoders no time before, now named. + pub(super) fn trail_due(&mut self, after: Duration) -> Option { + let stalled = self.since.get_or_insert_with(Instant::now).elapsed(); + let due = !self.trailed && stalled >= after; + self.trailed |= due; + due.then_some(stalled) + } + /// A waiter's wait ran out with its queue's front pending: the clock runs. How long it has run /// where it passed `after` and no waiter probes, this one then probing. pub(super) fn ran_out(&mut self, after: Duration) -> Option { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs index 9fe8d0475..78ecd9e61 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs @@ -89,6 +89,8 @@ impl CommandBuffer { summary: recorded.summary, sparse: Vec::new(), twin_writes: Vec::new(), + trail: (device.shared().encoder_trail) + .then(|| std::sync::Arc::from("the runtime's storage form switch")), }, ); state.retained.extend(recorded.retained.into_entry()); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 66e0f97e7..965f3a0ef 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -216,7 +216,7 @@ use super::hang; use super::kept_barriers::{KeptBarriers, SlotStamps}; use super::{lock, recording_error, submission_error, CommandBufferShared, State}; use crate::deferred::Deferred; -use crate::encoder::{count_shadow_copies, RecordedSegment}; +use crate::encoder::{count_shadow_copies, Recorded, RecordedSegment}; use crate::error::CommandBufferError; use crate::error::{internal, Error}; use crate::event::EventShared; @@ -446,6 +446,11 @@ impl CommandBufferShared { let raw = shared.vk(); let queue = self.queue.vk_queue(); let mut state = lock(&self.state); + // What its encoders were, as the encoder trail names them (`encoder_trail.rs`). + let trail = match shared.encoder_trail { + true => batch_trail(&state.recorded[state.batch_range(index)]), + false => None, + }; // Whether the batch may wait in the scheduler's group for one kernel submission with the // batches after it (`group.rs`), as far as is known before anything changes; first work // it takes still sends it now. One that may not, or of another `VkQueue`, waits, @@ -1535,6 +1540,7 @@ impl CommandBufferShared { holds, after, held: false, + trail, }, handlers, forms, @@ -1614,6 +1620,7 @@ impl CommandBufferShared { holds, after: Vec::new(), held: false, + trail: None, }, handlers, forms, @@ -2131,3 +2138,19 @@ fn finishes_after( } after } + +/// What a batch's encoders (or parts of them) `recorded` were, as the encoder trail names them +/// (`encoder_trail.rs`): each noted one, in order; `None` where none was noted. +fn batch_trail(recorded: &[Recorded]) -> Option> { + let mut noted = recorded.iter().filter_map(|part| part.trail.as_ref()); + let first = noted.next()?; + let Some(second) = noted.next() else { + return Some(Arc::clone(first)); + }; + let mut text = format!("{first}; {second}"); + for more in noted { + text.push_str("; "); + text.push_str(more); + } + Some(Arc::from(text)) +} diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 93ccc8446..fcf83c7a9 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -444,6 +444,9 @@ impl ComputeCommandEncoder { this.core .check_device("set_compute_pipeline_state", state.bound_device()?)?; this.pipeline = Some(state.clone()); + if let Some(trail) = this.core.trail() { + trail.compute(state); + } (this.core.routes).state_set(state.indirect_command_writes(), || { vec![state.function_name().to_owned()] }); @@ -1478,6 +1481,9 @@ impl ComputeCommandEncoder { pipeline: Option, check: Option<(IndirectCommandCheck, IndirectCommandCheckNeeds)>, ) -> Result<(), Error> { + if let Some(trail) = self.core.trail() { + trail.execution(range.given()); + } self.sync_heaps(); // Its commands bind the heap sets as they record, later. self.core.command_buffer().state().heaps.executes_later(); diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 69dc56c29..4a81bc870 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -366,6 +366,8 @@ impl Device { assume_submissions_merge: false, // On where `METAL2VULKAN_PENDING_AUDIT` is set (`assemble`). pending_audit: false, + // On where `METAL2VULKAN_ENCODER_TRAIL` is set (`assemble`). + encoder_trail: false, announce_each: raw.announce_each, lowering_refuses: raw.lowering_refuses, view_reinterpretation, diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index 23ad6d0d0..6a48fef49 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -240,6 +240,15 @@ pub struct DeviceOptions { /// hold it to a finding. No Metal counterpart. #[doc(hidden)] pub pending_audit: bool, + /// Turn each device's encoder trail on: a diagnostic that submits each encoder in a + /// `vkQueueSubmit` of its own and, once no work of the device advanced for 2 s while some was + /// pending, names the encoder each stuck `VkQueue`'s oldest batch holds and the last one it + /// completed (id name `metal2vulkan-encoder-trail`, `encoder_trail.rs`); it changes when work + /// goes to the driver, never what it computes. Off by default; `METAL2VULKAN_ENCODER_TRAIL`, + /// set, turns it on for every device too. For the tests that hold it to its line. No Metal + /// counterpart. + #[doc(hidden)] + pub encoder_trail: bool, /// Color formats each device takes as no color attachment, as a device without the /// attachment feature of them does: their tilings' `COLOR_ATTACHMENT` and blend features and /// their attachment sample counts are left out of the description the device plans and @@ -411,6 +420,7 @@ impl std::fmt::Debug for DeviceOptions { fail_in_place_check, assume_submissions_merge, pending_audit, + encoder_trail, withheld_attachment_formats, color_attachment_limit, pipeline_records, @@ -446,6 +456,7 @@ impl std::fmt::Debug for DeviceOptions { .field("fail_in_place_check", fail_in_place_check) .field("assume_submissions_merge", assume_submissions_merge) .field("pending_audit", pending_audit) + .field("encoder_trail", encoder_trail) .field("withheld_attachment_formats", withheld_attachment_formats) .field("color_attachment_limit", color_attachment_limit) .field( @@ -2400,6 +2411,7 @@ pub(super) fn create_on( fail_in_place_check: options.fail_in_place_check, assume_submissions_merge: options.assume_submissions_merge, pending_audit: options.pending_audit, + encoder_trail: options.encoder_trail, view_reinterpretation, generated_commands, host_image_copy, @@ -2600,6 +2612,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { fail_in_place_check, assume_submissions_merge, pending_audit, + encoder_trail, withheld_attachment_formats, color_attachment_limit, pipeline_records: _, @@ -2630,6 +2643,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { && *fail_in_place_check == b.fail_in_place_check && *assume_submissions_merge == b.assume_submissions_merge && *pending_audit == b.pending_audit + && *encoder_trail == b.encoder_trail && *withheld_attachment_formats == b.withheld_attachment_formats && *color_attachment_limit == b.color_attachment_limit && *extra_queues == b.extra_queues diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 61b41748b..ceb4b014f 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -724,6 +724,10 @@ pub(super) struct DeviceShared { /// Its command buffers keep execution records (`DeviceOptions::record_executions`): where /// not, its encoders build none (`EncoderCore::executed`). pub(crate) record_executions: bool, + /// Its encoder trail is on (`DeviceOptions::encoder_trail`, or `METAL2VULKAN_ENCODER_TRAIL` + /// set; `encoder_trail.rs`): each encoder goes in a submission of its own, and a stall's line + /// names the encoder each stuck queue holds. + pub(crate) encoder_trail: bool, /// It loads no dynamic library from a file (`DeviceOptions::load_no_dynamic_library_file`, /// `dynamic_library.rs`). pub(crate) load_no_dynamic_library_file: bool, @@ -1943,6 +1947,9 @@ pub(super) struct Parts { /// Its pending audit is on (`DeviceOptions::pending_audit`; `pending_audit.rs`), as it is /// where `METAL2VULKAN_PENDING_AUDIT` is set. pub(super) pending_audit: bool, + /// Its encoder trail is on (`DeviceOptions::encoder_trail`; `encoder_trail.rs`), as it is + /// where `METAL2VULKAN_ENCODER_TRAIL` is set. + pub(super) encoder_trail: bool, /// Its views may reinterpret an image's components ([`DeviceShared`]'s field), outside /// `enabled`'s vocabulary. pub(super) view_reinterpretation: bool, @@ -2049,6 +2056,7 @@ impl Device { fail_in_place_check, assume_submissions_merge, pending_audit, + encoder_trail, view_reinterpretation, generated_commands, host_image_copy, @@ -2907,6 +2915,7 @@ impl Device { lowering_refuses, deferred: crate::render::DeferredEncoders::default(), record_executions, + encoder_trail: encoder_trail || metal2vulkan::env_vars::encoder_trail(), load_no_dynamic_library_file, views_epoch: AtomicU64::new(0), pipeline_recording: crate::warm::Recording::new(pipeline_records), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 2e525e9aa..78e0847da 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -160,6 +160,9 @@ pub(super) struct Recorded { /// their second decoded twins after its work (`texture/decoded_twin.rs`); none for any other /// encoder. pub(super) twin_writes: Vec, + /// What the encoder was, as the encoder trail names it, where the device's trail is on + /// (`encoder_trail.rs`). + pub(super) trail: Option>, } /// Commands an encoder left to record later (`deferred.rs`). @@ -393,6 +396,9 @@ pub(super) struct EncoderCore { /// nothing joined, moved or went since (`host_aliases::Quiet`): a command over those takes no /// lock. aliases_quiet: Quiet, + /// What the encoder did, for the encoder trail's line, where the device's trail is on + /// (`encoder_trail.rs`). + trail: Option>, /// The open runs of the index gather pass ([`gather`](Self::gather)), which record before /// the encoder's next command, and before its `VkCommandBuffer` ends. gathers: GatherRuns, @@ -701,6 +707,11 @@ impl EncoderCore { aliased_uses: Vec::new(), // The keys an ended encoder found, which hold here while the version stands. aliases_quiet: command_buffer.generation().aliases.quiet(), + trail: command_buffer + .device() + .shared() + .encoder_trail + .then(Box::default), gathers: GatherRuns::default(), id: CORES.fetch_add(1, Ordering::Relaxed), replaying: false, @@ -858,6 +869,7 @@ impl EncoderCore { unattached_as_called: false, aliased_uses: Vec::new(), aliases_quiet: Quiet::default(), + trail: None, gathers: GatherRuns::default(), id: CORES.fetch_add(1, Ordering::Relaxed), // A segment a rebind records again, its command buffer committed. @@ -2778,6 +2790,12 @@ impl EncoderCore { self.defer_into(Some(next), Deferred::Pending(Arc::new(dispatch))) } + /// The encoder trail's notes of what the encoder did, where the device's trail is on + /// (`encoder_trail.rs`). + pub(super) fn trail(&mut self) -> Option<&mut crate::encoder_trail::Notes> { + self.trail.as_deref_mut() + } + /// Metal fails the command buffer from this encoder on with `error`, as it commits: the /// encoder and every one after it run nothing (`State::fail_from`). pub(super) fn fail_command_buffer(&mut self, error: CommandBufferError) { @@ -2925,6 +2943,7 @@ impl EncoderCore { twin_writes, routes, aliases_quiet, + trail, .. } = self; ended.push(raw); @@ -2961,6 +2980,9 @@ impl EncoderCore { if let Some(why) = unlogged { state.encoder_unlogged(encoder, why); } + // What it was, as the encoder trail names it (`encoder_trail.rs`). + let command_buffer_id = open.command_buffer.object_id().get(); + let trail = trail.map(|notes| notes.described(kind, command_buffer_id, encoder)); state.encoder_holds(encoder, uses.held().to_vec()); match fails_command_buffer { Some(CommandBufferError::GpuHang) => { @@ -3005,6 +3027,7 @@ impl EncoderCore { summary: summary.fences_only(), sparse: Vec::new(), twin_writes: Vec::new(), + trail: (trail.as_ref()).map(|trail| Arc::from(format!("{trail}, left out"))), }, ); } @@ -3033,6 +3056,10 @@ impl EncoderCore { summary, sparse: Vec::new(), twin_writes, + trail: (trail.as_ref()).map(|trail| match count { + 1 => Arc::from(trail.as_str()), + _ => Arc::from(format!("{trail}, part {} of {count}", at + 1)), + }), }, ); } diff --git a/crates/metal2vulkan-runtime/src/encoder_trail.rs b/crates/metal2vulkan-runtime/src/encoder_trail.rs new file mode 100644 index 000000000..93bac8af3 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/encoder_trail.rs @@ -0,0 +1,342 @@ +//! The encoder trail: a default-off diagnostic, `METAL2VULKAN_ENCODER_TRAIL` +//! (`metal2vulkan::env_vars`), or `DeviceOptions::encoder_trail` for one device, that names the +//! encoder a device's GPU stopped in, and the last one that completed before it. +//! +//! - **Each encoder its own submission.** On a device with the trail on, each encoder's +//! recording, and each part of one that a host step splits off, ends its batch +//! (`command_buffer/batches.rs`, `Batches::alone`), and no batch waits in a group +//! (`command_buffer/group.rs`): each goes in a `vkQueueSubmit` of its own, which signals its +//! queue's timeline, so the value the timeline reached names the last encoder that completed. +//! That changes when work goes to the driver, never what it computes; its timing is not the +//! default's. +//! - **What an encoder was** ([`Notes`]): its kind, its command buffer's object ID and its place +//! among the command buffer's ended encoders; a render pass's area, its attachments' formats and +//! sizes, its Vulkan render pass instances and whether it is over a rasterization-rate map; its +//! executions of indirect commands; and the label hashes of the pipeline states it bound, each +//! once, in the order it first did, at most [`KEPT`]: the first 8 bytes of the SHA-256 of a +//! state's label and its functions' names ([`label_hash`]). No name and no shader text. +//! - **Host steps** ([`Step`]). A host step that records an ended encoder's segment +//! (`CommandBuffer::record_host_step`) notes the states its indirect commands name, as the GPU +//! and the CPU left the records, and its batch names them after the encoder's own. A submission +//! the step makes and waits for itself (a rasterization-rate map's fan-out probe, +//! `render/fan_out.rs`, or a predicated loop's check run again, `command_buffer/rerun.rs`) +//! signals no timeline: once it ran for [`AFTER`], one line names it ([`waited_line`]). +//! - **The line** (`command_buffer/completion.rs`'s `stalled`). Once no work of the device +//! advanced for [`AFTER`] while some was pending, one line for each `VkQueue` whose oldest batch +//! is pending, through the device's message sink at `Info` (id name [`ID_NAME`]), else on +//! stderr: what that batch's encoders were, and what the last batch the queue completed held, +//! and how long before. Once a stall: a timeline that advances ends it. +//! - **Off, it costs nothing**: the switch is read once a device is made; an encoder notes +//! nothing and no line is formatted. + +use crate::pipeline::{ComputePipelineState, RenderPipelineState}; +use crate::render_pass::PassLayout; +use crate::used_resources::EncoderKind; +use sha2::{Digest, Sha256}; +use std::fmt::Write as _; +use std::sync::Arc; +use std::time::Duration; + +/// How long no work of a device advances, with some pending, before its trail's lines; and how +/// long a submission the host waits for runs before its line. +pub(crate) const AFTER: Duration = Duration::from_secs(2); + +/// The most pipeline states a line names of one encoder. +const KEPT: usize = 16; + +/// The id name of the trail's lines. +pub(crate) const ID_NAME: &str = "metal2vulkan-encoder-trail"; + +/// What an encoder did, noted while the trail is on (the module docs). +#[derive(Default)] +pub(crate) struct Notes { + /// The label hash of each pipeline state it bound, once, in the order it first did. + states: Vec, + /// The states it bound past [`KEPT`]. + more: usize, + /// Its executions of indirect commands. + executions: u64, + /// The commands of those executions' ranges given in the call. + commands: u64, + /// The executions whose range a buffer holds. + indirect: u64, + /// A render pass's shape, noted at its end ([`pass_named`]). + pass: Option, +} + +impl Notes { + /// It bound a pipeline state labeled `label`, of `functions`. + pub(crate) fn state(&mut self, label: Option<&str>, functions: &[&str]) { + self.hashed(label_hash(label, functions)); + } + + /// It bound `state`, a render pipeline state. + pub(crate) fn render(&mut self, state: &RenderPipelineState) { + let names = state.function_names(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + self.state(state.label(), &names); + } + + /// It bound `state`, a compute pipeline state. + pub(crate) fn compute(&mut self, state: &ComputePipelineState) { + self.state(state.label(), &[state.function_name()]); + } + + /// It bound a state of label hash `hash`. + fn hashed(&mut self, hash: String) { + if self.states.contains(&hash) { + return; + } + match self.states.len() < KEPT { + true => self.states.push(hash), + false => self.more += 1, + } + } + + /// It executed indirect commands: `commands` of them, where the call gave the range. + pub(crate) fn execution(&mut self, commands: Option) { + self.executions += 1; + match commands { + Some(commands) => self.commands += commands, + None => self.indirect += 1, + } + } + + /// Its render pass, as [`pass_named`] names it. + pub(crate) fn pass(&mut self, pass: String) { + self.pass = Some(pass); + } + + /// The encoder of `kind`, at place `encoder` among the ended encoders of the command buffer + /// of object ID `command_buffer`, as a line names it. + pub(crate) fn described( + &self, + kind: EncoderKind, + command_buffer: u64, + encoder: usize, + ) -> String { + let mut text = format!("{kind:?} encoder {encoder} of command buffer {command_buffer}"); + if let Some(pass) = &self.pass { + let _ = write!(text, ", pass {pass}"); + } + if self.executions > 0 { + let _ = write!( + text, + ", {} execution(s) of indirect commands ({} commands in ranges given, {} ranges \ + a buffer holds)", + self.executions, self.commands, self.indirect + ); + } + let more = match self.more { + 0 => String::new(), + more => format!(" and {more} more"), + }; + let _ = write!(text, ", states [{}]{more}", self.states.join(" ")); + text + } +} + +/// What a host step noted as it recorded an ended encoder's segment (the module docs, **Host +/// steps**): the encoder as it ended, and the states its commands named. +pub(crate) struct Step { + encoder: Option>, + states: Notes, +} + +impl Step { + /// A step of the encoder `encoder` names, as it ended. + pub(crate) fn new(encoder: Option>) -> Step { + Step { + encoder, + states: Notes::default(), + } + } + + /// Its commands named the states of `notes`. + pub(crate) fn noted(&mut self, notes: Notes) { + for hash in notes.states { + self.states.hashed(hash); + } + self.states.more += notes.more; + } + + /// Whether its commands named any state. + fn named(&self) -> bool { + !self.states.states.is_empty() || self.states.more > 0 + } + + /// The encoder, and the states its commands named where they named any, as a line names it. + pub(crate) fn described(&self) -> String { + let encoder = self + .encoder + .as_deref() + .unwrap_or("an encoder noted nothing of"); + if !self.named() { + return encoder.to_owned(); + } + let more = match self.states.more { + 0 => String::new(), + more => format!(" and {more} more"), + }; + let states = self.states.states.join(" "); + format!("{encoder}, its host step's commands' states [{states}]{more}") + } + + /// The encoder's name after the step: [`described`](Self::described) where its commands + /// named a state, else `None` (it stays as it ended). + pub(crate) fn stepped(&self) -> Option> { + self.named().then(|| Arc::from(self.described())) + } +} + +/// A pipeline state's label hash: the first 8 bytes, in hex, of the SHA-256 of its label and +/// its functions' names, each after its length. +pub(crate) fn label_hash(label: Option<&str>, functions: &[&str]) -> String { + let mut hash = Sha256::new(); + hash.update(b"metal2vulkan encoder trail state\0"); + match label { + Some(label) => { + hash.update([1]); + hash.update((label.len() as u64).to_le_bytes()); + hash.update(label.as_bytes()); + } + None => hash.update([0]), + } + for function in functions { + hash.update((function.len() as u64).to_le_bytes()); + hash.update(function.as_bytes()); + } + let digest = hash.finalize(); + digest[..8].iter().fold(String::new(), |mut text, byte| { + let _ = write!(text, "{byte:02x}"); + text + }) +} + +/// A render pass over `layout`, recorded in `instances` Vulkan render pass instances, over a +/// rasterization-rate map where `rate_mapped`, as a line names it: its area, each color +/// attachment's format and size, and the depth/stencil attachment's. +pub(crate) fn pass_named(layout: &PassLayout, instances: usize, rate_mapped: bool) -> String { + let [width, height] = layout.extent; + let colors: Vec = (layout.colors.iter().enumerate()) + .filter_map(|(index, color)| { + let texture = &color.as_ref()?.target.texture; + Some(format!( + "{index}: {:?} {}x{}", + texture.pixel_format(), + texture.width(), + texture.height() + )) + }) + .collect(); + let depth_stencil = match layout.depth_stencil.as_ref().filter(|ds| !ds.hidden) { + Some(ds) => format!( + "{:?} {}x{}", + ds.target.texture.pixel_format(), + ds.target.texture.width(), + ds.target.texture.height() + ), + None => "none".to_owned(), + }; + let map = match rate_mapped { + true => ", over a rasterization-rate map", + false => "", + }; + format!( + "{width}x{height}, {} sample(s), colors [{}], depth/stencil {depth_stencil}, \ + {instances} Vulkan render pass instance(s){map}", + layout.samples, + colors.join(", ") + ) +} + +/// The line of `queue`'s stall of `stalled` (the module docs): `front`, its oldest pending batch's +/// encoders as noted, and `last`, the last batch it completed, with how long before. +pub(crate) fn line( + queue: usize, + stalled: Duration, + front: Option<&str>, + last: Option<(&str, Duration)>, +) -> String { + let last = match last { + Some((last, ago)) => format!("{last} ({ago:?} before)"), + None => "none since the device was made".to_owned(), + }; + format!( + "metal2vulkan: encoder trail: no work of the device advanced for {stalled:?} with some \ + pending; VkQueue {queue}'s oldest pending batch: {}; the last batch it completed: {last}", + front.unwrap_or("no encoder noted"), + ) +} + +/// The line of `what`, a submission on `queue` the host waits for itself (the module docs, **Host +/// steps**), which has run for `ran`; `last`, the last batch the queue completed, with how long +/// before. +pub(crate) fn waited_line( + queue: usize, + what: &str, + ran: Duration, + last: Option<(&str, Duration)>, +) -> String { + let last = match last { + Some((last, ago)) => format!("{last} ({ago:?} before)"), + None => "none since the device was made".to_owned(), + }; + format!( + "metal2vulkan: encoder trail: a submission the host waits for has run for {ran:?} on \ + VkQueue {queue}: {what}; the last batch it completed: {last}" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A state's hash covers its label and each function's name apart, and an encoder names each + /// state once, in the order bound, past the kept ones as a count. + #[test] + fn an_encoder_names_each_state_once_by_its_label_hash() { + let a = label_hash(Some("a"), &["v", "f"]); + // The hash a line names a state by, which a reader of a run's pipeline creation log + // computes again from the state's label and functions' names. + assert_eq!(a, "feece2ca5cb278a8"); + assert_ne!(a, label_hash(Some("a"), &["vf"])); + assert_ne!(a, label_hash(None, &["v", "f"])); + assert_eq!(a, label_hash(Some("a"), &["v", "f"])); + let mut notes = Notes::default(); + notes.state(Some("a"), &["v", "f"]); + notes.state(Some("a"), &["v", "f"]); + for i in 0..KEPT + 2 { + notes.state(None, &[&i.to_string()]); + } + notes.execution(Some(8162)); + notes.execution(None); + let text = notes.described(EncoderKind::Render, 7, 3); + assert!( + text.starts_with("Render encoder 3 of command buffer 7"), + "{text}" + ); + assert!(text.contains(&format!("states [{a} ")), "{text}"); + assert!(text.contains(" and 3 more"), "{text}"); + assert!( + text.contains("2 execution(s) of indirect commands (8162 commands in ranges given, 1"), + "{text}" + ); + assert_eq!(text.matches(&a).count(), 1, "{text}"); + // A host step's commands' states follow the encoder's, each once. + let mut step = Step::new(Some(Arc::from("Render encoder 3 of command buffer 7"))); + assert!(step.stepped().is_none()); + let mut named = Notes::default(); + named.state(Some("b"), &["v"]); + step.noted(named); + let mut again = Notes::default(); + again.state(Some("b"), &["v"]); + step.noted(again); + let b = label_hash(Some("b"), &["v"]); + let stepped = step.stepped().expect("a state named"); + assert_eq!( + &*stepped, + format!("Render encoder 3 of command buffer 7, its host step's commands' states [{b}]") + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/indirect_execute.rs b/crates/metal2vulkan-runtime/src/indirect_execute.rs index 77c6ad08c..503756d7b 100644 --- a/crates/metal2vulkan-runtime/src/indirect_execute.rs +++ b/crates/metal2vulkan-runtime/src/indirect_execute.rs @@ -203,6 +203,16 @@ pub(super) enum ExecutionRange { Indirect { buffer: Buffer, offset: u64 }, } +impl ExecutionRange { + /// The commands of a range the call gave; `None` for one a buffer holds. + pub(super) fn given(&self) -> Option { + match self { + ExecutionRange::Fixed(range) => Some(u64::from(range.end - range.start)), + ExecutionRange::Indirect { .. } => None, + } + } +} + /// The range of an execution `core` encodes from the [`RANGE_BYTES`] at `offset` of `buffer` /// (`executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:`), which its host step reads /// ([`ExecutionRange::commands`]). Read there in place where the host maps the bytes the GPU @@ -431,6 +441,23 @@ impl Execute { }; let (commands, written) = self.written_commands(piece, states, check)?; faults = ReplayFaults(faults.0 | written.0); + // The states the commands name, for the encoder trail, where it is on: each run of + // one state noted once (`encoder_trail.rs`, **Host steps**). + if command_buffer.device().shared().encoder_trail { + let mut notes = crate::encoder_trail::Notes::default(); + let mut last = None; + for own in commands + .iter() + .flatten() + .filter_map(|(_, own)| own.as_ref()) + { + if last != Some(own) { + notes.compute(own); + last = Some(own); + } + } + command_buffer.trail_step(notes); + } if reports { let executed = commands.iter().map(Option::as_ref); let read = (RecordsRead::HostStep, &residency); diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index be5774fee..c3682ce67 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -94,6 +94,7 @@ mod dynamic_library; mod dynamic_state; mod enables; mod encoder; +mod encoder_trail; mod error; mod etc; mod event; diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index cfeae45c6..ef6e443fa 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -3059,6 +3059,9 @@ impl RenderLowering { fn set_state(&mut self, state: &RenderPipelineState) -> Result<(), Error> { const CALL: &str = "set_render_pipeline_state"; self.core.check_device(CALL, state.bound_device()?)?; + if let Some(trail) = self.core.trail() { + trail.render(state); + } let drawn = drawn_as(self.layout.samples, state)?; let state = self.grouped_as(drawn.clone())?; // Routed once here: the check and each draw read it (`routing`). @@ -4654,6 +4657,14 @@ impl RenderLowering { if let Some(notes) = pass_notes { pass_log::ended(core.device(), ¬es, &layout, instances.len(), &residency); } + // The pass as the encoder trail names it, where it is on (`encoder_trail.rs`). + if let Some(trail) = core.trail() { + trail.pass(crate::encoder_trail::pass_named( + &layout, + instances.len(), + rate_mapped, + )); + } if grouped.is_none() && untouched::changes_nothing(&layout, called, &instances) { core.device().shared().counts.untouched_pass_skipped(); let targets: Vec = (layout.colors.iter().flatten()) diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 73eedbeb4..fcc77607d 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -559,6 +559,9 @@ impl RenderLowering { pipeline: Option, check: Option<(IndirectCommandCheck, IndirectCommandCheckNeeds)>, ) -> Result<(), Error> { + if let Some(trail) = self.core.trail() { + trail.execution(range.given()); + } self.sync_heaps(); // Its commands bind the heap sets as they record, later. self.core.command_buffer().state().heaps.executes_later(); @@ -2413,7 +2416,17 @@ impl RenderExecution { // records its probes alone, in one run, before the pass (`render/fan_out.rs`): it begins // no piece and cuts no draw into ranges. let probing = encoder.fan_run.as_ref().is_some_and(FanOutRun::probes); + // The states the commands name, for the encoder trail, where it is on: each run of one + // state noted once (`encoder_trail.rs`, **Host steps**). + let mut trail = (encoder.core.device().shared().encoder_trail) + .then(|| (crate::encoder_trail::Notes::default(), None)); for (place, (record, own)) in commands.into_iter().enumerate() { + if let (Some((notes, last)), Some(own)) = (&mut trail, own) { + if *last != Some(own) { + notes.render(own); + *last = Some(own); + } + } // A command's barrier: its draw records into the execution's next run, which its // pass runs in a render pass instance of its own after a barrier from everything // before, so it sees the earlier draws' writes as plain Metal's does; but where the @@ -2612,6 +2625,9 @@ impl RenderExecution { regions = note(found.piece_after(encoder)); } } + if let Some((notes, _)) = trail { + encoder.core.command_buffer().trail_step(notes); + } Ok(()) } @@ -4117,7 +4133,8 @@ impl DeferredPass { // SAFETY: the segment's command buffers, of the command buffer's pool, ended and // recorded for this submission alone; what they use the segment holds, which the pass's // joins. - let completed = unsafe { command_buffer.submit_waited(&recorded.raws) }?; + let what = "the rasterization-rate map's fan-out probe"; + let completed = unsafe { command_buffer.submit_waited(&recorded.raws, what) }?; // Its time read and counted, its submission done. drop(times); recorded.raws.clear(); diff --git a/crates/metal2vulkan-runtime/src/sparse/encoder.rs b/crates/metal2vulkan-runtime/src/sparse/encoder.rs index 997fa2977..46fd9dbc2 100644 --- a/crates/metal2vulkan-runtime/src/sparse/encoder.rs +++ b/crates/metal2vulkan-runtime/src/sparse/encoder.rs @@ -467,6 +467,12 @@ impl ResourceStateCommandEncoder { summary: Summary::of_fences(waits, fence_updates), sparse: updates, twin_writes: Vec::new(), + trail: (open.command_buffer.device().shared().encoder_trail).then(|| { + let id = open.command_buffer.object_id().get(); + std::sync::Arc::from(format!( + "ResourceState encoder {encoder} of command buffer {id}" + )) + }), }, ); drop(state); diff --git a/crates/metal2vulkan-runtime/src/tests/rate_mapped_fan_out.rs b/crates/metal2vulkan-runtime/src/tests/rate_mapped_fan_out.rs index b178b1a5d..6b6fc47d8 100644 --- a/crates/metal2vulkan-runtime/src/tests/rate_mapped_fan_out.rs +++ b/crates/metal2vulkan-runtime/src/tests/rate_mapped_fan_out.rs @@ -314,6 +314,29 @@ fn a_host_step_fans_out_the_commands_the_probe_does_not_flag() { /// Under `Exact` no probe runs and every command is drawn region by region; the pixels are the /// encoder's draws'. +/// With the encoder trail on (`encoder_trail.rs`), the host step notes the states its commands +/// name and its probe is a waited submission the trail watches; the execution is fanned out as +/// without, to the same pixels. +#[test] +fn the_encoder_trail_fans_out_the_same_pixels() { + let scratch = Scratch::new("rate-mapped-fan-out-trail"); + let mut options = options(&scratch.0); + options.policy.rate_map_regions = RateMapRegionPolicy::FanOut; + options.encoder_trail = true; + let workload = Workload::new(Device::system_default_with(&options).unwrap()); + assert!(workload.device.shared().encoder_trail); + let (drawn, _, _) = workload.frame(false); + let (fanned, before, after) = workload.frame(true); + let counts = fan_counts(&before, &after); + eprintln!("RATE-MAP-FAN-OUT-TRAIL counts {counts:?}"); + match fans_out(&workload.device) { + true => assert_eq!(counts, [1, 1, u64::from(COMMANDS - 1)]), + false => assert_eq!(counts, [0; 3]), + } + let differ = differing(&drawn, &fanned); + assert_eq!(differ, 0, "texels the fanned-out execution draws otherwise"); +} + #[test] fn exact_regions_draw_every_command_region_by_region() { let scratch = Scratch::new("rate-mapped-fan-out-exact"); diff --git a/crates/metal2vulkan-runtime/src/tests/stall.rs b/crates/metal2vulkan-runtime/src/tests/stall.rs index 9aa6258a4..1cc05cd58 100644 --- a/crates/metal2vulkan-runtime/src/tests/stall.rs +++ b/crates/metal2vulkan-runtime/src/tests/stall.rs @@ -94,6 +94,34 @@ fn device( device } +/// The device the cfg selects with its encoder trail on (`encoder_trail.rs`), its messages kept in +/// `heard`, its stall clock's bound left as it is (no probe within a test's wait). +fn trail_device(cache: &Path, heard: &Arc>) -> Device { + let heard = Arc::clone(heard); + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Integrated, + DeviceKind::Discrete, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + messages: Some(MessageSink::new(move |message| { + if message.degradation.is_none() { + heard.lock().unwrap().texts.push(message.text.clone()); + } + })), + encoder_trail: true, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + /// A committed command buffer that waits for `event` to reach 10, a signal of it reserved for the /// caller and not submitted, so it is pending on its `VkQueue`; then fills `buffer`. The /// reserved counter value. @@ -381,3 +409,79 @@ fn a_front_past_the_watchdog_fails_as_metals_timeout() { // the reservation named, which nothing before it waits for. unsafe { parked.signal_semaphore(&info) }.unwrap(); } + +/// With the encoder trail on (`encoder_trail.rs`), each encoder goes in a submission of its own, +/// and once no work advanced for 2 s, a line names the encoder its queue's oldest pending batch +/// holds and the last batch that queue completed: here the first of two blit encoders after a wait +/// for a signal reserved and not yet made, and the one blit encoder of a command buffer of the +/// queue that completed before. The stuck command buffer completes once the host signals. +#[test] +fn the_encoder_trail_names_the_stuck_encoder_and_the_last_one_completed() { + let scratch = Scratch::new(); + let heard = Arc::new(Mutex::new(Heard::default())); + let device = trail_device(&scratch.0, &heard); + let buffer = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); + // An unshared queue never moves between `VkQueue`s (`queue_share.rs`). + let queue = device.new_command_queue_unshared(4).unwrap(); + let done = queue.command_buffer().unwrap(); + let mut blit = done.blit_command_encoder().unwrap(); + blit.fill_buffer(&buffer, 0..4096, 2).unwrap(); + blit.end_encoding().unwrap(); + done.commit().unwrap(); + assert!(done.wait_until_completed_for(WAIT).is_ok()); + let event = device.new_event().unwrap(); + // SAFETY: the signal is made from the host below, once. + let reserved = unsafe { event.reserve_vk_signal(10) }.unwrap(); + let VkEventSignal::Counter { counter, .. } = reserved else { + panic!("a first reservation names a counter: {reserved:?}"); + }; + let before = device.work_counts().queue_submissions; + let stuck = queue.command_buffer().unwrap(); + stuck.encode_wait_for_event((&event).into(), 10).unwrap(); + for value in [3, 4] { + let mut blit = stuck.blit_command_encoder().unwrap(); + blit.fill_buffer(&buffer, 0..4096, value).unwrap(); + blit.end_encoding().unwrap(); + } + stuck.commit().unwrap(); + let deadline = Instant::now() + WAIT; + let line = loop { + let found = (heard.lock().unwrap().texts.iter()) + .find(|text| text.contains("encoder trail")) + .cloned(); + if let Some(line) = found { + break line; + } + assert!(Instant::now() < deadline, "no trail line in {WAIT:?}"); + std::thread::sleep(Duration::from_millis(50)); + }; + // SAFETY: the event's semaphore, signalled once from the host to the reserved counter, which + // nothing before it waits for. + let semaphore = unsafe { event.vk_semaphore() }; + let info = vk::SemaphoreSignalInfo::default() + .semaphore(semaphore) + .value(counter); + // SAFETY: as above; the device is live. + unsafe { device.shared().vk().signal_semaphore(&info) }.unwrap(); + assert!(stuck.wait_until_completed_for(WAIT).is_ok()); + assert_eq!( + (stuck.status(), stuck.error()), + (CommandBufferStatus::Completed, None) + ); + let submitted = device.work_counts().queue_submissions - before; + eprintln!( + "ENCODER-TRAIL {}: {submitted} submissions for the stuck command buffer's 2 encoders; {line}", + device.name() + ); + let stuck_id = stuck.object_id().get(); + let oldest = format!("oldest pending batch: Blit encoder 0 of command buffer {stuck_id}"); + assert!(line.contains(&oldest), "{line}"); + assert!( + !line.contains(&format!("encoder 1 of command buffer {stuck_id}")), + "the second encoder went in the first's batch: {line}" + ); + let done_id = done.object_id().get(); + let last = format!("the last batch it completed: Blit encoder 0 of command buffer {done_id}"); + assert!(line.contains(&last), "{line}"); + assert!(submitted >= 2, "{submitted} submissions for 2 encoders"); +} diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index fbd6bf89f..32278de7e 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -145,7 +145,7 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan-air/src/lib.rs", compile), ("metal2vulkan/src/cache/digest.rs", "the content digest, which defines the artifact rather than acting on it"), ("metal2vulkan/src/cache/mod.rs", "the plan's specialization and variant keys, whose values the plan digest holds, and RUNTIME_VERSION itself, which cannot be among the sources it versions"), - ("metal2vulkan/src/env_vars.rs", "the operational variables' accessors: the runtime reads only METAL2VULKAN_LOG_PIPELINES, METAL2VULKAN_DUMP_PIPELINES, METAL2VULKAN_LOG_MEMORY, METAL2VULKAN_LOG_SHADOWS, METAL2VULKAN_LOG_PASSES, METAL2VULKAN_PENDING_AUDIT and METAL2VULKAN_QUEUE_TIMES, default-off diagnostics that print (and write the pipelines' SPIR-V into the dump directory) or note command buffers' queue times, and change no run"), + ("metal2vulkan/src/env_vars.rs", "the operational variables' accessors: the runtime reads only METAL2VULKAN_LOG_PIPELINES, METAL2VULKAN_DUMP_PIPELINES, METAL2VULKAN_LOG_MEMORY, METAL2VULKAN_LOG_SHADOWS, METAL2VULKAN_LOG_PASSES, METAL2VULKAN_PENDING_AUDIT, METAL2VULKAN_QUEUE_TIMES and METAL2VULKAN_ENCODER_TRAIL, default-off diagnostics that print (and write the pipelines' SPIR-V into the dump directory), note command buffers' queue times or submit each encoder alone, and change no run's answers"), ("metal2vulkan/src/error/mod.rs", "the error vocabulary: the runtime's code decides which error a run reports, and a record keeps the error as reported"), ("metal2vulkan/src/library/mod.rs", compile), ("metal2vulkan/src/lower/access/imageblock.rs", compile), diff --git a/crates/metal2vulkan/src/env_vars.rs b/crates/metal2vulkan/src/env_vars.rs index 2fbf2ef92..f4fffa42b 100644 --- a/crates/metal2vulkan/src/env_vars.rs +++ b/crates/metal2vulkan/src/env_vars.rs @@ -136,6 +136,24 @@ pub const REGISTRY: &[EnvVar] = &[ (CommandBuffer::queue_head_time, CommandBuffer::submit_returned_time); it \ changes no work; set to anything but empty or 0", }, + EnvVar { + name: "METAL2VULKAN_ENCODER_TRAIL", + default: "unset (off)", + effect: "metal2vulkan-runtime's diagnostics: each device submits each encoder (or each \ + part of one a host step splits off) in a vkQueueSubmit of its own that signals \ + its queue's timeline, grouping no batches, and notes what the encoder was: its \ + kind, its command buffer's object ID, its place among the command buffer's \ + encoders, a render pass's area and attachments' formats and sizes, its \ + indirect command executions, and the label hashes of the pipeline states it \ + bound (a SHA-256 of each state's label and functions' names: no name and no \ + shader text), and those its indirect commands named at a host step; once no \ + work of the device advanced for 2 s while some was pending, one line through \ + the device's message sink or on stderr for each queue whose oldest batch is \ + pending names that encoder and the last one the queue completed, and a line \ + names a host step's own waited submission (a rate-map fan-out probe, a loop's \ + check) that ran for 2 s; costs when set: a submission per encoder and a line \ + formatted at each encoder's end; set to anything but empty or 0", + }, ]; /// Multi-line `--help` block listing every registry var. @@ -217,6 +235,14 @@ pub fn queue_times() -> bool { .is_some_and(|value| !value.is_empty() && value != "0") } +/// Whether each metal2vulkan-runtime device submits each encoder alone and names the encoder its +/// GPU stopped in (`REGISTRY`): set, and neither empty nor `0`. A default-off diagnostic: it +/// changes how the work is split into submissions, never what it computes, and prints. +pub fn encoder_trail() -> bool { + std::env::var_os("METAL2VULKAN_ENCODER_TRAIL") + .is_some_and(|value| !value.is_empty() && value != "0") +} + /// Optional path override for an external tool `cmd` (`llvm-as`, `spirv-val`, …), read from /// `METAL2VULKAN_` (uppercased, `-`→`_`). A dynamic family — one var per tool the binary or /// the crate's test support runs — documented in `REGISTRY` as a single `METAL2VULKAN_` diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 1d6b874cc..d1628ed19 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2115,6 +2115,7 @@ field metal2vulkan-runtime::DeviceOptions.announce_each pub announce_each: BTree field metal2vulkan-runtime::DeviceOptions.assume_submissions_merge pub assume_submissions_merge: bool field metal2vulkan-runtime::DeviceOptions.color_attachment_limit pub color_attachment_limit: Option field metal2vulkan-runtime::DeviceOptions.device_extensions pub device_extensions: Vec +field metal2vulkan-runtime::DeviceOptions.encoder_trail pub encoder_trail: bool field metal2vulkan-runtime::DeviceOptions.extra_queues pub extra_queues: Vec field metal2vulkan-runtime::DeviceOptions.fail_in_place_check pub fail_in_place_check: bool field metal2vulkan-runtime::DeviceOptions.gpu_times_from_host pub gpu_times_from_host: bool diff --git a/docs/API.md b/docs/API.md index e9b876bcf..0841a8e60 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1894,6 +1894,21 @@ signals, and a secondary through each primary that executes it. It reads those t `metal2vulkan-pending-audit`, `Info` severity): what was done, the thread, the command buffer, the timeline, its counter and the value, with the thread's backtrace for the first 8; and a line as the device is made and as it goes, with the checks and findings by kind. It changes no work. +With `METAL2VULKAN_ENCODER_TRAIL` set (or `DeviceOptions::encoder_trail`), a device submits each +encoder, and each part of one a host step splits off, in a `vkQueueSubmit` of its own that signals +its queue's timeline, grouping no batches, and notes what each encoder was: its kind, its command +buffer's object ID, its place among the command buffer's encoders, a render pass's area, sample +count, attachments' formats and sizes, Vulkan render pass instances and whether it is over a +rasterization-rate map, its executions of indirect commands, and the label hash of each pipeline +state it bound (the first 8 bytes of the SHA-256 of the state's label and its functions' names; no +name and no shader text), and of each state its indirect commands named at a host step. Once no +work of the device advanced for 2 s while some was pending, it logs one line for each `VkQueue` +whose oldest batch is pending (id name `metal2vulkan-encoder-trail`, `Info` severity): that +batch's encoders, and the last batch the queue completed, with how long before; once a stall. A +submission a host step makes and waits for itself (a rasterization-rate map's fan-out probe, a +predicated loop's check run again) signals no timeline: once it ran for 2 s, one line names it, +the encoder whose step made it and the states its commands named. It changes when work goes to the driver, and its +timing, never what the work computes. Whatever the variables, a placement heap's `newTextureWithDescriptor:offset:` that makes no texture (`Nil` or `OutOfMemory`) at an offset inside the heap says so (id name `metal2vulkan-heap-texture-refused`, `Info` severity): the descriptor, the offset, the heap's size,