Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
192 changes: 175 additions & 17 deletions crates/xtp-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,60 @@ static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [

/// How long a submission took: on the GPU, and in all (preparing, GPU,
/// copying back, bottom-of-pipe writes).
#[derive(Debug, Clone, Copy, Default)]
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct Ran {
pub(crate) gpu: std::time::Duration,
pub(crate) total: std::time::Duration,
}

impl std::ops::Add for Ran {
type Output = Ran;

fn add(self, other: Ran) -> Ran {
Ran {
gpu: self.gpu + other.gpu,
total: self.total + other.total,
}
}
}

/// What the parts of a title submission run in parts ([`Host::run_as`])
/// took so far: their lists, and their times, each added once it ran.
type Parts = std::sync::Arc<Mutex<(usize, Ran)>>;

/// A title submission, or a part of one, as the frame-rate line counts it.
enum Title {
/// A whole submission, or the last part of one with what the parts
/// before it took: counted once it has run.
Last(Option<Parts>),
/// A part before the last: what it took goes to the last.
Part(Parts),
}

impl Title {
/// What the frame-rate line counts once this has run (`lists` lists,
/// `ran`), if anything yet. Parts finish in order, the last after the
/// others (`Host::run_as` waits for each before the next).
fn counted(self, lists: usize, ran: Ran) -> Option<(usize, Ran)> {
let add = |parts: &Parts| {
let mut so_far = parts.lock().unwrap_or_else(|e| e.into_inner());
*so_far = (so_far.0 + lists, so_far.1 + ran);
*so_far
};
match self {
Title::Last(None) => Some((lists, ran)),
Title::Last(Some(parts)) => Some(add(&parts)),
Title::Part(parts) => {
add(&parts);
None
}
}
}
}

/// The title's submissions since the last frame-rate line (one per
/// `ExecuteCommandLists`; ours, the present copy, are not counted).
/// `ExecuteCommandLists`, however many parts it ran in; ours, the present
/// copy, are not counted).
static TITLE: Mutex<Submissions> = Mutex::new(Submissions::new());

/// Title submissions over a frame-rate window.
Expand Down Expand Up @@ -287,6 +333,19 @@ pub(crate) fn sync_submit() -> bool {
})
}

/// How many of `runs` come before the first one named a second time (all
/// of them when none is): where a submission is split ([`Host::run_as`]).
/// Submissions name few lists; a search beats building a set.
fn first_repeat<T>(runs: &[&T]) -> usize {
(1..runs.len())
.find(|&i| runs[..i].iter().any(|r| std::ptr::eq(*r, runs[i])))
.unwrap_or(runs.len())
}

/// Calls, waits before a repeated list, and microseconds spent in those waits.
#[cfg(feature = "diagnostics")]
static SPLITS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];

/// What the runtime does when the host GPU fails for good: report it like a
/// crash and end the run. The console has no such state, and carrying on
/// draws nothing at seconds per frame.
Expand Down Expand Up @@ -632,6 +691,20 @@ mod tests {
worker.join().unwrap();
}

/// A submission is split before each list it names again, by identity
/// (equal values in two places are two lists).
#[test]
fn a_submission_is_split_before_a_list_named_again() {
let (a, b, c, a_twin) = (1, 2, 3, 1);
assert_eq!(first_repeat::<i32>(&[]), 0);
assert_eq!(first_repeat(&[&a]), 1);
assert_eq!(first_repeat(&[&a, &b, &c]), 3);
assert_eq!(first_repeat(&[&a, &a]), 1);
assert_eq!(first_repeat(&[&a, &b, &a]), 2);
assert_eq!(first_repeat(&[&a, &b, &c, &b, &a]), 3);
assert_eq!(first_repeat(&[&a, &a_twin]), 2);
}

/// Where a list stopped, the device-removed report names the commands
/// between the barriers around it by their markers, and the noted
/// commands after them: DRED's count may lag the GPU (xcl#1592).
Expand Down Expand Up @@ -732,6 +805,35 @@ mod tests {
assert_eq!(outside(100.0, 130.0), 0.0);
}

/// A title submission run in parts (a list named again) counts once on
/// the frame-rate line, by its last part, with every part's lists and
/// times; a whole one counts as itself.
#[test]
fn the_frame_line_counts_a_split_submission_once() {
let ms = std::time::Duration::from_millis;
let ran = |gpu, total| Ran {
gpu: ms(gpu),
total: ms(total),
};
let mut s = Submissions::new();
let parts = Parts::default();
// [a, b, a, c, a] runs as [a, b], [a, c], [a].
assert_eq!(Title::Part(parts.clone()).counted(2, ran(10, 15)), None);
assert_eq!(Title::Part(parts.clone()).counted(2, ran(20, 30)), None);
let (lists, all) = Title::Last(Some(parts)).counted(1, ran(5, 8)).unwrap();
s.add(lists, all);
let whole = Title::Last(None).counted(3, ran(1, 2)).unwrap();
s.add(whole.0, whole.1);
let want = PerFrame {
submissions: 2.0,
lists: 4.0,
longest_ms: 53.0,
longest_gpu_ms: 35.0,
longest_lists: 5,
};
assert_eq!(s.per_frame(1.0), want);
}

/// The GPU's time and the copying back the title's threads did not
/// wait for: all of it waited for (synchronous submission) is no
/// overlap; never below zero (the GPU's time is measured roughly).
Expand Down Expand Up @@ -1199,9 +1301,11 @@ struct Pending {
/// Its bottom-of-pipe writes, in list order: address, what, bytes.
writes: Vec<(usize, crate::queue::Written, usize)>,
submitted: std::time::Instant,
/// For a title submission (the frame-rate line counts those): the
/// time it took to prepare.
title: Option<std::time::Duration>,
/// The time it took to prepare.
preparing: std::time::Duration,
/// For a title submission or a part of one: how the frame-rate line
/// counts it.
title: Option<Title>,
}

impl Pending {
Expand Down Expand Up @@ -1272,6 +1376,7 @@ impl Pending {
back,
writes,
submitted: std::time::Instant::now(),
preparing: std::time::Duration::ZERO,
title: None,
};
(pending, touches)
Expand Down Expand Up @@ -1461,6 +1566,8 @@ impl Host {
/// As [`Host::run`], waited for and finished before returning with
/// `sync`.
fn run_as(&self, runs: &[&HostList], title: bool, sync: bool) {
#[cfg(feature = "diagnostics")]
SPLITS[0].fetch_add(1, Ordering::Relaxed);
if !sync {
self.finisher.call_once(|| {
let spawned = std::thread::Builder::new()
Expand All @@ -1471,6 +1578,48 @@ impl Host {
}
});
}
// A title may name a list more than once in a submission; D3D12 runs
// a list again only once its previous execution has finished, in one
// `ExecuteCommandLists` or not (debug layer message 553), and each
// run of a list rewrites its prelude, upload memory and budget word.
// Such a submission goes in parts, each up to the next list named
// again, run once the part before has finished: the GPU runs the
// same lists in the same order, and each run finds what the run
// before wrote. The wait releases the host submission lock, but a
// title queue retains its line lock and a held submission retains
// release_held's global lock, delaying other queues. Counted once, by
// its last part, with all its parts' lists and their times
// preparing, on the GPU and copying back; the waits between them
// count as waiting, as a caller's would.
let mut rest = runs;
let mut parts: Option<Parts> = None;
loop {
let (part, next) = rest.split_at(first_repeat(rest));
let counted = title.then(|| match next {
[] => Title::Last(parts.take()),
_ => Title::Part(parts.get_or_insert_default().clone()),
});
self.run_part(part, counted, sync);
let Some(again) = next.first() else {
return;
};
#[cfg(feature = "diagnostics")]
let waiting = {
SPLITS[1].fetch_add(1, Ordering::Relaxed);
std::time::Instant::now()
};
self.settle(again.last.load(Ordering::Acquire));
#[cfg(feature = "diagnostics")]
SPLITS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
rest = next;
}
}

/// Runs `runs`, no list among them twice: one submission, a title's
/// (or a part of one) with `title`, counted for the frame-rate line as
/// it says.
fn run_part(&self, runs: &[&HostList], title: Option<Title>, sync: bool) {
let is_title = title.is_some();
// One submission at a time from preparation to submission (to
// copy-back with `XTP_SYNC_SUBMIT`): what a step waits for is
// decided against the submissions before it.
Expand Down Expand Up @@ -1517,7 +1666,7 @@ impl Host {
}
// Records the title copied into its placed descriptor heaps as
// bytes, before the lists' own work at submission (their sweeps).
if title {
if is_title {
crate::descriptor::sync_heaps();
}
for list in runs {
Expand Down Expand Up @@ -1560,7 +1709,8 @@ impl Host {
let now = std::time::Instant::now();
let preparing = (now - started).saturating_sub(waited);
recording.finish(now, waited_now, preparing, &batch.work);
pending.title = title.then_some(preparing);
pending.preparing = preparing;
pending.title = title;
// Diagnostics: each list on its own, timed and waited for
// (`XTP_GPU_TIMING`).
#[cfg(feature = "diagnostics")]
Expand Down Expand Up @@ -1620,15 +1770,15 @@ impl Host {
let _ = &firsts;
for list in runs {
list.last.store(*submitted, Ordering::Release);
list.ours.store(!title, Ordering::Release);
list.ours.store(!is_title, Ordering::Release);
}
// `XTP_PLANE_PROBE`: the probes of the lists' depth plane passes
// are read once this submission has run.
#[cfg(feature = "diagnostics")]
runs.iter()
.for_each(|list| list.twins_submitted(*submitted));
self.timeline.push(*submitted, touches, pending);
crate::timestamps::submitted(&self.queue, runs, *submitted, title);
crate::timestamps::submitted(&self.queue, runs, *submitted, is_title);
// `XTP_SYNC_SUBMIT`, and timed lists: finished before returning,
// still one submission at a time.
#[cfg(feature = "diagnostics")]
Expand Down Expand Up @@ -1953,14 +2103,15 @@ impl Host {
what.write(at as *mut u8, bytes);
}
self.log_messages();
if let Some(preparing) = p.title {
TITLE.lock().unwrap_or_else(|e| e.into_inner()).add(
p.lists.len(),
Ran {
gpu: ran,
total: preparing + ran + back,
},
);
let took = Ran {
gpu: ran,
total: p.preparing + ran + back,
};
if let Some((lists, ran)) = p.title.and_then(|t| t.counted(p.lists.len(), took)) {
TITLE
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(lists, ran);
}
}

Expand Down Expand Up @@ -3633,6 +3784,13 @@ impl Meter {
making = crate::pipeline::making()
);
tracing::info!("snapshots per frame: {snapshot_ms:.3} ms");
#[cfg(feature = "diagnostics")]
tracing::info!(
calls = SPLITS[0].load(Ordering::Relaxed),
waits = SPLITS[1].load(Ordering::Relaxed),
wait_us = SPLITS[2].load(Ordering::Relaxed),
"submission split totals"
);
tracing::info!("guards and write watch per frame: {watch_ms:.3} ms");
#[cfg(feature = "diagnostics")]
tracing::info!(
Expand Down
83 changes: 83 additions & 0 deletions crates/xtp-gpu/src/host/submissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -919,3 +919,86 @@ fn a_list_of_ours_waits_for_its_submission_when_reset() {
list.0.close();
host.drain();
}

/// A list named more than once in a submission runs that many times, in
/// order, each run finding what the one before wrote, with no layer error
/// (D3D12 message 553: a list executed again before its previous execution
/// finished). The list shifts four buffers along (`d = c`, `c = b`,
/// `b = a`): `a`'s words reach `c` only through a first run's `b`, and `d`
/// only through a second run's `c`. Ours and a title's alike.
#[test]
fn a_list_named_again_in_a_submission_runs_again_after_itself() {
let test = "host::submissions::a_list_named_again_in_a_submission_runs_again_after_itself";
let _serial = serial();
let Some(gpu) = device(test) else { return };
let host = gpu.host();
let kernel = Kernel::new(host);
let shifted = |runs: usize| {
let [a, b, c, d] = [(); 4].map(|()| TitleBuffer::new(256));
a.set_words(|i| 0xa000_0000 + i as u32);
let list = host.new_list().unwrap();
for (from, to) in [(&c, &d), (&b, &c), (&a, &b)] {
kernel.dispatch(&list, Pass::Copy, from.address(), to.address());
}
list.close();
let named = vec![&list; runs];
if runs == 2 {
host.execute(&named);
} else {
host.submit(&named);
}
host.drain();
assert!(!list.running());
(a.words(), [b.words(), c.words(), d.words()])
};
let zeros = vec![0; 64];
let (a, [b, c, d]) = shifted(2);
assert_eq!((&b, &c), (&a, &a), "the second run found the first's b");
assert_eq!(d, zeros, "two runs, not three");
let (a, [b, c, d]) = shifted(3);
assert_eq!((&b, &c, &d), (&a, &a, &a), "the third found the second's c");
}

/// The wait between the parts of a submission split before a list named
/// again is outside the submission lock: while it waits for its first part,
/// held on the GPU, another thread's submission goes in and returns. An
/// earlier version waited under the lock, which stopped every other
/// submission until the gate's timer.
#[test]
fn a_split_submission_waits_between_its_parts_outside_the_lock() {
let test = "host::submissions::a_split_submission_waits_between_its_parts_outside_the_lock";
let _serial = serial();
let Some(gpu) = device(test) else { return };
let host = gpu.host();
let [named, other] = [(); 2].map(|()| Shared(host.new_list().unwrap()));
named.get().close();
other.get().close();
let mut gate = Gate::close(host);
let (done, executed) = std::sync::mpsc::channel();
let (first_part, returned) = std::thread::scope(|s| {
let submitter = s.spawn(|| host.submit(&[named.get(), named.get()]));
// Its first part is in flight, held by the gate: the submitter waits
// for it before the second.
let started = std::time::Instant::now();
while !named.get().running() && started.elapsed() < std::time::Duration::from_secs(10) {
std::thread::yield_now();
}
let first_part = named.get().running();
s.spawn(|| {
host.execute(&[other.get()]);
let _ = done.send(());
});
let returned = executed.recv_timeout(std::time::Duration::from_secs(10));
let held = !submitter.is_finished();
gate.open();
submitter.join().unwrap();
(first_part, returned.is_ok() && held)
});
assert!(first_part, "the first part went in alone");
assert!(
returned,
"another submission returns while the split one waits"
);
host.drain();
assert!(!named.get().running() && !other.get().running());
}
2 changes: 1 addition & 1 deletion crates/xtp-gpu/src/resource/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub(super) fn recorded(
let previous = to.content.swap(version, Ordering::Relaxed);
let runs = predicate
.as_ref()
.is_none_or(|p| p.decide(previous != version, crate::timestamps::submissions()));
.is_none_or(|p| p.decide(previous != version));
#[cfg(test)]
if runs {
to.decode_count.fetch_add(1, Ordering::Relaxed);
Expand Down
Loading
Loading