The encoder trail names each execution's GPU form, and its line reads the form's scratch while pending

The 3090 hang's rerun (its trail line, read in place) named a pass whose two executions of
indirect commands, both through ranges a buffer holds, carried no host-step note: commit recorded
them for good in their merged GPU form (render/executions/gpu.rs), where the trail noted nothing,
so the line could not tell what the GPU read.

encoder_trail.rs:
- GpuForm: an execution's GPU form, its shape (recorded at commit or by its host step, merged or a
  draw per command, indexed, primitive type, the commands its preprocess runs over and from where,
  and the range buffer's offset), with its scratch region, layout and the command buffer's status
  words.
- Named: a part's (and a batch's) trail text with the GPU forms its executions took; the line's
  front batch is described with each form's scratch read now: the range the GPU copied, the
  merged draw's two VkDrawIndirectCommands, the commands whose arguments draw, their vertices or
  indices times instances and the most of them (its index entry where indexed), and the status
  words. The last-completed batch keeps its text alone.
- Step carries forms through a host step; commit's recording of each segment runs under a Step of
  its own (CommandBuffer::noting_forms), whose forms alone it keeps, joined to the part that holds
  the segment (State::trail_forms).

upload.rs: Upload::glimpse, volatile u32 reads of a region of the host-coherent chunk mapping,
read-only, no lock, no wait. completion.rs: the line's names are taken under the pending lock and
formatted (and the scratch read) after it. Off, nothing changes: no note is made.

Test: tests::trail_gpu_forms (device): four CPU-written triangle commands through a range buffer
of [1, 2], recorded at commit merged; after completion the form reads the range 1+2, the merged
draws [2147483646 x 0; 48 x 1 from vertex 2^31], 2 drawing arguments (7x2, 12x3), the most
command 2's, no fault.
This commit is contained in:
Anees Iqbal committed 2026-11-12 23:03:44 -08:00
1 parent 5009abbc40
commit bbf86acd0e
12 files changed
+568 -73

No files matched your search

@@ -317,7 +317,7 @@ pub(crate) struct Submitted {
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<Arc<str>>,
pub(crate) trail: Option<crate::encoder_trail::Named>,
}
/// A batch of another `VkQueue` that a batch waited for and finishes after
@@ -631,7 +631,7 @@ fn turns(watch: &Watch, lists: &mut FenceLists) -> bool {
// 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()));
pending.trails[*queue] = Some((Arc::clone(trail.text()), Instant::now()));
}
}
// The waiters of the queues whose batches it took, where they sleep and their
@@ -1333,9 +1333,10 @@ 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.
/// pending, once a stall. What they name is taken under the lock; formatted after it, where the
/// GPU forms' scratch is read (`encoder_trail.rs`, **GPU forms**), and said.
fn trail(watch: &Watch, device: &Device, queue: usize, front: Front, value: u64) {
let lines = {
let (stalled, named) = {
let mut pending = lock(&watch.pending);
if value > pending.reached[queue] || value >= front.value {
return;
@@ -1349,21 +1350,22 @@ fn trail(watch: &Watch, device: &Device, queue: usize, front: Front, value: u64)
trails,
..
} = &*pending;
let mut lines = Vec::new();
let pool = device.shared().pipeline_pool.queued();
let mut named = 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, pool,
));
let last =
(trails[queue].as_ref()).map(|(trail, at)| (Arc::clone(trail), at.elapsed()));
named.push((queue, oldest.trail.clone(), last));
}
lines
(stalled, named)
};
for line in lines {
let pool = device.shared().pipeline_pool.queued();
for (queue, front, last) in named {
let front = front.as_ref().map(crate::encoder_trail::Named::pending);
let last = (last.as_ref()).map(|(trail, ago)| (&**trail, *ago));
let line = crate::encoder_trail::line(queue, stalled, front.as_deref(), last, pool);
device.inform(crate::encoder_trail::ID_NAME, line);
}
}
@@ -2074,6 +2074,21 @@ impl State {
part.summary = part.summary.fences_only();
}
/// Join the GPU forms `commit`'s recording of each segment took (`forms`, one list per
/// segment in encoding order) to the encoder trail's name of the part that holds it
/// (`encoder_trail.rs`, **GPU forms**).
fn trail_forms(&mut self, forms: Vec<Vec<Arc<crate::encoder_trail::GpuForm>>>) {
let mut forms = forms.into_iter();
for part in &mut self.recorded {
for _ in &part.segments {
let took = forms.next().unwrap_or_default();
if let Some(trail) = part.trail.as_mut().filter(|_| !took.is_empty()) {
trail.join_forms(took);
}
}
}
}
/// Hand `commit`'s work on the segments, one per segment in encoding order, to them: the
/// recording of a segment `commit` made, for good where no host step records it, and what a
/// host step needs.
@@ -2573,8 +2588,39 @@ impl CommandBuffer {
}
}
/// Run `made`, a segment's recording at `commit`, and return what it made and the GPU forms
/// it took, where the device's encoder trail is on (`encoder_trail.rs`, **GPU forms**): it
/// notes as a host step does, and `commit` keeps the forms alone.
fn noting_forms<T>(
&self,
made: impl FnOnce() -> T,
) -> (T, Vec<Arc<crate::encoder_trail::GpuForm>>) {
if !self.device().shared().encoder_trail {
return (made(), Vec::new());
}
*lock(&self.0.step_trail) = Some(crate::encoder_trail::Step::new(None));
let made = made();
let step = lock(&self.0.step_trail).take();
(
made,
step.map(crate::encoder_trail::Step::into_forms)
.unwrap_or_default(),
)
}
/// The text of each GPU form its encoders' parts took, as the encoder trail reads it now
/// (`encoder_trail.rs`, **GPU forms**): a device test's view.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn trail_form_texts(&self) -> Vec<String> {
(self.state().recorded.iter())
.filter_map(|part| part.trail.as_ref())
.flat_map(crate::encoder_trail::Named::forms)
.collect()
}
/// 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.
/// commands to name (`encoder_trail.rs`, **Host steps**), or that `commit`'s recording of a
/// segment noted (`noting_forms`); nothing outside either.
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);
@@ -3791,12 +3837,18 @@ impl CommandBuffer {
// use).
let listing = Listing::new(device, used);
// Recorded, or settled for their host steps, with the lock free: their dispatches take it,
// and announce degradations.
// and announce degradations. The GPU forms each recording took, for the encoder trail
// (`encoder_trail.rs`, **GPU forms**).
let mut forms = Vec::new();
let prepared: Result<Vec<_>, Error> = match segments.is_empty() {
true => Ok(Vec::new()),
false => commit_times::phase(Phase::Recording, || {
(segments.iter().zip(&places))
.map(|((work, host), _)| work.prepare(self, *host))
.map(|((work, host), _)| {
let (prepared, took) = self.noting_forms(|| work.prepare(self, *host));
forms.push(took);
prepared
})
.collect()
}),
};
@@ -3888,6 +3940,7 @@ impl CommandBuffer {
state.fail(failure);
}
state.prepare(prepared);
state.trail_forms(forms);
state.plan_checks();
// A refused commit's commands run nothing: none of what follows is made for them.
if run == CommitRun::Refused {
@@ -91,7 +91,7 @@ impl CommandBuffer {
twin_writes: Vec::new(),
overwrites: Vec::new(),
trail: (device.shared().encoder_trail)
.then(|| std::sync::Arc::from("the runtime's storage form switch")),
.then(|| crate::encoder_trail::Named::new("the runtime's storage form switch")),
},
);
state.retained.extend(recorded.retained.into_entry());
@@ -2146,18 +2146,8 @@ fn finishes_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<Arc<str>> {
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))
fn batch_trail(recorded: &[Recorded]) -> Option<crate::encoder_trail::Named> {
crate::encoder_trail::Named::joined(recorded.iter().filter_map(|part| part.trail.as_ref()))
}
/// The images whose first use among `parts` (a batch's, in order) writes every texel before any
+9 -4
View File
@@ -167,7 +167,7 @@ pub(super) struct Recorded {
pub(super) overwrites: Vec<Overwrite>,
/// What the encoder was, as the encoder trail names it, where the device's trail is on
/// (`encoder_trail.rs`).
pub(super) trail: Option<Arc<str>>,
pub(super) trail: Option<crate::encoder_trail::Named>,
}
/// A texture whose image an encoder writes whole, every texel of every aspect, before any of its
@@ -3072,7 +3072,9 @@ impl EncoderCore {
sparse: Vec::new(),
twin_writes: Vec::new(),
overwrites: Vec::new(),
trail: (trail.as_ref()).map(|trail| Arc::from(format!("{trail}, left out"))),
trail: (trail.as_ref()).map(|trail| {
crate::encoder_trail::Named::new(format!("{trail}, left out"))
}),
},
);
}
@@ -3106,8 +3108,11 @@ impl EncoderCore {
twin_writes,
overwrites: overwrites.take().unwrap_or_default(),
trail: (trail.as_ref()).map(|trail| match count {
1 => Arc::from(trail.as_str()),
_ => Arc::from(format!("{trail}, part {} of {count}", at + 1)),
1 => crate::encoder_trail::Named::new(trail.as_str()),
_ => crate::encoder_trail::Named::new(format!(
"{trail}, part {} of {count}",
at + 1
)),
}),
},
);
+275 -21
View File
@@ -23,7 +23,19 @@
//! fanned out or region by region), the executions it recorded in their GPU form, and the kept
//! chunks it ran again (`render/executions/kept.rs`), whose draws it did not read. Its batch
//! names them after the encoder's own; the line names the device's pipeline pool's makings
//! waiting and under way. A submission
//! waiting and under way.
//! - **GPU forms** ([`GpuForm`]). An execution recorded in its GPU form, at `commit` or by a host
//! step (`render/executions/gpu.rs`), whose records the host never reads, is named by its
//! shape: merged into one draw or a draw per command, indexed or not, its primitive type, the
//! commands its preprocess runs over and where its range comes from. Where its batch is the
//! oldest pending one, the line reads the scratch the GPU writes, as it stands while the work
//! is pending: the range the GPU copied, the merged draw's two `VkDrawIndirectCommand`s, the
//! commands with arguments and their vertices or indices times instances, the most of them,
//! and the command buffer's execution status words. It reads host-visible, host-coherent
//! memory the pending command buffer holds (`upload.rs`), already mapped, and only reads it: a
//! word the GPU writes meanwhile may read either value. It takes no lock and waits for
//! nothing. An encoder encoded again (`command_buffer/reencode.rs`) names none of its 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`]).
@@ -37,7 +49,10 @@
use crate::pipeline::{ComputePipelineState, RenderPipelineState};
use crate::render_pass::PassLayout;
use crate::upload::Upload;
use crate::used_resources::EncoderKind;
use metal2vulkan::bind::DrawReplayLayout;
use metal2vulkan::metal::PrimitiveType;
use sha2::{Digest, Sha256};
use std::fmt::Write as _;
use std::sync::Arc;
@@ -50,6 +65,9 @@ pub(crate) const AFTER: Duration = Duration::from_secs(2);
/// The most pipeline states a line names of one encoder.
const KEPT: usize = 16;
/// The most commands of a GPU form's arguments the line reads.
const READ_COMMANDS: u32 = 1 << 20;
/// The id name of the trail's lines.
pub(crate) const ID_NAME: &str = "metal2vulkan-encoder-trail";
@@ -70,6 +88,8 @@ pub(crate) struct Notes {
pass: Option<String>,
/// What a host step drew of its commands.
drawn: Drawn,
/// The executions recorded in their GPU form.
forms: Vec<Arc<GpuForm>>,
}
/// What a host step drew of an execution's commands (the module docs, **Host steps**).
@@ -249,9 +269,10 @@ impl Notes {
self.drawn.routes[route as usize] += 1;
}
/// A host step recorded an execution in its GPU form.
pub(crate) fn gpu_alone(&mut self) {
/// An execution was recorded in its GPU form `form`.
pub(crate) fn gpu_form(&mut self, form: GpuForm) {
self.drawn.gpu_alone += 1;
self.forms.push(Arc::new(form));
}
/// A host step ran a kept chunk of `commands` again.
@@ -294,16 +315,237 @@ impl Notes {
}
}
/// What a batch's encoders (or parts of them) were, as the trail names them: the text, and the
/// executions of theirs recorded in their GPU form (the module docs, **GPU forms**), whose
/// scratch the line reads where the batch is the oldest pending one.
#[derive(Clone)]
pub(crate) struct Named {
text: Arc<str>,
forms: Vec<Arc<GpuForm>>,
}
impl Named {
/// An encoder (or a part of one) named `text`, of no GPU form yet.
pub(crate) fn new(text: impl Into<Arc<str>>) -> Named {
Named {
text: text.into(),
forms: Vec::new(),
}
}
/// Its text.
pub(crate) fn text(&self) -> &Arc<str> {
&self.text
}
/// The same, `more` after its text.
pub(crate) fn after(&self, more: &str) -> Named {
Named {
text: Arc::from(format!("{}{more}", self.text)),
forms: self.forms.clone(),
}
}
/// Its executions took the GPU forms `forms` too.
pub(crate) fn join_forms(&mut self, forms: Vec<Arc<GpuForm>>) {
self.forms.extend(forms);
}
/// `parts`, each noted one of a batch's in order, as one: their texts joined by `; `, and
/// their forms; `None` where none was noted.
pub(crate) fn joined<'a>(mut parts: impl Iterator<Item = &'a Named>) -> Option<Named> {
let first = parts.next()?;
let Some(second) = parts.next() else {
return Some(first.clone());
};
let mut text = format!("{}; {}", first.text, second.text);
let mut forms = first.forms.clone();
forms.extend(second.forms.iter().cloned());
for more in parts {
text.push_str("; ");
text.push_str(&more.text);
forms.extend(more.forms.iter().cloned());
}
Some(Named {
text: Arc::from(text),
forms,
})
}
/// Its text, then each GPU form's shape and its scratch as it stands now, its work pending
/// (the module docs, **GPU forms**).
pub(crate) fn pending(&self) -> String {
let mut text = self.text.to_string();
for form in &self.forms {
let _ = write!(text, "; {}", form.described());
}
text
}
/// The text of each of its GPU forms ([`GpuForm::described`]): a device test's view.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn forms(&self) -> Vec<String> {
self.forms.iter().map(|form| form.described()).collect()
}
}
/// An execution recorded in its GPU form (`render/executions/gpu.rs`), as the trail names it (the
/// module docs, **GPU forms**): its shape, and where its scratch lies.
pub(crate) struct GpuForm {
/// Recorded at `commit`, else by a host step.
at_commit: bool,
/// Indexed draws among its commands, merged into one draw alone.
indexed: bool,
primitive_type: PrimitiveType,
/// The first command its preprocess runs over (the range given; 0 for one read from a
/// buffer, whose every command it runs over).
first: u32,
/// The offset in its buffer of the range read from one; `None` for a range given.
range_from: Option<u64>,
/// Its scratch (`bind::DrawReplayLayout`), and the command buffer's execution status words.
scratch: Upload,
layout: DrawReplayLayout,
status: Upload,
}
impl GpuForm {
/// The GPU form of an execution of commands from `first`, drawing `primitive_type`, `indexed`
/// or not, its range read at `range_from` of a buffer or given, recorded `at_commit` or by a
/// host step, into `scratch` of `layout`, with the command buffer's status words `status`.
pub(crate) fn new(
(at_commit, indexed, primitive_type): (bool, bool, PrimitiveType),
(first, range_from): (u32, Option<u64>),
(scratch, layout, status): (Upload, DrawReplayLayout, Upload),
) -> GpuForm {
GpuForm {
at_commit,
indexed,
primitive_type,
first,
range_from,
scratch,
layout,
status,
}
}
/// Its shape, then its scratch's words as they stand now: the range the GPU copied, the
/// merged draw's two `VkDrawIndirectCommand`s, the commands whose arguments draw and their
/// vertices or indices times instances, the most of them (with its index entry's whole indices
/// and index size where indexed), and the command buffer's status words. Each word read once,
/// as it stood (`Upload::glimpse`).
pub(crate) fn described(&self) -> String {
let layout = &self.layout;
let when = match self.at_commit {
true => "at commit",
false => "by its host step",
};
let merged = match layout.merged {
Some(_) => "merged into one draw",
None => "a draw per command",
};
let indexed = match self.indexed {
true => ", indexed",
false => "",
};
let range = match self.range_from {
Some(offset) => format!("its range read from a buffer at offset {offset}"),
None => "its range given".to_owned(),
};
let mut text = format!(
"an execution's GPU form, recorded {when}: {merged}{indexed}, of primitive type {:?}, over {} command(s) from {}, {range}; read while the work is pending:",
self.primitive_type, layout.commands, self.first
);
if self.range_from.is_some() {
let [location, length] = word_pair(&self.scratch.glimpse(layout.range_offset(), 2));
let _ = write!(text, " the range copied {location}+{length},");
}
if let Some(merged) = layout.merged {
let draws = self.scratch.glimpse(merged.draw_offset(0), 8);
let draw = |words: &[u32]| match words {
[vertices, instances, first, base] => {
format!(
"{vertices} vertices x {instances} from vertex {first}, instance {base}"
)
}
_ => "unread".to_owned(),
};
let _ = write!(
text,
" the merged draws [{}; {}],",
draw(draws.get(..4).unwrap_or_default()),
draw(draws.get(4..).unwrap_or_default())
);
}
let read = layout.commands.min(READ_COMMANDS);
let words = (read as usize) * (layout.types as usize) * 4;
let arguments = self.scratch.glimpse(layout.argument_offset(0, 0), words);
let (mut drawing, mut work) = (0u64, 0u64);
let mut most: Option<(u64, u32, [u32; 4])> = None;
for (at, draw) in arguments.chunks_exact(4).enumerate() {
let [vertices, instances, first, base] = [draw[0], draw[1], draw[2], draw[3]];
let draws = u64::from(vertices) * u64::from(instances);
if draws == 0 {
continue;
}
drawing += 1;
work = work.saturating_add(draws);
if most.is_none_or(|(most, ..)| most < draws) {
let command = at as u32 / layout.types.max(1);
most = Some((draws, command, [vertices, instances, first, base]));
}
}
let past = match layout.commands > read {
true => format!(" (of the first {read})"),
false => String::new(),
};
let _ = write!(
text,
" {drawing} argument(s) that draw{past}, {work} vertices or indices times instances"
);
if let Some((_, command, [vertices, instances, first, base])) = most {
let _ = write!(
text,
", the most command {command}'s: {vertices} x {instances} from {first}, instance {base}"
);
if let Some(merged) = layout.merged.filter(|_| self.indexed) {
let entry = merged.indices_offset + u64::from(command) * 16;
let entry = self.scratch.glimpse(entry, 4);
if let [_, _, whole, size] = entry[..] {
let _ = write!(text, " ({whole} whole indices of {size} byte(s))");
}
}
}
let status = self.status.glimpse(0, 3);
if let [bits, misses, faults] = status[..] {
let _ = write!(
text,
"; status bits {bits:#x}, resident misses {misses}, replay faults {faults:#x}"
);
}
text
}
}
/// The two words of `words`, zero where they were not read.
fn word_pair(words: &[u32]) -> [u32; 2] {
match words {
[a, b, ..] => [*a, *b],
_ => [0, 0],
}
}
/// 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.
/// steps**), or what `commit` noted as it recorded one (its GPU forms alone): the encoder as it
/// ended, and the states its commands named.
pub(crate) struct Step {
encoder: Option<Arc<str>>,
encoder: Option<Named>,
states: Notes,
}
impl Step {
/// A step of the encoder `encoder` names, as it ended.
pub(crate) fn new(encoder: Option<Arc<str>>) -> Step {
pub(crate) fn new(encoder: Option<Named>) -> Step {
Step {
encoder,
states: Notes::default(),
@@ -317,6 +559,12 @@ impl Step {
}
self.states.more += notes.more;
self.states.drawn.join(notes.drawn);
self.states.forms.extend(notes.forms);
}
/// The GPU forms its recording took: what `commit` keeps of its notes.
pub(crate) fn into_forms(self) -> Vec<Arc<GpuForm>> {
self.states.forms
}
/// Whether its commands named any state, or it drew any.
@@ -326,10 +574,8 @@ impl Step {
/// 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");
let encoder =
(self.encoder.as_ref()).map_or("an encoder noted nothing of", |named| &*named.text);
if !self.named() {
return encoder.to_owned();
}
@@ -346,9 +592,19 @@ impl Step {
}
/// 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<Arc<str>> {
self.named().then(|| Arc::from(self.described()))
/// named a state, else `None` (it stays as it ended), with the GPU forms it ended with and
/// those the step's recording took.
pub(crate) fn stepped(&self) -> Option<Named> {
self.named().then(|| {
let mut forms = (self.encoder.as_ref())
.map(|named| named.forms.clone())
.unwrap_or_default();
forms.extend(self.states.forms.iter().cloned());
Named {
text: Arc::from(self.described()),
forms,
}
})
}
}
@@ -490,7 +746,7 @@ mod tests {
);
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")));
let mut step = Step::new(Some(Named::new("Render encoder 3 of command buffer 7")));
assert!(step.stepped().is_none());
let mut named = Notes::default();
named.state(Some("b"), &["v"]);
@@ -501,7 +757,7 @@ mod tests {
let b = label_hash(Some("b"), &["v"]);
let stepped = step.stepped().expect("a state named");
assert_eq!(
&*stepped,
&**stepped.text(),
format!("Render encoder 3 of command buffer 7, its host step's commands' states [{b}]")
);
// What the step drew follows: the ranges it read, its draws and their work, the draw of
@@ -515,12 +771,12 @@ mod tests {
drawn.routed(Route::Plain);
drawn.routed(Route::FannedOut);
drawn.routed(Route::FannedOut);
drawn.gpu_alone();
drawn.drawn.gpu_alone += 1;
step.noted(drawn);
let stepped = step.stepped().expect("a state named");
let work = 72 + 6 * u64::from(u32::MAX) + 300;
assert_eq!(
&*stepped,
&**stepped.text(),
format!(
"Render encoder 3 of command buffer 7, its host step's commands' states [{b}]; \
its host step read ranges [4+9 ran 4..10], drew 3 draw(s) of {work} vertices \
@@ -537,9 +793,7 @@ mod tests {
drawn.drew(true, 3, 3, 1);
unnamed.noted(drawn);
let stepped = unnamed.stepped().expect("a draw noted");
assert!(
stepped.contains("drew 1 draw(s) of 3 vertices"),
"{stepped}"
);
let text = stepped.pending();
assert!(text.contains("drew 1 draw(s) of 3 vertices"), "{text}");
}
}
@@ -2183,13 +2183,8 @@ impl RenderExecution {
let snapshot = &self.snapshot;
let device = command_buffer.device().clone();
if let Some(form) = gpu {
if device.shared().encoder_trail {
let mut notes = crate::encoder_trail::Notes::default();
notes.gpu_alone();
command_buffer.trail_step(notes);
}
let encoder =
self.record_gpu(core, (command_buffer, residency), form, (storage, rendered))?;
let at = (command_buffer, residency);
let encoder = self.record_gpu(core, at, (form, step), (storage, rendered))?;
return self.finish(encoder, found, rendered, &device);
}
if let Some(routes) = routes {
@@ -482,15 +482,17 @@ impl RenderExecution {
}
/// Record the execution's GPU form `form` (the module docs) through `core`, a segment of
/// `command_buffer` with `residency` (the command buffer's): the preprocess and the barrier
/// after it, then the commands' draws into a secondary begun against the execution's
/// instance, over the pass's `storage`, in the call's layout as `rendered` backs it. Returns
/// the encoder that drew them, its runs to end ([`finish`](Self::finish)).
/// `command_buffer` with `residency` (the command buffer's), at `commit` or by its host step
/// (`step`): the preprocess and the barrier after it, then the commands' draws into a
/// secondary begun against the execution's instance, over the pass's `storage`, in the call's
/// layout as `rendered` backs it. The encoder trail notes the form and its scratch
/// (`encoder_trail.rs`, **GPU forms**). Returns the encoder that drew them, its runs to end
/// ([`finish`](Self::finish)).
pub(super) fn record_gpu(
&self,
mut core: EncoderCore,
(command_buffer, residency): (&CommandBuffer, &Residency),
form: &GpuForm,
(form, step): (&GpuForm, bool),
(storage, rendered): (PassStorage, &mut Rendered),
) -> Result<RenderLowering, Error> {
let snapshot = &self.snapshot;
@@ -515,10 +517,24 @@ impl RenderExecution {
.ok_or_else(no_address)?;
let head = scratch_head(pre, sink)?;
let scratch = cb.uploads.upload(&device, &head, pre.layout.bytes)?;
let status = cb.status_address(&device)?.ok_or_else(no_address)?;
(scratch, status)
(scratch, cb.status_words(&device)?)
};
let address = scratch.device_address().ok_or_else(no_address)?;
if device.shared().encoder_trail {
let (first, range_from) = match &self.range {
ExecutionRange::Fixed(range) => (range.start, None),
ExecutionRange::Indirect { offset, .. } => (0, Some(*offset)),
};
let indexed = draw_replay_indexed(form.decided);
let mut notes = crate::encoder_trail::Notes::default();
notes.gpu_form(crate::encoder_trail::GpuForm::new(
(!step, indexed, form.primitive_type),
(first, range_from),
(scratch.clone(), pre.layout, status.clone()),
));
command_buffer.trail_step(notes);
}
let status = status.device_address().ok_or_else(no_address)?;
let mut push = pre.push_constants.clone();
for hole in &pre.push_holes {
let (offset, value) = match *hole {
@@ -690,6 +690,8 @@ mod tiled_texture_step;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod told_once;
mod tracker;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod trail_gpu_forms;
mod trails;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod twin_flights;
@@ -0,0 +1,145 @@
//! The encoder trail's GPU forms (`encoder_trail.rs`, **GPU forms**): an execution of render
//! commands through a range read from a buffer, which `commit` records in its merged GPU form
//! (`render/executions/gpu.rs`), is named by its shape, and its scratch reads as the GPU left it
//! once the command buffer completed: the range the GPU copied, the merged draw's corners, the
//! arguments of the commands inside the range and the most of them, and status words of no fault.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs, on the kind of device
//! the cfg selects (docs/VALIDATION.md). Its functions are `tob_rect` and `tob_solid` of
//! `validation/fixtures/public/engine/tob_renders.ll` (`llvm-as`).
use super::blit_holds::{Scratch, WAIT};
use super::encoder_holds::{bytes_of, library, pass};
use crate::{
CommandBufferStatus, Device, DeviceKind, DeviceOptions, IndirectCommandBufferDescriptor,
PipelineOptions, ResourceOptions, ShaderCacheOptions, TextureDescriptor,
};
use metal2vulkan::metal::{
IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureUsage,
};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
/// Each command's vertices and instances: the range read from the buffer runs commands 1 and 2.
const DRAWS: [(u32, u32); 4] = [(6, 1), (7, 2), (12, 3), (6, 4)];
const RANGE: [u32; 2] = [1, 2];
/// A device of the kind the cfg selects with its encoder trail on, its shader cache in `cache`.
fn trail_device(cache: &std::path::Path) -> Device {
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()
},
encoder_trail: true,
..DeviceOptions::default()
};
Device::system_default_with(&options).unwrap()
}
/// Four commands of triangles the CPU wrote, executed through the range `RANGE` a buffer holds:
/// `commit` records the execution in its merged GPU form, and its trail names it with its range
/// read from the buffer at offset 0. Once the command buffer completed, its scratch holds the
/// range the GPU copied, the merged draw of commands 1 and 2's whole triangles (7 vertices make
/// 2 triangles, times 2 instances; 12 make 4, times 3: 48 corners) in its second draw, from
/// vertex `2^31`, the arguments of those two commands alone (7 times 2 and 12 times 3, the most
/// command 2's), and status words of no fault.
#[test]
fn a_merged_gpu_form_names_its_range_and_draws_as_its_scratch_holds_them() {
let scratch = Scratch::new("trail-gpu-forms");
let device = trail_device(&scratch.0);
let library = library(&device, "engine/tob_renders.ll");
let vertex = library.new_function_with_name("tob_rect").unwrap();
let fragment = library.new_function_with_name("tob_solid").unwrap();
let mut descriptor =
RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor()));
descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor()));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
descriptor.support_indirect_command_buffers = true;
let state = device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
let shared = ResourceOptions::shared();
let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes);
let corners = device.new_buffer_with_bytes(&corners, shared).unwrap();
let color = bytes_of(&[0.2f32, 0.4, 0.6, 1.0], f32::to_le_bytes);
let color = device.new_buffer_with_bytes(&color, shared).unwrap();
let range = bytes_of(&RANGE, u32::to_le_bytes);
let range = device.new_buffer_with_bytes(&range, shared).unwrap();
let mut commands = IndirectCommandBufferDescriptor::new();
commands.command_types = IndirectCommandType::DRAW;
commands.inherit_pipeline_state = true;
commands.max_vertex_buffer_bind_count = 1;
commands.max_fragment_buffer_bind_count = 1;
let icb = device
.new_indirect_command_buffer(&commands, DRAWS.len() as u64, shared)
.unwrap();
for (at, (vertices, instances)) in DRAWS.into_iter().enumerate() {
let command = icb.indirect_render_command_at(at as u64).unwrap();
command.set_vertex_buffer(Some(&corners), 0, 0).unwrap();
command.set_fragment_buffer(Some(&color), 0, 0).unwrap();
command
.draw_primitives(
PrimitiveType::Triangle,
0,
vertices.into(),
instances.into(),
0,
)
.unwrap();
}
let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 8, 8, false);
target.usage = TextureUsage::RENDER_TARGET;
target.resource_options = ResourceOptions::private();
let target = device.new_texture(&target).unwrap();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer
.render_command_encoder(&pass(&target))
.unwrap();
encoder.set_render_pipeline_state(&state).unwrap();
let read = ResourceUsage::READ;
encoder
.use_resource(corners.as_resource(), read, RenderStages::VERTEX)
.unwrap();
encoder
.use_resource(color.as_resource(), read, RenderStages::FRAGMENT)
.unwrap();
encoder
.execute_commands_in_buffer_indirect(&icb, &range, 0)
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(
(command_buffer.status(), command_buffer.error()),
(CommandBufferStatus::Completed, None)
);
let forms = command_buffer.trail_form_texts();
eprintln!("TRAIL-GPU-FORMS {}: {forms:?}", device.name());
if forms.is_empty() && device.work_counts().gpu_form_commands == 0 {
eprintln!("TRAIL-GPU-FORMS: the device records no execution in its GPU form");
return;
}
let [form] = &forms[..] else {
panic!("one GPU form, not {forms:?}");
};
let expected = [
"an execution's GPU form, recorded at commit: merged into one draw, of primitive type \
Triangle, over 4 command(s) from 0, its range read from a buffer at offset 0; read while \
the work is pending: the range copied 1+2,",
" the merged draws [2147483646 vertices x 0 from vertex 0, instance 0; 48 vertices x 1 \
from vertex 2147483648, instance 0],",
" 2 argument(s) that draw, 50 vertices or indices times instances, the most command 2's: \
12 x 3 from 0, instance 0",
"; status bits 0x0, resident misses 0, replay faults 0x0",
];
assert_eq!(form, &expected.concat());
}
+26
View File
@@ -419,6 +419,32 @@ impl Upload {
.map(|address| address + self.offset)
}
/// Up to `words` little-endian `u32`s of the region from its byte `at` (a multiple of 4), cut
/// to the region, as they stand now, while commands may still write them: the encoder trail's
/// view of a pending execution's scratch (`encoder_trail.rs`, **GPU forms**). Each word is
/// read once, volatile, from the chunk's mapping, which is host-coherent and lives while the
/// region does; a word a command writes meanwhile reads either value. It writes nothing,
/// takes no lock and waits for nothing.
pub(super) fn glimpse(&self, at: u64, words: usize) -> Vec<u32> {
let Some(mapped) = self.buffer.mapped_contents() else {
unreachable!("upload chunks are Shared buffers")
};
let fit = (self.len.saturating_sub(at) / 4).min(words as u64) as usize;
let start = (self.offset + at) as usize;
(0..fit)
.map(|word| {
// SAFETY: word `word` lies inside the region (`fit`), inside the chunk's mapping,
// which the region's buffer keeps mapped; the region starts 16-aligned and `at`
// is a multiple of 4, so the word is aligned. A volatile read of memory the GPU
// may write, which the host only reads.
let bytes = unsafe {
std::ptr::read_volatile(mapped.as_ptr().add(start + 4 * word).cast::<[u8; 4]>())
};
u32::from_le_bytes(bytes)
})
.collect()
}
/// The region's first `N` bytes as the device left them. The caller has waited for every
/// command that writes them, and made their writes visible to the host.
pub(super) fn read<const N: usize>(&self) -> [u8; N] {
+12 -5
View File
@@ -1914,11 +1914,18 @@ that step drew: each range it read from a buffer (its location and length as the
and the commands it ran), its draws, their vertices or indices times their instances summed, the
draw of the most of those (its primitive type, count and instances), the route each draw took
(plain, a rate-mapped pass's probe, fanned out, or region by region), the executions it recorded in
their GPU form, and the kept chunks it ran again, whose draws it did not read. 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,
the last batch the queue completed, with how long before, and the device's pipeline pool's makings
waiting and under way; once a stall. A
their GPU form, and the kept chunks it ran again, whose draws it did not read. An execution of render
commands recorded in its GPU form, at the commit or by a host step, is named by its shape (merged
into one draw or a draw per command, indexed or not, its primitive type, the commands its
preprocess runs over and where its range comes from). 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, with each GPU form's scratch
read while its work is pending (the range the GPU copied, the merged draw's two indirect draws,
the commands whose arguments draw, their vertices or indices times instances and the most of them,
and the command buffer's execution status words: only reads of host-visible memory already mapped,
taking no lock and waiting for nothing, each word as it stood when read), the last batch the queue
completed, with how long before, and the device's pipeline pool's makings waiting and under way;
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. The stall probe and the