diff --git a/crates/xtp-gpu/src/host.rs b/crates/xtp-gpu/src/host.rs index a40be27..6968f23 100644 --- a/crates/xtp-gpu/src/host.rs +++ b/crates/xtp-gpu/src/host.rs @@ -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>; + +/// 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), + /// 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 = Mutex::new(Submissions::new()); /// Title submissions over a frame-rate window. @@ -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(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. @@ -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::(&[]), 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). @@ -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). @@ -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, + /// 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, } impl Pending { @@ -1272,6 +1376,7 @@ impl Pending { back, writes, submitted: std::time::Instant::now(), + preparing: std::time::Duration::ZERO, title: None, }; (pending, touches) @@ -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() @@ -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. @@ -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 { @@ -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")] @@ -1620,7 +1770,7 @@ 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. @@ -1628,7 +1778,7 @@ impl Host { 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")] @@ -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); } } @@ -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!( diff --git a/crates/xtp-gpu/src/host/submissions.rs b/crates/xtp-gpu/src/host/submissions.rs index 4264118..33d5c01 100644 --- a/crates/xtp-gpu/src/host/submissions.rs +++ b/crates/xtp-gpu/src/host/submissions.rs @@ -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()); +} diff --git a/crates/xtp-gpu/src/resource/decode.rs b/crates/xtp-gpu/src/resource/decode.rs index be7be86..7a89d5f 100644 --- a/crates/xtp-gpu/src/resource/decode.rs +++ b/crates/xtp-gpu/src/resource/decode.rs @@ -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); diff --git a/crates/xtp-gpu/src/texture.rs b/crates/xtp-gpu/src/texture.rs index 12ee2c4..22dd0a2 100644 --- a/crates/xtp-gpu/src/texture.rs +++ b/crates/xtp-gpu/src/texture.rs @@ -617,7 +617,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) && !staging.blank.load(Ordering::Acquire) && target.as_ref().is_none_or(|t| staging.copy_due(t)); let runs = match &predicate { - Some(p) => p.decide(due, crate::timestamps::submissions()), + Some(p) => p.decide(due), None => true, }; COPIES[usize::from(runs)].fetch_add(1, Ordering::Relaxed); @@ -1644,9 +1644,6 @@ static PREDICATE_WORDS: OnceLock<Option<Predicates>> = OnceLock::new(); pub(crate) struct Predicate { of: &'static Predicates, at: u32, - /// The submission being prepared (`timestamps::submissions`, plus one) - /// when the word was last set to run; 0: never. - ran_in: AtomicU64, } impl Predicate { @@ -1671,11 +1668,7 @@ impl Predicate { once!("texture copy predicates ran out: copies run every time"); return None; }; - let p = Predicate { - of, - at, - ran_in: AtomicU64::new(0), - }; + let p = Predicate { of, at }; p.set(true); Some(p) } @@ -1703,20 +1696,13 @@ impl Predicate { u64::from(self.at) * 8 } - /// At the list's submission (`submission`: the submissions made - /// before it): its copy runs if `due`, or if it was let run earlier in - /// the same submission, which names the list twice. Both runs read the - /// one word, so the second decision must not take the copy from the - /// first (VIctory #1500, by A6thGraderFr, handles that case too). - /// Returns whether the copy runs. - pub(crate) fn decide(&self, due: bool, submission: u64) -> bool { - let this = submission + 1; - let runs = due || self.ran_in.load(Ordering::Relaxed) == this; - if runs { - self.ran_in.store(this, Ordering::Relaxed); - } - self.set(runs); - runs + /// At the list's submission: its copy runs if `due`. A submission that + /// names the list again runs it again only once this run has finished + /// (`Host::run_as`), so no other run reads the word meanwhile. Returns + /// whether the copy runs. + pub(crate) fn decide(&self, due: bool) -> bool { + self.set(due); + due } /// Before the list runs: whether its copy runs. @@ -3253,14 +3239,14 @@ mod tests { let _ = other; } - /// A list named twice in one submission runs its copy in both runs if - /// the first needs it: both read its one predicate word. Submitted - /// again in a later submission, nothing changed, it does not: the - /// submissions are counted with timestamps off too (the default here). + /// A list named twice in one submission runs twice, the second run + /// once the first has finished (D3D12 message 553 otherwise, #45): the + /// first copies, the second finds the texture current and does not. + /// Submitted again in a later submission, nothing changed, it does not + /// either. The layer raises nothing. #[test] - fn a_list_named_twice_in_a_submission_copies() { - crate::testgpu::known_layer_errors(&[553], "#45"); - let test = "texture::tests::a_list_named_twice_in_a_submission_copies"; + fn a_list_named_twice_in_a_submission_copies_once() { + let test = "texture::tests::a_list_named_twice_in_a_submission_copies_once"; let Some(gpu) = crate::testgpu::device(test) else { return; }; @@ -3291,17 +3277,17 @@ mod tests { list.close(); host.execute(&[&list, &list]); host.drain(); - assert_eq!(decided(&staging), [true, true, true]); + assert_eq!(decided(&staging), [true, true, false]); let read = read_back(host, texture, COPY_DEST); let texels: Vec<u8> = (0..16) .flat_map(|y| read[y * 256..y * 256 + 64].to_vec()) .collect(); assert!(texels.iter().all(|&b| b == 0x77), "{:x?}", &texels[..16]); - // The same recording in a submission of its own, the memory as it - // was: told from a second run of the last one by the count. + // The same recording in a submission of its own: nothing changed + // since the last run, so it does not copy either. host.execute(&[&list]); host.drain(); - assert_eq!(decided(&staging), [true, true, true, false]); + assert_eq!(decided(&staging), [true, true, false, false]); type Release = extern "system" fn(This) -> u32; assert_eq!(crate::object::slot::<Release>(resource, 0x10)(resource), 0); } diff --git a/crates/xtp-gpu/src/timestamps.rs b/crates/xtp-gpu/src/timestamps.rs index 5478a35..c8cc15d 100644 --- a/crates/xtp-gpu/src/timestamps.rs +++ b/crates/xtp-gpu/src/timestamps.rs @@ -573,8 +573,7 @@ struct Submission { static SUBMISSIONS: AtomicU64 = AtomicU64::new(0); /// How many host submissions were made so far: while one is prepared, the -/// number of those before it (`texture` tells a list named twice in one -/// submission by it). +/// number of those before it (`texture` counts its checks by it). pub(crate) fn submissions() -> u64 { SUBMISSIONS.load(Ordering::Acquire) } @@ -583,11 +582,9 @@ pub(crate) fn submissions() -> u64 { /// timestamps are read once it has finished. pub(crate) fn submitted(queue: &ID3D12CommandQueue, runs: &[&HostList], value: u64, title: bool) { // Counted whether timestamps are on or not, so before the check below: - // `texture` tells a list named twice in one submission from one - // submitted again in a later one by this count - // (`texture::Predicate::decide`), and timestamps are off by default. - // Counted after it, the second submission would run a copy that is not - // due (`submissions_are_counted_with_timestamps_off`). + // `texture`'s diagnostics count its checks per submission by this count, + // and timestamps are off by default + // (`submissions_are_counted_with_timestamps_off`). SUBMISSIONS.fetch_add(1, Ordering::Release); if !on() { return; @@ -1147,8 +1144,7 @@ mod tests { } /// Submissions are counted with timestamps off (the default) too: - /// `texture` tells a list named twice in one submission from one - /// submitted again in a later one by the count. + /// `texture`'s diagnostics count its checks per submission by the count. #[test] fn submissions_are_counted_with_timestamps_off() { if std::env::var_os("XTP_GPU_TIMESTAMPS").is_some() { diff --git a/docs/analysis/gpu-frame.md b/docs/analysis/gpu-frame.md index 8c6ae7d..aac8c5d 100644 --- a/docs/analysis/gpu-frame.md +++ b/docs/analysis/gpu-frame.md @@ -377,9 +377,14 @@ page-mapping drains **13.7** (2.0–32.6), finishing at submission 1.3, and only if the host copy has not got the staging buffer's current contents (`Staging::copy_due`: a count of detilings, and the count and the host copy, held weakly, the last copy gave). So the first list after a change - copies and the others' copies are skipped by the GPU. A list named twice - in one submission reads one word: a second decision there keeps the copy - the first let run. Without a free word, or with + copies and the others' copies are skipped by the GPU. If a submission + names a list again, `Host::run_as` splits before that repeat and settles the + first part before submitting the next, so the list can run again without + D3D12 message 553. This releases the host submission lock, but the title + queue's line lock and, for held submissions, `release_held`'s global lock + remain held. Diagnostics log cumulative `submission split totals` + (calls, split waits and microseconds waiting) beside each frame line to + measure the cost. Without a free word, or with `XTP_TEXTURE_PREDICATION=0`, the copy runs as before. - Tests (WARP, `texture::tests`): a texture copied by the first of two lists and not the second, then not at all while its memory does not @@ -389,8 +394,8 @@ page-mapping drains **13.7** (2.0–32.6), finishing at submission 1.3, and real section view not hashed nor copied without a write, then hashed, detiled and copied after a CPU write and after a write through another view that the writer reports; a copy into another host copy is due; a - list named twice in one submission copies in both runs (fails without - the rule above). + list named twice in one submission copies once across both runs: the repeat + skips the copy after the first run (fails without the split above). ### 7.2 Before and after @@ -452,9 +457,9 @@ the same two things another way: | when a copy runs | once per change, in one list of its own run before the submission's lists (`Host::record_uploads`), with the textures moved to the copy destination there | once per change, by the first list after it: every list records its copy under a predicate, set at submission | | what stays per list | nothing: lists record no copy and no copy-destination round trip | the copy-destination round trip, `SetPredication` twice and the skipped copy: 1.8 ms of GPU a frame for about 320 recordings (B3) | | bookkeeping | detilings counted per staging buffer, the count the host copy last got | the same, plus which host copy got it | -| a list named twice | handled | handled, after reading #1500 (credited in the code) | +| a list named twice | handled | split before each repeat; counted once on the frame line, with all parts' lists and times added at the last part | | textures in views | still hashed whole at every check, on up to 8 threads (one per 4 MiB) at the batch's refresh points | not hashed unless a guard reports a write (ds-guards made that sound in XTP) | -| files | `host.rs` (`Batch`, `run_as`, `Step::Texture`), `texture.rs` | `texture.rs` only | +| files | `host.rs` (`Batch`, `run_as`, `Step::Texture`), `texture.rs` | `texture.rs`, `host.rs` (repeated-list splitting) | #1500's layout saves the per-list round trip and the skipped copies, about 1.8 ms of GPU a frame here, but needs `run_as` and `Batch` reordered in